pyccel.ast.core module#
- class pyccel.ast.core.AliasAssign(lhs, rhs)[source]#
Bases:
PyccelAstNode
Representing assignment of an alias to its local_alias.
Represents aliasing for code generation. An alias is any statement of the form lhs := rhs where lhs is a pointer and rhs is a local_alias. In other words the contents of lhs will change if the contents of rhs are modified.
- Parameters:
lhs (TypedAstNode) –
- In the syntactic stage:
Object representing the lhs of the expression. These should be singular objects, such as one would use in writing code. Notable types include PyccelSymbol, and IndexedElement. Types that subclass these types are also supported.
- In the semantic stage:
Variable.
rhs (PyccelSymbol | Variable, IndexedElement) – The local_alias of the assignment. A PyccelSymbol in the syntactic stage, a Variable or a Slice of an array in the semantic stage.
Examples
>>> from pyccel.ast.internals import PyccelSymbol >>> from pyccel.ast.core import AliasAssign >>> from pyccel.ast.core import Variable >>> n = Variable(PythonNativeInt(), 'n') >>> x = Variable(PythonNativeInt(), 'x', rank=1, shape=[n]) >>> y = PyccelSymbol('y') >>> AliasAssign(y, x)
- property lhs#
- property rhs#
- class pyccel.ast.core.AllDeclaration(values)[source]#
Bases:
PyccelAstNode
Class representing the __all__ declaration of public methods in a module.
Class representing the __all__ declaration of public methods/variables/classes in a module.
- Parameters:
values (iterable[LiteralString]) – A PythonList/PythonTuple of strings.
- property values#
An iterable of LiteralStrings describing the public methods/variables/classes/etc.
An iterable of LiteralStrings describing the public methods/variables/classes/etc.
- class pyccel.ast.core.Allocate(variable, *, shape, status, like=None, alloc_type=None)[source]#
Bases:
PyccelAstNode
Represents memory allocation for code generation.
Represents memory allocation (usually of an array) for code generation. This is relevant to low-level target languages, such as C or Fortran, where the programmer must take care of heap memory allocation.
- Parameters:
variable (pyccel.ast.core.Variable) – The typed variable (usually an array) that needs memory allocation.
shape (int or iterable or None) – Shape of the array after allocation (None for scalars).
status (str {'allocated'|'unallocated'|'unknown'}) – Variable allocation status at object creation.
like (TypedAstNode, optional) – A TypedAstNode describing the amount of memory which must be allocated. In C this provides the size which will be passed to malloc. In Fortran this provides the source argument of the allocate function.
alloc_type (str {'init'|'reserve'|'resize'}, optional) –
Specifies the memory allocation strategy for containers with dynamic memory management. This parameter is relevant for any container type where memory allocation patterns need to be specified based on usage.
’init’ refers to direct allocation with predefined data (e.g., x = [1, 2, 4]).
’reserve’ refers to cases where the container will be appended to.
’resize’ refers to cases where the container is populated via indexed elements.
Notes
An object of this class is immutable, although it contains a reference to a mutable Variable object.
- property alloc_type#
Determines the allocation type for homogeneous containers.
Returns a string that indicates the allocation type used for memory allocation. The value is either ‘init’ for containers initialized with predefined data, ‘reserve’ for containers populated through appending, and ‘resize’ for containers populated through indexed element assignment.
- property like#
TypedAstNode describing the amount of memory needed for the allocation.
A TypedAstNode describing the amount of memory which must be allocated. In C this provides the size which will be passed to malloc. In Fortran this provides the source argument of the allocate function.
- property order#
The order that the variable will be allocated with.
The order that the variable will be allocated with.
- property shape#
The shape that the variable should be allocated to.
The shape that the variable should be allocated to.
- property status#
The allocation status of the variable before this allocation.
The allocation status of the variable before this allocation. One of {‘allocated’|’unallocated’|’unknown’}.
- property variable#
The variable to be allocated.
The variable to be allocated.
- class pyccel.ast.core.AnnotatedComment(accel, txt)[source]#
Bases:
PyccelAstNode
Represents a Annotated Comment in the code.
- Parameters:
accel (str) – accelerator id. One among {‘acc’}
txt (str) – statement to print
Examples
>>> from pyccel.ast.core import AnnotatedComment >>> AnnotatedComment('acc', 'parallel') AnnotatedComment(acc, parallel)
- property accel#
- property txt#
- class pyccel.ast.core.AsName(obj, local_alias)[source]#
Bases:
PyccelAstNode
Represents a renaming of an object, used with Import.
A class representing the renaming of an object such as a function or a variable. This usually occurs during an Import.
- Parameters:
obj (PyccelAstNode or PyccelAstNodeType) – The variable, function, or module being renamed.
local_alias (str) – Name of variable or function in this context.
Examples
>>> from pyccel.ast.core import AsName, FunctionDef >>> from pyccel.ast.numpyext import NumpyFull >>> func = FunctionDef('old', (), (), ()) >>> AsName(func, 'new') old as new >>> AsName(NumpyFull, 'fill_func') full as fill_func
- property local_alias#
The local_alias name of the object.
The name used to identify the object in the local scope.
- property name#
The original name of the object
- property object#
The underlying object described by this AsName
- class pyccel.ast.core.Assert(test)[source]#
Bases:
PyccelAstNode
Represents an assert statement in the code.
Represents an assert statement in the code.
- Parameters:
test (TypedAstNode) – Boolean expression to check.
- property test#
- class pyccel.ast.core.Assign(lhs, rhs, *, python_ast=None)[source]#
Bases:
PyccelAstNode
Represents variable assignment for code generation.
Class representing an assignment node, where the result of an expression (rhs: right hand side) is saved into a variable (lhs: left hand side).
- Parameters:
lhs (TypedAstNode) –
- In the syntactic stage:
Object representing the lhs of the expression. These should be singular objects, such as one would use in writing code. Notable types include PyccelSymbol, and IndexedElement. Types that subclass these types are also supported.
- In the semantic stage:
Variable or IndexedElement.
rhs (TypedAstNode) –
- In the syntactic stage:
Object representing the rhs of the expression.
- In the semantic stage :
TypedAstNode with the same shape as the lhs.
python_ast (ast.Ast) – The ast object parsed by Python’s ast module.
Examples
>>> from pyccel.ast.datatypes import PythonNativeInt >>> from pyccel.ast.internals import symbols >>> from pyccel.ast.variable import Variable >>> from pyccel.ast.core import Assign >>> x, y, z = symbols('x, y, z') >>> Assign(x, y) x := y >>> Assign(x, 0) x := 0 >>> A = Variable(PythonNativeInt(), 'A', rank = 2) >>> Assign(x, A) x := A >>> Assign(A[0,1], x) IndexedElement(A, 0, 1) := x
- property is_alias#
Returns True if the assignment is an alias.
- property lhs#
- property rhs#
- class pyccel.ast.core.AugAssign(lhs, op, rhs, *, python_ast=None)[source]#
Bases:
Assign
Represents augmented variable assignment for code generation.
Represents augmented variable assignment for code generation. Augmented variable assignment is an assignment which modifies the variable using its initial value rather than simply replacing the value; for example via an addition (+=).
- Parameters:
lhs (PyccelSymbol | TypedAstNode) – Object representing the lhs of the expression. In the syntactic stage this may be a PyccelSymbol, or an IndexedElement. In later stages the object should inherit from TypedAstNode and be fully typed.
op (str) – Operator (+, -, /, *, %).
rhs (TypedAstNode) – Object representing the rhs of the expression.
python_ast (ast.AST) – The AST node where the object appeared in the original code.
Examples
>>> from pyccel.ast.core import Variable >>> from pyccel.ast.core import AugAssign >>> s = Variable(PythonNativeInt(), 's') >>> t = Variable(PythonNativeInt(), 't') >>> AugAssign(s, '+', 2 * t + 1) s += 1 + 2*t
- property op#
Get the string describing the operator which modifies the lhs variable.
Get the string describing the operator which modifies the lhs variable.
- property pyccel_operator#
Get the PyccelOperator which modifies the lhs variable.
Get the PyccelOperator which modifies the lhs variable.
- class pyccel.ast.core.Break[source]#
Bases:
PyccelAstNode
Represents a break in the code.
- class pyccel.ast.core.ClassDef(name, attributes=(), methods=(), imports=(), superclasses=(), interfaces=(), docstring=None, scope=None, class_type=None)[source]#
Bases:
ScopedAstNode
Represents a class definition.
Class representing a class definition in the code. It holds all objects which may be defined in a class including methods, interfaces, attributes, etc. It also handles inheritance.
- Parameters:
name (str) – The name of the class.
attributes (iterable) – The attributes to the class.
methods (iterable) – Class methods.
imports (list, tuple) – A list of required imports.
superclasses (iterable) – The definition of all classes from which this class inherits.
interfaces (iterable) – The interface methods.
docstring (CommentBlock, optional) – The doc string of the class.
scope (Scope) – The scope for the class contents.
class_type (PyccelType) – The data type associated with this class.
Examples
>>> from pyccel.ast.core import Variable, Assign >>> from pyccel.ast.core import ClassDef, FunctionDef >>> x = Variable(PythonNativeFloat(), 'x') >>> y = Variable(PythonNativeFloat(), 'y') >>> z = Variable(PythonNativeFloat(), 'z') >>> t = Variable(PythonNativeFloat(), 't') >>> a = Variable(PythonNativeFloat(), 'a') >>> b = Variable(PythonNativeFloat(), 'b') >>> body = [Assign(y,x+a)] >>> translate = FunctionDef('translate', [x,y,a,b], [z,t], body) >>> attributes = [x,y] >>> methods = [translate] >>> ClassDef('Point', attributes, methods) ClassDef(Point, (x, y), (FunctionDef(translate, (x, y, a, b), (z, t), [y := a + x], [], [], None, False, function),), [public])
- add_new_attribute(attr)[source]#
Add a new attribute to the current class.
Add a new attribute to the current ClassDef.
- Parameters:
attr (Variable) – The Variable that will be added.
- add_new_interface(interface)[source]#
Add a new interface to the current class.
Add a new interface to the current ClassDef.
- Parameters:
interface (FunctionDef) – The interface that will be added.
- add_new_method(method)[source]#
Add a new method to the current class.
Add a new method to the current ClassDef.
- Parameters:
method (FunctionDef) – The Method that will be added.
- property attributes#
The attributes of a class.
Returns a tuple containing the attributes of a ClassDef. Each element within the tuple is of type Variable.
- property attributes_as_dict#
Returns a dictionary that contains all attributes, where the key is the attribute’s name.
- property class_type#
The PyccelType of an object of the described class.
The PyccelType of an object of the described class.
- property docstring#
The docstring of the class.
The docstring of the class.
- get_method(name, raise_error_from=None)[source]#
Get the method name of the current class.
Look through all methods and interfaces of the current class to find a method called name. If this class inherits from another class, that class is also searched to ensure that the inherited methods are available.
- Parameters:
name (str) – The name of the attribute we are looking for.
raise_error_from (PyccelAstNode, optional) – If an error should be raised then this variable should contain the node that the error should be raised from. This allows the correct, line/column error information to be reported.
- Returns:
The definition of the method.
- Return type:
- Raises:
ValueError – Raised if the method cannot be found.
- property hide#
Indicate whether the class should be hidden.
Indicate whether the class should be hidden. A hidden class does not appear in the printed code.
- property imports#
- property interfaces#
- property is_iterable#
Returns True if the class has an iterator.
- property is_unused#
Indicates whether the class has any users.
This function always returns False as a class definition shouldn’t be invalidated and deleted due to a lack of users.
- property is_with_construct#
Returns True if the class is a with construct.
- property methods#
- property methods_as_dict#
Returns a dictionary that contains all methods, where the key is the method’s name.
- property name#
The name of the class.
The name of the class.
- property superclasses#
Get the superclasses.
Get the class definitions for the classes from which this class inherits.
- update_interface(syntactic_interface, semantic_interface)[source]#
Replace an existing interface with a new interface.
Replace an existing interface with a new semantic interface. When translating a .py file this will always be an operation which replaces a syntactic interface with its semantic equivalent. The syntactic interface is inserted into the class at its creation to ensure that the method can be located when it is called, but it is only treated on the first call (or once the rest of the enlosing Module has been translated) to ensure that all global variables that it may use have been declared. When the method is visited to create the semantic version, this method is called to update the stored interface.
When translating a .pyi file, an additional case is seen due to the use of the @overload decorator. When this decorator is used each FunctionDef in the Interface is visited individually. When the first implementation is visited, the syntactic interface will be replaced by the semantic interface, but when subsequent implementations are visited, the syntactic interface will already have been removed, rather it is the previous semantic interface (identified by its name) which will be replaced.
- Parameters:
syntactic_interface (FunctionDef) – The syntactic interface that should be removed from the class. In the case of a .pyi file this interface may not appear in the class any more.
semantic_interface (FunctionDef) – The new interface that should appear in the class.
- update_method(syntactic_method, semantic_method)[source]#
Replace a syntactic_method with its semantic equivalent.
Replace a syntactic_method with its semantic equivalent.
- Parameters:
syntactic_method (FunctionDef) – The method that has already been added to the class.
semantic_method (FunctionDef) – The method that will replace the syntactic_method.
- class pyccel.ast.core.CodeBlock(body, unravelled=False)[source]#
Bases:
PyccelAstNode
Represents a block of statements.
Represents a list of statements for code generation. Each statement represents a line of code.
- Parameters:
body (iterable) – The lines of code to be grouped together.
unravelled (bool, default=False) – Indicates whether the loops in the code have already been unravelled. This is useful for printing in languages which don’t support vector expressions.
- property body#
- insert2body(*obj, back=True)[source]#
Insert object(s) to the body of the codeblock The object(s) are inserted at the back by default but can be inserted at the front by setting back to False
- property lhs#
- set_current_ast(ast_node)[source]#
Set the ast.AST object which describes the parsed code that this node currently represents.
Set the AST (abstract syntax tree) object which Python parsed in the original code and which resulted in the creation (or use) of this PyccelAstNode. This object describes the Python code being translated. It provides line numbers and columns which can be used to report the origin of any potential errors.
- Parameters:
ast_node (ast.AST) – The AST object which was parsed.
- property unravelled#
Indicates whether the vector syntax of python has been unravelled into for loops
- class pyccel.ast.core.Comment(text)[source]#
Bases:
PyccelAstNode
Represents a Comment in the code.
Represents a Comment in the code.
- Parameters:
text (str) – The comment line.
Examples
>>> from pyccel.ast.core import Comment >>> Comment('this is a comment') # this is a comment
- property text#
- class pyccel.ast.core.CommentBlock(txt, header='CommentBlock')[source]#
Bases:
PyccelAstNode
Represents a Block of Comments
- Parameters:
txt (str)
- property comments#
- property header#
- class pyccel.ast.core.Concatenate(arg1, arg2)[source]#
Bases:
TypedAstNode
A class representing the + operator for Python tuples.
A class representing the + operator for Python tuples.
- Parameters:
arg1 (TypedAstNodes) – The first tuple.
arg2 (TypedAstNodes) – The second tuple.
- property args#
- class pyccel.ast.core.ConstructorCall(func, arguments, cls_variable)[source]#
Bases:
FunctionCall
Represents a Constructor call in the code.
A node which holds all information necessary to represent a Constructor call in the code.
- Parameters:
func (FunctionDef, str) – An instance of FunctionDef or function name.
arguments (list, tuple, None) – A list of arguments.
cls_variable (Variable) – The variable on the left-hand side of an assignment, where the right-hand side is a constructor call. Used to store data inside the class, set during object creation.
- property cls_variable#
Get the class variable associated with the constructor.
The cls_variable property allows accessing the class variable associated with the constructor.
- Returns:
The class variable associated with the constructor, or None if not provided.
- Return type:
CustomDataType or None
- class pyccel.ast.core.Continue[source]#
Bases:
PyccelAstNode
Represents a continue in the code.
- class pyccel.ast.core.Deallocate(variable)[source]#
Bases:
PyccelAstNode
Class representing memory deallocation.
Represents memory deallocation (usually of an array) for code generation. This is relevant to low-level target languages, such as C or Fortran, where the programmer must take care of heap memory deallocation.
- Parameters:
variable (pyccel.ast.core.Variable) – The typed variable (usually an array) that needs memory deallocation.
Notes
An object of this class is immutable, although it contains a reference to a mutable Variable object.
- property variable#
- class pyccel.ast.core.Declare(variable, intent=None, value=None, static=False, external=False, module_variable=False)[source]#
Bases:
PyccelAstNode
Represents a variable declaration in the code.
Represents a variable declaration in the translated code.
- Parameters:
variable (Variable) – A single variable which should be declared.
intent (str, optional) – One among {‘in’, ‘out’, ‘inout’}.
value (TypedAstNode, optional) – The initialisation value of the variable.
static (bool, default=False) – True for a static declaration of an array.
external (bool, default=False) – True for a function declared through a header.
module_variable (bool, default=False) – True for a variable which belongs to a module.
Examples
>>> from pyccel.ast.core import Declare, Variable >>> Declare(Variable(PythonNativeInt(), 'n')) Declare(n, None) >>> Declare(Variable(PythonNativeFloat(), 'x'), intent='out') Declare(x, out)
- property external#
- property intent#
- property module_variable#
Indicates whether the variable is scoped to a module
- property static#
- property value#
- property variable#
- class pyccel.ast.core.Decorator(name)[source]#
Bases:
PyccelAstNode
Class representing a function decorator. For now this is just designed to handle the pyccel decorators
- Parameters:
name (str) – The name of the decorator
- property name#
Return the name of the decorator
- class pyccel.ast.core.Del(expr)[source]#
Bases:
PyccelAstNode
Represents a memory deallocation in the code.
Represents a memory deallocation in the code.
- Parameters:
expr (Variable) – The variable being deallocated.
Examples
>>> from pyccel.ast.core import Del, Variable >>> x = Variable(PythonNativeFloat(), 'x', rank=2, shape=(10,2), memory_handling='heap') >>> Del([x]) Del([x])
- property variables#
- class pyccel.ast.core.Duplicate(val, length)[source]#
Bases:
TypedAstNode
Class representing the duplicate operator in Python.
Class representing the duplicate operator in Python. This is equivalent to the * operator for Python tuples, lists, strings, etc. In other words it represents the * operator when it duplicates the first argument passed to the operator, rather than acting as a numerical operator.
- Parameters:
val (TypedAstNode) – The object being duplicated.
length (TypedAstNode) – The number of times the val should appear in the final object.
- property length#
- property val#
- class pyccel.ast.core.EmptyNode[source]#
Bases:
PyccelAstNode
Represents an empty node in the abstract syntax tree (AST). When a subtree is removed from the AST, we replace it with an EmptyNode object that acts as a placeholder. Using an EmptyNode instead of None is more explicit and avoids confusion. Further, finding a None in the AST is signal of an internal bug.
- Parameters:
text (str) – the comment line
Examples
>>> from pyccel.ast.core import EmptyNode >>> EmptyNode()
- class pyccel.ast.core.Exit[source]#
Bases:
PyccelAstNode
Basic class for exits.
- class pyccel.ast.core.For(target, iter_obj, body, scope=None)[source]#
Bases:
ScopedAstNode
Represents a ‘for-loop’ in the code.
- Expressions are of the form:
- “for target in iter:
body…”
- Parameters:
target (Variable) – Variable representing the iterator.
iter_obj (Iterable) – Iterable object. Multiple iterators are supported but these are translated to a range object in the Iterable class.
body (list[PyccelAstNode]) – List of statements representing the body of the For statement.
scope (Scope) – The scope for the loop.
Examples
>>> from pyccel.ast.variable import Variable >>> from pyccel.ast.core import Assign, For >>> from pyccel.ast.internals import symbols >>> i,b,e,s,x = symbols('i,b,e,s,x') >>> A = Variable(PythonNativeInt(), 'A', rank = 2) >>> For(i, (b,e,s), [Assign(x, i), Assign(A[0, 1], x)]) For(i, (b, e, s), (x := i, IndexedElement(A, 0, 1) := x))
- property body#
- property end_annotation#
- property iterable#
- property local_vars#
List of variables defined in the loop
- property target#
- class pyccel.ast.core.FunctionAddress(name, arguments, results, is_optional=False, is_kwonly=False, is_argument=False, memory_handling='stack', **kwargs)[source]#
Bases:
FunctionDef
Represents a function address.
A function definition can have a FunctionAddress as an argument.
- Parameters:
name (str) – The name of the function address.
arguments (iterable) – The arguments to the function address.
results (iterable) – The direct outputs of the function address.
is_optional (bool) – If object is an optional argument of a function [Default value: False].
is_kwonly (bool) – If object is an argument which can only be specified using its keyword.
is_argument (bool) – If object is the argument of a function [Default value: False].
memory_handling (str) – Must be ‘heap’, ‘stack’ or ‘alias’ [Default value: ‘stack’].
**kwargs (dict) – Any keyword arguments which should be passed to the super class FunctionDef.
See also
FunctionDef
The super class from which this object derives.
Examples
>>> from pyccel.ast.core import Variable, FunctionAddress, FunctionDef >>> x = Variable(PythonNativeFloat(), 'x') >>> y = Variable(PythonNativeFloat(), 'y') >>> # a function definition can have a FunctionAddress as an argument >>> FunctionDef('g', [FunctionAddress('f', [x], [y])], [], [])
- property is_alias#
Indicates if the instance of FunctionAddress is an alias
- property is_argument#
- property is_kwonly#
- property is_optional#
- property memory_handling#
Returns the memory handling of the instance of FunctionAddress
- property name#
Name of the function
- class pyccel.ast.core.FunctionCall(func, args, current_function=None)[source]#
Bases:
TypedAstNode
Represents a function call in the code.
A node which holds all information necessary to represent a function call in the code.
- Parameters:
func (FunctionDef) – The function being called.
args (list of FunctionCallArgument) – The arguments passed to the function.
current_function (FunctionDef, default: None) – The function where the call takes place.
- property args#
List of FunctionCallArguments provided to the function call (contains default values after semantic stage)
- property func_name#
The name of the function called by this function call
- property funcdef#
The function called by this function call
- property interface#
The interface called by this function call
- property interface_name#
The name of the interface called by this function call
- property is_alias#
Check if the result of the function call is an alias type.
Check if the result of the function call is an alias type.
- class pyccel.ast.core.FunctionCallArgument(value, keyword=None, *, python_ast=None)[source]#
Bases:
PyccelAstNode
An argument passed in a function call.
Class describing an argument passed to a function in a function call.
- Parameters:
value (TypedAstNode) – The expression passed as an argument.
keyword (str, optional) – If the argument is passed by keyword then this is that keyword.
python_ast (ast.Ast) – The ast object parsed by Python’s ast module.
- property has_keyword#
Indicates whether the argument was passed by keyword
- property keyword#
The keyword used to pass the argument
- property value#
The value passed as argument
- class pyccel.ast.core.FunctionDef(name, arguments, body, results=None, *, global_vars=(), cls_name=None, is_static=False, imports=(), decorators={}, headers=(), is_recursive=False, is_pure=False, is_elemental=False, is_private=False, is_header=False, is_external=False, is_imported=False, functions=(), interfaces=(), result_pointer_map={}, docstring=None, scope=None)[source]#
Bases:
ScopedAstNode
Represents a function definition.
Node containing all the information necessary to describe a function. This information should provide enough information to print a functionally equivalent function in any target language.
- Parameters:
name (str) – The name of the function.
arguments (iterable of FunctionDefArgument) – The arguments to the function.
body (iterable) – The body of the function.
results (FunctionDefResult, optional) – The direct outputs of the function.
global_vars (list of Symbols) – Variables which will not be passed into the function.
cls_name (str) – The alternative name of the function required for classes.
is_static (bool) – True for static functions. Needed for iso_c_binding interface.
imports (list, tuple) – A list of needed imports.
decorators (dict) – A dictionary whose keys are the names of decorators and whose values contain their implementation.
headers (list,tuple) – A list of headers describing the function.
is_recursive (bool) – True for a function which calls itself.
is_pure (bool) – True for a function without side effect.
is_elemental (bool) – True for a function that is elemental.
is_private (bool) – True for a function that is private.
is_header (bool) – True for a function which has no body available.
is_external (bool) – True for a function which cannot be explicitly imported or renamed.
is_imported (bool, default : False) – True for a function that is imported.
functions (list, tuple) – A list of functions defined within this function.
interfaces (list, tuple) – A list of interfaces defined within this function.
result_pointer_map (dict[FunctionDefResult, list[int]]) – A dictionary connecting any pointer results to the index of the possible target arguments.
docstring (str) – The doc string of the function.
scope (parser.scope.Scope) – The scope containing all objects scoped to the inside of this function.
See also
FunctionDefArgument
The type used to store the arguments.
Examples
>>> from pyccel.ast.variable import Variable >>> from pyccel.ast.core import FunctionDefArgument, FunctionDefResult >>> from pyccel.ast.core import Assign, FunctionDef >>> from pyccel.ast.operators import PyccelAdd >>> from pyccel.ast.literals import LiteralInteger >>> x = Variable(PythonNativeFloat(), 'x') >>> y = Variable(PythonNativeFloat(), 'y') >>> args = [FunctionDefArgument(x)] >>> results = [FunctionDefResult(y)] >>> body = [Assign(y,PyccelAdd(x,LiteralInteger(1)))] >>> FunctionDef('incr', args, results, body) FunctionDef(incr, (x,), (y,), [y := x + 1], [], [], None, False, function)
One can also use parametrized argument, using FunctionDefArgument
>>> from pyccel.ast.core import Variable >>> from pyccel.ast.core import Assign >>> from pyccel.ast.core import FunctionDef >>> from pyccel.ast.core import FunctionDefArgument >>> n = FunctionDefArgument('n', value=4) >>> x = Variable(PythonNativeFloat(), 'x') >>> y = Variable(PythonNativeFloat(), 'y') >>> args = [x, n] >>> results = [y] >>> body = [Assign(y,x+n)] >>> FunctionDef('incr', args, results, body) FunctionDef(incr, (x, n=4), (y,), [y := 1 + x], [], [], None, False, function, [])
- property arguments#
List of variables which are the function arguments
- property body#
CodeBlock containing all the statements in the function.
Return a CodeBlock containing all the statements in the function.
- clone(newname, **new_kwargs)[source]#
Create an almost identical FunctionDef with name newname.
Create an almost identical FunctionDef with name newname. Additional parameters can be passed to alter the resulting FunctionDef.
- Parameters:
newname (str) – New name for the FunctionDef.
**new_kwargs (dict) – Any new keyword arguments to be passed to the new FunctionDef.
- Returns:
The clone of the function definition.
- Return type:
- property cls_name#
String containing an alternative name for the function if it is a class method.
If a function is a class method then in some languages an alternative name is required. For example in Fortran a name is required for the definition of the class in the module. This name is different from the name of the method which is used when calling the function via the class variable.
- property decorators#
List of decorators applied to the function
- property docstring#
The docstring of the function.
The docstring of the function.
- property functions#
List of functions within this function
- property global_vars#
List of global variables used in the function
- property headers#
List of headers applied to the function
- property imports#
List of imports in the function
- property interfaces#
List of interfaces within this function
- property is_elemental#
returns True if the function is marked as elemental and False otherwise An elemental function is a function with a single scalar operator and a scalar return value which can also be called on an array. When it is called on an array it returns the result of the function called elementwise on the array
- property is_external#
Indicates if the function is from an external library.
Indicates if the function is from an external library which has no associated imports. Such functions must be declared locally to satisfy the compiler. For example this method returns True if the function is exposed through a pyi file and describes a method from a f77 module.
- property is_header#
True if the implementation of the function body is not provided False otherwise
- property is_imported#
Indicates if the function was imported from another file.
Indicates if the function was imported from another file.
- property is_inline#
True if the function should be printed inline
- property is_private#
True if the function should not be exposed to other modules. This includes the wrapper module and means that the function cannot be used in an import or exposed to python
- property is_pure#
Returns True if the function is marked as pure and False otherwise Pure functions must not have any side effects. In other words this means that the result must be the same no matter how many times the function is called e.g: >>> a = f() >>> a = f()
gives the same result as >>> a = f()
This is notably not true for I/O functions
- property is_recursive#
Returns True if the function is recursive (i.e. calls itself) and False otherwise
- property is_semantic#
Indicates if the function was created with semantic information.
Indicates if the function has been annotated with type descriptors in the semantic stage.
- property is_static#
Indicates if the function is static.
Indicates if the function is static.
- property is_unused#
Indicates whether the class has any users
- property local_vars#
List of variables defined in the function.
A list of all variables which are local to the function. This includes arguments, results, and variables defined inside the function.
- property name#
Name of the function
- rename(newname)[source]#
Rename the FunctionDef name newname.
- Parameters:
newname (str) – new name for the FunctionDef
- property result_pointer_map#
A dictionary connecting any pointer results to the index of the possible target arguments.
A dictionary whose keys are FunctionDefResult objects and whose values are a list of integers. The integers specify the position of the argument which is a target of the FunctionDefResult.
- property results#
List of variables which are the function results
- class pyccel.ast.core.FunctionDefArgument(name, *, value=None, kwonly=False, annotation=None, bound_argument=False, persistent_target=False)[source]#
Bases:
TypedAstNode
Node describing the argument of a function.
An object describing the argument of a function described by a FunctionDef. This object stores all the information which describes an argument but is superfluous for a Variable.
- Parameters:
name (PyccelSymbol, Variable, FunctionAddress) – The name of the argument.
value (TypedAstNode, default: None) – The default value of the argument.
kwonly (bool) – Indicates if the argument must be passed by keyword.
annotation (str) – The type annotation describing the argument.
bound_argument (bool) – Indicates if the argument is bound to the function call. This is the case if the argument is the first argument of a method of a class.
persistent_target (bool, default: False) – Indicate if the object passed as this argument becomes a target. This argument will usually only be passed by the wrapper.
See also
FunctionDef
The class where these objects will be stored.
Examples
>>> from pyccel.ast.core import FunctionDefArgument >>> n = FunctionDefArgument('n') >>> n n
- property annotation#
The argument annotation providing dtype information.
The argument annotation providing dtype information.
- property bound_argument#
Indicate if the argument is bound to the function call.
Indicate if the argument is bound to the function call. This is the case if the argument is the first argument of a method of a class.
- property default_call_arg#
The FunctionCallArgument which is passed to FunctionCall if no value is provided for this argument
- property has_default#
Indicates whether the argument has a default value (if not then it must be provided)
- property inout#
Indicates whether the argument may be modified by the function.
True if the argument may be modified in the function. False if the argument remains constant in the function.
- property is_kwonly#
Indicates if the argument must be passed by keyword
- make_const()[source]#
Indicate that the argument does not change in the function.
Indicate that the argument does not change in the function by modifying the inout flag.
- property name#
The name of the argument
- property persistent_target#
Indicate if the object passed as this argument becomes a target.
Indicate if the object passed as this argument becomes a pointer target after a call to the function associated with this argument. This may be the case in class methods.
- property value#
The default value of the argument
- property var#
The variable representing the argument (available after the semantic treatment)
- class pyccel.ast.core.FunctionDefResult(var, *, annotation=None)[source]#
Bases:
TypedAstNode
Node describing the result of a function.
An object describing the result of a function described by a FunctionDef. This object stores all the information which describes an result but is superfluous for a Variable.
- Parameters:
var (Variable) – The variable which represents the returned value.
annotation (str, default: None) – The type annotation describing the argument.
See also
FunctionDef
The class where these objects will be stored.
Examples
>>> from pyccel.ast.core import FunctionDefResult >>> n = FunctionDefResult('n') >>> n n
- property annotation#
The result annotation providing dtype information.
The annotation which provides all information about the data types, rank, etc, necessary to fully define the result.
- property is_argument#
Indicates if the result was declared as an argument.
Indicates if the result of the function was initially declared as an argument of the same function. If this is the case then the result may be printed simply as an inout argument.
- property var#
The variable representing the result.
The variable which represents the result. This variable is only available after the semantic stage.
- class pyccel.ast.core.If(*args)[source]#
Bases:
PyccelAstNode
Represents an if statement in the code.
Represents an if statement in the code.
- Parameters:
*args (IfSection) – All arguments are sections of the complete If block.
Examples
>>> from pyccel.ast.internals import PyccelSymbol >>> from pyccel.ast.core import Assign, If >>> n = PyccelSymbol('n') >>> i1 = IfSection((n>1), [Assign(n,n-1)]) >>> i2 = IfSection(True, [Assign(n,n+1)]) >>> If(i1, i2) If(IfSection((n>1), [Assign(n,n-1)]), IfSection(True, [Assign(n,n+1)]))
- property blocks#
The IfSection blocks inside this if.
The IfSection blocks inside this if.
- class pyccel.ast.core.IfSection(cond, body)[source]#
Bases:
PyccelAstNode
Represents one condition and code block in an if statement.
Represents a condition and associated code block in an if statement in the code.
- Parameters:
cond (TypedAstNode) – A boolean expression indicating whether or not the block should be executed.
body (CodeBlock) – The code to be executed if the condition is satisfied.
Examples
>>> from pyccel.ast.internals import PyccelSymbol >>> from pyccel.ast.core import Assign, IfSection, CodeBlock >>> n = PyccelSymbol('n') >>> IfSection((n>1), CodeBlock([Assign(n,n-1)])) IfSection((n>1), CodeBlock([Assign(n,n-1)]))
- property body#
- property condition#
- class pyccel.ast.core.Import(source, target=None, ignore_at_print=False, mod=None)[source]#
Bases:
PyccelAstNode
Represents inclusion of dependencies in the code.
Represents the importation of targets from another source code. This is usually used to represent an import statement in the original code but it is also used to import language/library specific dependencies.
- Parameters:
source (str, DottedName, AsName) – The module from which we import.
target (str, AsName, list, tuple) – Targets to import.
ignore_at_print (bool) – Indicates whether the import should be printed.
mod (Module) – The module describing the source.
Examples
>>> from pyccel.ast.core import Import >>> from pyccel.ast.core import DottedName >>> Import('foo') import foo
>>> abc = DottedName('foo', 'bar', 'baz') >>> Import(abc) import foo.bar.baz
>>> Import('foo', 'bar') from foo import bar
- define_target(new_target)[source]#
Add an additional target to the imports.
Add an additional target to the imports. I.e. if imp is an Import defined as: >>> from numpy import ones
and we call imp.define_target(‘cos’) then it becomes: >>> from numpy import ones, cos
- find_module_target(new_target)[source]#
Find the specified target amongst the targets of the Import.
Find the specified target amongst the targets of the Import.
- Parameters:
new_target (str) – The name of the target that has been imported.
- Returns:
The name of the target in the local scope or None if the target is not found.
- Return type:
str
- property ignore#
- remove_target(target_to_remove)[source]#
Remove a target from the imports.
Remove a target from the imports. I.e., if imp is an Import defined as: >>> from numpy import ones, cos
and we call imp.remove_target(‘cos’) then it becomes: >>> from numpy import ones
- property source#
- property source_module#
The module describing the Import source
- property target#
Get the objects that are being imported.
Get the objects that are being imported.
- class pyccel.ast.core.InlineFunctionDef(*args, namespace_imports=None, global_funcs=None, **kwargs)[source]#
Bases:
FunctionDef
Represents a function definition for an inline function.
Represents a function definition for an inline function.
- Parameters:
*args (list) – The FunctionDef class arguments.
namespace_imports (dict) – The imports available in the function Scope.
global_funcs (iterable, optional) – The global functions used in the function.
**kwargs (dict) – The FunctionDef class keyword arguments.
- property global_funcs#
List of global functions used in the function
- property is_inline#
True if the function should be printed inline
- property namespace_imports#
The objects in the scope which are available due to imports
- reinstate_presence_checks()[source]#
Modify the body by reinstating all expressions checking for the presence of an optional variable
- remove_presence_checks()[source]#
Modify the body by replacing all expressions checking for the presence of an optional variable. Either the If is removed or the check is replaced with its literal result
- class pyccel.ast.core.Interface(name, functions, is_argument=False, is_imported=False, syntactic_node=None)[source]#
Bases:
PyccelAstNode
Class representing an interface function.
A class representing an interface function. An interface function represents a Python function which accepts multiple types. In low-level languages this is a collection of functions.
- Parameters:
name (str) – The name of the interface function.
functions (iterable) – The internal functions that can be accessed via the interface.
is_argument (bool) – True if the interface is used for a function argument.
is_imported (bool) – True if the interface is imported from another file.
syntactic_node (FunctionDef, default: None) – The syntactic node that is not annotated.
Examples
>>> from pyccel.ast.core import Interface, FunctionDef >>> f = FunctionDef('F', [], [], []) >>> Interface('I', [f])
- clone(newname, **new_kwargs)[source]#
Create an almost identical Interface with name newname.
Create an almost identical Interface with name newname. Additional parameters can be passed to alter the resulting FunctionDef.
- Parameters:
newname (str) – New name for the Interface.
**new_kwargs (dict) – Any new keyword arguments to be passed to the new Interface.
- Returns:
The clone of the interface.
- Return type:
- property docstring#
The docstring of the function.
The docstring of the interface function.
- property functions#
“Functions of the interface.
- property is_argument#
True if the interface is used for a function argument.
- property is_imported#
Indicates if the function was imported from another file.
Indicates if the function was imported from another file.
- property is_inline#
Flag to check if the node is inlined.
Flag to check if the node is inlined.
- property is_semantic#
Flag to check if the node is annotated.
Flag to check if the node has been annotated with type descriptors in the semantic stage.
- property name#
Name of the interface.
- point(args)[source]#
Return the actual function that will be called, depending on the passed arguments.
From the arguments passed in the function call, determine which of the FunctionDef objects in the Interface is actually called.
- Parameters:
args (tuple[TypedAstNode]) – The arguments passed in the function call.
- Returns:
The function definition which corresponds with the arguments.
- Return type:
- rename(newname)[source]#
Rename the Interface name to a newname.
Rename the Interface name to a newname.
- Parameters:
newname (str) – New name for the Interface.
- property syntactic_node#
The syntactic node that is not annotated.
The syntactic node that is not annotated.
- class pyccel.ast.core.Module(name, variables, funcs, init_func=None, free_func=None, program=None, interfaces=(), classes=(), imports=(), scope=None, is_external=False)[source]#
Bases:
ScopedAstNode
Represents a module in the code.
The Pyccel node representing a Python module. A module consists of everything inside a given Python file.
- Parameters:
name (str) – Name of the module.
variables (list) – List of the variables that appear in the block.
funcs (list) – A list of FunctionDef instances.
init_func (FunctionDef, default: None) – The function which initialises the module (expressions in the python module which are executed on import).
free_func (FunctionDef, default: None) – The function which frees any variables allocated in the module.
program (Program/CodeBlock) – CodeBlock containing any expressions which are only executed when the module is executed directly.
interfaces (list) – A list of Interface instances.
classes (list) – A list of ClassDef instances.
imports (list, tuple) – List of needed imports.
scope (Scope) – The scope of the module.
is_external (bool) – Indicates if the Module’s definition is found elsewhere. This is notably the case for gFTL extensions.
Examples
>>> from pyccel.ast.variable import Variable >>> from pyccel.ast.core import FunctionDefArgument, Assign, FunctionDefResult >>> from pyccel.ast.core import ClassDef, FunctionDef, Module >>> from pyccel.ast.operators import PyccelAdd, PyccelMinus >>> from pyccel.ast.literals import LiteralInteger >>> x = Variable(PythonNativeFloat(), 'x') >>> y = Variable(PythonNativeFloat(), 'y') >>> z = Variable(PythonNativeFloat(), 'z') >>> t = Variable(PythonNativeFloat(), 't') >>> a = Variable(PythonNativeFloat(), 'a') >>> b = Variable(PythonNativeFloat(), 'b') >>> body = [Assign(z,PyccelAdd(x,a))] >>> args = [FunctionDefArgument(arg) for arg in [x,y,a,b]] >>> results = [FunctionDefResult(res) for res in [z,t]] >>> translate = FunctionDef('translate', args, results, body) >>> attributes = [x,y] >>> methods = [translate] >>> Point = ClassDef('Point', attributes, methods) >>> incr = FunctionDef('incr', [FunctionDefArgument(x)], [FunctionDefResult(y)], [Assign(y,PyccelAdd(x,LiteralInteger(1)))]) >>> decr = FunctionDef('decr', [FunctionDefArgument(x)], [FunctionDefResult(y)], [Assign(y,PyccelMinus(x,LiteralInteger(1)))]) >>> Module('my_module', [], [incr, decr], classes = [Point]) Module(my_module, [], [FunctionDef(), FunctionDef()], [], [ClassDef(Point, (x, y), (FunctionDef(),), [public], (), [], [])], ())
- property body#
Returns the functions, interfaces and classes defined in the module
- property classes#
Any classes defined in the module
- property declarations#
Get the declarations of all variables in the module.
Get the declarations of all variables in the module.
- property free_func#
The function which frees any variables allocated in the module
- property funcs#
Any functions defined in the module
- property imports#
Any imports in the module
- property init_func#
The function which initialises the module (expressions in the python module which are executed on import)
- property interfaces#
Any interfaces defined in the module
- property is_external#
Indicate if the Module’s definition is found elsewhere.
This is notably the case for gFTL extensions.
- property name#
Name of the module
- property program#
CodeBlock or Program containing any expressions which are only executed when the module is executed directly
- property variables#
Module global variables
- class pyccel.ast.core.ModuleHeader(module)[source]#
Bases:
PyccelAstNode
Represents the header file for a module.
This class is simply a wrapper around a module. It is helpful to differentiate between headers and sources when printing.
- Parameters:
module (Module) – The module described by the header.
See also
Module
The module itself.
Examples
>>> from pyccel.ast.variable import Variable >>> from pyccel.ast.core import FunctionDefArgument, Assign, FunctionDefResult >>> from pyccel.ast.core import ClassDef, FunctionDef, Module >>> from pyccel.ast.operators import PyccelAdd, PyccelMinus >>> from pyccel.ast.literals import LiteralInteger >>> x = Variable(PythonNativeFloat(), 'x') >>> y = Variable(PythonNativeFloat(), 'y') >>> z = Variable(PythonNativeFloat(), 'z') >>> t = Variable(PythonNativeFloat(), 't') >>> a = Variable(PythonNativeFloat(), 'a') >>> b = Variable(PythonNativeFloat(), 'b') >>> body = [Assign(z,PyccelAdd(x,a))] >>> args = [FunctionDefArgument(arg) for arg in [x,y,a,b]] >>> results = [FunctionDefResult(res) for res in [z,t]] >>> translate = FunctionDef('translate', args, results, body) >>> attributes = [x,y] >>> methods = [translate] >>> Point = ClassDef('Point', attributes, methods) >>> incr = FunctionDef('incr', [FunctionDefArgument(x)], [FunctionDefResult(y)], [Assign(y,PyccelAdd(x,LiteralInteger(1)))]) >>> decr = FunctionDef('decr', [FunctionDefArgument(x)], [FunctionDefResult(y)], [Assign(y,PyccelMinus(x,LiteralInteger(1)))]) >>> Module('my_module', [], [incr, decr], classes = [Point]) >>> ModuleHeader(mod) Module(my_module, [], [FunctionDef(), FunctionDef()], [], [ClassDef(Point, (x, y), (FunctionDef(),), [public], (), [], [])], ())
- property module#
- class pyccel.ast.core.Pass[source]#
Bases:
PyccelAstNode
Basic class for pass instruction.
- class pyccel.ast.core.Program(name, variables, body, imports=(), scope=None)[source]#
Bases:
ScopedAstNode
Represents a Program in the code.
A class representing a program in the code. A program is a set of statements that are executed when the module is run directly. In Python these statements are located in an if __name__ == ‘__main__’: block.
- Parameters:
name (str) – The name used to identify the program (this is used for printing in Fortran).
variables (Iterable[Variable]) – An iterable object containing the variables that appear in the program.
body (CodeBlock) – An CodeBlock containing the statements in the body of the program.
imports (Iterable[Import]) – An iterable object containing the imports used by the program.
scope (Scope) – The scope of the program.
- property body#
Statements in the program
- property imports#
Imports imported in the program
- property name#
Name of the executable
- property variables#
Variables contained within the program
- class pyccel.ast.core.PyccelFunctionDef(name, func_class, *, decorators={}, argument_description={})[source]#
Bases:
FunctionDef
Class used for storing PyccelFunction objects in a FunctionDef.
Class inheriting from FunctionDef which can store a pointer to a class type defined by pyccel for treating internal functions. This is useful for importing builtin functions and for defining classes which have PyccelFunction objects as attributes or methods.
- Parameters:
name (str) – The name of the function.
func_class (type inheriting from PyccelFunction / TypedAstNode) – The class which should be instantiated upon a FunctionCall to this FunctionDef object.
decorators (dictionary) – A dictionary whose keys are the names of decorators and whose values contain their implementation.
argument_description (dict, optional) – A dictionary containing all arguments and their default values. This is useful in order to reuse types with similar functionalities but different default values.
- property argument_description#
Get a description of the arguments.
Return a dictionary whose keys are the arguments with default values and whose values are the default values for the function described by the PyccelFunctionDef
- class_type = <pyccel.ast.datatypes.SymbolicType object>#
- class pyccel.ast.core.Raise[source]#
Bases:
PyccelAstNode
Represents a raise in the code.
- class pyccel.ast.core.Return(expr, stmt=None)[source]#
Bases:
PyccelAstNode
Represents a return statement in a function in the code.
Represents a return statement in a function in the code.
- Parameters:
expr (TypedAstNode) – The expression to return.
stmt (PyccelAstNode) – Any assign statements in the case of expression return.
- property expr#
- property n_explicit_results#
The number of variables explicitly returned.
The number of variables explicitly returned.
- property stmt#
- class pyccel.ast.core.SeparatorComment(n)[source]#
Bases:
Comment
Represents a Separator Comment in the code.
- Parameters:
mark (str) – marker
Examples
>>> from pyccel.ast.core import SeparatorComment >>> SeparatorComment(n=40) # ........................................
- class pyccel.ast.core.StarredArguments(args)[source]#
Bases:
PyccelAstNode
- property args_var#
- class pyccel.ast.core.SympyFunction(name, arguments, body, results=None, *, global_vars=(), cls_name=None, is_static=False, imports=(), decorators={}, headers=(), is_recursive=False, is_pure=False, is_elemental=False, is_private=False, is_header=False, is_external=False, is_imported=False, functions=(), interfaces=(), result_pointer_map={}, docstring=None, scope=None)[source]#
Bases:
FunctionDef
Represents a function definition.
- class pyccel.ast.core.While(test, body, scope=None)[source]#
Bases:
ScopedAstNode
Represents a ‘while’ statement in the code.
- Expressions are of the form:
- “while test:
body…”
- Parameters:
test (TypedAstNode) – Test condition given as an expression.
body (list of Pyccel objects) – List of statements representing the body of the While statement.
scope (Scope) – The scope for the loop.
Examples
>>> from pyccel.ast.internals import PyccelSymbol >>> from pyccel.ast.core import Assign, While >>> n = PyccelSymbol('n') >>> While((n>1), [Assign(n,n-1)]) While(n > 1, (n := n - 1,))
- property body#
- property local_vars#
List of variables defined in the loop
- property test#
- class pyccel.ast.core.With(test, body, scope=None)[source]#
Bases:
ScopedAstNode
Represents a ‘with’ statement in the code.
Represents a ‘with’ statement in the code. Expressions are of the form:
>>> with statement: >>> body...
!! This code is untested.
- Parameters:
test (TypedAstNode) – With definition statement given as an expression.
body (list of PyccelAstNodes) – List of statements representing the body of the With statement.
scope (Scope) – The scope of the block.
- property body#
- property test#