-- Common LPEG parsers used by different modules of the static analyzer explcheck.

local latex3 = require("explcheck-latex3")
local get_option = require("explcheck-config").get_option

local lpeg = require("lpeg")
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local C, Cb, Cc, Cg, Cp, Cs, Ct, Cmt = lpeg.C, lpeg.Cb, lpeg.Cc, lpeg.Cg, lpeg.Cp, lpeg.Cs, lpeg.Ct, lpeg.Cmt

-- Base parsers
---- Generic
local any = P(1)
local eof = -any
local fail = P(false)
local success = P(true)

---- Tokens
local ampersand = P("&")
local backslash = P([[\]])
local slash = P("/")
local circumflex = P("^")
local colon = P(":")
local comma = P(",")
local control_character = R("\x00\x1F") + P("\x7F")
local dollar_sign = P("$")
local form_feed = P("\x0C")
local hash_sign = P("#")
local lbrace = P("{")
local letter = R("AZ", "az")
local percent_sign = P("%")
local rbrace = P("}")
local tilde = P("~")
local underscore = P("_")
local decimal_digit = R("09")
local lowercase_hexadecimal_digit = decimal_digit + R("af")
local lower_half_ascii_character = R("\x00\x3F")
local upper_half_ascii_character = R("\x40\x7F")

---- Spacing
local newline = (
  P("\n")
  + P("\r\n")
  + P("\r")
)
local linechar = any - newline
local space = P(" ")
local tab = P("\t")

---- Comma-lists
local function comma_list(item_parser)
  return Ct(
    eof
    + C(item_parser)
    * (
      P(",") * C(item_parser)
    )^0
    * P(",")^-1
    * eof
  )
end

-- Intermediate parsers
---- Default expl3 category code table, corresponds to `\c_code_cctab` in expl3
local expl3_endlinechar = ' '
local expl3_catcodes = {
  [0] = backslash,  -- escape character
  [1] = lbrace,  -- begin grouping
  [2] = rbrace,  -- end grouping
  [3] = dollar_sign,  -- math shift
  [4] = ampersand,  -- alignment tab
  [5] = newline,  -- end of line
  [6] = hash_sign,  -- parameter
  [7] = circumflex,  -- superscript
  [8] = fail,  -- subscript
  [9] = space + tab,  -- ignored character
  [10] = tilde,  -- space
  [11] = letter + colon + underscore,  -- letter
  [13] = form_feed,  -- active character
  [14] = percent_sign,  -- comment character
  [15] = control_character - newline,  -- invalid character
}
expl3_catcodes[12] = any  -- other
for catcode = 0, 15 do
  local parser = expl3_catcodes[catcode]
  if catcode ~= 12 then
    expl3_catcodes[12] = expl3_catcodes[12] - parser
  end
end

local determine_expl3_catcode = fail
for catcode = 0, 15 do
  local parser = expl3_catcodes[catcode]
  determine_expl3_catcode = (
    determine_expl3_catcode
    + parser
    / function()
      return catcode
    end
  )
end

