add lv | fix cat function bugs and allow lang-specific cat functions | ||
| Line 835: | Line 835: | ||
and `POS` is the user-provided part of speech (which may be nil). | and `POS` is the user-provided part of speech (which may be nil). | ||
]=] | ]=] | ||
function export.fetch_categories_and_labels(normalized_tag_set, lang, POS) | function export.fetch_categories_and_labels(normalized_tag_set, lang, POS, pagename, lemmas) | ||
local m_cats = mw.loadData(export.form_of_cats_module) | local m_cats = mw.loadData(export.form_of_cats_module) | ||
local categories = {} | local categories = {} | ||
| Line 843: | Line 843: | ||
-- First split any two-level multipart tags into multiple sets, to make our life easier. | -- First split any two-level multipart tags into multiple sets, to make our life easier. | ||
for _, tag_set in ipairs(export.split_two_level_multipart_tag_set(normalized_tag_set)) do | for _, tag_set in ipairs(export.split_two_level_multipart_tag_set(normalized_tag_set)) do | ||
-- Call a named function, either from the lang-specific data in [[Module:form of/lang-specific/LANGCODE]] or | |||
local function make_function_table() | |||
-- in [[Module:form of/cats]]. | |||
| ⚫ | |||
local function call_named_function(name, funtype) | |||
| ⚫ | |||
local data = { | |||
| ⚫ | |||
pagename = pagename or mw.title.getCurrentTitle().subpageText, | |||
| ⚫ | |||
lemmas = lemmas, | |||
| ⚫ | |||
| ⚫ | |||
| ⚫ | |||
} | } | ||
-- First try lang-specific. | |||
local langcode = lang and lang:getCode() | |||
local lang_specific_module | |||
if langcode and export.langs_with_lang_specific_tags[langcode] then | |||
lang_specific_module = export.form_of_lang_data_module_prefix .. langcode .. "/functions" | |||
local langdata = require(lang_specific_module) | |||
if langdata.cat_functions then | |||
local fn = langdata.cat_functions[name] | |||
| ⚫ | |||
return fn(data) | |||
| ⚫ | |||
| ⚫ | |||
end | |||
| ⚫ | |||
| ⚫ | |||
| ⚫ | |||
end | |||
local lang_specific_part | |||
if lang_specific_module then | |||
lang_specific_part = ("[[%s]] or "):format(lang_specific_module) | |||
else | |||
lang_specific_part = "" | |||
end | |||
error(("No %s function named '%s' in %s[[%s]]"):format(funtype, name, lang_specific_part, | |||
| ⚫ | |||
end | end | ||
| Line 988: | Line 1,017: | ||
end | end | ||
return condval, 4 | return condval, 4 | ||
elseif | elseifpredicate == "call" then | ||
return fn(call_named_function(spec[2], "condition")), 3 | |||
| ⚫ | |||
| ⚫ | |||
error("No condition function named '" .. spec[2] .. "'") | |||
| ⚫ | |||
return fn(make_function_table()), 3 | |||
else | else | ||
error("Unrecognized predicate: " .. predicate) | error("Unrecognized predicate: " .. predicate) | ||
| Line 1,041: | Line 1,066: | ||
return false | return false | ||
elseif predicate == "call" then | elseif predicate == "call" then | ||
| ⚫ | |||
| ⚫ | |||
| ⚫ | |||
error("No spec function named '" .. spec[2] .. "'") | |||
| ⚫ | |||
| ⚫ | |||
else | else | ||
local condval, ifspec = check_condition(spec) | local condval, ifspec = check_condition(spec) | ||
| Line 1,102: | Line 1,123: | ||
`.lemma_face`: (RECOMMENDED) "Face" to use when displaying the lemma objects. Usually should be set to "term". | `.lemma_face`: (RECOMMENDED) "Face" to use when displaying the lemma objects. Usually should be set to "term". | ||
`.POS`: (RECOMMENDED) Categorizing part-of-speech tag. Comes from the p= or POS= argument of {{inflection of}}. | `.POS`: (RECOMMENDED) Categorizing part-of-speech tag. Comes from the p= or POS= argument of {{inflection of}}. | ||
`.pagename`: Page name of "current" page or nil to use the actual page title; for testing purposes. | |||
`.enclitics`: List of enclitics to display after the lemmas, in parens. | `.enclitics`: List of enclitics to display after the lemmas, in parens. | ||
`.no_format_categories`: If true, don't format the categories derived from the inflection tags; just return them. | `.no_format_categories`: If true, don't format the categories derived from the inflection tags; just return them. | ||
| Line 1,164: | Line 1,186: | ||
local cur_infl = {} | local cur_infl = {} | ||
local this_categories, this_labels = export.fetch_categories_and_labels(normalized_tag_set, data.lang, | local this_categories, this_labels = export.fetch_categories_and_labels(normalized_tag_set, data.lang, | ||
data.POS, data.pagename, type(data.lemmas) == "table" and data.lemmas or nil) | |||
data.POS) | |||
if not data.nocat then | if not data.nocat then | ||
m_table.extendList(categories, this_categories) | m_table.extendList(categories, this_categories) | ||
functionexport.format_form_of(data)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.is_link_or_html(tag)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.lookup_shortcut(tag,lang,do_track)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.lookup_tag(tag,lang)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.normalize_tag_set(tag_set,lang,do_track)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.combine_multipart_tags(tag_set)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.normalize_tags(tags,lang,recombine_multitags,do_track)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.split_two_level_multipart_tag_set(tag_set)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.split_tag_set(tag_set)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.combine_tag_sets(tag_sets)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.parse_tag_set_properties(tag_set)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.normalize_pos(pos)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.get_tag_display_form(tagspec,lang,joiner)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.get_tag_set_display_form(normalized_tag_set,lang,joiner)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.fetch_categories_and_labels(normalized_tag_set,lang,POS,pagename,lemmas)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.tagged_inflections(data)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.to_Wikidata_IDs(tag_set,lang,skip_tags_without_ids)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
functionexport.dump_form_of_data(frame)
This function lacks documentation. Please add a description of its usages, inputs and outputs, or its difference from similar functions, or make it local to remove it from the function list.
localexport={}export.force_cat=false-- for testing; set to true to display categories even on non-mainspace pageslocalm_links=require("Module:links")localm_table=require("Module:table")localput_module="Module:parse utilities"locallabels_module="Module:labels"export.form_of_pos_module="Module:form of/pos"export.form_of_functions_module="Module:form of/functions"export.form_of_cats_module="Module:form of/cats"export.form_of_lang_data_module_prefix="Module:form of/lang-data/"export.form_of_data_module="Module:form of/data"export.form_of_data2_module="Module:form of/data2"localulen=mw.ustring.lenlocalrsubn=mw.ustring.gsublocalrmatch=mw.ustring.matchlocalrsplit=mw.text.splitexport.langs_with_lang_specific_tags={["en"]=true,["got"]=true,["lt"]=true,["lv"]=true,["nl"]=true,["pi"]=true,["sw"]=true,}--[=[This module implements the underlying processing of {{form of}}, {{inflection of}} and specific variants such as{{past participle of}} and {{alternative spelling of}}. Most of the logic in this file is to handle tags in{{inflection of}}. Other related files:* [[Module:form of/templates]] contains the majority of the logic that implements the templates themselves.* [[Module:form of/data]] is a data-only file containing information on the more common inflection tags, listing the tags, their shortcuts, the category they belong to (tense-aspect, case, gender, voice-valence, etc.), the appropriate glossary link and the wikidata ID.* [[Module:form of/data2]] is a data-only file containing information on the less common inflection tags, in the same format as [[Module:form of/data]].* [[Module:form of/lang-data/LANGCODE]] is a data-only file containing information on the language-specific inflection tags for the language with code LANGCODE, in the same format as [[Module:form of/data]]. Language-specific tags override general tags.* [[Module:form of/cats]] is a data-only file listing the language-specific categories that are added when the appropriate combinations of tags are seen for a given language.* [[Module:form of/pos]] is a data-only file listing the recognized parts of speech and their abbreviations, used for categorization. FIXME: This should be unified with the parts of speech listed in [[Module:links]].* [[Module:form of/functions]] contains functions for use with [[Module:form of/data]] and [[Module:form of/cats]]. They are contained in this module because data-only modules can't contain code. The functions in this file are of two types: (1) Display handlers allow for customization of the display of multipart tags (see below). Currently there is only one such handler, for handling multipart person tags such as '1//2//3'. (2) Cat functions allow for more complex categorization logic, and are referred to by name in [[Module:form of/cats]]. Currently no such functions exist.The following terminology is used in conjunction with {{inflection of}}:* A TAG is a single grammatical item, as specified in a single numbered parameter of {{inflection of}}. Examples are 'masculine', 'nominative', or 'first-person'. Tags may be abbreviated, e.g. 'm' for 'masculine', 'nom' for 'nominative', or '1' for 'first-person'. Such abbreviations are called ALIASES, and some tags have multiple equivalent aliases (e.g. 'p' or 'pl' for 'plural'). The full, non-abbreviated form of a tag is called its CANONICAL FORM.* The DISPLAY FORM of a tag is the way it's displayed to the user. Usually the displayed text of the tag is the same as its canonical form, and it normally functions as a link to a glossary entry explaining the tag. Usually the link is to an entry in [[Appendix:Glossary]], but sometimes the tag is linked to an individual dictionary entry or to a Wikipedia entry. Occasionally, the display text differs from the canonical form of the tag. An example is the tag 'comparative case', which has the display text read as simply 'comparative'. Normally, tags referring to cases don't have the word "case" in them, but in this case the tag 'comparative' was already used as an alias for the tag 'comparative degree', so the tag was named 'comparative case' to avoid clashing. A similar situation occurs with 'adverbial case' vs. the grammar tag 'adverbial' (as in 'adverbial participle').* A TAG SET is an ordered list of tags, which together express a single inflection, for example, '1|s|pres|ind', which can be expanded to canonical-form tags as 'first-person|singular|present|indicative'.* A CONJOINED TAG SET is a tag set that consists of multiple individual tag sets separated by a semicolon, e.g. '1|s|pres|ind|;|2|s|imp', which specifies two tag sets, '1|s|pres|ind' as above and '2|s|imp' (in canonical form, 'second-person|singular|imperative'). Multiple tag sets specified in a single call to {{inflection of}} are specified in this fashion. Conjoined tag sets can also occur in list-tag shortcuts.* A MULTIPART TAG is a tag that embeds multiple tags within it, such as 'f//n' or 'nom//acc//voc'. These are used in the case of [[syncretism]], when the same form applies to multiple inflections. Examples are the Spanish present subjunctive, where the first-person and third-person singular have the same form (e.g. [[siga]] from [[seguir]] "to follow"), or Latin third-declension adjectives, where the dative and ablative plural of all genders have the same form (e.g. [[omnibus]] from [[omnis]] "all"). These would be expressed respectively as '1//3|s|pres|sub' and 'dat//abl|m//f//n|p', where the use of the multipart tag compactly encodes the syncretism and avoids the need to individually list out all of the inflections. Multipart tags currently display as a list separated by a slash, e.g. ''dative/ablative'' or ''masculine/feminine/neuter'' where each individual word is linked appropriately. As a special case, multipart tags involving persons display specially; for example, the multipart tag ''1//2//3'' displays as ''first-, second- and third-person'', with the word "person" occurring only once.* A TWO-LEVEL MULTIPART TAG is a special type of multipart tag that joins two or more tag sets instead of joining individual tags. The tags within the tag set are joined by a colon, e.g. '1:s//3:p', which is displayed as ''first-person singular and third-person plural'', e.g. for use with the form [[μέλλον]] of the verb [[μέλλω]] "to intend", which uses the tag set '1:s//3:p|impf|actv|indc|unaugmented' to express the syncretism between the first singular and third plural forms of the imperfect active indicative unaugmented conjugation. Two-level multipart tags should be used sparingly; if in doubt, list out the inflections separately. [FIXME: Make two-level multipart tags obsolete.]* A SHORTCUT is a tag that expands to any type of tag described above, or to any type of tag set described above. Aliases are a particular type of shortcut whose expansion is a single non-multipart tag.* A MULTIPART SHORTCUT is a shortcut that expands into a multipart tag, for example '123', which expands to the multipart tag '1//2//3'. Only the most common such combinations exist as shortcuts.* A LIST SHORTCUT is a special type of shortcut that expands to a list of tags instead of a single tag. For example, the shortcut '1s' expands to '1|s' (first-person singular). Only the most common such combinations exist as shortcuts.* A CONJOINED SHORTCUT is a special type of list shortcut that consists of a conjoined tag set (multiple logical tag sets). For example, the English language-specific shortcut 'ed-form' expands to 'spast|;|past|part', expressing the common syncretism between simple past and past participle in English (and in this case, 'spast' is itself a list shortcut that expands to 'simple|past').]=]-- version of rsubn() that discards all but the first return valuelocalfunctionrsub(term,foo,bar)localretval=rsubn(term,foo,bar)returnretvalendlocalfunctionnormalize_index(list,index)ifindex<0thenreturn#list+index+1endreturnindexend-- FIXME, consider moving to [[Module:table]]-- Return true if the list `tags1`, treated as a set, is a subset of the list `tags2`, also treated as a set.localfunctionis_subset(tags1,tags2)tags1=m_table.listToSet(tags1)tags2=m_table.listToSet(tags2)fortag,_inpairs(tags1)doifnottags2[tag]thenreturnfalseendendreturntrueend-- FIXME, move to [[Module:table]]localfunctionslice(list,i,j)--checkType("slice", 1, list, "table")--checkType("slice", 2, i, "number", true)--checkType("slice", 3, j, "number", true)ifi==niltheni=1elsei=normalize_index(list,i)endj=normalize_index(list,jor-1)localretval={}localk=0forindex=i,jdok=k+1retval[k]=list[index]endreturnretvalend-- Add tracking category for PAGE when called from {{inflection of}} or-- similar TEMPLATE. The tracking category linked to is-- [[Template:tracking/inflection of/PAGE]].localfunctiontrack(page)require("Module:debug/track")("inflection of/"..-- avoid including links in pages (may cause error)page:gsub("%[","("):gsub("%]",")"):gsub("|","!"))endlocalfunctionwrap_in_span(text,classes)return("<span class='%s'>%s</span>"):format(classes,text)end--[=[Lowest-level implementation of form-of templates, including the general {{form of}} as well as those that deal withinflection tags, such as the general {{inflection of}}, semi-specific variants such as {{participle of}}, and specificvariants such as {{past participle of}}. `data` contains all the information controlling the display, with thefollowing fields:`.text`: Text to insert before the lemmas. Wrapped in the value of `.text_classes`, or its default; see below.`.lemmas`: List of objects describing the lemma(s) of which the term in question is a non-lemma form. These are passed directly to full_link() in [[Module:links]]. Each object should have at minimum a `.lang` field containing the language of the lemma and a `.term` field containing the lemma itself. Each object is formatted using full_link() and then if there are more than one, they are joined using serialCommaJoin() in [[Module:table]]. Alternatively, `.lemmas` can be a string, which is displayed directly, or omitted, to show no lemma links and omit the connecting text.`.lemma_face`: "Face" to use when displaying the lemma objects. Usually should be set to "term".`.enclitics`: List of enclitics to display after the lemmas, in parens.`.base_lemmas`: List of base lemmas to display after the lemmas, in the case where the lemmas in `.lemmas` arethemselves forms of another lemma (the base lemma), e.g. a comparative, superlative or participle. Eachobject is of the form { paramobj = PARAM_OBJ, lemmas = {LEMMA_OBJ, LEMMA_OBJ, ...} } where PARAM_OBJdescribes the properties of the base lemma parameter (i.e. the relationship between the intermediateand base lemmas) and LEMMA_OBJ is an object suitable to be passed to full_link in [[Module:links]].PARAM_OBJ is of the format { param = "PARAM", tags = {"TAG", "TAG", ...} } where PARAM is the name ofthe parameter to {{inflection of}} etc. that holds the base lemma(s) of the specified relationship andthe tags describe the relationship, such as {"comd"} or {"past", "part"}.`.text_classes`: CSS classes used to wrap the tag text and lemma links. Default is "form-of-definition use-with-mention" for the tag text and lemma links, and additionally "form-of-definition-link" specifically for the lemma links. (FIXME: Should separate out the lemma links into their own field.)`.posttext`: Additional text to display after the lemma links.]=]functionexport.format_form_of(data)iftype(data)~="table"thenerror("Internal error: First argument must now be a table of arguments")endlocaltext_classes=data.text_classesor"form-of-definition use-with-mention"locallemma_classes=data.text_classesor"form-of-definition-link"localparts={}localfunctionins(text)table.insert(parts,text)endins("<span class='"..text_classes.."'>")ins(data.text)ifdata.text~=""anddata.lemmasthenins(" ")endifdata.lemmastheniftype(data.lemmas)=="string"thenins(wrap_in_span(data.lemmas,lemma_classes))elselocalformatted_terms={}for_,lemmainipairs(data.lemmas)dotable.insert(formatted_terms,wrap_in_span(m_links.full_link(lemma,data.lemma_face,false),lemma_classes))endins(m_table.serialCommaJoin(formatted_terms))endendifdata.encliticsand#data.enclitics>0then-- The outer parens need to be outside of the text_classes span so they show in upright instead of italic, or-- they will clash with upright parens generated by link annotations such as transliterations and pos=.ins("</span>")localformatted_terms={}for_,encliticinipairs(data.enclitics)do-- FIXME, should we have separate clitic face and/or classes?table.insert(formatted_terms,wrap_in_span(m_links.full_link(enclitic,data.lemma_face,false,"show qualifiers"),lemma_classes))endins(" (")ins(wrap_in_span("with enclitic"..(#data.enclitics>1and"s"or"").." ",text_classes))ins(m_table.serialCommaJoin(formatted_terms))ins(")")ins("<span class='"..text_classes.."'>")endifdata.base_lemmasand#data.base_lemmas>0thenfor_,base_lemmainipairs(data.base_lemmas)doins(", the </span>")ins(export.tagged_inflections{lang=base_lemma.lemmas[1].lang,tags=base_lemma.paramobj.tags,lemmas=base_lemma.lemmas,lemma_face=data.lemma_face,no_format_categories=true,nocat=true,text_classes=data.text_classes,})ins("<span class='"..text_classes.."'>")endend-- FIXME, should posttext go before enclitics? If so we need to have separate handling for the-- final colon when there are multiple tag sets in tagged_inflections().ifdata.posttextthenins(data.posttext)endins("</span>")returntable.concat(parts)endfunctionexport.is_link_or_html(tag)returntag:find("[[",nil,true)ortag:find("|",nil,true)ortag:find("<",nil,true)end-- Look up a tag (either a shortcut of any sort of a canonical long-form tag) and return its expansion. The expansion-- will be a string unless the shortcut is a list-tag shortcut such as "1s"; in that case, the expansion will be a-- list. The caller must handle both cases. Only one level of expansion happens; hence, "acc" expands to "accusative",-- "1s" expands to {"1", "s"} (not to {"first", "singular"}) and "123" expands to "1//2//3". The expansion will be the-- same as the passed-in tag in the following circumstances:---- 1. The tag is ";" (this is special-cased, and no lookup is done).-- 2. The tag is a multipart tag such as "nom//acc" (this is special-cased, and no lookup is done).-- 3. The tag contains a raw link (this is special-cased, and no lookup is done).-- 4. The tag contains HTML (this is special-cased, and no lookup is done).-- 5. The tag is already a canonical long-form tag.-- 6. The tag is unrecognized.---- This function first looks up in the lang-specific data module [[Module:form of/lang-data/LANGCODE]], then in-- [[Module:form of/data]] (which includes more common non-lang-specific tags) and finally (only if the tag is not-- recognized as a shortcut or canonical tag, and is not of types 1-4 above) in [[Module:form of/data2]].---- If the expansion is a string and is different from the tag, track it if DO_TRACK is true.functionexport.lookup_shortcut(tag,lang,do_track)-- If there is HTML or a link in the tag, return it directly; don't try-- to look it up, which will fail.iftag==";"ortag:find("//",nil,true)orexport.is_link_or_html(tag)thenreturntagendlocalexpansionlocallangcode=langandlang:getCode()iflangcodeandexport.langs_with_lang_specific_tags[langcode]thenlocallangdata=mw.loadData(export.form_of_lang_data_module_prefix..langcode)-- If this is a canonical long-form tag, just return it, and don't check for shortcuts. This is an-- optimization; see below.iflangdata.tags[tag]thenreturntagendexpansion=langdata.shortcuts[tag]endifnotexpansionthenlocalm_data=mw.loadData(export.form_of_data_module)-- If this is a canonical long-form tag, just return it, and don't check for shortcuts (which will cause-- [[Module:form of/data2]] to be loaded, because there won't be a shortcut entry in [[Module:form of/data]] ---- or, for that matter, in [[Module:form of/data2]]). This is an optimization; the code will still work without-- it, but will use up more memory.ifm_data.tags[tag]thenreturntagendexpansion=m_data.shortcuts[tag]endifnotexpansionthenlocalm_data2=mw.loadData(export.form_of_data2_module)expansion=m_data2.shortcuts[tag]endifnotexpansionthenreturntagend-- Maybe track the expansion if it's not the same as the raw tag.ifdo_trackandexpansion~=tagandtype(expansion)=="string"thentrack("tag/"..tag)endreturnexpansionend-- Look up a normalized/canonicalized tag and return the data object associated with it. If the tag isn't found, return-- nil. This first looks up in the lang-specific data module [[Module:form of/lang-data/LANGCODE]], then in-- [[Module:form of/data]] (which includes more common non-lang-specific tags) and then finally in-- [[Module:form of/data2]].functionexport.lookup_tag(tag,lang)locallangcode=langandlang:getCode()iflangcodeandexport.langs_with_lang_specific_tags[langcode]thenlocallangdata=mw.loadData(export.form_of_lang_data_module_prefix..langcode)iflangdata.tags[tag]thenreturnlangdata.tags[tag]endendlocalm_data=mw.loadData(export.form_of_data_module)localtagobj=m_data.tags[tag]iftagobjthenreturntagobjendlocalm_data2=mw.loadData(export.form_of_data2_module)localtagobj2=m_data2.tags[tag]iftagobj2thenreturntagobj2endreturnnilend-- Normalize a single tag, which may be a shortcut but should not be a multipart tag, a multipart shortcut or a list-- shortcut.localfunctionnormalize_single_tag(tag,lang,do_track)localexpansion=export.lookup_shortcut(tag,lang,do_track)iftype(expansion)~="string"thenerror("Tag '"..tag.."' is a list shortcut, which is not allowed here")endtag=expansionifnotexport.lookup_tag(tag,lang)anddo_trackthen-- If after all expansions and normalizations we don't recognize the canonical tag, track it.track("unknown")track("unknown/"..tag)endreturntagend--[=[Normalize a component of a multipart tag. This should not have any // in it, but may join multiple individual tags witha colon, and may be a single list-tag shortcut, which is treated as if colon-separated. The return value may be a listof tags.]=]localfunctionnormalize_multipart_component(tag,lang,do_track)-- If there is HTML or a link in the tag, don't try to split on colon. A colon may legitimately occur in either one,-- and we don't want these things parsed. Note that we don't do this check before splitting on //, which we don't-- expect to occur in links or HTML; see comment in normalize_tag().ifexport.is_link_or_html(tag)thenreturntagendlocalcomponents=rsplit(tag,":",true)if#components==1then-- We allow list-tag shortcuts inside of multipart tags, e.g.-- '1s//3p'. Check for this now.tag=export.lookup_shortcut(tag,lang,do_track)iftype(tag)=="table"then-- Temporary tracking as we will disallow this.track("list-tag-inside-of-multipart")-- We found a list-tag shortcut; treat as if colon-separated.components=tagelsereturnnormalize_single_tag(tag,lang,do_track)endendlocalnormtags={}-- Temporary tracking as we will disallow this.track("two-level-multipart")for_,componentinipairs(components)doifdo_trackthen-- There are multiple components; track each of the individual-- raw tags.track("tag/"..component)endtable.insert(normtags,normalize_single_tag(component,lang,do_track))endreturnnormtagsend--[=[Normalize a single tag. The return value may be a list (in the case of multipart tags), which will contain nested listsin the case of two-level multipart tags.]=]localfunctionnormalize_tag(tag,lang,do_track)-- We don't check for links or HTML before splitting on //, which we don't expect to occur in links or HTML. Doing-- it this way allows for a tag like '{{lb|grc|Epic}}//{{lb|grc|Ionic}}' to function correctly (the template calls-- will be expanded before we process the tag, and will contain links and HTML). The only check we do is for a URL,-- which shouldn't normally occur, but might if the user tries to put an external link into the tag. URL's with //-- normally have the sequence ://, which should never normally occur when // and : are used in their normal ways.iftag:find("://",nil,true)thenreturntagendlocalsplit_tags=rsplit(tag,"//",true)if#split_tags==1thenlocalretval=normalize_multipart_component(tag,lang,do_track)iftype(retval)=="table"then-- The user gave a tag like '1:s', i.e. with colon but without //. Allow this, but we need to return a-- nested list.return{retval}endreturnretvalendlocalnormtags={}for_,single_taginipairs(split_tags)doifdo_trackthen-- If the tag was a multipart tag, track each of individual raw tags.track("tag/"..single_tag)endtable.insert(normtags,normalize_multipart_component(single_tag,lang,do_track))endreturnnormtagsend--[=[Normalize a tag set (a list of tags) into its canonical-form tags. The return value is a list of normalized tag sets(a list because of there may be conjoined shortcuts among the input tags). A normalized tag set is a list of tagelements, where each element is either a string (the canonical form of a tag), a list of such strings (in the case ofmultipart tags) or a list of lists of such strings (in the case of two-level multipart tags). For example, the multiparttag "nom//acc//voc" will be represented in canonical form as {"nominative", "accusative", "vocative"}, and thetwo-level multipart tag "1:s//3:p" will be represented as {{"first-person", "singular"}, {"third-person", "plural"}}.Example 1:normalize_tag_set({"nom//acc//voc", "n", "p"}) = {{{"nominative", "accusative", "vocative"}, "masculine", "plural"}}Example 2:normalize_tag_set({"ed-form"}, ENGLISH) = {{"simple", "past"}, {"past", "participle"}}Example 3:normalize_tag_set({"archaic", "ed-form"}, ENGLISH) = {{"archaic", "simple", "past"}, {"archaic", "past", "participle"}}]=]functionexport.normalize_tag_set(tag_set,lang,do_track)-- We track usage of shortcuts, normalized forms and (in the case of multipart tags or list tags) intermediate-- forms. For example, if the tags 1s|mn|gen|indefinite are passed in, we track the following:-- [[Template:tracking/inflection of/tag/1s]]-- [[Template:tracking/inflection of/tag/1]]-- [[Template:tracking/inflection of/tag/s]]-- [[Template:tracking/inflection of/tag/first-person]]-- [[Template:tracking/inflection of/tag/singular]]-- [[Template:tracking/inflection of/tag/mn]]-- [[Template:tracking/inflection of/tag/m//n]]-- [[Template:tracking/inflection of/tag/m]]-- [[Template:tracking/inflection of/tag/n]]-- [[Template:tracking/inflection of/tag/masculine]]-- [[Template:tracking/inflection of/tag/neuter]]-- [[Template:tracking/inflection of/tag/gen]]-- [[Template:tracking/inflection of/tag/genitive]]-- [[Template:tracking/inflection of/tag/indefinite]]localoutput_tag_set={}localsaw_semicolon=falsefor_,taginipairs(tag_set)doifdo_trackthen-- Track the raw tag.track("tag/"..tag)end-- Expand the tag, which may generate a new tag (either a fully canonicalized tag, a multipart tag, or a list-- of tags).tag=export.lookup_shortcut(tag,lang,do_track)iftype(tag)=="table"thensaw_semicolon=m_table.contains(tag,";")ifsaw_semicolonthen-- If we saw a conjoined shortcut, we need to use a more general algorithm that can expand a single-- tag set into multiple.breakendfor_,tinipairs(tag)doifdo_trackthen-- If the tag expands to a list of raw tags, track each of those.track("tag/"..t)endtable.insert(output_tag_set,normalize_tag(t,lang,do_track))endelsetable.insert(output_tag_set,normalize_tag(tag,lang,do_track))endendifnotsaw_semicolonthenreturn{output_tag_set}end-- Use a more general algorithm that handles conjoined shortcuts.localoutput_tag_set={}fori,taginipairs(tag_set)doifdo_trackthen-- Track the raw tag.track("tag/"..tag)end-- Expand the tag, which may generate a new tag (either a fully canonicalized tag, a multipart tag, or a list-- of tags).tag=export.lookup_shortcut(tag,lang,do_track)iftype(tag)=="table"thenlocaloutput_tag_sets={}localshortcut_tag_sets=export.split_tag_set(tag)localnormalized_shortcut_tag_sets={}for_,shortcut_tag_setinipairs(shortcut_tag_sets)dom_table.extendList(normalized_shortcut_tag_sets,export.normalize_tag_set(shortcut_tag_set,lang,do_track))endlocalafter_tags=slice(tag_set,i+1)localnormalized_after_tags_sets=export.normalize_tag_set(after_tags,lang,do_track)for_,normalized_shortcut_tag_setinipairs(normalized_shortcut_tag_sets)dofor_,normalized_after_tags_setinipairs(normalized_after_tags_sets)dotable.insert(output_tag_sets,m_table.append(output_tag_set,normalized_shortcut_tag_set,normalized_after_tags_set))endendreturnoutput_tag_setselsetable.insert(output_tag_set,normalize_tag(tag,lang,do_track))endenderror("Internal error: Should not get here")endfunctionexport.combine_multipart_tags(tag_set)fori,taginipairs(tag_set)doiftype(tag)=="table"thenforj,subtaginipairs(tag)doiftype(subtag)=="table"thentag[j]=table.concat(subtag,":")endendtag_set[i]=table.concat(tag,"//")endendreturntag_setendfunctionexport.normalize_tags(tags,lang,recombine_multitags,do_track)localtag_sets=export.normalize_tag_set(tags,lang,do_track)ifrecombine_multitagsthenfori,tag_setinipairs(tag_sets)dotag_sets[i]=export.combine_multipart_tags(tag_set)endreturnexport.combine_tag_sets(tag_sets)endreturntag_setsend-- Split a tag set containing two-level multipart tags into one or more tag sets not containing such tags.-- Single-level multipart tags are left alone. (If we need to, a slight modification of the following code-- will also split single-level multipart tags.) This assumes that multipart tags are represented as lists-- and two-level multipart tags are represented as lists of lists, as is output by normalize_tag_set().-- NOTE: We have to be careful to properly handle imbalanced two-level multipart tags such as-- <code>def:s//p</code> (or the reverse, <code>s//def:p</code>).functionexport.split_two_level_multipart_tag_set(tag_set)fori,taginipairs(tag_set)doiftype(tag)=="table"then-- We saw a multipart tag. Check if any of the parts are two-level.localsaw_two_level_tag=falsefor_,first_level_taginipairs(tag)doiftype(first_level_tag)=="table"thensaw_two_level_tag=truebreakendendifsaw_two_level_tagthen-- We found a two-level multipart tag.-- (1) Extract the preceding tags.localpre_tags=slice(tag_set,1,i-1)-- (2) Extract the following tags.localpost_tags=slice(tag_set,i+1)-- (3) Loop over each tag set alternant in the two-level multipart tag.-- For each alternant, form the tag set consisting of pre_tags + alternant + post_tags,-- and recursively split that tag set.localresulting_tag_sets={}for_,first_level_tag_setinipairs(tag)dolocalexpanded_tag_set={}m_table.extendList(expanded_tag_set,pre_tags)-- The second level may have a string or a list.iftype(first_level_tag_set)=="table"thenm_table.extendList(expanded_tag_set,first_level_tag_set)elsetable.insert(expanded_tag_set,first_level_tag_set)endm_table.extendList(expanded_tag_set,post_tags)m_table.extendList(resulting_tag_sets,export.split_two_level_multipart_tag_set(expanded_tag_set))endreturnresulting_tag_setsendendendreturn{tag_set}end-- Split a tag set that may consist of multiple semicolon-separated tag sets into the component tag sets.functionexport.split_tag_set(tag_set)localsplit_tag_sets={}localcur_tag_set={}for_,taginipairs(tag_set)doiftag==";"thenif#cur_tag_set>0thentable.insert(split_tag_sets,cur_tag_set)endcur_tag_set={}elsetable.insert(cur_tag_set,tag)endendif#cur_tag_set>0thentable.insert(split_tag_sets,cur_tag_set)endreturnsplit_tag_setsendexport.split_tags_into_tag_sets=export.split_tag_set--[=[-- Combine multiple tag sets in a tag set group into a simple tag set, with logical tag sets separated by semicolons.-- This is the opposite of split_tag_set().]=]functionexport.combine_tag_sets(tag_sets)if#tag_sets==1thenreturntag_sets[1]endlocalcombined_tag_set={}for_,tag_setinipairs(tag_sets)doif#combined_tag_set>0thentable.insert(combined_tag_set,";")endm_table.extendList(combined_tag_set,tag_set)endreturntagsendlocaltag_set_param_mods={lb={item_dest="labels",convert=function(arg,parse_err)returnrsplit(arg,"//")end,}}-- Parse tag set properties from a tag set (list of tags). Currently no per-tag properties are recognized, and the only-- per-tag-set property recognized is <lb:...> for specifing label(s) for the tag set. Per-tag-set properties must be-- attached to the last tag.functionexport.parse_tag_set_properties(tag_set)localfunctiongenerate_tag_set_obj(last_tag)tag_set[#tag_set]=last_tagreturn{tags=tag_set}endlocallast_tag=tag_set[#tag_set]-- Check for inline modifier, e.g. מרים<tr:Miryem>. But exclude HTML entry with <span ...>, <i ...>, <br/> or-- similar in it, caused by wrapping an argument in {{l|...}}, {{af|...}} or similar. Basically, all tags of-- the sort we parse here should consist of a less-than sign, plus letters, plus a colon, e.g. <lb:...>, so if-- we see a tag on the outer level that isn't in this format, we don't try to parse it. The restriction to the-- outer level is to allow generated HTML inside of e.g. qualifier tags, such as foo<q:similar to {{m|fr|bar}}>.iflast_tag:find("<")andnotlast_tag:find("^[^<]*<[a-z]*[^a-z:]")thenreturnrequire(put_module).parse_inline_modifiers(last_tag,{param_mods=tag_set_param_mods,generate_obj=generate_tag_set_obj,})elsereturngenerate_tag_set_obj(last_tag)endendfunctionexport.normalize_pos(pos)ifnotposthenreturnnilendreturnmw.loadData(export.form_of_pos_module)[pos]orposend-- Return the display form of a single canonical-form tag. The value-- passed in must be a string (i.e. it cannot be a list describing a-- multipart tag). To handle multipart tags, use get_tag_display_form().localfunctionget_single_tag_display_form(normtag,lang)localdata=export.lookup_tag(normtag,lang)-- If the tag has a special display form, use itifdataanddata.displaythennormtag=data.displayend-- If there is a nonempty glossary index, then show a link to itifdataanddata.glossarythenifdata.glossary_type=="wikt"thennormtag="[["..data.glossary.."|"..normtag.."]]"elseifdata.glossary_type=="wp"thennormtag="[[w:"..data.glossary.."|"..normtag.."]]"elsenormtag="[[Appendix:Glossary#"..mw.uri.anchorEncode(data.glossary).."|"..normtag.."]]"endendreturnnormtagend--[=[Turn a canonicalized tag spec (which describes a single, possibly multipart tag) into the displayed form. The tag specmay be a string (a canonical-form tag); a list of canonical-form tags (in the case of a simple multipart tag); or alist of mixed canonical-form tags and lists of such tags (in the case of a two-level multipart tag). `joiner` indicateshow to join the parts of a multipart tag, and can be either "and" ("foo and bar", or "foo, bar and -- baz" for 3 ormore), "slash" ("foo/bar"), "en-dash" ("foo–bar") or nil, which uses the global default found inmultipart_join_strategy() in [[Module:form of/functions]]. (NOTE: The global default is "slash" and this seems unlikelyto change.)]=]functionexport.get_tag_display_form(tagspec,lang,joiner)iftype(tagspec)=="string"thenreturnget_single_tag_display_form(tagspec,lang)end-- We have a multipart tag. See if there's a display handler to display them specially.for_,handlerinipairs(require(export.form_of_functions_module).display_handlers)dolocaldisplayval=handler(tagspec,joiner)ifdisplayvalthenreturndisplayvalendend-- No display handler.localdisplayed_tags={}for_,first_level_taginipairs(tagspec)doiftype(first_level_tag)=="string"thentable.insert(displayed_tags,get_single_tag_display_form(first_level_tag,lang))else-- A first-level element of a two-level multipart tag. Currently we just separate the individual components-- with spaces, but other ways are possible, e.g. using an underscore, colon, parens or braces.localcomponents={}for_,componentinipairs(first_level_tag)dotable.insert(components,get_single_tag_display_form(component,lang))endtable.insert(displayed_tags,table.concat(components," "))endendreturnrequire(export.form_of_functions_module).join_multiparts(displayed_tags,joiner)end--[=[Given a normalized tag set (i.e. as output by normalize_tag_set(); all tags are in canonical form, multipart tags arerepresented as lists, and two-level multipart tags as lists of lists), convert to displayed form (a string). Seeget_tag_display_form() for the meaning of `joiner`.]=]functionexport.get_tag_set_display_form(normalized_tag_set,lang,joiner)localparts={}for_,tagspecinipairs(normalized_tag_set)dolocalto_insert=export.get_tag_display_form(tagspec,lang,joiner)-- Maybe insert a space before inserting the display form of the tag. We insert a space if-- (a) we're not the first tag; and-- (b) the tag we're about to insert doesn't have the "no_space_on_left" property; and-- (c) the preceding tag doesn't have the "no_space_on_right" property.-- NOTE: We depend here on the fact that-- (1) all tags with either of the above properties set have the same display form as canonical form, and-- (2) all tags with either of the above properties set are single-character tags.-- The second property is an optimization to avoid looking up display forms resulting from multipart tags,-- which won't be found and which will trigger loading of [[Module:form of/data2]]. If multichar punctuation is-- added in the future, it's ok to change the == 1 below to <= 2 or <= 3.---- If the first property above fails to hold in the future, we need to track the canonical form of each tag-- (including the previous one) as well as the display form. This would also avoid the need for the == 1 check.if#parts>0thenlocalmost_recent_tagobj=ulen(parts[#parts])==1andexport.lookup_tag(parts[#parts],lang)localto_insert_tagobj=ulen(to_insert)==1andexport.lookup_tag(to_insert,lang)if((notmost_recent_tagobjornotmost_recent_tagobj.no_space_on_right)and(notto_insert_tagobjornotto_insert_tagobj.no_space_on_left))thentable.insert(parts," ")endendtable.insert(parts,to_insert)endreturntable.concat(parts)end--[=[Given a normalized tag set (i.e. as output by normalize_tag_set(); all tags are in canonical form, multipart tags arerepresented as lists, and two-level multipart tags as lists of lists), fetch the associated categories and labels.Return two values, a list of categories and a list of labels. `lang` is the language of term represented by the tag set,and `POS` is the user-provided part of speech (which may be nil).]=]functionexport.fetch_categories_and_labels(normalized_tag_set,lang,POS,pagename,lemmas)localm_cats=mw.loadData(export.form_of_cats_module)localcategories={}locallabels={}POS=export.normalize_pos(POS)-- First split any two-level multipart tags into multiple sets, to make our life easier.for_,tag_setinipairs(export.split_two_level_multipart_tag_set(normalized_tag_set))do-- Call a named function, either from the lang-specific data in [[Module:form of/lang-specific/LANGCODE]] or-- in [[Module:form of/cats]].localfunctioncall_named_function(name,funtype)localdata={pagename=pagenameormw.title.getCurrentTitle().subpageText,lemmas=lemmas,tag_set=normalized_tag_set,lang=lang,POS=POS}-- First try lang-specific.locallangcode=langandlang:getCode()locallang_specific_moduleiflangcodeandexport.langs_with_lang_specific_tags[langcode]thenlang_specific_module=export.form_of_lang_data_module_prefix..langcode.."/functions"locallangdata=require(lang_specific_module)iflangdata.cat_functionsthenlocalfn=langdata.cat_functions[name]iffnthenreturnfn(data)endendendlocalfn=require(export.form_of_functions_module).cat_functions[name]iffnthenreturnfn(data)endlocallang_specific_partiflang_specific_modulethenlang_specific_part=("[[%s]] or "):format(lang_specific_module)elselang_specific_part=""enderror(("No %s function named '%s' in %s[[%s]]"):format(funtype,name,lang_specific_part,export.form_of_functions_module))end-- Given a tag from the current tag set (which may be a list in case of a multipart tag),-- and a tag from a categorization spec, check that the two match.-- (1) If both are strings, we just check for equality.-- (2) If the spec tag is a string and the tag set tag is a list (i.e. it originates from a-- multipart tag), we check that the spec tag is in the list. This is because we want to treat-- multipart tags in user-specified tag sets as if the user had specified multiple tag sets.-- For example, if the user said "1//3|s|pres|ind" and the categorization spec says {"has", "1"},-- we want this to match, because "1//3|s|pres|ind" should be treated equivalently to two tag-- sets "1|s|pres|ind" and "3|s|pres|ind", and the former matches the categorization spec.-- (3) If the spec tag is a list (i.e. it originates from a multipart tag), we check that the-- tag set tag is also a list and is a superset of the spec tag. For example, if the categorization-- spec says {"has", "1//3"}, then the tag set tag must be a multipart tag that has both "1" and "3"-- in it. "1//3" works, as does "1//2//3".localfunctiontag_set_tag_matches_spec_tag(tag_set_tag,spec_tag)iftype(spec_tag)=="table"theniftype(tag_set_tag)=="table"andis_subset(spec_tag,tag_set_tag)thenreturntrueendelseiftype(tag_set_tag)=="table"thenifm_table.contains(tag_set_tag,spec_tag)thenreturntrueendelseiftag_set_tag==spec_tagthenreturntrueendreturnfalseend-- Check that the current tag set matches the given spec tag. This means that any of the tags-- in the current tag set match, according to tag_set_tag_matches_spec_tag(); see above. If the-- current tag set contains only string tags (i.e. no multipart tags), and the spec tag is a-- string (i.e. not a multipart tag), this boils down to list containment, but it gets more-- complex when multipart tags are present.localfunctiontag_set_matches_spec_tag(spec_tag)spec_tag=normalize_tag(spec_tag,lang)for_,tag_set_taginipairs(tag_set)doiftag_set_tag_matches_spec_tag(tag_set_tag,spec_tag)thenreturntrueendendreturnfalseend-- Check whether the given spec matches the current tag set. Two values are returned:-- (1) whether the spec matches the tag set; (2) the index of the category to add if-- the spec matches.localfunctioncheck_condition(spec)iftype(spec)=="boolean"thenreturnspecelseiftype(spec)~="table"thenerror("Wrong type of condition "..spec..": "..type(spec))endlocalpredicate=spec[1]ifpredicate=="has"thenreturntag_set_matches_spec_tag(spec[2]),3elseifpredicate=="hasall"thenfor_,taginipairs(spec[2])doifnottag_set_matches_spec_tag(tag)thenreturnfalse,3endendreturntrue,3elseifpredicate=="hasany"thenfor_,taginipairs(spec[2])doiftag_set_matches_spec_tag(tag)thenreturntrue,3endendreturnfalse,3elseifpredicate=="tags="thenlocalnormalized_spec_tag_sets=export.normalize_tag_set(spec[2],lang)if#normalized_spec_tag_sets>1thenerror("Internal error: No support for conjoined shortcuts in category/label specs in ".."[[Module:form of/cats]] when processing spec tag set "..table.concat(spec[2],"|"))endlocalnormalized_spec_tag_set=normalized_spec_tag_sets[1]-- Check for and disallow two-level multipart tags in the specs. FIXME: Remove this when we remove-- support for two-level multipart tags.for_,taginipairs(normalized_spec_tag_set)doiftype(tag)=="table"thenfor_,subtaginipairs(tag)doiftype(subtag)=="table"thenerror("Internal error: No support for two-level multipart tags in category/label specs".."[[Module:form of/cats]] when processing spec tag set "..table.concat(spec[2],"|"))endendendend-- Allow tags to be in different orders, and multipart tags to be in different orders. To handle this,-- we first check that both tag set tags and spec tags have the same length. If so, we sort the-- multipart tags in the tag set tags and spec tags, and then check that all tags in the spec tags are-- in the tag set tags.if#tag_set~=#normalized_spec_tag_setthenreturnfalse,3endlocaltag_set_tags=m_table.deepcopy(tag_set)fori=1,#tag_set_tagsdoiftype(tag_set_tags[i])=="table"thentable.sort(tag_set_tags[i])endiftype(normalized_spec_tag_set[i])=="table"thentable.sort(normalized_spec_tag_set[i])endendfori=1,#tag_set_tagsdoifnotm_table.contains(tag_set_tags,normalized_spec_tag_set[i])thenreturnfalse,3endendreturntrue,3elseifpredicate=="p="thenreturnPOS==export.normalize_pos(spec[2]),3elseifpredicate=="pany"thenfor_,specposinipairs(spec[2])doifPOS==export.normalize_pos(specpos)thenreturntrue,3endendreturnfalse,3elseifpredicate=="pexists"thenreturnPOS~=nil,2elseifpredicate=="not"thenlocalcondval=check_condition(spec[2])returnnotcondval,3elseifpredicate=="and"thenlocalcondval=check_condition(spec[2])ifcondvalthencondval=check_condition(spec[3])endreturncondval,4elseifpredicate=="or"thenlocalcondval=check_condition(spec[2])ifnotcondvalthencondval=check_condition(spec[3])endreturncondval,4elseifpredicate=="call"thenreturnfn(call_named_function(spec[2],"condition")),3elseerror("Unrecognized predicate: "..predicate)endend-- Process a given spec. This checks any conditions in the spec against the-- tag set, and insert any resulting categories into `categories`. Return value-- is true if the outermost condition evaluated to true and a category was inserted-- (this is used in {"cond" ...} conditions, which stop when a subcondition evaluates-- to true).localfunctionprocess_spec(spec)ifnotspecthenreturnfalseelseiftype(spec)=="string"then-- A category. Substitute POS request with user-specified part of speech or default.spec=rsub(spec,"<<p=(.-)>>",function(default)returnPOSorexport.normalize_pos(default)end)table.insert(categories,lang:getCanonicalName().." "..spec)returntrueelseiftype(spec)=="table"andspec.labelsthen-- A label spec.for_,labelinipairs(spec.labels)dom_table.insertIfNot(labels,label)endreturntrueelseiftype(spec)~="table"thenerror("Wrong type of specification "..spec..": "..type(spec))endlocalpredicate=spec[1]ifpredicate=="multi"then-- WARNING! #spec doesn't work for objects loaded from loadData()fori,spinipairs(spec)doifi>1thenprocess_spec(sp)endendreturntrueelseifpredicate=="cond"then-- WARNING! #spec doesn't work for objects loaded from loadData()fori,spinipairs(spec)doifi>1andprocess_spec(sp)thenreturntrueendendreturnfalseelseifpredicate=="call"thenreturnprocess_spec(call_named_function(spec[2],"spec"))elselocalcondval,ifspec=check_condition(spec)ifcondvalthenprocess_spec(spec[ifspec])returntrueelseprocess_spec(spec[ifspec+1])-- FIXME: Are we sure this is correct?returnfalseendendendlocallangspecs=m_cats[lang:getCode()]iflangspecsthenfor_,specinipairs(langspecs)doprocess_spec(spec)endendiflang:getCode()~="und"thenlocallangspecs=m_cats["und"]iflangspecsthenfor_,specinipairs(langspecs)doprocess_spec(spec)endendendendreturncategories,labelsend--[=[Implementation of templates that display inflection tags, such as the general {{inflection of}}, semi-specific variantssuch as {{participle of}}, and specific variants such as {{past participle of}}. `data` contains all the informationcontrolling the display, with the following fields:`.lang`: (REQUIRED) Language to use when looking up language-specific inflection tags, categories and labels, and for displaying categories and labels.`.tags`: (REQUIRED UNLESS `.tag_sets` IS GIVEN) List of non-canonicalized inflection tags. Multiple tag sets can be indicated by a ";" as one of the tags, and tag-set properties may be attached to the last tag of a tag set. The tags themselves may come directly from the user (as in {{inflection of}}); come partly from the user (as in {{participle of}}, which adds the tag 'part' to user-specified inflection tags); or be entirely specified by the template (as in {{past participle of}}).`.tag_sets`: (REQUIRED UNLESS `.tags` IS GIVEN) List of non-canonicalized tag sets and associated per-tag-set properties. Each element of the list is an object of the form {tags = {"TAG", "TAG", ...}, labels = {"LABEL", "LABEL", ...}}. If `.tag_sets` is specified, `.tags` should not be given and vice-versa.`.lemmas`: (RECOMMENDED) List of objects describing the lemma(s) of which the term in question is a non-lemma form. These are passed directly to full_link() in [[Module:links]]. Each object should have at minimum a `.lang` field containing the language of the lemma and a `.term` field containing the lemma itself. Each object is formatted using full_link() and then if there are more than one, they are joined using serialCommaJoin() in [[Module:table]]. Alternatively, `.lemmas` can be a string, which is displayed directly. If omitted entirely, no lemma links are shown and the connecting "of" is also omitted.`.lemma_face`: (RECOMMENDED) "Face" to use when displaying the lemma objects. Usually should be set to "term".`.POS`: (RECOMMENDED) Categorizing part-of-speech tag. Comes from the p= or POS= argument of {{inflection of}}.`.pagename`: Page name of "current" page or nil to use the actual page title; for testing purposes.`.enclitics`: List of enclitics to display after the lemmas, in parens.`.no_format_categories`: If true, don't format the categories derived from the inflection tags; just return them.`.sort`: Sort key for formatted categories. Ignored when .no_format_categories = true.`.nocat`: Suppress computation of categories (even if `.no_format_categories` is not given).`.notext`: Disable display of all tag text and "inflection of" text. (FIXME: Maybe not implemented correctly.)`.capfirst`: Capitalize the first word displayed.`.pretext`: Additional text to display before the inflection tags, but after any top-level labels.`.posttext`: Additional text to display after the lemma links.`.text_classes`: CSS classes used to wrap the tag text and lemma links. Default is "form-of-definition use-with-mention" for the tag text, "form-of-definition-link" for the lemma links. (FIXME: Should separate out the lemma links into their own field.)`.joiner`: Override the joiner (normally a slash) used to join multipart tags. You should normally not specify this.A typical call might look like this (for Spanish [[amo]]):local lang = require("Module:languages").getByCode("es")local lemma_obj = {lang = lang,term = "amar",}return m_form_of.tagged_inflections({lang = lang, tags = {"1", "s", "pres", "ind"}, lemmas = {lemma_obj}, lemma_face = "term", POS = "verb"})Normally, one value is returned, the formatted text, which has appended to it the formatted categories derived from thetag-set-related categories generated by the specs in [Module:form of/cats]]. To suppress this, setdata.no_format_categories = true, in which case two values are returned, the formatted text without any formattedcategories appended and a list of the categories to be formatted.NOTE: There are two sets of categories that may be generated: (1) categories derived directly from the tag sets, asspecified in [[Module:form of/cats]]; (2) categories derived from tag-set labels, either (a) set explicitly by thecaller in data.tag_sets, (b) specified by the user using <lb:...> attached to the last tag in a tag set, or(c) specified in [[Module:form of/cats]]. The second type (label-related categories) are currently not returned inthe second return value of tagged_inflections(), and are currently inserted into the output text even ifdata.no_format_categories is set to true; but they can be suppressed by setting data.nocat = true (which alsosuppresses the first type of categories, those derived directly from tag sets, even if data.no_format_categories is setto true).]=]functionexport.tagged_inflections(data)ifnotdata.tagsandnotdata.tag_setsthenerror("First argument must be a table of arguments, and `.tags` or `.tag_sets` must be specified")endifdata.tagsanddata.tag_setsthenerror("Both `.tags` and `.tag_sets` cannot be specified")endlocaltag_sets=data.tag_setsifnottag_setsthentag_sets=export.split_tag_set(data.tags)fori,tag_setinipairs(tag_sets)dotag_sets[i]=export.parse_tag_set_properties(tag_set)endendlocalinflections={}localcategories={}for_,tag_setinipairs(tag_sets)dolocalnormalized_tag_sets=export.normalize_tag_set(tag_set.tags,data.lang,"do-track")for_,normalized_tag_setinipairs(normalized_tag_sets)dolocalcur_infl={}localthis_categories,this_labels=export.fetch_categories_and_labels(normalized_tag_set,data.lang,data.POS,data.pagename,type(data.lemmas)=="table"anddata.lemmasornil)ifnotdata.nocatthenm_table.extendList(categories,this_categories)endlocalcur_infl=export.get_tag_set_display_form(normalized_tag_set,data.lang,data.joiner)if#cur_infl>0theniftag_set.labelsthenthis_labels=m_table.append(tag_set.labels,this_labels)endtable.insert(inflections,{infl_text=cur_infl,labels=this_labels})endendendlocaloverall_labels,need_per_tag_set_labelsfor_,inflectioninipairs(inflections)doifoverall_labels==nilthenoverall_labels=inflection.labelselseifnotm_table.deepEquals(overall_labels,inflection.labels)thenneed_per_tag_set_labels=trueoverall_labels=nilbreakendendifnotneed_per_tag_set_labelsthenfor_,inflectioninipairs(inflections)doinflection.labels=nilendendlocalformat_data=m_table.shallowcopy(data)localfunctionformat_labels(labels,notext)iflabelsand#labels>0thenreturnrequire(labels_module).show_labels{labels=labels,lang=data.lang,sort=data.sort,nocat=data.nocat}..(notextand(data.pretextor"")==""and""or" ")elsereturn""endendlocalof_text=data.lemmasand" of"or""localformatted_textif#inflections==1thenifneed_per_tag_set_labelsthenerror("Internal error: need_per_tag_set_labels should not be set with one inflection")endformat_data.text=format_labels(overall_labels,data.notext)..(data.pretextor"")..(data.notextand""or((data.capfirstandrequire("Module:string utilities").ucfirst(inflections[1].infl_text)orinflections[1].infl_text)..of_text))formatted_text=export.format_form_of(format_data)elseformat_data.text=format_labels(overall_labels,data.notext)..(data.pretextor"")..(data.notextand""or((data.capfirstand"Inflection"or"inflection")..of_text))format_data.posttext=(data.posttextor"")..":"locallink=export.format_form_of(format_data)localtext_classes=data.text_classesor"form-of-definition use-with-mention"fori,inflectioninipairs(inflections)doinflections[i]="\n## "..format_labels(inflection.labels,false).."<span class='"..text_classes.."'>"..inflection.infl_text.."</span>"endformatted_text=link..table.concat(inflections)endifnotdata.no_format_categoriesthenif#categories>0thenformatted_text=formatted_text..require("Module:utilities").format_categories(categories,data.lang,data.sort,nil,force_cat)endreturnformatted_textendreturnformatted_text,categoriesend-- Given a tag set, return a flattened list all Wikidata ID's of all tags in the tag set.-- FIXME: Only used in a debugging function in [[Module:se-verbs]]; move there.functionexport.to_Wikidata_IDs(tag_set,lang,skip_tags_without_ids)localret={}localfunctionget_wikidata_id(tag)localdata=export.lookup_tag(tag,lang)ifnotdataornotdata.wikidatathenifnotskip_tags_without_idsthenerror('The tag "'..tag..'" does not have a Wikidata ID defined in the form-of data modules')elsereturnnilendelsereturndata.wikidataendendlocalnormalized_tag_sets=export.normalize_tag_set(tag_set,lang)for_,tag_setinipairs(normalized_tag_sets)dofor_,taginipairs(tag_set)doiftype(tag)=="table"thenfor_,subtaginipairs(tag)doiftype(subtag)=="table"then-- two-level multipart tag; FIXME: delete support for thisfor_,subsubtaginipairs(subtag)dotable.insert(ret,get_wikidata_id(subsubtag))endelsetable.insert(ret,get_wikidata_id(subtag))endendelsetable.insert(ret,get_wikidata_id(tag))endendendreturnretendfunctionexport.dump_form_of_data(frame)localdata={data=require(export.form_of_data_module),data2=require(export.form_of_data2_module)}returnrequire("Module:JSON").toJSON(data)endreturnexport