Module:DependencyList: Difference between revisions

From The Deadlock Wiki
Jump to navigation Jump to search
osrsw>CephHunter
Module:Enum -> Module:Array
m 20 revisions imported
 
(7 intermediate revisions by 4 users not shown)
Line 1: Line 1:
-- <nowiki>
require("strict")
local p = {}
local p = {}
local libraryUtil = require( 'libraryUtil' )
local libraryUtil = require('libraryUtil')
local arr = require( 'Module:Array' )
local arr = require('Module:Array')
local yn = require( 'Module:Yesno' )
local yn = require('Module:Yesno')
local param = require( 'Module:Paramtest' )
local param = require('Module:Paramtest')
local dpl = require( 'Module:DPLlua' )
local dpl = require('Module:DPLlua')
local tooltip = require( 'Module:Tooltip' )
local tooltip = require('Module:Tooltip')
local moduleIsUsed = false
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30
local dynamicRequireListQueryCache = {}
local dynamicRequireListQueryCache = {}


--- Used in case 'require( varName )' is found. Attempts to find a string value stored in 'varName'.
local builtins = {
---@param content string    The content of the module to search in
["libraryUtil"] = {
---@param varName string
link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil",
---@return string
categories = {},
local function substVarValue( content, varName )
},
    local res = content:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or content:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
["strict"] = {
    if res:find( '^(["\'])[Mm]odule:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict",
        return mw.text.trim( res )
categories = { "[[Category:Strict mode modules]]" },
    else
},
        return ''
}
    end
 
-- Used in case 'require( varName )' is found. Attempts to find a string value stored in 'varName'.
local function substVarValue( moduleContent, varName )
local res = moduleContent:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or moduleContent:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
if res:find( '^(["\'])[Mm]odule:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
return mw.text.trim( res )
else
return ''
end
end
end


---@param capture string
local function extractModuleName( capture, moduleContent )
---@param content string    The content of the module to search in
capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )
---@return string
local function extractModuleName( capture, content )
    capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )


    if capture:find( '^(["\']).-%1$' ) then -- Check if it is already a pure string
if capture:find( '^(["\']).-%1$' ) then -- Check if it is already a pure string
        return capture
return capture
    elseif capture:find( '^[%a_][%w_]*$' ) then -- Check if if is a single variable
elseif capture:find( '^[%a_][%w_]*$' ) then -- Check if if is a single variable
        return substVarValue( content, capture )
return substVarValue( moduleContent, capture )
    end
end


    return capture
return capture
end
end


---@param str string
---@return string
local function formatPageName( str )
local function formatPageName( str )
    local name = mw.text.trim(str)
local name = mw.text.trim(str)
        :gsub( '^([\'\"])(.-)%1$', function(_, x) return x end ) -- Only remove quotes at start and end of string if both are the same type
:gsub( '^([\'\"])(.-)%1$', '%2' ) -- Only remove quotes at start and end of string if both are the same type
        :gsub( '_', ' ' )
:gsub( '_', ' ' )
        :gsub( '^.', string.upper )
:gsub( '^.', string.upper )
        :gsub( ':.', string.upper )
:gsub( '^([^:]-:)(.)', function(a,b) return a..string.upper(b) end )


    return name
return name
end
end


---@param str string
local function formatModuleName( str, allowBuiltins )
---@return string
if allowBuiltins then
local function formatModuleName( str )
local name = mw.text.trim(str)
    local module = formatPageName( str )
