Python math-function frontend¶
oracq.infrastructure.mathfunc.frontend
Pure-function compilation frontend that reads the Python AST; it never executes the function being compiled.
- oracq.infrastructure.mathfunc.frontend.ELEMENTARY = {'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'exp', 'log', 'log10', 'phase', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'}¶
Set of elementary math function names compilable into intrinsic nodes; phase, polar and rect are cmath only.
- oracq.infrastructure.mathfunc.frontend.REAL_EXTRA = {'atan2', 'hypot'}¶
Set of additional binary math function names supported on the real domain only.
- oracq.infrastructure.mathfunc.frontend.BUILTINS = {'abs', 'complex', 'max', 'min'}¶
Set of Python builtin function names allowed to be called directly by name.
- oracq.infrastructure.mathfunc.frontend.KINDS = {'bool': 'bool', 'complex': 'complex', 'float': 'real', 'int': 'real'}¶
Mapping from Python annotation or type names to MIR value kinds; unannotated parameters are treated as float.
- exception oracq.infrastructure.mathfunc.frontend.FunctionCompileError[source]¶
Bases:
ValidationErrorException raised when the math function frontend fails to parse or compile restricted Python source.
- class oracq.infrastructure.mathfunc.frontend.Value(id, kind)[source]¶
Bases:
objectCompile-time SSA value: a pair of node index and value kind.
- Variables:
id (int) – Position of the node backing this value within the current function’s node sequence.
kind (str) – Value kind: real, complex or bool.
- id¶
- kind¶
- class oracq.infrastructure.mathfunc.frontend.Source(tree, namespace)[source]¶
Bases:
objectLocation record of a function to compile: its AST definition and evaluation namespace.
- Variables:
tree (ast.FunctionDef) – The function’s
ast.FunctionDefdefinition node.namespace (dict[str, object]) – Mapping of global and closure variables used to resolve name references.
- tree¶
- namespace¶
- class oracq.infrastructure.mathfunc.frontend.Frontend(source, *, inputs=None, constants=None, helpers=None, max_unroll=128, entry=None)[source]¶
Bases:
objectCompiles restricted pure Python function source into an MIR math function graph.
Reads and interprets the AST of an ordinary Python function without executing the function being compiled. In source-string form, every def other than the entry is kept as a pure helper in its own MIR function; calls are represented as call nodes and are not expanded at compile time.
- Parameters:
source – An ordinary Python function object, or a source string containing several defs and math/cmath imports; the module docstring and
__future__imports are ignored.inputs – Mapping from parameter names to real/complex/bool or
Index(width); inferred from annotations when omitted.constants – Mapping from parameter names to finite numeric values, bound as generation-time constants.
helpers – Helper functions appended to the entry namespace.
max_unroll – Maximum number of iterations a static range loop may unroll.
entry – Entry function name for the source-string form; the last def is used when omitted.
- Raises:
FunctionCompileError – The source has a syntax error, contains unsupported statements, or has no usable function definition.
- functions¶
- cache¶
- active¶
- max_unroll¶
- sources¶
- entry¶
- source(function)[source]¶
Normalize a function object or Source into a location record.
Reads the source of
function, locates the def of the same name uniquely, and builds the evaluation namespace from its globals and closure variables.- Parameters:
function – An ordinary Python function object, or an already constructed Source.
- Returns:
The location record, ready to be handed to compile.
- Return type:
- Raises:
FunctionCompileError – The input is not an ordinary function with readable source, the source is unavailable, or the definition cannot be located uniquely.
- static imports(stmt, namespace)[source]¶
Handle one math/cmath import statement and write it into the namespace.
- Parameters:
stmt – An
ast.Importorast.ImportFromnode.namespace – The mapping that receives the imported names.
- Raises:
FunctionCompileError – The import target is not math/cmath, or an unsupported math name was imported.
- fail(node, message)[source]¶
Raise an error carrying the source location.
- Parameters:
node – The AST node marking the error location; a question mark replaces the line number when no location info exists.
message – Description of the error.
- Returns:
Never returns; always ends by raising
FunctionCompileError.- Return type:
NoReturn
- Raises:
FunctionCompileError – Always raised, with the message prefixed by the current function label and line number.
- compile(source, inputs=None, constants=None)[source]¶
Compile one function definition to MIR and return its symbol name.
Infers dynamic input kinds, interprets the function body as an SSA node sequence, and caches repeated compilations by AST, inputs, constants and captured values; the symbol name is derived from a hash of the function graph content.
- Parameters:
source – A Python function object, Source or source string.
inputs – Mapping from parameter names to kinds; when None, inferred from annotations and defaulting to real when unannotated.
constants – Mapping from parameter names to finite numeric values, bound as generation-time constants.
- Returns:
The function symbol name registered in
self.functions.- Return type:
str
- Raises:
FunctionCompileError – A parameter declaration, statement or expression leaves the restricted subset, or a recursive helper is detected.
- node(op, kind, args=(), data=())[source]¶
Construct or reuse one SSA node and return its value.
Only one node with identical op, kind, inputs and data is kept per current function.
- Parameters:
op – Node operation name, such as add, select or intrinsic.
kind – Result value kind: real/complex/bool.
args – List of operand Values.
data – Extra data attached to the node, such as a constant value or an intrinsic name.
- Returns:
The compile-time value pointing to the node.
- Return type:
- constant(value, node)[source]¶
Freeze one finite numeric value into a const node.
- Parameters:
value – A bool, int, float or complex constant.
node – The AST node used for error location.
- Returns:
The constant value with a kind matching the constant.
- Return type:
- Raises:
FunctionCompileError – The numeric type is unsupported, or the value is non-finite such as NaN/Inf.
- literal(value, node)[source]¶
Extract the Python numeric value carried by a compile-time constant node.
- Parameters:
value – A Value expected to be a const node.
node – The AST node used for error location.
- Returns:
The raw Python numeric value of the constant; complex values are represented as complex.
- Raises:
FunctionCompileError – The value is not a constant node.
- binary(op, a, b, node)[source]¶
Construct a binary operation node and infer the result kind.
Arithmetic between real/complex is typed by the promotion rules, comparisons and boolean operations produce bool; when both sides are constants the operation is evaluated at generation time and folded into a single constant node.
- Parameters:
op – Operation name, such as add, sub, mul, div, pow, lt, eq, and, or.
a – Left operand Value.
b – Right operand Value.
node – The AST node used for error location.
- Returns:
The operation result value.
- Return type:
- Raises:
FunctionCompileError – An operand is not a scalar, the type combination is illegal, or constant folding hits an undefined operation.
- choose(test, yes, no, node)[source]¶
Construct a select node choosing branch values by a boolean condition.
Tuple branches are selected element-wise; real and complex branches are unified by the promotion rules.
- Parameters:
test – The condition value of bool kind.
yes – The value, or tuple of values, chosen when the condition is true.
no – The value, or tuple of values, chosen when the condition is false.
node – The AST node used for error location.
- Returns:
The selection result, shaped like the branches.
- Return type:
Value or tuple
- Raises:
FunctionCompileError – The condition is not boolean, or the two branches disagree in structure or type.
- expr(node, env)[source]¶
Interpret one expression AST as a compile-time value.
Supports constants, names, tuple/list, generation-time tuple subscripts, math/cmath constant attributes, arithmetic, comparisons, boolean short-circuiting, conditional expressions and function calls.
- Parameters:
node – The expression AST node.
env – Mapping from local names to Values or tuples of them.
- Returns:
The value of the expression; tuple/list expressions produce a tuple of Values.
- Return type:
Value or tuple
- Raises:
FunctionCompileError – The expression leaves the restricted subset.
- call(node, env)[source]¶
Interpret a function call expression.
Handles the
conjugatemethod, named pure helper calls, the whitelisted builtins complex/abs/min/max, and math/cmath intrinsics; helper calls are kept as call nodes and are not expanded at compile time.- Parameters:
node – The
ast.Callnode.env – Mapping from local names to values.
- Returns:
The call result; multi-return helpers give a tuple of Values.
- Return type:
Value or tuple
- Raises:
FunctionCompileError – The call target, argument count/types or keyword usage is unsupported.
- assign(target, value, env)[source]¶
Bind a value to an assignment target.
Supports a single local name and tuple/list unpacking; mutation targets such as attributes are forbidden.
- Parameters:
target – The assignment target AST node.
value – The Value, or tuple of Values, to bind.
env – The local name mapping to update.
- Raises:
FunctionCompileError – The target is not a local name, or the unpacking structure does not match.
- statements(body, env)[source]¶
Interpret a statement block sequentially, returning the resulting environment and return value.
Supports return, assignment/unpacking, augmented assignment, imports, structured if (the environments and return values of both branches are merged via select) and full unrolling of static bounded range loops.
- Parameters:
body – List of statement AST nodes.
env – The local name mapping when entering the block.
- Returns:
(environment, return value); the return value is None when there is no return.- Return type:
tuple
- Raises:
FunctionCompileError – A statement leaves the restricted subset, an if return path is incomplete, or a loop exceeds the unroll limit.
- program()[source]¶
Collect the compilation results and return the validated MIR program.
- Returns:
The entry points at the compiled symbol name, and the function table is sorted by symbol name.
- Return type:
MathProgram- Raises:
ValidationError – The produced function graph failed MIR structural validation.