---- Syntax recognized by TeX's input and token processors
local optional_spaces = expl3_catcodes[9]^0
local optional_spaces_and_newline = (
  optional_spaces
  * (
    newline
    * optional_spaces
  )^-1
)
local blank_line = (
  optional_spaces
  * newline
)
local blank_or_empty_last_line = (
  optional_spaces
  * (
    newline
    + eof
  )
)
local tex_line = (
  (
    (
      linechar
      - (expl3_catcodes[9] * #blank_or_empty_last_line)
    )^1
    * (
      blank_or_empty_last_line / ""
    )
  )
  + (
    (
      linechar
      - (expl3_catcodes[9] * #blank_line)
    )^0
    * (
      blank_line / ""
    )
  )
)
local tex_lines = Ct(
  Ct(
    Cp()
    * Cs(tex_line)
    * Cp()
  )^0
)

local double_superscript_convention = (
  Cmt(
    C(expl3_catcodes[7]),
    function(input, position, capture)
      if input:sub(position, position) == capture then
        return position + 1
      else
        return nil
      end
    end
  )
  * (
    C(lowercase_hexadecimal_digit * lowercase_hexadecimal_digit)
    / function(hexadecimal_digits)
      return string.char(tonumber(hexadecimal_digits, 16)), 4
    end
    + C(lower_half_ascii_character)
    / function(character)
      return string.char(string.byte(character) + 64), 3
    end
    + C(upper_half_ascii_character)
    / function(character)
      return string.char(string.byte(character) - 64), 3
    end
  )
)

---- Arguments and argument specifiers
local argument = (
  expl3_catcodes[1]
  * (any - expl3_catcodes[2])^0
  * expl3_catcodes[2]
)

local N_type_argument_specifier = S("NV")
local n_type_argument_specifier = S("ncvoxefTF")
local x_type_argument_specifier = S("x")
local csname_argument_specifier = S("Nc")
local expansionless_argument_specifier = S("NVnTF")
local parameter_argument_specifier = S("p")
local weird_argument_specifier = S("w")
local do_not_use_argument_specifier = S("D")
local N_or_n_type_argument_specifier = (
  N_type_argument_specifier
  + n_type_argument_specifier
)
local N_or_n_type_argument_specifiers = (
  N_or_n_type_argument_specifier^0
  * eof
)
local argument_specifier = (
  N_type_argument_specifier
  + n_type_argument_specifier
  + parameter_argument_specifier
  + weird_argument_specifier
  + do_not_use_argument_specifier
)
local argument_specifiers = (
  argument_specifier^0
  * eof
)
local variant_argument_specifiers = comma_list(argument_specifier^0)

local function any_argument_specifiers(parser)
  return (any - parser)^0 * parser
end

local x_type_argument_specifiers = any_argument_specifiers(x_type_argument_specifier)
local do_not_use_argument_specifiers = any_argument_specifiers(do_not_use_argument_specifier)

local compatible_argument_specifiers = (
  P("N") * Cc({"N", "c"})
  + P("n") * Cc({"n", "o", "V", "v", "f", "e", "x"})
  + Ct(C(S("TFp")))
  + Cc({})
)
local deprecated_argument_specifiers = (
  P("n") * Cc({"N", "c"})
  + P("N") * Cc({"n", "o", "V", "v", "f", "e", "x"})
  + Cc({})
)

---- Expl3 control sequence names
local expl3_function_csname = (
  (underscore * underscore)^-1 * letter^1  -- module
  * underscore
  * letter * (letter + underscore)^0  -- description
  * colon
  * argument_specifier^0  -- argspec
  * #(eof + -letter)
)

local any_type = C(
  letter^1  -- type
  * #(
    eof
    + (
      any
      - letter
      - underscore
      - colon
    )
  )
)
local any_expl3_variable_or_constant_csname = (
  S("cgl")  -- scope
  * underscore
  * (
    letter * (letter + underscore * -#any_type)^0  -- just description
    + underscore^-1 * letter^1  -- module
    * underscore
    * letter * (letter + underscore * -#any_type)^0  -- description
  )
  * underscore
  * any_type
)

local expl3like_material = (
  expl3_catcodes[0]
  * (
    expl3_function_csname
    + any_expl3_variable_or_constant_csname
  )
  / 0
)

local expl3_expandable_variable_or_constant_type = (
  P("bitset")
  + P("clist")
  + P("dim")
  + P("fp") * -#P("array")
  + P("int") * -#P("array")
  + P("muskip")
  + P("skip")
  + P("str")
  + P("tl")
  + P("toks")
)
local expl3_unexpandable_variable_or_constant_type = (
  P("bool")
  + P("cctab")
  + S("hv")^-1 * P("box")
  + P("coffin")
  + P("flag")
  + P("fparray")
  + P("intarray")
  + P("io") * S("rw")
  + P("keyval")
  + P("prop")
  + P("quark")
  + P("regex")
  + P("scan")
  + P("seq")
)

local expl3_variable_or_constant_type = (
  expl3_expandable_variable_or_constant_type
  + expl3_unexpandable_variable_or_constant_type
)

local expl3_unexpandable_variable_or_constant_csname = (
  (
    -#(expl3_unexpandable_variable_or_constant_type * eof)
    * (any - underscore)^0
    * underscore
  )^0
  * C(expl3_unexpandable_variable_or_constant_type)
  * eof
)

local expl3_well_known_prefixes = (
  expl3_variable_or_constant_type
  + P("benchmark")
  + P("char")
  + P("codepoint")
  + S("hv") * P("coffin")
  + P("color")
  + P("cs")
  + P("debug")
  + P("draw")
  + P("exp")
  + P("file")
  + P("graphics")
  + P("graph")  -- part of the lt3graph package
  + P("group")
  + P("hook")  -- part of the lthooks module
  + P("if")
  + P("keys")
  + P("keyval")
  + P("legacy")
  + P("lua")
  + P("mark")  -- part of the ltmarks module
  + P("mode")
  + P("msg")
  + P("opacity")
  + P("para")  -- part of the ltpara module
  + P("pdf")
  * (
    P("annot")  -- part of the l3pdfannot module
    + P("dict")  -- part of the l3pdfdict module
    + P("field")  -- part of the l3pdffield module
    + P("file")  -- part of the l3pdffile module
    + P("management")  -- part of the l3pdfmanagement module
    + P("meta")  -- part of the l3pdfmeta module
    + P("xform")  -- part of the l3pdfxform module
  )^0
  + P("peek")
  + P("prg")
  + P("property")  -- part of the ltproperties module
  + P("quark")
  + P("reverse_if")
  + P("scan")
  + P("socket")  -- part of the ltsockets module
  + P("sort")
  + P("sys")
  + P("tag")  -- part of the tagpdf package
  + P("text")
  + P("token")
  + P("use")
  + P("withargs")  -- part of the withargs package
)

local function latex3_prefixes(options, pathname)
  local l3prefixes_max_first_registered_date = get_option("l3prefixes_max_first_registered_date", options, pathname)

  return Cmt(
    latex3.prefixes,
    function(_, _, maybe_first_registered_date)
      return (
        not l3prefixes_max_first_registered_date  -- no maximum first registered date has been specified by us
        or maybe_first_registered_date ~= nil  -- actual first registered date has been specified in the file "l3prefixes.csv"
        and maybe_first_registered_date <= l3prefixes_max_first_registered_date  -- and this actual date is less than our maximum
      )
    end
  )
end
local function latex3_csname(definition_type, options, pathname)
  local latex3_definitions_max_added_date = get_option("latex3_definitions_max_added_date", options, pathname)

  return (
    Cg(latex3.definitions[definition_type], "definition")
    * Cmt(
      Cb("definition"),
      function(_, _, definition)
        return (
          not latex3_definitions_max_added_date  -- no maximum added date has been specified by us
          or (definition ~= nil and definition.added_date ~= nil)  -- actual added date has been specified in "l3*.dtx" files
          and definition.added_date <= latex3_definitions_max_added_date  -- and this actual date is less than our maximum
        )
      end
    )
    * Cb("definition")
  )
end

local function expl3_well_known_csname(options, pathname)
  local imported_prefixes = get_option('imported_prefixes', options, pathname)
  local defined_csnames = get_option('defined_csnames', options, pathname)

  local other_prefixes = fail
  for _, prefix_text in ipairs(imported_prefixes) do
    other_prefixes = (
      other_prefixes +
      #(P(prefix_text) * (underscore + colon))
      * P(prefix_text)
    )
  end
  local _latex3_prefixes = latex3_prefixes(options, pathname)
  local prefix = (
    #(expl3_well_known_prefixes * (underscore + colon))
    * expl3_well_known_prefixes
    + #(_latex3_prefixes * (underscore + colon))
    * _latex3_prefixes
    + other_prefixes
  )

  local defined_csname
  if #defined_csnames > 0 then
    local defined_csname_index = {}
    for _, csname in ipairs(defined_csnames) do
      defined_csname_index[csname] = true
    end
    defined_csname = Cmt(
      C(any^1),
      function(_, _, csname)
        return defined_csname_index[csname] == true
      end
    )
  else
    defined_csname = fail
  end

  local well_known_function_csname = (
    P("__")^-1
    * prefix
    * (
      underscore
      * (any - colon)^0
    )^0
    * colon
    + latex3_csname("function", options, pathname)
  )
  local well_known_variable_or_constant_csname = (
    S("cgl")  -- scope
    * underscore
    * underscore^-1
    * prefix
    * underscore
    + latex3_csname("variable", options, pathname)
  )

  return (
    P("q_no_value")
    + defined_csname
    + well_known_function_csname
    + well_known_variable_or_constant_csname
  )
end

local function expl3_deprecated_csname(l3obsolete_max_deprecated_date)
  return Cmt(
    latex3.obsolete.deprecated_csname,
    function(_, _, maybe_deprecated_date)
      return (
        not l3obsolete_max_deprecated_date  -- no maximum deprecation date has been specified by us
        or maybe_deprecated_date  -- actual deprecation date has been specified in the file `l3obsolete.txt`
        and maybe_deprecated_date <= l3obsolete_max_deprecated_date  -- and this actual date is less than our maximum
      )
    end
  )
end

local expl3like_function_with_underscores_csname = (
  underscore^0
  * letter^1
  * underscore  -- a csname with at least one underscore in the middle
  * (letter + underscore)^1
  * (
    colon
    * letter^0
  )^-1
  * eof
)
local expl3like_function_csname = (
  underscore^0
  * letter^1
  * (letter + underscore)^0
  * colon  -- a csname with at least one colon at the end
  * letter^0
  * eof
)
local expl3like_csname = (
  expl3like_function_with_underscores_csname
  + expl3like_function_csname
)

local expl3_function_with_boolean_expression_argument_csname = (
  P("bool")
  * underscore
  * (
    P("do_until:n") * Cc({1})
    + P("do_while:n") * Cc({1})
    + P("if:n") * Cc({1})
    + P("if_p:n") * Cc({1})
    + P("lazy_all:n") * Cc({1})  -- TODO: Recognize these arguments separately as containing a list of boolean expressions.
    + P("lazy_all_p:n") * Cc({1})  -- TODO: Recognize these arguments separately as containing a list of boolean expressions.
    + P("lazy_and:nn") * Cc({1, 2})
    + P("lazy_and_p:nn") * Cc({1, 2})
    + P("lazy_any:n") * Cc({1})  -- TODO: Recognize these arguments separately as containing a list of boolean expressions.
    + P("lazy_any_p:n") * Cc({1})  -- TODO: Recognize these arguments separately as containing a list of boolean expressions.
    + P("lazy_or:nn") * Cc({1, 2})
    + P("lazy_or_p:nn") * Cc({1, 2})
    + P("lazy_xor:nn") * Cc({1, 2})
    + P("lazy_xor_p:nn") * Cc({1, 2})
    + P("log:n") * Cc({1})
    + P("show:n") * Cc({1})
    + P("not_p:n") * Cc({1})
    + P("to_str:n") * Cc({1})
    + P("until_do:n") * Cc({1})
    + P("while_do:n") * Cc({1})
  )
  + P("debug_assert:nn") * Cc({2})
  + Cc({})
)

---- Comments
local commented_line_letter = (
  linechar
  + newline
  - expl3_catcodes[0]
  - expl3_catcodes[9]
  - expl3_catcodes[14]
)
local function commented_line(closer)
  return (
    (
      commented_line_letter
      - closer
    )^1  -- initial state
    + (
      expl3_catcodes[0]  -- even backslash
      * (
        expl3_catcodes[0]
        + #closer
      )
    )^1
    + (
      expl3_catcodes[0]  -- odd backslash
      * (
        expl3_catcodes[9]
        + expl3_catcodes[14]
        + commented_line_letter
      )
    )
    + (
      #(
        expl3_catcodes[9]^1
        * -expl3_catcodes[14]
      )
      * expl3_catcodes[9]^1  -- spaces
    )
  )^0
  * (
    #(
      expl3_catcodes[9]^0
      * expl3_catcodes[14]
    )
    * Cp()
    * (
      (
        expl3_catcodes[9]^0
        * expl3_catcodes[14]  -- comment
        * linechar^0
        * Cp()
        * closer
        * (
          #blank_line  -- blank line
          + expl3_catcodes[9]^0  -- leading spaces
        )
      )
    )
    + closer
  )
end

local commented_lines = Ct(
  commented_line(newline)^0
  * commented_line(eof)
  * eof
  + eof
)

------ Explcheck issues
local issue_code_prefix = (
  S("EeSsTtWw")
  * decimal_digit^-3
)
local ignored_issues = (
  optional_spaces
  * Cp()
  * expl3_catcodes[14]
  * (
    optional_spaces
    * expl3_catcodes[14]
  )^0
  * optional_spaces
  * P("noqa")
  * Ct(
    P(":")
    * optional_spaces
    * (
      Cs(issue_code_prefix)
      * optional_spaces
      * comma
      * optional_spaces
    )^0
    * Cs(issue_code_prefix)
    * optional_spaces
    + optional_spaces
  )
  * eof
)

---- Standard delimiters
local provides = (
  expl3_catcodes[0]
  * P("ProvidesExpl")
  * (
      P("Package")
      + P("Class")
      + P("File")
    )
  * optional_spaces_and_newline
  * argument
  * optional_spaces_and_newline
  * argument
  * optional_spaces_and_newline
  * argument
  * optional_spaces_and_newline
  * argument
)
local expl_syntax_on = expl3_catcodes[0] * P("ExplSyntaxOn")
local expl_syntax_off = expl3_catcodes[0] * P("ExplSyntaxOff")
local endinput = (
  expl3_catcodes[0]
  * (
    P("tex_endinput:D")
    + P("endinput")
    + P("file_input_stop:")
  )
)

---- Commands from LaTeX style files
local latex_style_file_csname =
(
  -- LaTeX2e package writer commands
  -- See <https://www.latex-project.org/help/documentation/clsguide.pdf>.
  P("AddToHook")
  + P("AtBeginDocument")
  + P("AtEndDocument")
  + P("AtEndOfClass")
  + P("AtEndOfPackage")
  + P("BCPdata")
  + P("CheckCommand")
  + P("ClassError")
  + P("ClassInfo")
  + P("ClassWarning")
  + P("ClassWarningNoLine")
  + P("CurrentOption")
  + P("DeclareInstance")
  + P("DeclareKeys")
  + P("DeclareOption")
  + P("DeclareRobustCommand")
  + P("DeclareTemplateCode")
  + P("DeclareTemplateInterface")
  + P("DeclareUnknownKeyHandler")
  + P("ExecuteOptions")
  + P("IfClassAtLeastTF")
  + P("IfClassLoadedTF")
  + P("IfClassLoadedWithOptionsTF")
  + P("IfFileAtLeastTF")
  + P("IfFileExists")
  + P("IfFileLoadedTF")
  + P("IfFormatAtLeastTF")
  + P("IfPackageAtLeastTF")
  + P("IfPackageLoadedTF")
  + P("IfPackageLoadedWithOptionsTF")
  + P("InputIfFileExists")
  + P("LinkTargetOff")
  + P("LinkTargetOn")
  + P("LoadClass")
  + P("LoadClassWithOptions")
  + P("MakeLinkTarget")
  + P("MakeLowercase")
  + P("MakeTitlecase")
  + P("MakeUppercase")
  + P("MessageBreak")
  + P("NeedsTeXFormat")
  + P("NewDocumentCommand")
  + P("NewDocumentEnvironment")
  + P("NewProperty")
  + P("NewTemplateType")
  + P("NextLinkTarget")
  + P("OptionNotUsed")
  + P("PackageError")
  + P("PackageInfo")
  + P("PackageWarning")
  + P("PackageWarningNoLine")
  + P("PassOptionsToClass")
  + P("PassOptionsToPackage")
  + P("ProcessKeyOptions")
  + P("ProcessOptions")
  + P("ProvidesClass")
  + P("ProvidesFile")
  + P("ProvidesPackage")
  + P("RecordProperties")
  + P("RefProperty")
  + P("RefUndefinedWarn")
  + P("RequirePackage")
  + P("RequirePackageWithOptions")
  + P("SetKeys")
  + P("SetProperty")
  + P("UseInstance")
  -- LaTeX3 package writer commands
  + P("ProvidesExplClass")
  + P("ProvidesExplPackage")
  -- Other LaTeX2e commands
  -- See <http://mirrors.ctan.org/macros/latex/base/source2e.pdf>.
  + P("@gobble")
  + P("@ifpackagelater")
  + P("@ifpackageloaded")
)

local latex_style_file_content = (
  (
    any
    - #(
      expl3_catcodes[0]
      * latex_style_file_csname
    )
  )^0
  * expl3_catcodes[0]
  * latex_style_file_csname
)

