🏷️ headers#

Writes a header at the top of every function, with what calls it and in which execution context.

beet_default(ctx: Context)[source]#

Main entry point for the headers plugin.

Parameters:

ctx – The beet context.

cache#

Reuse of the previous build’s header analysis.

Building the @within graph and inferring macro argument types walks every function body, then walks the callers of every macro function recursively. The answer is a pure function of the function contents plus the tags, advancements, dialogs and enchantments that can reference them, so a build whose inputs are all unchanged can restore the previous answer instead of computing it again. Anything at all changing in those inputs invalidates the whole record, which is what keeps a cross-referencing analysis honest: a single edited body can change the header of a function on the other side of the pack.

CACHE_NAME: str = 'auto_headers'[source]#

Beet cache slot holding the analysis of the previous build.

CACHE_KEY: str = 'analysis'[source]#

Key of the file inside that slot, resolved through the cache so the path stays beet’s business.

analysis_signature(
ctx: Context,
contents: dict[str, str],
) → str[source]#

Hash everything the analyzers read, so any change to any of it invalidates the stored analysis.

Only the fields the analyzers actually consume are hashed. Reading more would mean deserializing pack files that this plugin deliberately never touches, which would re-encode them on output.

Parameters:
  • ctx – The beet context.

  • contents – The raw content of every function, keyed by path.

Returns:

Hexadecimal digest covering every input of the analysis.

Return type:

str

restore_analysis(
cache: Cache,
signature: str,
mcfunctions: dict[str, Header],
) → list[str] | None[source]#

Put the previous build’s analysis back into the headers, when it still applies.

Everything is parsed and validated before a single header is touched: the analyzers append to within rather than replacing it, so a half applied record would silently duplicate entries.

Parameters:
  • cache – The beet cache slot holding the record.

  • signature – Signature the inputs must still match.

  • mcfunctions – Headers to fill in, keyed by function path.

Returns:

The warnings the skipped analysis had emitted, or None when nothing was restored.

Return type:

list[str] | None

store_analysis(
cache: Cache,
signature: str,
mcfunctions: dict[str, Header],
warnings: list[str],
) → None[source]#

Record the analysis so the next build with the same inputs can skip it.

Parameters:
  • cache – The beet cache slot to write to.

  • signature – Signature of the inputs this analysis was computed from.

  • mcfunctions – The analyzed headers, keyed by function path.

  • warnings – Warnings emitted while analyzing, replayed on every restore.

context_analyzer#

Context analysis utilities for determining execution contexts of Minecraft functions.

This module handles analyzing function call relationships and determining the execution context based on caller information.

PLAYER_CONTEXT: str = 'as the player & at current position'[source]#

The context of a function an advancement reward or a dialog button runs.

DEFAULT_CONTEXT_CALLERS: tuple[str, ...] = ('#minecraft:tick', '#minecraft:load')[source]#

Callers running a function with no context at all.

EXECUTE_KEYWORDS: tuple[str, ...] = ('as ', 'at ', 'positioned ', 'rotated ', 'facing ', 'in ', 'anchored ', 'align ')[source]#

What a bracketed caller suffix must hold to be an execution context rather than an NBT path.

class ContextAnalyzer(
mcfunctions: dict[str, Header],
)[source]#

Bases: object

Analyzes and determines execution contexts for Minecraft functions.

determine_execution_context(
func_path: str,
visited: set[str] | None = None,
) → str | None[source]#

Execution context of a function deduced from its callers, None if unknown.

Advancements and dialog buttons run as the player, while tick and scheduled callers carry no context.

>>> h = Header("test:func", ["advancement test:my_advancement"], [], "say hi")
>>> ctx_analyzer = ContextAnalyzer({"test:func": h})
>>> ctx_analyzer.determine_execution_context("test:func")
'as the player & at current position'
>>> h4 = Header("test:child", ["test:parent [ as @e at @s ]"], [], "say hi")
>>> ctx_analyzer4 = ContextAnalyzer({"test:child": h4})
>>> ctx_analyzer4.determine_execution_context("test:child").strip()
'as @e at @s'
context_from_callers(
within: list[str],
visited: set[str],
) → str | None[source]#

