Python 数学函数前端¶
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[源代码]¶
-
Exception raised when the math function frontend fails to parse or compile restricted Python source.
- class oracq.infrastructure.mathfunc.frontend.Value(id, kind)[源代码]¶
基类:
objectCompile-time SSA value: a pair of node index and value kind.
- 变量:
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)[源代码]¶
基类:
objectLocation record of a function to compile: its AST definition and evaluation namespace.
- 变量:
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)[源代码]¶
基类:
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.
- 参数:
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.
- 抛出:
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)[源代码]¶
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.- 参数:
function -- An ordinary Python function object, or an already constructed Source.
- 返回:
The location record, ready to be handed to compile.
- 返回类型:
- 抛出:
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)[源代码]¶
Handle one math/cmath import statement and write it into the namespace.
- 参数:
stmt -- An
ast.Importorast.ImportFromnode.namespace -- The mapping that receives the imported names.
- 抛出:
FunctionCompileError -- The import target is not math/cmath, or an unsupported math name was imported.
- fail(node, message)[源代码]¶
Raise an error carrying the source location.
- 参数:
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.
- 返回:
Never returns; always ends by raising
FunctionCompileError.- 返回类型:
NoReturn
- 抛出:
FunctionCompileError -- Always raised, with the message prefixed by the current function label and line number.
- compile(source, inputs=None, constants=None)[源代码]¶
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.
- 参数:
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.
- 返回:
The function symbol name registered in
self.functions.- 返回类型:
str
- 抛出:
FunctionCompileError -- A parameter declaration, statement or expression leaves the restricted subset, or a recursive helper is detected.
- node(op, kind, args=(), data=())[源代码]¶
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.
- 参数:
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.
- 返回:
The compile-time value pointing to the node.
- 返回类型:
- constant(value, node)[源代码]¶
Freeze one finite numeric value into a const node.
- 参数:
value -- A bool, int, float or complex constant.
node -- The AST node used for error location.
- 返回:
The constant value with a kind matching the constant.
- 返回类型:
- 抛出:
FunctionCompileError -- The numeric type is unsupported, or the value is non-finite such as NaN/Inf.
- literal(value, node)[源代码]¶
Extract the Python numeric value carried by a compile-time constant node.
- 参数:
value -- A Value expected to be a const node.
node -- The AST node used for error location.
- 返回:
The raw Python numeric value of the constant; complex values are represented as complex.
- 抛出:
FunctionCompileError -- The value is not a constant node.
- binary(op, a, b, node)[源代码]¶
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.
- 参数:
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.
- 返回:
The operation result value.
- 返回类型:
- 抛出:
FunctionCompileError -- An operand is not a scalar, the type combination is illegal, or constant folding hits an undefined operation.
- choose(test, yes, no, node)[源代码]¶
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.
- 参数:
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.
- 返回:
The selection result, shaped like the branches.
- 返回类型:
Value or tuple
- 抛出:
FunctionCompileError -- The condition is not boolean, or the two branches disagree in structure or type.
- expr(node, env)[源代码]¶
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.
- 参数:
node -- The expression AST node.
env -- Mapping from local names to Values or tuples of them.
- 返回:
The value of the expression; tuple/list expressions produce a tuple of Values.
- 返回类型:
Value or tuple
- 抛出:
FunctionCompileError -- The expression leaves the restricted subset.
- call(node, env)[源代码]¶
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.- 参数:
node -- The
ast.Callnode.env -- Mapping from local names to values.
- 返回:
The call result; multi-return helpers give a tuple of Values.
- 返回类型:
Value or tuple
- 抛出:
FunctionCompileError -- The call target, argument count/types or keyword usage is unsupported.
- assign(target, value, env)[源代码]¶
Bind a value to an assignment target.
Supports a single local name and tuple/list unpacking; mutation targets such as attributes are forbidden.
- 参数:
target -- The assignment target AST node.
value -- The Value, or tuple of Values, to bind.
env -- The local name mapping to update.
- 抛出:
FunctionCompileError -- The target is not a local name, or the unpacking structure does not match.
- statements(body, env)[源代码]¶
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.
- 参数:
body -- List of statement AST nodes.
env -- The local name mapping when entering the block.
- 返回:
(environment, return value); the return value is None when there is no return.- 返回类型:
tuple
- 抛出:
FunctionCompileError -- A statement leaves the restricted subset, an if return path is incomplete, or a loop exceeds the unroll limit.
- program()[源代码]¶
Collect the compilation results and return the validated MIR program.
- 返回:
The entry points at the compiled symbol name, and the function table is sorted by symbol name.
- 返回类型:
MathProgram- 抛出:
ValidationError -- The produced function graph failed MIR structural validation.