Utilities

d20.utils.ast_adv_copy(ast, advtype)[source]

Returns a minimally shallow copy of a dice AST with respect to advantage.

>>> tree = parse("1d20 + 5")
>>> str(tree)
'1d20 + 5'
>>> str(ast_adv_copy(tree, AdvType.ADV))
'2d20kh1 + 5'
Parameters
Returns

The copied AST.

Return type

d20.ast.Node

d20.utils.dfs(node, predicate)[source]

Returns the first node in the tree such that predicate(node) is True, searching depth-first left-to-right.

Parameters
Return type

d20.ast.ChildMixin

d20.utils.leftmost(root)[source]

Returns the leftmost leaf in this tree.

Parameters

root (d20.ast.ChildMixin) – The root node of the tree.

Return type

d20.ast.ChildMixin

d20.utils.rightmost(root)[source]

Returns the rightmost leaf in this tree.

Parameters

root (d20.ast.ChildMixin) – The root node of the tree.

Return type

d20.ast.ChildMixin

d20.utils.simplify_expr(expr, **kwargs)[source]

Transforms an expression in place by simplifying it (removing all dice and evaluating branches with respect to annotations).

>>> expr = roll("1d20[foo] + 3 - 1d4[bar]").expr
>>> simplify_expr(expr)
>>> SimpleStringifier().stringify(expr)
"7 [foo] - 2 [bar] = 5"
Parameters
d20.utils.simplify_expr_annotations(expr, ambig_inherit=None)[source]

Transforms an expression in place by simplifying the annotations using a bubble-up method.

>>> expr = roll("1d20[foo]+3").expr
>>> simplify_expr_annotations(expr.roll)
>>> SimpleStringifier().stringify(expr)
"1d20 (4) + 3 [foo] = 7"
Parameters
  • expr (d20.Number) – The expression to transform.

  • ambig_inherit (Optional[str]) – When encountering a child node with no annotation and the parent has ambiguous types, which to inherit. Can be None for no inherit, 'left' for leftmost, or 'right' for rightmost.

d20.utils.tree_map(func, node)[source]

Returns a copy of the tree, with each node replaced with func(node).

Parameters