The context the first caller able to tell gives, a function inheriting the context of the function calling it.

A scheduled caller tells nothing, since the call runs on a later tick.

analyze_all_contexts() → None[source]#

Analyze and determine execution contexts for all functions.

bracketed_context(caller: str) → str | None[source]#

The execution context between ` [` and the last ] of a caller, None when it holds none.

>>> bracketed_context("t:f [ as @a ]"), bracketed_context("t:f {path:a[0]}")
(' as @a ', None)

execution_parser#

Execution context parsing utilities for Minecraft function headers.

This module handles parsing execute commands to extract execution contexts like ‘as @e[…] & at @s’ from command lines.

FIXED_ARGUMENTS: dict[str, int] = {'align': 1, 'anchored': 1, 'facing': 3, 'in': 1, 'rotated': 2}[source]#

Subcommands taking a fixed number of words, facing entity <target> <anchor> being three like facing <x> <y> <z>.

POSITION_KEYWORDS: tuple[str, ...] = ('positioned', 'align', 'rotated', 'anchored', 'in')[source]#

Context parts an at replaces, matched anywhere in the part.

SIMPLIFIED_ATTRIBUTES: tuple[str, ...] = ('tag', 'predicate')[source]#

Selector attributes shown as ... when a selector repeats them.

parse_execution_context_from_line(line: str) → str | None[source]#

Execution context of a line calling a function, None for the default one.

>>> parse_execution_context_from_line("execute as @e[type=zombie] at @s run function test:func")
'as @e[type=zombie] & at @s'
>>> None is parse_execution_context_from_line("execute if score @s data matches 1 run function test:func")
True
read_subcommand(
parts: list[str],
index: int,
context: list[str],
) → int[source]#

Add the context the subcommand at index sets to context, and return where the next one starts.

A subcommand setting no context, or missing its arguments, is skipped one word at a time.

read_selector(
parts: list[str],
start: int,
) → tuple[str, int][source]#

The selector or argument starting at start, joined back when its brackets hold spaces, and the index after it.

>>> read_selector(["@e[tag=a,", "tag=b]", "run"], 0)
('@e[tag=...]', 2)
simplify_selector(selector: str) → str[source]#

A selector with its long NBT and its repeated tags and predicates shortened to ....

A repeated attribute keeps its first occurrence only, and an NBT over 50 characters becomes {...}.

>>> simplify_selector("@e[tag=a,tag=!b,type=zombie,nbt={a:1}]")
'@e[tag=...,type=zombie,nbt={a:1}]'
simplify_attribute(
part: str,
counts: Counter[str],
seen: set[str],
) → str | None[source]#

One selector attribute as shown, None for a repeat of an attribute already shown, which seen records.

function_analyzer#

Function relationship analysis for Minecraft datapack headers.

This module handles building the relationships between functions, tags, advancements, and function calls to create the @within information.

COMMAND_CALL_RE = re.compile('(?:^\\s*\\$?\\s*|\\brun\\s+|(?P<sched>\\bschedule\\s+))function\\s+([#]?[\\w./-]+:(?:[\\w./-]|\\$\\(\\w+\\))+)')[source]#

A command call to a function, the “function” keyword sitting at the start of the command or right after “run “ or “schedule “.

A “$” macro prefix may come first, and the path may hold macro placeholders ($function ns:types/$(type)), never the namespace. References inside an argument string, like a tellraw suggest_command “/function ns:foo”, are left out: their trailing JSON must never be mistaken for a macro ({…}) or a schedule time (100t). Since “run “ also appears inside quoted dialog commands (command:"/execute ... run function ns:foo"), a match is only a real command when it is not inside a string, see FunctionAnalyzer.is_inside_string().

QUOTED_ID_RE = re.compile('\\w*function\\w*["\']?\\s*:\\s*(["\'])([\\w.-]+:[\\w./-]+)\\1')[source]#

A quoted function id under a key naming a function ({give_function:”ns:x”}, “function”: “ns:x”).

It is handed to a macro running “$function $(id)” or to a run_function effect. Other keys are left out, since a dialog id can equal a function id.

class FunctionAnalyzer(
ctx: Context,
mcfunctions: dict[str, Header],
)[source]#

Bases: object

