Utilities

d20.utils.ast_adv_copy(ast: ASTNode, advtype: d20.dice.AdvType)ASTNode[source]

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

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

The copied AST.

Return type

d20.ast.Node

d20.utils.dfs(node: TreeType, predicate: Callable[[TreeType], bool])Optional[TreeType][source]

Returns the first node in the tree such that predicate(node) is True, searching depth-first left-to-right. Returns None if no node satisfying the predicate was found.

Parameters
Return type

Optional[d20.ast.ChildMixin]

d20.utils.leftmost(root: TreeType)TreeType[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: TreeType)TreeType[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: d20.expression.Expression, **kwargs)[source]

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

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

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

>>> roll_expr = d20.roll("1d20[foo]+3").expr
>>> simplify_expr_annotations(roll_expr.roll)
>>> d20.SimpleStringifier().stringify(roll_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: Callable[[TreeType], TreeType], node: TreeType)TreeType[source]

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

Parameters
Return type

d20.ast.ChildMixin