if statement.mainsnak and statement.mainsnak.datatype == 'quantity' then
local value = (statement.mainsnak.datavalue or {}).value
if value then
local amount = value.amount
if amount then
amount = tostring(amount) -- in case amount is ever a number
if amount:sub(1, 1) == '+' then
amount = amount:sub(2)
end
local unit = value.unit
if type(unit) == 'string' then
unit = unit:match('Q%d+$') -- unit item id is at end of URL
local ucode = make_unit(tdata.wikidata_units, parms, unit)
if ucode then
local skip
if t.statqual then
if done[t.statqual] then
skip = true
else
done[t.statqual] = true
end
else
if statement.rank == 'preferred' then
skip_normal = true
elseif skip_normal then
skip = true
end
end
if not skip then
result:add({ amount, ucode })
end
end
end
end
end
end
end
return result
end  
local function input_from_text(tdata, parms, text, insert2)
-- Given string should be of form "<value><space><unit>" or
-- "<value1><space>ft<space><value2><space>in" for a special case (feet and inches).
-- Return true if values/units were extracted and inserted, or return nothing.
text = text:gsub('&nbsp;', ' '):gsub('%s+', ' ')
local pos = text:find(' ', 1, true)
if pos then
-- Leave checking of value to convert which can handle fractions.
local value = text:sub(1, pos - 1)
local uid = text:sub(pos + 1)
if uid:sub(1, 3) == 'ft ' and uid:sub(-3) == ' in' then
-- Special case for enwiki to allow
insert2(uid:sub(4, -4), 'in')
insert2(value, 'ft')
else
insert2(value, make_unit(tdata.wikidata_units, parms, uid) or uid)
end
return true
end
end  
local function adjustparameters(tdata, parms, index)
-- For Module:Convert, adjust parms (a table of parameters).
-- Return true if successful or return false, t where t is an error message table.
-- This is intended mainly for use in infoboxes where the input might be
-- <value><space><unit> or
-- <wikidata-property-id>
-- If successful, insert values and units in parms, before given index.
local text = parms.input -- should be a trimmed, non-empty string
local pid = text:match('^P%d+$')
local sep = ','
local special = specials[parms[index]]
if special then
parms.out_unit = special[1]
sep = special[2] or sep
table.remove(parms, index)
end
local function quit
return false, pid and { 'cvt_no_output' } or { 'cvt_bad_input', text }
end
local function insert2(first, second)
table.insert(parms, index, second)
table.insert(parms, index, first)
end
if pid then
parms.input_text = '' -- output an empty string if an error occurs
local result = input_from_property(tdata, parms, pid)
if result.n == 0 then
return quit
end
local ucode
for i, t in ipairs(result) do
-- Convert requires each input unit to be identical.
if i == 1 then
ucode = t[2]
elseif ucode ~= t[2] then
return quit
end
end
local item = ucode
if item == parms[index] then
-- Remove specified output unit if it is the same as the Wikidata unit.
-- For example, with property "12 km".
table.remove(parms, index)
end
for i = result.n, 1, -1 do
insert2(result[i][1], item)
item = sep
end
return true
else
if input_from_text(tdata, parms, text, insert2) then
return true
end
end
return quit
end  
---
--- List units and check syntax of definitions ---------------------------------
---
local specifications = {
-- seq = sequence in which fields are displayed
base = {
title = 'SI base units',
fields = {
symbol = { seq = 2, mandatory = true },
name1 = { seq = 3, mandatory = true },
name2 = { seq = 4 },
link = { seq = 5 },
},
noteseq = 6,
header = '{|\n!si !!symbol !!name1 !!name2 !!link !!note',
item = '|-\n|%s ||%s ||%s ||%s ||%s ||%s',
footer = '|}',
},
alias = {
title = 'Aliases for convert',
fields = {
ucode = { seq = 2, mandatory = true },
si = { seq = 3 },
},
noteseq = 4,
header = '{|\n!alias !!ucode !!base !!note',
item = '|-\n|%s ||%s ||%s ||%s',
footer = '|}',
},
known = {
title = 'Units known to convert',
fields = {
ucode = { seq = 2, mandatory = true },
label = { seq = 3, mandatory = true },
},
noteseq = 4,
header = '{|\n!qid !!ucode !!label !!note',
item = '|-\n|%s ||%s ||%s ||%s',
footer = '|}',
},
unknown = {
title = 'Units not known to convert',
fields = {
_ucode = { seq = 2, mandatory = true },
si = { seq = 3 },
name1 = { seq = 4 },
name2 = { seq = 5 },
link = { seq = 6 },
label = { seq = 7, mandatory = true },
},
noteseq = 8,
header = '{|\n!qid !!_ucode !!base !!name1 !!name2 !!link !!label !!note',
item = '|-\n|%s ||%s ||%s ||%s ||%s ||%s ||%s ||%s',
footer = '|}',
},
}  
local function listunits(tdata, ulookup)
-- For Module:Convert, make wikitext to list the built-in Wikidata units.
-- Return true, wikitext if successful or return false, t where t is an
-- error message table. Currently, an error return never occurs.
-- The syntax of each unit definition is checked and a note is added if
-- a problem is detected.
local function safe_cells(t)
-- This is not currently needed, but in case definitions ever use wikitext
-- like 'kg', escape the text so it works in a table cell.
local result = {}
for i, v in ipairs(t) do
if v:find('|', 1, true) then
v = v:gsub('(%[%^%[%-)|(.-%]%])', '%1\0%2') -- replace pipe in piped link with a zero byte
v = v:gsub('|', '&#124;') -- escape '|'
v = v:gsub('%z', '|') -- restore pipe in piped link
end
result[i] = v:gsub('{', '&#123;') -- escape '{'
end
return unpack(result)
end
local wdunits = tdata.wikidata_units
local speckeys = { 'base', 'alias', 'unknown', 'known' }
for _, sid in ipairs(speckeys) do
specifications[sid].units = Collection.new
end
local keys = Collection.new
for k, v in pairs(wdunits) do
keys:add(k)
end
table.sort(keys)
local note_count = 0
for _, key in ipairs(keys) do
local unit = wdunits[key]
local ktext, sid
if key:match('^Q%d+$') then
ktext = * .. key .. *
if unit.ucode then
sid = 'known'
else
sid = 'unknown'
end
elseif unit.ucode then
ktext = key
sid = 'alias'
else
ktext = key
sid = 'base'
end
local result = { ktext }
local spec = specifications[sid]
local fields = spec.fields
local note = Collection.new
for k, v in pairs(unit) do
if fields[k] then
local seq = fields[k].seq
if result[seq] then
note:add('duplicate ' .. k) -- cannot happen since keys are unique
else
result[seq] = v
end
else
note:add('invalid ' .. k)
end
end
for k, v in pairs(fields) do
local value = result[v.seq]
if value then
if k == 'si' and not wdunits[value] then
note:add('need si ' .. value)
end
if k == 'label' then
local wdl = mw.wikibase.label(key)
if wdl ~= value then
note:add('label changed to ' .. tostring(wdl))
end
end
else
result[v.seq] = ''
if v.mandatory then
note:add('missing ' .. k)
end
end
end
local text
if note.n > 0 then
note_count = note_count + 1
text = '*' .. note:join('
')
end
result[spec.noteseq] = text or ''
spec.units:add(result)
end
local results = Collection.new
if note_count > 0 then
local text = note_count .. (note_count == 1 and ' note' or ' notes')
results:add("**Search for * to see " .. text .. "**\n")
end
for _, sid in ipairs(speckeys) do
local spec = specifications[sid]
results:add("**" .. spec.title .. "**")
results:add(spec.header)
local fmt = spec.item
for _, unit in ipairs(spec.units) do
results:add(string.format(fmt, safe_cells(unit)))
end
results:add(spec.footer)
end
return true, results:join('\n')
end  
return { _adjustparameters = adjustparameters, _listunits = listunits }