Analyzes function relationships and builds @within information.

analyze_function_tags() → None[source]#

Analyze function tags and build relationships.

analyze_advancements() → None[source]#

Analyze advancements and build relationships.

analyze_dialogs() → None[source]#

Record the functions dialog buttons call, which would otherwise look like orphans (@within ???).

Commands are found in the serialized .text, wherever the dialog schema puts them. Reading .data would deserialize the file, re-encoding it on output and losing its formatting.

>>> from types import SimpleNamespace
>>> dialog = SimpleNamespace(
...     text='{"actions":[{"action":{"type":"run_command","command":"/function test:menu"}}]}'
... )
>>> ctx = SimpleNamespace(data=SimpleNamespace(dialogs={"test:config": dialog}))
>>> menu = Header("test:menu", [], [], "")
>>> FunctionAnalyzer(ctx, {"test:menu": menu}).analyze_dialogs()  # type: ignore[arg-type]
>>> menu.within
['dialog test:config']
analyze_enchantments() → None[source]#

Analyze enchantments, whose run_function effects name a function as a plain JSON string.

Scanned as serialized text for the same reason as analyze_dialogs().

>>> from types import SimpleNamespace
>>> enchantment = SimpleNamespace(
...     text='{"effects":{"minecraft:tick":[{"effect":{"type":"run_function","function":"test:on_tick"}}]}}'
... )
>>> ctx = SimpleNamespace(data=SimpleNamespace(enchantments={"test:magic": enchantment}))
>>> on_tick = Header("test:on_tick", [], [], "")
>>> FunctionAnalyzer(ctx, {"test:on_tick": on_tick}).analyze_enchantments()  # type: ignore[arg-type]
>>> on_tick.within
['enchantment test:magic']
add_text_references(
caller: str,
text: str,
) → None[source]#

Record caller on every function that text names, as a command or as a quoted id.

Parameters:
  • caller – The @within entry to add.

  • text – The serialized file to scan.

analyze_function_calls() → None[source]#

Record in the header of every called function which function calls it, with the macro payload it passes.

A reference inside an argument string, like a tellraw suggest_command, is a “string in <caller>”, keeping the payload written right after it. A placeholder in the called path stands for every function it can match.

>>> caller = Header("test:caller", [], [], '$function test:target {slot:"$(slot)"}')
>>> mcfunctions = {"test:caller": caller, "test:target": Header("test:target", [], [], "")}
>>> FunctionAnalyzer(None, mcfunctions).analyze_function_calls()  # type: ignore[arg-type]
>>> mcfunctions["test:target"].within
['test:caller {slot:"$(slot)"}']
analyze_line(path: str, line: str) → None[source]#

Record the calls one line of path makes, as a command or from inside a string.

add_command_call(
path: str,
line: str,
command_match: Match[str],
) → None[source]#

Record a command call with what follows it, macro data or a schedule time, and the context it runs in.

The references nested in its macro payload (function #tag:run {with: {on_exit_point: “function ns:path”}}) share that caller.

static context_suffix(
line: str,
is_scheduled: bool,
) → str[source]#

The ` [ … ]` a caller ends with: the execution context of its line, empty when it sets none.

A scheduled call runs on a later tick, outside any context, and is marked scheduled so the context analyzer inherits nothing.

>>> FunctionAnalyzer.context_suffix("execute as @a[tag=a, tag=b] run function t:f", is_scheduled=False)
' [ as @a[tag=...] ]'
add_caller(
called: str,
caller: str,
) → None[source]#

Add caller to the @within of called once, when called is one of the pack’s functions.

analyze_all_relationships() → None[source]#

Analyze all function relationships.

resolve_call(called: str) → list[str][source]#

Return the functions a call can reach: the id itself, or every id its placeholders can match.

Parameters:

called – The called id, possibly holding $(name) placeholders.

>>> headers = {path: Header(path) for path in ("t:a/x", "t:a/y/z", "t:b")}
>>> analyzer = FunctionAnalyzer(None, headers)  # type: ignore[arg-type]
>>> analyzer.resolve_call("t:a/$(id)")
['t:a/x', 't:a/y/z']
>>> analyzer.resolve_call("t:b")
['t:b']
mark_public_functions(
namespace: str,
version: str,
) → None[source]#

Mark the uncalled functions of the project outside its versioned folder as (public).

Those are run by hand or by other packs (ns:config, ns:_give_all), so ??? stays for dead code. Projects without a ns:v<version>/ folder are left alone: nothing tells their API apart.

Parameters:
  • namespace – The project namespace.

  • version – The project version.

>>> headers = {"t:config": Header("t:config"), "t:v1.0/dead": Header("t:v1.0/dead"), "other:x": Header("other:x")}
>>> FunctionAnalyzer(None, headers).mark_public_functions("t", "1.0")  # type: ignore[arg-type]
>>> [header.within for header in headers.values()]
[['(public)'], [], []]
static extract_macro_payload(
line: str,
pos: int,
) → str[source]#

Return the balanced {...} compound following the function reference that ends at pos, or “” if there is none.

Only a compound right after the reference counts as macro data, so the JSON surrounding a suggest_command reference, which closes with a quote and }}], yields an empty string.