---- Argument expansion functions from the module l3expan
local expl3_expansion_csname = (
  P("exp")
  * underscore
  * letter * (letter + underscore)^0
  * colon
)

---- Functions and conditional functions
------ Function definitions
local expl3_function_definition_type_signifier = (
  P("new") * Cc(false) * Cc(true)  -- definition
  + (  -- assignment
    C(true)
    * (
      P("gset") * Cc(true)  -- global
      + P("set") * Cc(false)  -- local
    )
  )
)
local expl3_direct_function_definition_csname = (
  (
    P("cs_") * Cc(false)  -- non-conditional function
    * (
      P("generate_from_arg_count") * Cc(false)  -- indirect application of a creator function
      + Cc(true) * expl3_function_definition_type_signifier  -- direct application of a creator function
      * (P("_protected") * Cc(true) + Cc(false))
      * (P("_nopar") * Cc(true) + Cc(false))
    )
    + P("prg_") * Cc(true)  -- conditional function
    * Cc(true)  -- conditional functions don't support indirect application of a creator function
    * expl3_function_definition_type_signifier
    * (P("_protected") * Cc(true) + Cc(false))
    * Cc(false)  -- conditional functions cannot be "nopar"
    * P("_conditional")
  )
  * colon
  * argument_specifier
)
local expl3_indirect_function_definition_csname = (
  (
    P("cs_") * Cc(false)  -- non-conditional function
    * expl3_function_definition_type_signifier
    * P("_eq")
    + P("prg_") * Cc(true)  -- conditional function
    * expl3_function_definition_type_signifier
    * P("_eq_conditional")
  )
  * colon
  * argument_specifier
  * argument_specifier
)
local expl3_function_definition_csname = Ct(
  Cc(true) * expl3_direct_function_definition_csname
  + Cc(false) * expl3_indirect_function_definition_csname
)