-- Only remove quotes at start and end of string if both are the same type
:gsub([[^(['"])(.-)%1$]], '%2')


    if not string.find( module, '^[Mm]odule:' ) then
if builtins[name] then
        module = 'Module:' .. module
return name
    end
end
end


    return module
local module = formatPageName( str )
 
if not string.find( module, '^[Mm]odule:' ) then
module = 'Module:' .. module
end
 
return module
end
end


local function dualGmatch( str, pat1, pat2 )
local function dualGmatch( str, pat1, pat2 )
    local f1 = string.gmatch( str, pat1 )
local f1 = string.gmatch( str, pat1 )
    local f2 = string.gmatch( str, pat2 )
if pat2 then
    return function()
local f2 = string.gmatch( str, pat2 )
        return f1() or f2()
return function()
    end
return f1() or f2()
end
else
return f1
end
end
 
local function isDynamicPath( str )
return string.find( str, '%.%.' ) or string.find( str, '%%%a' )
end
end


--- Used in case a construct like 'require( "Module:wowee/" .. isTheBest )' is found.
-- Used in case a construct like 'require( "Module:wowee/" .. isTheBest )' is found.
--- Will return a list of pages which satisfy this pattern where 'isTheBest' can take any value.
-- Will return a list of pages which satisfy this pattern where 'isTheBest' can take any value.
---@param query string
---@return string[]    Sequence of strings
local function getDynamicRequireList( query )
local function getDynamicRequireList( query )
    if query:find( '%.%.' ) then
if query:find( '%.%.' ) then
        query = mw.text.split( query, '..', true )
query = mw.text.split( query, '..', true )
        query = arr.map( query, function(x) return mw.text.trim(x) end )
query = arr.map( query, function(x) return (x:match('^%s*[\'\"](.-)[\'\"]%s*$') or '%') end )
        query = arr.map( query, function(x) return (x:match('^[\'\"](.-)[\'\"]$') or '%') end )
query = table.concat( query )
        query = table.concat( query )
else
    else
local _, _query = query:match( '(["\'])(.-)%1' )
        _, query = query:match( '(["\'])(.-)%1' )
query = _query:gsub( '%%%a', '%%' ) -- Replace lua string.format specifiers with a dpl wildcard
        query = query:gsub( '%%%a', '%%' )
end
    end
query = query:gsub( '^[Mm]odule:', '' )
    query = query:gsub( '^[Mm]odule:', '' )


    if query:find( '^[Ee]xchange/' ) or query:find( '^[Dd]ata/' ) then
query = mw.language.getContentLanguage():ucfirst(query)
        return { 'Module:' .. query }  -- This format will later be used by formatDynamicQueryLink()
if query:find( '^Exchange/' ) or query:find( '^Data/' ) then
    end
return { 'Module:' .. query }  -- This format will later be used by formatDynamicQueryLink()
end


    if dynamicRequireListQueryCache[ query ] then
if dynamicRequireListQueryCache[ query ] then
        return dynamicRequireListQueryCache[ query ]
return dynamicRequireListQueryCache[ query ]
    end
end


    local list = dpl.ask{
local list = dpl.ask{
        namespace = 'Module',
namespace = 'Module',
        titlematch = query,
titlematch = query,
        nottitlematch = '%/doc|'..query..'/%',
nottitlematch = '%/doc|'..query..'/%',
        distinct = 'strict',
distinct = 'strict',
        ignorecase = true,
ordermethod = 'title',
        ordermethod = 'title',
count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
        count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
skipthispage = 'no',
        skipthispage = 'no',
allowcachedresults = true,
        allowcachedresults = true,
cacheperiod = 604800 -- One week
        cacheperiod = 604800 -- One week
}
    }


    if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
        list = { 'Module:' .. query }
list = { 'Module:' .. query }
    end
end


    dynamicRequireListQueryCache[ query ] = list
dynamicRequireListQueryCache[ query ] = list


    return list
return list
end
end


--- Returns a list of modules loaded and required by module 'moduleName'.
--- Returns a list of modules loaded and required by module 'moduleName'.
---@param moduleName string
local function getRequireLists( moduleContent )
---@param searchForUsedTemplates boolean
local requireList = arr{}
---@return string[], string[], string[]
local loadDataList = arr{}
local function getRequireList( moduleName, searchForUsedTemplates )
local loadJsonDataList = arr{}
    local content = mw.title.new( moduleName ):getContent()
local dynamicRequirelist = arr{}
    local requireList = arr{}
local dynamicLoadDataList = arr{}
    local loadDataList = arr{}
local dynamicLoadJsonDataList = arr{}
    local usedTemplateList = arr{}
local extraCategories = arr{}
    local dynamicRequirelist = arr{}
    local dynamicLoadDataList = arr{}


    assert( content ~= nil, string.format( '%s does not exist', moduleName ) )
local function getList( pat1, pat2, list, dynList )
for match in dualGmatch( moduleContent, pat1, pat2 ) do
match = mw.text.trim( match )
local name = extractModuleName( match, moduleContent )


    content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' ) -- Strip comments
if isDynamicPath( name ) then
dynList:insert( getDynamicRequireList( name ), true )
elseif name ~= '' then
name = formatModuleName( name, true )
table.insert( list, name )


    for match in dualGmatch( content, 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)' ) do
if builtins[name] then
        match = mw.text.trim( match )
extraCategories = extraCategories:insert( builtins[name].categories, true )
        match = extractModuleName( match, content )
end
end
end
end


        if match:find( '%.%.' ) or match:find( '%%%a' ) then
getList( 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)', requireList, dynamicRequirelist )
            for _, x in ipairs( getDynamicRequireList( match ) ) do
getList( 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)', loadDataList, dynamicLoadDataList )
                table.insert( dynamicRequirelist, x )
getList( 'mw%.loadJsonData%s*(%b())', 'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)', loadJsonDataList, dynamicLoadJsonDataList )
            end
getList( 'pcall%s*%(%s*require%s*,([^%),]+)', nil, requireList, dynamicRequirelist )
        elseif match ~= '' then
getList( 'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)', nil, loadDataList, dynamicLoadDataList )
            match = formatModuleName( match )
getList( 'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)', nil, loadJsonDataList, dynamicLoadJsonDataList )
            table.insert( requireList, match )
        end
    end


    for match in dualGmatch( content, 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)' ) do
requireList = requireList .. dynamicRequirelist
        match = mw.text.trim( match )
requireList = requireList:unique()
        match = extractModuleName( match, content )
loadDataList = loadDataList .. dynamicLoadDataList .. loadJsonDataList .. dynamicLoadJsonDataList
loadDataList = loadDataList:unique()
extraCategories = extraCategories:unique()
table.sort( requireList )
table.sort( loadDataList )
table.sort( extraCategories )


        if match:find( '%.%.' ) or match:find( '%%%a' ) then
return {
            for _, x in ipairs( getDynamicRequireList( match ) ) do
require = requireList,
                table.insert( dynamicLoadDataList, x )
loadData = loadDataList,
            end
extraCategories = extraCategories,
        elseif match ~= '' then
}
            match = formatModuleName( match )
end
            table.insert( loadDataList, match )
        end
    end


    for func, match in string.gmatch( content, 'pcall%s*%(([^,]+),([^%),]+)' ) do
local function getUsedTemplatesList( moduleContent )
        func = mw.text.trim( func )
local usedTemplateList = arr{}
        match = mw.text.trim( match )


        if func == 'require' then
for preprocess in string.gmatch( moduleContent, ':preprocess%s*(%b())' ) do
            for _, x in ipairs( getDynamicRequireList( match ) ) do
local function recursiveGMatch( str, pat )
                table.insert( dynamicRequirelist, x )
local list = {}
            end
local i = 0
        elseif func == 'mw.loadData' then
repeat
            for _, x in ipairs( getDynamicRequireList( match ) ) do
for match in string.gmatch( list[i] or str, pat ) do
                table.insert( dynamicLoadDataList, x )
table.insert( list, match )
            end
end
        end
i =  i + 1
    end
until i > #list or i > 100


    if searchForUsedTemplates then
i = 0
        for preprocess in string.gmatch( content, ':preprocess%s*(%b())' ) do
return function()
            local function recursiveGMatch( str, pat )
i = i + 1
                local list = {}
return list[i]
                local i = 0
end
                repeat
end
                    for match in string.gmatch( list[i] or str, pat ) do
                        table.insert( list, match )
                    end
                    i =  i + 1
                until i > #list or i > 100


                i = 0
for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
                return function()
local name = string.match( template, '{(.-)[|{}]' )
                    i = i + 1
if name ~= '' then
                    return list[i]
if name:find( ':' ) then
                end
local ns = name:match( '^(.-):' )
            end
if arr.contains( {'', 'template', 'calculator', 'user'}, ns:lower() ) then
table.insert( usedTemplateList, name )
elseif ns == ns:upper() then
table.insert( usedTemplateList, ns ) -- Probably a magic word
end
else
if name:match( '^%u+$' ) or name == '!' then
table.insert( usedTemplateList, name ) -- Probably a magic word
else
table.insert( usedTemplateList, 'Template:'..name )
end
end
end
end
end


            for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
usedTemplateList = usedTemplateList:unique()
                local name = string.match( template, '{(.-)[|{}]' )
table.sort( usedTemplateList )
                if name ~= '' then
                    if name:find( ':' ) then
                        local ns = name:match( '^(.-):' )
                        if arr.contains( {'', 'template', 'calculator', 'user'}, ns:lower() ) then
                            table.insert( usedTemplateList, name )
                        elseif ns == ns:upper() then
                            table.insert( usedTemplateList, ns ) -- Probably a magic word
                        end
                    else
                        if name:match( '^%u+$' ) or name == '!' then
                            table.insert( usedTemplateList, name ) -- Probably a magic word
                        else
                            table.insert( usedTemplateList, 'Template:'..name )
                        end
                    end
                end
            end
        end
    end


    requireList = requireList .. dynamicRequirelist:reject( loadDataList )
return usedTemplateList
    requireList = requireList:unique()
end
    loadDataList = loadDataList .. dynamicLoadDataList:reject( requireList )
    loadDataList = loadDataList:unique()
    usedTemplateList = usedTemplateList:unique()
    table.sort( requireList )
    table.sort( loadDataList )
    table.sort( usedTemplateList )


    return requireList, loadDataList, usedTemplateList
-- Returns a list with module and function names used in all '{{#Invoke:moduleName|funcName}}' found on page 'templateName'.
local function getInvokeCallList( pageName )
local pageContent = mw.title.new( pageName ):getContent()
local invokeList = {}
 
assert( pageContent, string.format( 'Failed to retrieve text content of page "%s"', pageName ) )
 
for moduleName, funcName in string.gmatch( pageContent, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
moduleName = formatModuleName( moduleName )
funcName = mw.text.trim( funcName )
if string.find( funcName, '^{{{' ) then
funcName = funcName ..  '}}}'
end
table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
end
 
-- For form calcs invoking the module directly
for config in dualGmatch( pageContent, '<[pd][ri][ev]%s+class%s*=%s*["\']jcConfig["\'](.-)</[pd][ri][ev]>', '{{[Ff]orm calculator%s*|(.+)}}' ) do
local moduleName = string.match( config, 'module%s*=%s*(.-)[\n|]' )
if param.has_content( moduleName ) then
moduleName = formatModuleName( moduleName )
local funcName = string.match( config, 'modulefunc%s*=%s*(.-)[\n|]' ) or 'main'
table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
end
end
 
invokeList = arr.unique( invokeList, function(x) return x.moduleName..x.funcName end )
table.sort( invokeList, function(x, y) return x.moduleName..x.funcName < y.moduleName..y.funcName end )
 
return invokeList
end
end


--- Returns a list with module and function names used in all '{{#Invoke:moduleName|funcName}}' found on page 'templateName'.
local function getInvokedByList( moduleName )
---@param templateName string
local whatTemplatesLinkHere = dpl.ask( {
---@return table<string, string>[]
namespace = 'Template|Calculator',
local function getInvokeCallList( templateName )
linksto = moduleName,
    local content = mw.title.new( templateName ):getContent()
distinct = 'strict',
    local invokeList = {}
ordermethod = 'title',
allowcachedresults = true,
cacheperiod = 604800 -- One week
} )


    assert( content ~= nil, string.format( '%s does not exist', templateName ) )
local function lcfirst( str )
return string.gsub( str, '^[Mm]odule:.', string.lower )
end


    for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
local invokedByList = {}
        moduleName = formatModuleName( moduleName )
        funcName = mw.text.trim( funcName )
        if string.find( funcName, '^{{{' ) then
        funcName = funcName ..  '}}}'
        end
        table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
    end


    -- For form calcs invoking the module directly
for _, templateName in ipairs( whatTemplatesLinkHere ) do
    for config in dualGmatch( content, '<pre%s+class%s*=%s*["\']jcConfig["\'](.-)</pre>', '{{[Ff]orm calculator%s*|(.+)}}' ) do
local invokeList = getInvokeCallList( templateName )
        local moduleName = string.match( config, 'module%s*=%s*(.-)[\n|]' )
        if param.has_content( moduleName ) then
            moduleName = formatModuleName( moduleName )
            local funcName = string.match( config, 'modulefunc%s*=%s*(.-)[\n|]' ) or 'main'
            table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
        end
    end


    invokeList = arr.unique( invokeList, function(x) return x.moduleName..x.funcName end )
for _, invokeData in ipairs( invokeList ) do
    table.sort( invokeList, function(x, y) return x.moduleName..x.funcName < y.moduleName..y.funcName end )
if lcfirst( invokeData.moduleName ) == lcfirst( moduleName ) then
table.insert( invokedByList, { templateName=templateName, funcName=invokeData.funcName } )
end
end
end


    return invokeList
return invokedByList
end
end


---@param pageName string
local function messageBoxUnused()
---@param addCategories boolean
local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
---@return string
html:tag( 'td' )
local function messageBoxUnused( pageName, addCategories )
:attr( 'width', '40xp' )
    local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
:wikitext( '[[File:Willow logs (historical).png|center|30px|link=]]' )
    html:tag( 'td' )
:done()
        :attr( 'width', '40xp' )
:tag( 'td' )
        :wikitext( '[[File:Willow logs (historical).png|center|30px|link=]]' )
:wikitext( "'''This module is unused.'''" )
    :done()
:tag( 'div' )
    :tag( 'td' )
:css{ ['font-size']='0.85em', ['line-height']='1.45em' }
        :wikitext( "'''This module is unused.'''" )
:wikitext( 'This module is neither invoked by a template nor required/loaded by another module. If this is in error, make sure to add <code>{{[[Template:Documentation|Documentation]]}}</code>/<code>{{[[Template:No documentation|No&nbsp;documentation]]}}</code> to the calling template\'s or parent\'s module documentation.' )
        :tag( 'div' )
:done()
            :css{ ['font-size']='0.85em', ['line-height']='1.45em' }
:done()
            :wikitext( string.format( 'This module is neither invoked by a template nor required/loaded by another module. If this is in error, make sure to add <code>{{[[Template:Documentation|Documentation]]}}</code>/<code>{{[[Template:No documentation|No&nbsp;documentation]]}}</code> to the calling template\'s or parent\'s module documentation.', pageName ) )
            :wikitext( addCategories and '[[Category:Unused modules]]' or '' )
        :done()
    :done()


    return tostring( html )
return tostring( html )
end
end


local function collapseList( list, id, listType )
local function collapseList( list, id, listType )
    local text = string.format( '%d %s', #list, listType )
local text = string.format( '%d %s', #list, listType )
    local button = tooltip._span{ name=id, alt=text }
local button = tooltip._span{ name=id, alt=text }
    list = arr.map( list, function(x) return '\n# '..x end )
list = arr.map( list, function(x) return '\n# '..x end )
    local content = tooltip._div{ name=id, content='\n'..table.concat( list )..'\n\n' }
local content = tooltip._div{ name=id, content='\n'..table.concat( list )..'\n\n' }


    return { tostring( button ) .. tostring( content ) }
return { tostring( button ) .. tostring( content ) }
end
end


--- Creates a link to [[Special:Search]] showing all pages found by getDynamicRequireList() in case it found more than MAX_DYNAMIC_REQUIRE_LIST_LENGTH pages.
-- Creates a link to [[Special:Search]] showing all pages found by getDynamicRequireList() in case it found more than MAX_DYNAMIC_REQUIRE_LIST_LENGTH pages.
---@param query string      @This will be in a format like 'Module:Wowee/%' or 'Module:Wowee/%/data'
-- Input query uses DPL % wildcards like 'Module:Wowee/%' or 'Module:Wowee/%/data'
---@return string
local function formatDynamicQueryLink( query )
local function formatDynamicQueryLink( query )
    local prefix = query:match( '^([^/]+)' )
local prefix = query:match( '^([^/]+)' )
    local linkText = query:gsub( '%%', '&lt; ... &gt;' )
local linkText = query:gsub( '%%', '&lt; ... &gt;' )


    query = query:gsub( '^Module:',  '' )
query = query:gsub( '^Module:',  '' )


    query = query:gsub( '([^/]+)/?', function ( match )
query = query:gsub( '([^/]+)/?', function ( match )
        if match == '%' then
if match == '%' then
            return '\\/[^\\/]+'
return '\\/[^\\/]+'
        else
else
            return '\\/"' .. match .. '"'
return '\\/"' .. match .. '"'
        end
end
    end )
end )


    query = query:gsub( '^\\/', '' )
query = query:gsub( '^\\/', '' )


    query = string.format(
query = string.format(
        'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
        query,
query,
        query:find( '"$' ) and '' or '""',
query:find( '"$' ) and '' or '""',
        query,
query,
        prefix
prefix
    )
)


    return string.format( '<span class="plainlinks">[%s %s]</span>', tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
return string.format( '<span class="plainlinks">[%s %s]</span>', tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
end
end


---@param templateName string
local function formatModuleLinks( pages )
---@param addCategories boolean
local links = arr{}
---@param invokeList table<string, string>[]    @This is the list returned by getInvokeCallList()
---@return string
local function formatInvokeCallList( templateName, addCategories, invokeList )
    local category = addCategories and '[[Category:Lua-based templates]]' or ''
    local res = {}


    for _, item in ipairs( invokeList ) do
for _, moduleName in ipairs(pages) do
        table.insert( res, string.format(
if moduleName:find( '%%' ) then
            "<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[RuneScape:Lua|Lua]].</div>",
links:insert( formatDynamicQueryLink( moduleName ) )
            templateName,
elseif builtins[moduleName] then
            item.funcName,
links:insert( '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]' )
            item.moduleName
else
        ) )
links:insert( '[[' .. moduleName .. ']]' )
    end
end
end


    if #invokeList > 0 then
return links
        table.insert( res, category )
end
    end


    return table.concat( res )
local function formatTemplateLinks( pages )
end
local links = arr{}


---@param moduleName string
for _, templateName in ipairs(pages) do
---@param addCategories boolean
if string.find( templateName, ':' ) then -- Real templates are prefixed by a namespace, magic words are not
---@param whatLinksHere string    @A list generated by a dpl of pages in the Template or Calculator namespace which link to moduleName.
links:insert( '[['..templateName..']]' )
---@return string
else
local function formatInvokedByList( moduleName, addCategories, whatLinksHere )
links:insert( "'''&#123;&#123;"..templateName.."&#125;&#125;'''" ) -- Magic words don't have a page so make them bold instead
local function lcfirst( str )
end
return string.gsub( str, '^[Mm]odule:.', string.lower )
end
end


    local templateData = arr.map( whatLinksHere, function(x) return {templateName=x, invokeList=getInvokeCallList(x)} end )
return links
    templateData = arr.filter( templateData, function(x)
end
        return arr.any( x.invokeList, function(y)
 
            return lcfirst(y.moduleName) == lcfirst(moduleName)
local function formatInvokeCallList( templateName, invokeList )
        end )
local res = {}
    end )


    local invokedByList = {}
for _, item in ipairs( invokeList ) do
table.insert( res, string.format(
"<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[RuneScape:Lua|Lua]].</div>",
templateName,
item.funcName,
item.moduleName
) )
end


    for _, template in ipairs( templateData ) do
return table.concat( res )
        for _, invoke in ipairs( template.invokeList ) do
end
            table.insert( invokedByList, string.format( "function '''%s''' is invoked by [[%s]]", invoke.funcName, template.templateName ) )
        end
    end


    table.sort( invokedByList)
local function formatInvokedByList( moduleName, invokedByList )
for i, invoke in ipairs( invokedByList ) do
invokedByList[i] = string.format( "function '''%s''' is invoked by [[%s]]", invoke.funcName, invoke.templateName )
end


    local res = {}
table.sort( invokedByList)


    if #invokedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
local res = {}
        table.insert( res, string.format(
            "<div class='seealso'>'''%s''' is invoked by %s.</div>",
            moduleName,
            collapseList( invokedByList, 'invokedBy', 'templates' )[1]
        ) )
    else
        for _, item in ipairs( invokedByList ) do
            table.insert( res, string.format(
                "<div class='seealso'>'''%s's''' %s.</div>",
                moduleName,
                item
            ) )
        end
    end


    if #templateData > 0 then
if #invokedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        moduleIsUsed = true
table.insert( res, string.format(
        table.insert( res, (addCategories and '[[Category:Template invoked modules]]' or '') )
"<div class='seealso'>'''%s''' is invoked by %s.</div>",
    end
moduleName,
collapseList( invokedByList, 'invokedBy', 'templates' )[1]
) )
else
for _, item in ipairs( invokedByList ) do
table.insert( res, string.format(
"<div class='seealso'>'''%s's''' %s.</div>",
moduleName,
item
) )
end
end


    return table.concat( res )
return table.concat( res )
end
end


---@param moduleName string
local function formatRequiredByList( moduleName, requiredByLists )
---@param addCategories boolean
local requiredByList = formatModuleLinks( requiredByLists.require )
---@param whatLinksHere string      @A list generated by a dpl of pages in the Module namespace which link to moduleName.
local loadedByList = formatModuleLinks( requiredByLists.loadData )
---@return string
local function formatRequiredByList( moduleName, addCategories, whatLinksHere )
    local childModuleData = arr.map( whatLinksHere, function ( title )
        local requireList, loadDataList = getRequireList( title )
        return {name=title, requireList=requireList, loadDataList=loadDataList}
    end )


    local requiredByList = arr.map( childModuleData, function ( item )
if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        if arr.any( item.requireList, function(x) return x:lower()==moduleName:lower() end ) then
requiredByList = collapseList( requiredByList, 'requiredBy', 'modules' )
            if item.name:find( '%%' ) then
end
                return formatDynamicQueryLink( item.name )
            else
                return '[[' .. item.name .. ']]'
            end
        end
    end )


    local loadedByList = arr.map( childModuleData, function ( item )
if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        if arr.any( item.loadDataList, function(x) return x:lower()==moduleName:lower() end ) then
loadedByList = collapseList( loadedByList, 'loadedBy', 'modules' )
            if item.name:find( '%%' ) then
end
                return formatDynamicQueryLink( item.name )
            else
                return '[[' .. item.name .. ']]'
            end
        end
    end )


    if #requiredByList > 0 or #loadedByList > 0 then
local res = {}
        moduleIsUsed  = true
    end


    if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
for _, requiredByModuleName in ipairs( requiredByList ) do
        requiredByList = collapseList( requiredByList, 'requiredBy', 'modules' )
table.insert( res, string.format(
    end
"<div class='seealso'>'''%s''' is required by %s.</div>",
moduleName,
requiredByModuleName
) )
end


    if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
for _, loadedByModuleName in ipairs( loadedByList ) do
        loadedByList = collapseList( loadedByList, 'loadedBy', 'modules' )
table.insert( res, string.format(
    end
"<div class='seealso'>'''%s''' is loaded by %s.</div>",
moduleName,
loadedByModuleName
) )
end


    local res = {}
return table.concat( res )
end


    for _, requiredByModuleName in ipairs( requiredByList ) do
local function formatImportList( currentPageName, moduleList, id, message )
        table.insert( res, string.format(
moduleList = formatModuleLinks( moduleList )
            "<div class='seealso'>'''%s''' is required by %s.</div>",
            moduleName,
            requiredByModuleName
        ) )
    end


    if #requiredByList > 0 then
if #moduleList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        table.insert( res, (addCategories and '[[Category:Modules required by modules]]' or '') )
moduleList = collapseList( moduleList, id, 'modules' )
    end
end


    for _, loadedByModuleName in ipairs( loadedByList ) do
local res = arr.map( moduleList, function( moduleName )
        table.insert( res, string.format(
return '<div class="seealso">' .. string.format( message, currentPageName, moduleName ) .. '</div>'
            "<div class='seealso'>'''%s''' is loaded by %s.</div>",
end )
            moduleName,
            loadedByModuleName
        ) )
    end


    if #loadedByList > 0 then
return table.concat( res )
        table.insert( res, (addCategories and '[[Category:Module data]]' or '') )
    end
 
    return table.concat( res )
end
end


local function formatRequireList( currentPageName, addCategories, requireList )
local function formatUsedTemplatesList( currentPageName, usedTemplateList )
    local res = {}
usedTemplateList = formatTemplateLinks( usedTemplateList )
local res = {}


    if #requireList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        requireList = collapseList( requireList, 'require', 'modules' )
usedTemplateList = collapseList( usedTemplateList, 'usedTemplates', 'templates' )
    end
end


    for _, requiredModuleName in ipairs( requireList ) do
for _, templateName in ipairs( usedTemplateList ) do
        table.insert( res, string.format(
table.insert( res, string.format(
            "<div class='seealso'>'''%s''' requires %s.</div>",
"<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp>.</div>",
            currentPageName,
currentPageName,
            requiredModuleName
templateName
        ) )
) )
    end
end


    if #requireList > 0 then
return table.concat( res )
        table.insert( res, (addCategories and '[[Category:Modules requiring modules]]' or '') )
end
    end


    return table.concat( res )
local function setBucketFields( requireLists )
if mw.title.getCurrentTitle().subpageText ~= 'doc' and (#requireLists.require > 0 or #requireLists.loadData > 0) then
bucket( 'dependency_list' ).put{
require = requireLists.require,
load_data = requireLists.loadData
}
end
end
end


local function formatLoadDataList( currentPageName, addCategories, loadDataList )
local function getRequiredByLists( currentPageName )
    local res = {}
local requiredByListRaw = bucket( 'dependency_list' ).select( 'page_name' ).where( 'require', currentPageName ).run()
local loadedByListRaw = bucket( 'dependency_list' ).select( 'page_name' ).where( 'load_data', currentPageName ).run()
local requiredByList = {}
local loadedByList = {}


    if #loadDataList > COLLAPSE_LIST_LENGTH_THRESHOLD then
for _, bucketItem in ipairs( requiredByListRaw ) do
        loadDataList = collapseList( loadDataList, 'loadData', 'modules' )
table.insert( requiredByList, bucketItem.page_name )
    end
end
for _, bucketItem in ipairs( loadedByListRaw ) do
table.insert( loadedByList, bucketItem.page_name )
end


    for _, loadedModuleName in ipairs( loadDataList ) do
requiredByList = arr.unique( requiredByList )
        table.insert( res, string.format(
loadedByList = arr.unique( loadedByList )
            "<div class='seealso'>'''%s''' loads data from %s.</div>",
table.sort( requiredByList )
            currentPageName,
table.sort( loadedByList )
            loadedModuleName
        ) )
    end


    if #loadDataList > 0 then
return {
        table.insert( res, (addCategories and '[[Category:Modules using data]]' or '') )
require = requiredByList,
    end
loadData = loadedByList
 
}
    return table.concat( res )
end
end


local function formatUsedTemplatesList( currentPageName, addCategories, usedTemplateList )
local function templateDependencyList( currentPageName, addCategories )
    local res = {}
local invokeList = getInvokeCallList( currentPageName )
local res = formatInvokeCallList( currentPageName, invokeList )


    if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if addCategories and #invokeList > 0 then
        usedTemplateList = collapseList( usedTemplateList, 'usedTemplates', 'templates' )
res = res .. '[[Category:Lua-based templates]]'
    end
end


    for _, templateName in ipairs( usedTemplateList ) do
return res
        table.insert( res, string.format(
            "<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp>.</div>",
            currentPageName,
            templateName
        ) )
    end
 
    return table.concat( res )
end
end


function p.main( frame )
local function moduleDependencyList( currentPageName, addCategories, isUsed )
    local args = frame:getParent().args
local moduleContent = mw.title.new( currentPageName ):getContent()
    return p._main( args[1], args.category, args.isUsed )
assert( moduleContent, string.format( 'Failed to retrieve text content of page "%s"', currentPageName ) )
end
moduleContent = moduleContent:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' ) -- Strip comments


---@param currentPageName string|nil
local requireLists = getRequireLists( moduleContent )
---@param addCategories boolean|string|nil
local usedTemplateList = getUsedTemplatesList( moduleContent )
---@return string
local requiredByLists = getRequiredByLists( currentPageName )
function p._main( currentPageName, addCategories, isUsed )
local invokedByList = getInvokedByList( currentPageName )
    libraryUtil.checkType( 'Module:RequireList._main', 1, currentPageName, 'string', true )
    libraryUtil.checkTypeMulti( 'Module:RequireList._main', 2, addCategories, {'boolean', 'string', 'nil'} )
    libraryUtil.checkTypeMulti( 'Module:RequireList._main', 3, isUsed, {'boolean', 'string', 'nil'} )


    local title = mw.title.getCurrentTitle()
setBucketFields( requireLists )


    -- Leave early if not in module, template or calculator namespace or if module is part of exchange or data groups
local res = arr{}
    if param.is_empty( currentPageName ) and (
        ( not arr.contains( {'Module', 'Template', 'Calculator'}, title.nsText ) ) or
        ( title.nsText == 'Module' and ( arr.contains( {'Exchange', 'Exchange historical', 'Data'}, title.text:match( '^(.-)/' ) ) ) )
    ) then
        return ''
    end


    currentPageName = param.default_to( currentPageName, title.fullText )
res:insert( formatInvokedByList( currentPageName, invokedByList ) )
    currentPageName = string.gsub( currentPageName, '/[Dd]oc$', '' )
res:insert( formatImportList( currentPageName, requireLists.require, 'require', "'''%s''' requires %s." ) )
    currentPageName = formatPageName( currentPageName )
res:insert( formatImportList( currentPageName, requireLists.loadData, 'loadData', "'''%s''' loads data from %s." ) )
    addCategories = yn( param.default_to( addCategories, title.subpageText~='doc' ) )
res:insert( formatUsedTemplatesList( currentPageName, usedTemplateList ) )
    moduleIsUsed = yn( param.default_to( isUsed, false ) )
res:insert( formatRequiredByList( currentPageName, requiredByLists ) )


    if title.text:lower():find( 'sandbox' ) then
if addCategories then
    moduleIsUsed = true -- Don't show sandbox modules as unused
res:insert( requireLists.extraCategories, true )
    end


    if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) then
if #requireLists.require > 0 then
        local invokeList = getInvokeCallList( currentPageName )
res:insert( '[[Category:Modules requiring modules]]')
        return formatInvokeCallList( currentPageName, addCategories, invokeList )
end
    end
if #requireLists.loadData > 0 then
res:insert( '[[Category:Modules using data]]')
end
if #requiredByLists.require > 0 then
res:insert( '[[Category:Modules required by modules]]')
end
if #requiredByLists.loadData > 0 then
res:insert( '[[Category:Module data]]')
end
if #invokedByList > 0 then
res:insert( '[[Category:Template invoked modules]]')
end
end


    local whatTemplatesLinkHere, whatModulesLinkHere = dpl.ask( {
if
        namespace = 'Template|Calculator',
not (
        linksto = currentPageName,
yn( isUsed )
        distinct = 'strict',
or currentPageName:lower():find( 'sandbox' )
        ignorecase = true,
or #requiredByLists.require > 0
        ordermethod = 'title',
or #requiredByLists.loadData > 0
        allowcachedresults = true,
or #invokedByList > 0
        cacheperiod = 604800 -- One week
)
    }, {
then
        namespace = 'Module',
table.insert( res, 1, messageBoxUnused() )
        linksto = currentPageName,
        nottitlematch = '%/doc|Exchange/%|Exchange historical/%|Data/%|' .. currentPageName:gsub( 'Module:', '' ),
        distinct = 'strict',
        ignorecase = true,
        ordermethod = 'title',
        allowcachedresults = true,
        cacheperiod = 604800 -- One week
    } )


    local requireList, loadDataList, usedTemplateList = getRequireList( currentPageName, true )
if addCategories then
res:insert( '[[Category:Unused modules]]')
end
end


    requireList = arr.map( requireList, function ( moduleName )
return table.concat( res )
        if moduleName:find( '%%' ) then
end
            return formatDynamicQueryLink( moduleName )
        else
            return '[[' .. moduleName .. ']]'
        end
    end )


    loadDataList = arr.map( loadDataList, function ( moduleName )
function p.main( frame )
        if moduleName:find( '%%' ) then
local args = frame:getParent().args
            return formatDynamicQueryLink( moduleName )
return p._main( args[1], args.category, args.isUsed )
        else
end
            return '[[' .. moduleName .. ']]'
 
        end
function p._main( currentPageName, addCategories, isUsed )
    end )
libraryUtil.checkType( 'Module:RequireList._main', 1, currentPageName, 'string', true )
libraryUtil.checkTypeMulti( 'Module:RequireList._main', 2, addCategories, {'boolean', 'string', 'nil'} )
libraryUtil.checkTypeMulti( 'Module:RequireList._main', 3, isUsed, {'boolean', 'string', 'nil'} )
 
local title = mw.title.getCurrentTitle()


    usedTemplateList = arr.map( usedTemplateList, function( templateName )
-- Leave early if not in module, template or calculator namespace or if module is part of exchange or data groups
        if string.find( templateName, ':' ) then -- Real templates are prefixed by a namespace, magic words are not
if param.is_empty( currentPageName ) and (
            return '[['..templateName..']]'
( not arr.contains( {'Module', 'Template', 'Calculator'}, title.nsText ) ) or
        else
( title.nsText == 'Module' and ( arr.contains( {'Exchange', 'Exchange historical', 'Data'}, title.text:match( '^(.-)/' ) ) ) )
            return "'''&#123;&#123;"..templateName.."&#125;&#125;'''" -- Magic words don't have a page so make them bold instead
) then
        end
return ''
    end )
end


    local res = {}
currentPageName = param.default_to( currentPageName, title.fullText )
currentPageName = string.gsub( currentPageName, '/[Dd]oc$', '' )
currentPageName = formatPageName( currentPageName )


    table.insert( res, formatInvokedByList( currentPageName, addCategories, whatTemplatesLinkHere ) )
if (addCategories == nil) then
    table.insert( res, formatRequireList( currentPageName, addCategories, requireList ) )
addCategories = title.subpageText~='doc'
    table.insert( res, formatLoadDataList( currentPageName, addCategories, loadDataList ) )
end
    table.insert( res, formatUsedTemplatesList( currentPageName, addCategories, usedTemplateList ) )
addCategories = yn(addCategories)
    table.insert( res, formatRequiredByList( currentPageName, addCategories, whatModulesLinkHere ) )


    if not moduleIsUsed then
if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) then
        table.insert( res, 1, messageBoxUnused( currentPageName:gsub( 'Module:', '' ), addCategories ) )
return templateDependencyList( currentPageName, addCategories )
    end
end


    return table.concat( res )
return moduleDependencyList( currentPageName, addCategories, isUsed )
end
end


return p
return p
-- </nowiki>

Latest revision as of 17:12, 25 August 2026

Documentation for this module may be created at Module:DependencyList/doc

require("strict")
local p = {}
local libraryUtil = require('libraryUtil')
local arr = require('Module:Array')
local yn = require('Module:Yesno')
local param = require('Module:Paramtest')
local dpl = require('Module:DPLlua')
local tooltip = require('Module:Tooltip')
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30
local dynamicRequireListQueryCache = {}

local builtins = {
	["libraryUtil"] = {
		link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil",
		categories = {},
	},
	["strict"] = {
		link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict",
		categories = { "[[Category:Strict mode modules]]" },
	},
}

-- Used in case 'require( varName )' is found. Attempts to find a string value stored in 'varName'.
local function substVarValue( moduleContent, varName )
	local res = moduleContent:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or moduleContent:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
	if res:find( '^(["\'])[Mm]odule:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
		return mw.text.trim( res )
	else
		return ''
	end
end

local function extractModuleName( capture, moduleContent )
	capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )

	if capture:find( '^(["\']).-%1$' ) then -- Check if it is already a pure string
		return capture
	elseif capture:find( '^[%a_][%w_]*$' ) then -- Check if if is a single variable
		return substVarValue( moduleContent, capture )
	end

	return capture
end

local function formatPageName( str )
	local name = mw.text.trim(str)
		:gsub( '^([\'\"])(.-)%1$', '%2' ) -- Only remove quotes at start and end of string if both are the same type
		:gsub( '_', ' ' )
		:gsub( '^.', string.upper )
		:gsub( '^([^:]-:)(.)', function(a,b) return a..string.upper(b) end )

	return name
end

local function formatModuleName( str, allowBuiltins )
	if allowBuiltins then
		local name = mw.text.trim(str)
			-- Only remove quotes at start and end of string if both are the same type
			:gsub([[^(['"])(.-)%1$]], '%2')

		if builtins[name] then
			return name
		end
	end

	local module = formatPageName( str )

	if not string.find( module, '^[Mm]odule:' ) then
		module = 'Module:' .. module
	end

	return module
end

local function dualGmatch( str, pat1, pat2 )
	local f1 = string.gmatch( str, pat1 )
	if pat2 then
		local f2 = string.gmatch( str, pat2 )
		return function()
			return f1() or f2()
		end
	else
		return f1
	end
end

local function isDynamicPath( str )
	return string.find( str, '%.%.' ) or string.find( str, '%%%a' )
end

-- Used in case a construct like 'require( "Module:wowee/" .. isTheBest )' is found.
-- Will return a list of pages which satisfy this pattern where 'isTheBest' can take any value.
local function getDynamicRequireList( query )
	if query:find( '%.%.' ) then
		query = mw.text.split( query, '..', true )
		query = arr.map( query, function(x) return (x:match('^%s*[\'\"](.-)[\'\"]%s*$') or '%') end )
		query = table.concat( query )
	else
		local _, _query = query:match( '(["\'])(.-)%1' )
		query = _query:gsub( '%%%a', '%%' ) -- Replace lua string.format specifiers with a dpl wildcard
	end
	query = query:gsub( '^[Mm]odule:', '' )

	query = mw.language.getContentLanguage():ucfirst(query)
	if query:find( '^Exchange/' ) or query:find( '^Data/' ) then
		return { 'Module:' .. query }   -- This format will later be used by formatDynamicQueryLink()
	end

	if dynamicRequireListQueryCache[ query ] then
		return dynamicRequireListQueryCache[ query ]
	end

	local list = dpl.ask{
		namespace = 'Module',
		titlematch = query,
		nottitlematch = '%/doc|'..query..'/%',
		distinct = 'strict',
		ordermethod = 'title',
		count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
		skipthispage = 'no',
		allowcachedresults = true,
		cacheperiod = 604800 -- One week
	}

	if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
		list = { 'Module:' .. query }
	end

	dynamicRequireListQueryCache[ query ] = list

	return list
end

--- Returns a list of modules loaded and required by module 'moduleName'.
local function getRequireLists( moduleContent )
	local requireList = arr{}
	local loadDataList = arr{}
	local loadJsonDataList = arr{}
	local dynamicRequirelist = arr{}
	local dynamicLoadDataList = arr{}
	local dynamicLoadJsonDataList = arr{}
	local extraCategories = arr{}

	local function getList( pat1, pat2, list, dynList )
		for match in dualGmatch( moduleContent, pat1, pat2 ) do
			match = mw.text.trim( match )
			local name = extractModuleName( match, moduleContent )

			if isDynamicPath( name ) then
				dynList:insert( getDynamicRequireList( name ), true )
			elseif name ~= '' then
				name = formatModuleName( name, true )
				table.insert( list, name )

				if builtins[name] then
					extraCategories = extraCategories:insert( builtins[name].categories, true )
				end
			end
		end
	end

	getList( 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)', requireList, dynamicRequirelist )
	getList( 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)', loadDataList, dynamicLoadDataList )
	getList( 'mw%.loadJsonData%s*(%b())', 'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)', loadJsonDataList, dynamicLoadJsonDataList )
	getList( 'pcall%s*%(%s*require%s*,([^%),]+)', nil, requireList, dynamicRequirelist )
	getList( 'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)', nil, loadDataList, dynamicLoadDataList )
	getList( 'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)', nil, loadJsonDataList, dynamicLoadJsonDataList )

	requireList = requireList .. dynamicRequirelist
	requireList = requireList:unique()
	loadDataList = loadDataList .. dynamicLoadDataList .. loadJsonDataList .. dynamicLoadJsonDataList
	loadDataList = loadDataList:unique()
	extraCategories = extraCategories:unique()
	table.sort( requireList )
	table.sort( loadDataList )
	table.sort( extraCategories )

	return {
		require = requireList,
		loadData = loadDataList,
		extraCategories = extraCategories,
	}
end

local function getUsedTemplatesList( moduleContent )
	local usedTemplateList = arr{}

	for preprocess in string.gmatch( moduleContent, ':preprocess%s*(%b())' ) do
		local function recursiveGMatch( str, pat )
			local list = {}
			local i = 0
			repeat
				for match in string.gmatch( list[i] or str, pat ) do
					table.insert( list, match )
				end
				i =  i + 1
			until i > #list or i > 100

			i = 0
			return function()
				i = i + 1
				return list[i]
			end
		end

		for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
			local name = string.match( template, '{(.-)[|{}]' )
			if name ~= '' then
				if name:find( ':' ) then
					local ns = name:match( '^(.-):' )
					if arr.contains( {'', 'template', 'calculator', 'user'}, ns:lower() ) then
						table.insert( usedTemplateList, name )
					elseif ns == ns:upper() then
						table.insert( usedTemplateList, ns ) -- Probably a magic word
					end
				else
					if name:match( '^%u+$' ) or name == '!' then
						table.insert( usedTemplateList, name ) -- Probably a magic word
					else
						table.insert( usedTemplateList, 'Template:'..name )
					end
				end
			end
		end
	end

	usedTemplateList = usedTemplateList:unique()
	table.sort( usedTemplateList )

	return usedTemplateList
end

-- Returns a list with module and function names used in all '{{#Invoke:moduleName|funcName}}' found on page 'templateName'.
local function getInvokeCallList( pageName )
	local pageContent = mw.title.new( pageName ):getContent()
	local invokeList = {}

	assert( pageContent, string.format( 'Failed to retrieve text content of page "%s"', pageName ) )

	for moduleName, funcName in string.gmatch( pageContent, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
		moduleName = formatModuleName( moduleName )
		funcName = mw.text.trim( funcName )
		if string.find( funcName, '^{{{' ) then
			funcName = funcName ..  '}}}'
		end
		table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
	end

	-- For form calcs invoking the module directly
	for config in dualGmatch( pageContent, '<[pd][ri][ev]%s+class%s*=%s*["\']jcConfig["\'](.-)</[pd][ri][ev]>', '{{[Ff]orm calculator%s*|(.+)}}' ) do
		local moduleName = string.match( config, 'module%s*=%s*(.-)[\n|]' )
		if param.has_content( moduleName ) then
			moduleName = formatModuleName( moduleName )
			local funcName = string.match( config, 'modulefunc%s*=%s*(.-)[\n|]' ) or 'main'
			table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
		end
	end

	invokeList = arr.unique( invokeList, function(x) return x.moduleName..x.funcName end )
	table.sort( invokeList, function(x, y) return x.moduleName..x.funcName < y.moduleName..y.funcName end )

	return invokeList
end

local function getInvokedByList( moduleName )
	local whatTemplatesLinkHere = dpl.ask( {
		namespace = 'Template|Calculator',
		linksto = moduleName,
		distinct = 'strict',
		ordermethod = 'title',
		allowcachedresults = true,
		cacheperiod = 604800 -- One week
	} )

	local function lcfirst( str )
		return string.gsub( str, '^[Mm]odule:.', string.lower )
	end

	local invokedByList = {}

	for _, templateName in ipairs( whatTemplatesLinkHere ) do
		local invokeList = getInvokeCallList( templateName )

		for _, invokeData in ipairs( invokeList ) do
			if lcfirst( invokeData.moduleName ) == lcfirst( moduleName ) then
				table.insert( invokedByList, { templateName=templateName, funcName=invokeData.funcName } )
			end
		end
	end

	return invokedByList
end

local function messageBoxUnused()
	local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
	html:tag( 'td' )
		:attr( 'width', '40xp' )
		:wikitext( '[[File:Willow logs (historical).png|center|30px|link=]]' )
	:done()
	:tag( 'td' )
		:wikitext( "'''This module is unused.'''" )
		:tag( 'div' )
			:css{ ['font-size']='0.85em', ['line-height']='1.45em' }
			:wikitext( 'This module is neither invoked by a template nor required/loaded by another module. If this is in error, make sure to add <code>{{[[Template:Documentation|Documentation]]}}</code>/<code>{{[[Template:No documentation|No&nbsp;documentation]]}}</code> to the calling template\'s or parent\'s module documentation.' )
		:done()
	:done()

	return tostring( html )
end

local function collapseList( list, id, listType )
	local text = string.format( '%d %s', #list, listType )
	local button = tooltip._span{ name=id, alt=text }
	list = arr.map( list, function(x) return '\n# '..x end )
	local content = tooltip._div{ name=id, content='\n'..table.concat( list )..'\n\n' }

	return { tostring( button ) .. tostring( content ) }
end

-- Creates a link to [[Special:Search]] showing all pages found by getDynamicRequireList() in case it found more than MAX_DYNAMIC_REQUIRE_LIST_LENGTH pages.
-- Input query uses DPL % wildcards like 'Module:Wowee/%' or 'Module:Wowee/%/data'
local function formatDynamicQueryLink( query )
	local prefix = query:match( '^([^/]+)' )
	local linkText = query:gsub( '%%', '&lt; ... &gt;' )

	query = query:gsub( '^Module:',  '' )

	query = query:gsub( '([^/]+)/?', function ( match )
		if match == '%' then
			return '\\/[^\\/]+'
		else
			return '\\/"' .. match .. '"'
		end
	end )

	query = query:gsub( '^\\/', '' )

	query = string.format(
		'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
		query,
		query:find( '"$' ) and '' or '""',
		query,
		prefix
	)

	return string.format( '<span class="plainlinks">[%s %s]</span>', tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
end

local function formatModuleLinks( pages )
	local links = arr{}

	for _, moduleName in ipairs(pages) do
		if moduleName:find( '%%' ) then
			links:insert( formatDynamicQueryLink( moduleName ) )
		elseif builtins[moduleName] then
			links:insert( '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]' )
		else
			links:insert( '[[' .. moduleName .. ']]' )
		end
	end

	return links
end

local function formatTemplateLinks( pages )
	local links = arr{}

	for _, templateName in ipairs(pages) do
		if string.find( templateName, ':' ) then -- Real templates are prefixed by a namespace, magic words are not
			links:insert( '[['..templateName..']]' )
		else
			links:insert( "'''&#123;&#123;"..templateName.."&#125;&#125;'''" ) -- Magic words don't have a page so make them bold instead
		end
	end

	return links
end

local function formatInvokeCallList( templateName, invokeList )
	local res = {}

	for _, item in ipairs( invokeList ) do
		table.insert( res, string.format(
			"<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[RuneScape:Lua|Lua]].</div>",
			templateName,
			item.funcName,
			item.moduleName
		) )
	end

	return table.concat( res )
end

local function formatInvokedByList( moduleName, invokedByList )
	for i, invoke in ipairs( invokedByList ) do
		invokedByList[i] = string.format( "function '''%s''' is invoked by [[%s]]", invoke.funcName, invoke.templateName )
	end

	table.sort( invokedByList)

	local res = {}

	if #invokedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
		table.insert( res, string.format(
			"<div class='seealso'>'''%s''' is invoked by %s.</div>",
			moduleName,
			collapseList( invokedByList, 'invokedBy', 'templates' )[1]
		) )
	else
		for _, item in ipairs( invokedByList ) do
			table.insert( res, string.format(
				"<div class='seealso'>'''%s's''' %s.</div>",
				moduleName,
				item
			) )
		end
	end

	return table.concat( res )
end

local function formatRequiredByList( moduleName, requiredByLists )
	local requiredByList = formatModuleLinks( requiredByLists.require )
	local loadedByList = formatModuleLinks( requiredByLists.loadData )

	if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
		requiredByList = collapseList( requiredByList, 'requiredBy', 'modules' )
	end

	if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
		loadedByList = collapseList( loadedByList, 'loadedBy', 'modules' )
	end

	local res = {}

	for _, requiredByModuleName in ipairs( requiredByList ) do
		table.insert( res, string.format(
			"<div class='seealso'>'''%s''' is required by %s.</div>",
			moduleName,
			requiredByModuleName
		) )
	end

	for _, loadedByModuleName in ipairs( loadedByList ) do
		table.insert( res, string.format(
			"<div class='seealso'>'''%s''' is loaded by %s.</div>",
			moduleName,
			loadedByModuleName
		) )
	end

	return table.concat( res )
end

local function formatImportList( currentPageName, moduleList, id, message )
	moduleList = formatModuleLinks( moduleList )

	if #moduleList > COLLAPSE_LIST_LENGTH_THRESHOLD then
		moduleList = collapseList( moduleList, id, 'modules' )
	end

	local res = arr.map( moduleList, function( moduleName )
		return '<div class="seealso">' .. string.format( message, currentPageName, moduleName ) .. '</div>'
	end )

	return table.concat( res )
end

local function formatUsedTemplatesList( currentPageName, usedTemplateList )
	usedTemplateList = formatTemplateLinks( usedTemplateList )
	local res = {}

	if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
		usedTemplateList = collapseList( usedTemplateList, 'usedTemplates', 'templates' )
	end

	for _, templateName in ipairs( usedTemplateList ) do
		table.insert( res, string.format(
			"<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp>.</div>",
			currentPageName,
			templateName
		) )
	end

	return table.concat( res )
end

local function setBucketFields( requireLists )
	if mw.title.getCurrentTitle().subpageText ~= 'doc' and (#requireLists.require > 0 or #requireLists.loadData > 0) then
		bucket( 'dependency_list' ).put{
			require = requireLists.require,
			load_data = requireLists.loadData
		}
	end
end

local function getRequiredByLists( currentPageName )
	local requiredByListRaw = bucket( 'dependency_list' ).select( 'page_name' ).where( 'require', currentPageName ).run()
	local loadedByListRaw = bucket( 'dependency_list' ).select( 'page_name' ).where( 'load_data', currentPageName ).run()
	local requiredByList = {}
	local loadedByList = {}

	for _, bucketItem in ipairs( requiredByListRaw ) do
		table.insert( requiredByList, bucketItem.page_name )
	end
	for _, bucketItem in ipairs( loadedByListRaw ) do
		table.insert( loadedByList, bucketItem.page_name )
	end

	requiredByList = arr.unique( requiredByList )
	loadedByList = arr.unique( loadedByList )
	table.sort( requiredByList )
	table.sort( loadedByList )

	return {
		require = requiredByList,
		loadData = loadedByList
	}
end

local function templateDependencyList( currentPageName, addCategories )
	local invokeList = getInvokeCallList( currentPageName )
	local res = formatInvokeCallList( currentPageName, invokeList )

	if addCategories and #invokeList > 0 then
		res = res .. '[[Category:Lua-based templates]]'
	end

	return res
end

local function moduleDependencyList( currentPageName, addCategories, isUsed )
	local moduleContent = mw.title.new( currentPageName ):getContent()
	assert( moduleContent, string.format( 'Failed to retrieve text content of page "%s"', currentPageName ) )
	moduleContent = moduleContent:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' ) -- Strip comments

	local requireLists = getRequireLists( moduleContent )
	local usedTemplateList = getUsedTemplatesList( moduleContent )
	local requiredByLists = getRequiredByLists( currentPageName )
	local invokedByList = getInvokedByList( currentPageName )

	setBucketFields( requireLists )

	local res = arr{}

	res:insert( formatInvokedByList( currentPageName, invokedByList ) )
	res:insert( formatImportList( currentPageName, requireLists.require, 'require', "'''%s''' requires %s." ) )
	res:insert( formatImportList( currentPageName, requireLists.loadData, 'loadData', "'''%s''' loads data from %s." ) )
	res:insert( formatUsedTemplatesList( currentPageName, usedTemplateList ) )
	res:insert( formatRequiredByList( currentPageName, requiredByLists ) )

	if addCategories then
		res:insert( requireLists.extraCategories, true )

		if #requireLists.require > 0 then
			res:insert( '[[Category:Modules requiring modules]]')
		end
		if #requireLists.loadData > 0 then
			res:insert( '[[Category:Modules using data]]')
		end
		if #requiredByLists.require > 0 then
			res:insert( '[[Category:Modules required by modules]]')
		end
		if #requiredByLists.loadData > 0 then
			res:insert( '[[Category:Module data]]')
		end
		if #invokedByList > 0 then
			res:insert( '[[Category:Template invoked modules]]')
		end
	end

	if
		not (
			yn( isUsed )
			or currentPageName:lower():find( 'sandbox' )
			or #requiredByLists.require > 0
			or #requiredByLists.loadData > 0
			or #invokedByList > 0
		)
	then
		table.insert( res, 1, messageBoxUnused() )

		if addCategories then
			res:insert( '[[Category:Unused modules]]')
		end
	end

	return table.concat( res )
end

function p.main( frame )
	local args = frame:getParent().args
	return p._main( args[1], args.category, args.isUsed )
end

function p._main( currentPageName, addCategories, isUsed )
	libraryUtil.checkType( 'Module:RequireList._main', 1, currentPageName, 'string', true )
	libraryUtil.checkTypeMulti( 'Module:RequireList._main', 2, addCategories, {'boolean', 'string', 'nil'} )
	libraryUtil.checkTypeMulti( 'Module:RequireList._main', 3, isUsed, {'boolean', 'string', 'nil'} )

	local title = mw.title.getCurrentTitle()

	-- Leave early if not in module, template or calculator namespace or if module is part of exchange or data groups
	if param.is_empty( currentPageName ) and (
		( not arr.contains( {'Module', 'Template', 'Calculator'}, title.nsText ) ) or
		( title.nsText == 'Module' and ( arr.contains( {'Exchange', 'Exchange historical', 'Data'}, title.text:match( '^(.-)/' ) ) ) )
	) then
		return ''
	end

	currentPageName = param.default_to( currentPageName, title.fullText )
	currentPageName = string.gsub( currentPageName, '/[Dd]oc$', '' )
	currentPageName = formatPageName( currentPageName )

	if (addCategories == nil) then
		addCategories = title.subpageText~='doc'
	end
	addCategories = yn(addCategories)

	if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) then
		return templateDependencyList( currentPageName, addCategories )
	end

	return moduleDependencyList( currentPageName, addCategories, isUsed )
end

return p