>>> FunctionAnalyzer.extract_macro_payload('## /function ns:foo {x:-280,is_auto:1}', 19)
'{x:-280,is_auto:1}'
>>> FunctionAnalyzer.extract_macro_payload('function ns:foo {with:{a:1}}', 15)
'{with:{a:1}}'
>>> FunctionAnalyzer.extract_macro_payload('{"command":"/function ns:foo"}]', 27)
''
static is_inside_string(
line: str,
pos: int,
) → bool[source]#

Return whether character index pos in line sits inside a double-quoted string.

Counts unescaped double quotes before pos; an odd count means an unclosed string is open.

Parameters:
  • line – The line to scan.

  • pos – The character index whose string-membership is tested.

>>> FunctionAnalyzer.is_inside_string('run function a:b', 4)
False
>>> FunctionAnalyzer.is_inside_string('command:"/execute run function a:b"', 26)
True
>>> FunctionAnalyzer.is_inside_string('data set value {a:"x"} run function a:b', 30)
False

macro_analyzer#

Macro analysis utilities for automatically detecting and typing macro arguments.

This module combines macro variable extraction and type inference to automatically populate the @args section in function headers.

class MacroAnalyzer(
mcfunctions: dict[str, Header],
)[source]#

Bases: object

Analyzes macro functions and infers argument types.

Basic usage with simple macro:

>>> target = Header("test:target", ["test:caller {x:10,y:20}"], [], "$tp @s $(x) $(y) 0")
>>> analyzer = MacroAnalyzer({"test:target": target})
>>> analyzer.analyze_macro_arguments("test:target")
>>> target.args
{'x': ('int', []), 'y': ('int', [])}

With storage call (like StardustFragment):

>>> caller_content = (
...     'data modify storage test:temp macro set value {dimension:"minecraft:overworld",x:0,y:64,z:0}\n'
...     'function test:teleport with storage test:temp macro'
... )
>>> caller = Header("test:caller", [], [], caller_content)
>>> target = Header(
...     "test:teleport", ["test:caller with storage test:temp macro"], [], "$execute in $(dimension) run tp @s $(x) $(y) $(z)"
... )
>>> analyzer = MacroAnalyzer({"test:caller": caller, "test:teleport": target})
>>> analyzer.analyze_macro_arguments("test:teleport")
>>> target.args['dimension']
('string', [])
>>> target.args['x']
('int', [])

Preserving manual descriptions:

>>> target = Header("test:func", ["test:caller {value:100}"], [], "$say $(value)")
>>> target.args = {'value': ('int', ['manually added description'])}
>>> analyzer = MacroAnalyzer({"test:func": target})
>>> analyzer.analyze_macro_arguments("test:func")
>>> target.args['value']
('int', ['manually added description'])
analyze_macro_arguments(
func_path: str,
) → None[source]#

Analyze a single function’s macro arguments and update its header.

Recursively analyzes caller functions to ensure their types are available.

Parameters:

func_path – The path of the function to analyze

analyze_all_macros() → None[source]#

Analyze all macro functions and infer their argument types.

Uses recursive analysis to handle any depth of function call chains.

macro_parser#

Macro argument parsing utilities for Minecraft function headers.