------ Function undefinitions
local expl3_function_undefinition_csname = (
  P("cs_undefine")
  * colon
  * argument_specifier
)

------ Generating function variants
local expl3_function_variant_definition_csname = Ct(
  (
    -- A non-conditional function
    P("cs_generate_variant") * Cc(false)
    -- A conditional function
    + P("prg_generate_conditional_variant") * Cc(true)
  )
  * colon
  * S("Nc")
)

------ Function calls with Lua arguments
local expl3_function_call_with_lua_code_argument_csname = Ct(
  P("lua")
  * underscore
  * (
    P("now")
    + P("shipout")
  )
  * colon
  * S("noex")
  * eof
  * Cc(1)
  + success
)

------ Conditions in a conditional function definition
local condition = (
  P("p")
  + P("T") * P("F")^-1
  + P("F")
)
local conditions = comma_list(condition)

---- Variables and constants
------ Variable names
local expl3_variable_or_constant_csname = (
  S("cgl")  -- scope
  * underscore
  * (
    underscore^-1 * letter^1  -- module
    * underscore
    * letter * (letter + underscore * -#(expl3_variable_or_constant_type * eof))^0  -- description
  )
  * underscore
  * expl3_variable_or_constant_type  -- type
  * eof
)
local expl3_variable_or_constant_csname_scope = (
  C(S("cgl"))  -- scope
  * underscore
)
local expl3_variable_or_constant_csname_type = (
  (any - underscore)^0  -- scope
  * underscore^1
  * (any - underscore)^1  -- module and description
  * (any - #(underscore * expl3_variable_or_constant_type * eof))^0
  * underscore
  * C(expl3_variable_or_constant_type)  -- type
  * eof
)
local expl3_scratch_variable_csname = (
  S("gl")
  * underscore
  * P("tmp") * S("ab")
  * underscore
  * expl3_variable_or_constant_type
  * eof
)
local expl3_quark_or_scan_mark_csname = (
  S("qs")
  * underscore
)

------ Variable declarations
local expl3_variable_declaration_csname = Ct(
  C(expl3_variable_or_constant_type)
  * underscore
  * (
    P("g")^-1
    * (
      P("zero")
      + P("clear")
    )
    * underscore
  )^-1
  * P("new")
  * P("_linked")^-1
  * colon
)

------ Variable and constant definitions
local expl3_variable_definition_csname = Ct(
  Cg(expl3_variable_or_constant_type, "variable_type")
  * Cb("variable_type")
  * underscore
  * (
    Cc(true)^-2  -- constant definition
    * P("const")
    + Cc(false)  -- variable definition
    * (
      P("gset") * Cc(true)  -- global
      + P("set") * Cc(false)  -- local
    )
  )
  * P("_linked")^-1
  * Cg(Cb("variable_type"), "base_variable_type")
  * (
    underscore
    * (
      P("eq")
      + P("from")
      * underscore
      * Cg(expl3_variable_or_constant_type, "base_variable_type")
    )
    * P(":")
    * csname_argument_specifier
    * (
      Cc(false)  -- indirect
      * csname_argument_specifier
      + Cc(true)  -- direct
    )
    + Cc(true)  -- direct
    * P(":")
  )
  * Cb("base_variable_type")
)

------ Variable and constant use
local expl3_variable_use_csname = Ct(
  C(expl3_variable_or_constant_type)
  * underscore
  * (
    P("count")
    + P("open")
    + P("show")
    + P("use")
    + P("log")
  )
  * P(":")
)

---- Messages
------ Message names
local function expl3_well_known_message_name(options, pathname)
  local imported_prefixes = get_option('imported_prefixes', options, pathname)

  local other_prefixes = fail
  for _, prefix_text in ipairs(imported_prefixes) do
    other_prefixes = (
      other_prefixes
      + #(P(prefix_text) * slash)
      * P(prefix_text)
    )
  end
  local _latex3_prefixes = latex3_prefixes(options, pathname)
  return (
    #(expl3_well_known_prefixes * slash)
    * expl3_well_known_prefixes
    + #(_latex3_prefixes * slash)
    * _latex3_prefixes
    + other_prefixes
  )
end

------ Message definitions
local expl3_message_definition = (
  P("msg")
  * underscore
  * (
    P("new")
    + P("g")^-1
    * P("set")
  )
  * colon
)

------ Message use
local expl3_message_use = (
  P("msg")
  * underscore
  * (
    P("none")
    + P("show")
    + P("term")
    + P("log")
    + P("info")
    + P("note")
    + P("warning")
    + P("error")
    + P("expandable_error")
    + P("critical")
    + P("fatal")
  )
  * colon
)

return {
  any = any,
  any_expl3_variable_or_constant_csname = any_expl3_variable_or_constant_csname,
  argument_specifiers = argument_specifiers,
  commented_lines = commented_lines,
  compatible_argument_specifiers = compatible_argument_specifiers,
  condition = condition,
  conditions = conditions,
  decimal_digit = decimal_digit,
  deprecated_argument_specifiers = deprecated_argument_specifiers,
  determine_expl3_catcode = determine_expl3_catcode,
  do_not_use_argument_specifiers = do_not_use_argument_specifiers,
  double_superscript_convention = double_superscript_convention,
  endinput = endinput,
  eof = eof,
  expansionless_argument_specifier = expansionless_argument_specifier,
  expl3_catcodes = expl3_catcodes,
  expl3_deprecated_csname = expl3_deprecated_csname,
  expl3_endlinechar = expl3_endlinechar,
  expl3_expansion_csname = expl3_expansion_csname,
  expl3_function_call_with_lua_code_argument_csname = expl3_function_call_with_lua_code_argument_csname,
  expl3_function_csname = expl3_function_csname,
  expl3_function_definition_csname = expl3_function_definition_csname,
  expl3_function_variant_definition_csname = expl3_function_variant_definition_csname,
  expl3_function_with_boolean_expression_argument_csname = expl3_function_with_boolean_expression_argument_csname,
  expl3_message_definition = expl3_message_definition,
  expl3_message_use = expl3_message_use,
  expl3_quark_or_scan_mark_csname = expl3_quark_or_scan_mark_csname,
  expl3_scratch_variable_csname = expl3_scratch_variable_csname,
  expl3_function_undefinition_csname = expl3_function_undefinition_csname,
  expl3_unexpandable_variable_or_constant_csname = expl3_unexpandable_variable_or_constant_csname,
  expl3_variable_declaration_csname = expl3_variable_declaration_csname,
  expl3_variable_definition_csname = expl3_variable_definition_csname,
  expl3_variable_or_constant_csname = expl3_variable_or_constant_csname,
  expl3_variable_or_constant_csname_scope = expl3_variable_or_constant_csname_scope,
  expl3_variable_or_constant_csname_type = expl3_variable_or_constant_csname_type,
  expl3_variable_use_csname = expl3_variable_use_csname,
  expl3_well_known_csname = expl3_well_known_csname,
  expl3_well_known_message_name = expl3_well_known_message_name,
  expl3like_csname = expl3like_csname,
  expl3like_function_csname = expl3like_function_csname,
  expl3like_material = expl3like_material,
  expl_syntax_off = expl_syntax_off,
  expl_syntax_on = expl_syntax_on,
  fail = fail,
  ignored_issues = ignored_issues,
  latex_style_file_content = latex_style_file_content,
  latex3_csname = latex3_csname,
  linechar = linechar,
  newline = newline,
  N_or_n_type_argument_specifier = N_or_n_type_argument_specifier,
  N_or_n_type_argument_specifiers = N_or_n_type_argument_specifiers,
  n_type_argument_specifier = n_type_argument_specifier,
  N_type_argument_specifier = N_type_argument_specifier,
  provides = provides,
  space = space,
  success = success,
  tab = tab,
  tex_lines = tex_lines,
  variant_argument_specifiers = variant_argument_specifiers,
  x_type_argument_specifiers = x_type_argument_specifiers,
}