This module handles extracting macro variables from function content by finding lines that start with ‘$’ and extracting $(variable_name) patterns.

extract_macro_variables(content: str) → list[str][source]#

Unique macro variable names of a function content, in order of first appearance.

>>> content = '$data modify storage energy:temp list[0] value [$(part_1),$(part_2),$(scale)]'
>>> extract_macro_variables(content)
['part_1', 'part_2', 'scale']
is_macro_function(content: str) → bool[source]#

Whether a function content holds at least one macro line, starting with ‘$’.

>>> is_macro_function("say Hello")
False
>>> is_macro_function("$say $(message)")
True

object#

ARG_WITH_DESCRIPTION: Pattern[str] = re.compile('(\\w+)\\s*\\((\\w+)\\)\\s*:\\s*(.+)')[source]#

An argument line of @args: name (type): description.

ARG: Pattern[str] = re.compile('(\\w+)\\s*\\((\\w+)\\)')[source]#

An argument line of @args without a description: name (type).

class Header(
path: str,
within: list[str] | None = None,
other: list[str] | None = None,
content: str = '',
executed: str | None = None,
args: dict[str, tuple[str, list[str]]] | None = None,
)[source]#

Bases: object

A class representing a function header.

>>> header = Header("test:function", ["other:function"], ["Some info"], "say Hello")
>>> header.path
'test:function'
>>> header.within
['other:function']
>>> header.other
['Some info']
>>> header.content
'say Hello'
path[source]#

The path to the function (ex: “namespace:folder/function_name”)

within[source]#

List of functions that call this function

other[source]#

List of other information about the function

content[source]#

The content of the function

executed[source]#

The execution context (ex: “as the player & at current position”)

args[source]#

Dictionary mapping macro argument names to (type, description_lines), where description_lines is a list of strings (empty list if no description)

classmethod from_content(
path: str,
content: str,
) → Header[source]#

Create a Header object from a function’s content, parsing the #> block at its top.

>>> content = "#> test:function\n#\n# @within\tother:function\n# Some info\n#\nsay Hello"
>>> header = Header.from_content("test:function", content)
>>> header.within, header.other, header.content
(['other:function'], ['Some info'], 'say Hello')
to_str() → str[source]#

Convert the Header object to the function content with its header.

>>> content = '''
... #> test:function
... #
... # @within\tother:function
... #
... # Some info
... #
...
... say Hello\n\n'''
>>> header = Header("test:function", ["other:function"], ["Some info"], "say Hello")
>>> content.strip() == header.to_str().strip()
True
arg_lines() → list[str][source]#

One name (type): description line per argument, the further lines of a compound’s description indented under it.

skip_empty_comments(lines: list[str], i: int) → int[source]#

The index of the first line from i that is not a bare #.

read_args(
lines: list[str],
i: int,
args: dict[str, tuple[str, list[str]]],
) → int[source]#

Read the @args section starting on line i into args, and return the index of the line after it.

Each argument is an indented name (type): description line, followed by its - ... lines for a compound. The first one may sit on the @args line itself.

>>> args = {}
>>> read_args(["# @args count (int): How many", "#              - at least 1", "#       name (string)", "say"], 0, args), args
(3, {'count': ('int', ['How many', '- at least 1']), 'name': ('string', [])})
parse_arg(text: str) → tuple[str, str, list[str]] | None[source]#

An argument’s name, type and description lines, None when text is not an argument.

>>> parse_arg("count (int): How many"), parse_arg("name (string)"), parse_arg("- a field")
(('count', 'int', ['How many']), ('name', 'string', []), None)

silent#

type_inference#

Type inference utilities for macro function arguments.

This module handles inferring the types of macro arguments by analyzing how functions are called in the @within list.

WITHIN_CALLER_RE: Pattern[str] = re.compile('(?:string in )?([^\\s{]+)')[source]#

Isolates the function path at the head of a @within entry. It skips the optional “string in “ prefix and stops before the macro payload or context.

ESCAPED_QUOTE_RE: Pattern[str] = re.compile('\\\\(["\\\'])')[source]#

Matches a backslash-escaped quote. Payloads read from inside a JSON string (tellraw / dialog run_command) carry them, e.g. {jump:"green"}.

NBT_PAIR_RE: Pattern[str] = re.compile('["\\\']?(\\w+)["\\\']?\\s*:\\s*(.+)')[source]#

A key:value pair of a compound, the key possibly quoted.

NBT_NUMBER_RE: Pattern[str] = re.compile('([-+]?\\d+\\.?\\d*)([bslfd]?)')[source]#

A number and its type suffix.

MACRO_REF_RE: Pattern[str] = re.compile('\\$\\((\\w+)\\)')[source]#

A value that is another macro variable, $(name).

STORAGE_SET_RE: Pattern[str] = re.compile('data\\s+modify\\s+storage\\s+\\S+(?:\\s+\\S+)*\\s+set\\s+value\\s+({.+?})', re.DOTALL)[source]#

A compound set into a storage, data modify storage stardust:temp macro set value {...}, the path tokens optional.

parse_nbt_compound(
nbt_string: str,
) → dict[str, tuple[str, str]][source]#

Variable names of an NBT compound string mapped to their (value, type).

>>> parse_nbt_compound('{"id":"hello",Slot:1b,count:1,price:10.0f}')
{'id': ('hello', 'string'), 'Slot': ('1', 'byte'), 'count': ('1', 'int'), 'price': ('10.0', 'float')}
>>> parse_nbt_compound(r'{jump:\"green\",delay:20}')  # Inside a JSON string, quotes arrive escaped
{'jump': ('green', 'string'), 'delay': ('20', 'int')}
split_top_level(text: str) → list[str][source]#

The parts of text between the commas outside nested structures and quotes, stripped.

>>> split_top_level('a:1, b:{c:2,d:3},e:"f,g"')
['a:1', 'b:{c:2,d:3}', 'e:"f,g"']
nbt_value(value: str) → tuple[str, str][source]#

A value as written without its quotes or suffix, and its type, from its quotes, brackets or numeric suffix.

>>> nbt_value("'kJ'"), nbt_value("1.5f"), nbt_value("2.0"), nbt_value("[1]"), nbt_value("???")
(('kJ', 'string'), ('1.5', 'float'), ('2.0', 'double'), ('[1]', 'list'), ('???', 'unknown'))
infer_types_from_direct_call(
call_string: str,
macro_vars: list[str],
all_functions: dict[str, Header],
) → dict[str, str][source]#

Infer macro argument types from a direct function call passing an NBT compound.

>>> infer_types_from_direct_call('function test {"id":"hello",Slot:1b,count:1}', ['id', 'Slot', 'count'], {})
{'id': 'string', 'Slot': 'byte', 'count': 'int'}
passed_type(
value: str,
var_type: str,
call_string: str,
all_functions: dict[str, Header],
) → str | None[source]#

The type of a value a call passes, a $(name) reference taking the type the calling function gives its own name.

A quoted reference is an explicit string. None when the caller cannot be read off call_string.

>>> callers = {"t:c": Header("t:c", args={"n": ("int", [])})}
>>> passed_type("$(n)", "unknown", "t:c {x:$(n)}", callers), passed_type("$(n)", "string", "t:c", callers)
('int', 'string')
infer_types_from_storage_call(
within_list: list[str],
macro_vars: list[str],
all_functions: dict[str, Header],
) → dict[str, str][source]#

Infer macro argument types from the compounds a caller using with storage or with entity sets into a storage.

The first compound giving a variable decides its type.

>>> # This would need actual function content to work properly
>>> infer_types_from_storage_call(['test:caller with storage temp macro'], ['id', 'count'], {})
{}
infer_macro_types(
header: Header,
all_functions: dict[str, Header],
) → dict[str, str][source]#

Infer the type of every macro variable of a function from its callers, direct or through a storage.

>>> header = Header("test:func", ["test:caller {id:'hello',count:1}"], [], "$give @p $(id) $(count)")
>>> infer_macro_types(header, {})
{'id': 'string', 'count': 'int'}
>>> # An unparsable caller never shadows a later caller that does spell the type out
>>> header = Header("test:list", ["test:menu {jump:???}", 'test:remove {jump:"$(jump)"}'], [], "$say $(jump)")
>>> infer_macro_types(header, {})
{'jump': 'string'}