curry.interpreter package
A Curry interpreter.
The Interpreter manages compilation and evaluation of Curry code. Each instance has a separate copy of the settings and runtime.
- class curry.interpreter.Interpreter(flags={})[source]
Bases:
InterpreterRepresents one instance of a Curry system.
Key data and methods are as follows:
- Data:
- Methods:
compile()Compile a string containing Curry code.
eval()Evaluate a Curry expression.
expr()Build a Curry expression.
import_()Import a Curry module.
load()Load compiled Curry.
module()Look up a module by name.
reset()Soft-reset the interpreter.
save()Save compiled Curry.
stats()Report the statistics of the run.
symbol()Look up a symbol by name.
topython()Convert Curry data to Python.
type()Look up a data type by name.
- property backend
The backend object associated with this interpreter.
- compile(mode='module', imports=None, exprtype=None, modulename=None)
Compile a string containing Curry code. In mode ‘module’, the string is interpreted as a Curry module. In mode ‘expr’, the string is interpreted as a Curry expression.
- Parameters:
string – A string containing Curry code.
mode – Indicates how to interpret the string (see above).
imports – A list specifying additional modules to import. The elements can be strings or
CurryModuleobjects. Import statements will be prepended to the code string and CURRYPATH will be adjusted accordingly. This can be useful when importing dynamically-compiled modules whose names and locations are difficult to obtain.exprtype – A string specifying the expression type. This is what would appear to the right of
::in a Curry type annotation for the expression. Used only in ‘expr’ mode. Without it, the class constraints of the expression are defaulted with the table of the PAKCS REPL:NumtoInt,FractionaltoFloat,MonadtoIO, a loneDatatoBool; seecurry.typecheck.defaulting.modulename – Specifies the module name. Used only in ‘module’ mode. The module is placed in
curry.interpreter:Interpreter.modulesunder that name. By default, a unique name is chosen, which no later compile reuses.
- Returns:
In ‘module’ mode, a
CurryModule. In ‘expr’ mode, a Curry expression. A text that ends inwhere x, y freedeclares free variables, as in the REPL. A variable whose type is absent from the result type of the expression cannot show in a value, socurry.evalyields each value of such an expression with its binding (Bindings); a variable whose type occurs in the result type is left in the value. The REPL of PAKCS prints the binding of every declared variable. Withexprtype, or with a comment afterfree, the clause stays a local declaration and no binding is reported.- Raises:
CompileError – The front end rejects the text, or, in ‘expr’ mode without
exprtype, the table cannot default a class constraint.
- currytype(ty)
Gets the Curry type corresponding to a Python type. For instance, for the Python
booltype, this returns the type object forPrelude.Bool.
- describe(*args, **kwds)
The description of an expression: the arguments of
expr()as a tree, typed only when a consumer asks for its node. The DSL builds descriptions at every operator and types them once at the boundary, so that an outer context fixes the types of the inner parts. A description is an argument ofexpr()and ofeval;strprints it in Curry syntax; its methodtypeofgives its type. The keywordexprtypestates the type of the description; the other keywords are its anchors. SeeDescription.
- eval(*args, **kwds)
Evaluate a Curry goal.
- Parameters:
*args – Positional arguments that specify the goal. These are passed to
Interpreter.expr. One function symbol whose scheme has class constraints and no value parameter, a goal without a signature such asmain = Just 5, is applied to its dictionaries first: the constraints are defaulted with the table of the PAKCS REPL (seecurry.typecheck.defaulting), so the goal evaluates to a value and not to a partial application. An expression ofcurry.compile(mode='expr')whose text declaredwhere x freevariables absent from its result type yields its values with the bindings of those variables (curry.typecheck.goals.Bindings).converter – Keyword-only argument specifying the converter to use when returning results. The default is ‘default’, the flag
defaultconverter.'topython'appliescurry.topython(),Noneand any other name leave the Curry value, and a callablef(interp, value)converts as it pleases. See :func:curry.interpreter.conversions.getconverter.exprtype – Keyword-only argument: the type of the goal in Curry syntax, passed to
Interpreter.expr.**kwds – Any other keyword names an anchor, as in
Interpreter.expr.
- Raises:
EvaluationError – A Curry error occurred during evaluation.
CurryTypeError – The table cannot default a class constraint of the goal.
- Returns:
A generator producing the values of the specified Curry program.
- expr(*args, **kwds)
Builds a Curry expression.
The expression is typed before it is built (see
curry.typecheck.builder): the type schemes of the symbols are read from the FlatCurry interfaces of their modules, the arguments are unified with the parameter types, the class constraints are defaulted with the table of the PAKCS REPL, and the class dictionaries are supplied. Soexpr(curry.symbol('Prelude.+'), 1, 2)builds the call of the method atInt, andexpr(P.show, [P.Just, 1])finds theShowinstance ofMaybe Int. A typing failure raisesCurryTypeErrorat construction; nothing is evaluated. The flagtyped_exprturns the typing off.The arguments specify the expression to build. Each positional argument must be directly convertible to Curry or describe a node. A Python value converts by the type its position expects:
bool: Converted toPrelude.Bool.intPrelude.Int;Prelude.FloatunderFloat; thefromIntconversion under anotherNuminstance.floatConverted toPrelude.Float.strUnder[Char]one string of any length. Elsewhere a string of length one is aPrelude.Char, and another string is[Char].listConverted to a Curry list, in a loop. Every element takes the element type, so[1, 2.5]is[Float].tupleConverted to a Curry tuple.iteratorLazily converted to a Curry list. The element type is fixed when the expression is built; an item that does not convert ends the evaluation with anEvaluationError.NoneAn error that names the expected type.a Curry node Typed by a walk of its content, up to 100000 nodes;
curry.typed(node, 'T')states the type instead. A node alone passes through untouched.
Any (possibly nested) sequence whose first element is an instance of
NodeInfospecifies a node. The remaining arguments are recursively converted to Curry expressions to form the successors list. Thus, given suitable definitions, it is possible to build the Curry list[0,1,2]with the following code:expr([Cons, 0, [Cons, 1, [Cons, 2, Nil]]])
Fewer arguments than the symbol takes give a partial application; more arguments go through
Prelude.applywhen the result is a function. A symbol without a type scheme (a module without a FlatCurry interface, or a built-in of Sprite’s own Prelude) is built untyped when it stands alone, as the goal of a saved module does, and is an error when it is applied to arguments;typeof()refuses it either way.Several special symbols are provided. See
anchor,choice,cons,fail,free,nil,ref,typed, andunboxed. Afreemarker becomes a call ofPrelude.unknown, one node per marker, and achoicemarker a call ofPrelude.?, so the runtime assigns the ids.raw_exprbuilds the rawFreeandChoicenodes instead. Anunboxedmarker stands only as the payload of a primitive,[Prelude.Int, curry.unboxed(3)]; anywhere else it is aCurryTypeError.- Parameters:
interp – An interpreter object.
*args – Positional arguments used to construct expressions.
**kwds – Keyword arguments specifying subexpressions that may be referenced via
ref. Each keyword specifies the name of an anchor. See the examples below.exprtype – Keyword-only argument. The type of the expression in Curry syntax, for example
'Maybe Float'. Its type variables are rigid.target – Reserved keyword-only argument. If a target is supplied, then it will be rewritten with the specified expression. Otherwise a new node is created.
- Returns:
A Curry expression. Its type is recorded, so
typeof()answers for it, andevalconverts its values by it.
- property flags
A dict containing the configuration flags. Change its entries in place to change the behavior of the Curry system; the attribute cannot be assigned. The flag
backendis read when the interpreter is made, so a later change of it has no effect. Seecurry.interpreter.flags.
- import_(currypath=None, is_sourcefile=False)
Import one or more Curry modules.
- Parameters:
arg – A module descriptor indicating what to import. A module descriptor is a module name (string),
curry.icurry.IModuleobject, or a sequence of module descriptors.currypath – The search path for Curry files. By default,
self.pathis used.is_sourcefile – Indicates whether to interpret
argas a source file name rather than a module name.
- Returns:
A
CurryModuleor sequence thereof.
- load(filename, **kwds)
Loads a Curry module saved with
save().Aside from how the file is located, this follows the import protocol, so the module is added to the interpreter’s
modulesdict.- Parameters:
filename – The path to a file to load. The file type and suffix must match the interpreter.
from_plan – True when the import plan loads the current object of a module it imports, False for a file the user named (the C++ backend decides some refusals by it; see its loader).
- Returns:
A
CurryModule.
- property modules
A dict containing the imported Curry modules. Maps module names to
CurryModuleobjects.
- optimize(imodule, optimizers=default_optimizers)
- property path
A list of strings specifying the Curry search path. Change it in place to adjust where to search for Curry files. An assignment to the attribute replaces the entries of the same list.
- property prelude
The built-in module Prelude.
- raw_expr(*args, **kwds)
The untyped builder. Equivalent to
expr()without the types: every Python value converts by its Python type, only the arity of a symbol is checked, no dictionary is supplied, afreemarker becomes a rawFreenode with the id of the marker, a new node per occurrence, and achoicemarker a rawChoicenode with the id of the marker. Fewer arguments than the arity of a symbol give a partial application; a function applied to more goes throughPrelude.apply, one node per surplus argument, as a point-free definition needs; a constructor applied to more is an error. An expression that is not well typed evaluates with undefined behaviour.
- reset()[source]
Soft-resets the interpreter.
Clears the loaded modules, except the Prelude and the packages. Restores I/O streams to their defaults, resets the Curry path from the environment, releases the expression modules, and clears the signature table. The names of anonymous modules are not reused; see compile.py. This is much faster than building a new interpreter, which loads the Prelude.
- save(filename=None, goal=None, **kwds)
Saves a Curry module.
- Parameters:
cymodule – The argument to dump. Must be a valid argument to inspect.geticurry.
filename – A file name, stream, or None. If None, a string is returned. Otherwise, the file is created, if specified, and the output is written to the file or stream.
goal – The goal the saved program evaluates when it runs, unless
-gon its command line names another. A program needs one: withoutgoalthe call raisesValueError(issue #35). To save a module without a main program, forload(), passmodule_main=False. A goal with class constraints and no signature is defaulted with the table of the PAKCS REPL at run time; the file records its type, so it runs from any directory. A goal the table cannot default raises here, at save time. On the C++ backend the saved file is C++ source, and its record names the source of the module relative to the directory of the object (the product directory beside the source,.curry/<subdir>/). Compile the file in that directory, assprite-make --sodoes; an object compiled elsewhere loads, but its module has no source file (backends.cxx.loader.source_file).kwds – Additional keyword arguments passed to
IBackend.write_module. Possibly specific to the backend.
- Returns:
If
filenameis None, the module contents are returned as a string. Otherwise, None.
- property setfunctions
The built-in module Control.SetFunctions.
- property sigtable
SignatureTable <curry.typecheck.SignatureTable>: the type schemes of the loaded symbols, read on demand from the FlatCurry interfaces.
reset()clears it.- Type:
The signature table, a
- Type:
class
- stats()
Reports the statistics of the run.
- Returns:
wallSeconds since this process started (on Linux; elsewhere, since the Curry system was imported). The start time of a process has a resolution of one clock tick, 10 ms on most systems.
cpuUser plus system CPU seconds of this process. Child processes, such as the Curry front end and the C++ compiler, are not included.
stepsThe rewrite steps taken by the evaluations of this interpreter, a running evaluation included. A soft reset keeps the count.
forksThe number of times a configuration forked at a choice in those evaluations.
collectionsThe collections run in this process by the node collector of the C++ backend. The Python backend reports zero.
peak_rssThe peak resident set size of this process, in bytes.
compileSeconds this process spent in the steps of the toolchain: the Curry front end, the ICurry-JSON conversion, the code generator, and the C++ compiler. Zero when every file was current.
gc_secondsSeconds the node collector of the C++ backend spent in its collections. The Python backend reports zero.
swappedThe functions that tiered execution of the C++ backend swapped from the interpreter to compiled code in this process (the interpreter flag
interpretset to ‘tiered’). The Python backend reports zero.failed_compilesThe background compiles of tiered execution that failed in this process; the modules stay interpreted. The Python backend reports zero.
gc_roots_seconds,gc_trace_seconds,gc_sweep_seconds,gc_registries_secondsSeconds the collections of the node collector spent in each phase: the roots (the configurations of the queues and the nodes Python holds), the trace from the roots, the block sweep, and the registries (the free-variable tables, the generator nodes, the queues and the sets). The verifier of the stress mode is in none of them. The Python backend reports zero.
gc_marked,gc_marked_old,gc_marked_youngThe nodes the collections marked: all, those marked in the collection before as well (old), and those allocated since (young).
gc_configurations_pushedThe configurations whose roots the collections pushed.
gc_queues_destroyed,gc_configurations_destroyedThe queues of set functions no root reached, destroyed by the collections, and the configurations destroyed with them.
gc_old_redexes,gc_old_slot_writes,gc_old_nodes_written,gc_old_blocksThe writes into old nodes between the collections: the writes of a step into an old redex, the other pointer writes into an old node, the distinct old nodes written, and the blocks with such a write, summed over the intervals. Only a runtime built with the write counters (make GC_WRITE_COUNTERS=1) counts them; the default build reports zero.
A C++ runtime built with the scheduler counters (make COUNTERS=1) adds the keys of
SCHEDULER_KEYS; seescheduler_fields().- Return type:
A
Statsobject, a dict with these keys, in this order
- symbol(modulename=None)[source]
Look up a symbol by its fully-qualified name,
'Prelude.+'. The name splits at its first dot into a module and a name in it, so'Data.List.nub'needs the packageDataloaded, as an import ofData.Listleaves it. The second parameter has no effect.
- topython(convert_strings=True, exprtype=None)
Converts a Curry value to Python by substituting built-in types.
This functions converts (recursively) the types
int,float,str,bool,list, andtuple. Other types are passed through untouched.- Parameters:
value – The Curry value to convert.
convert_strings – If True, then lists of characters are converted to Python strings.
exprtype – The static type of the value, in Curry syntax or as a FlatCurry type, or None. The type is threaded through the lists and the tuples: an empty list under
[Char]converts to'', while a list under a type variable or without a type converts to a string when it holds characters.curry.evalpasses the type of the goal it built.
- Raises:
NotConstructorError – Non-ground data was encountered along a list spine.
- Returns:
The value converted to Python.
- typeof(defaulted=False)
The type of an expression in Curry syntax. Without
defaultedthe undefaulted scheme, what:typeprints:typeof(expr(plus, 1, 2))isNum a => a. Withdefaultedthe type after the table of the PAKCS REPL:Int.eis a nodeexpr()returned, any other Curry node (typed by its content), a symbol, a description ofdescribe(), or any argumentexpr()accepts.
- static unbox(arg)
Unbox a built-in primitive or IO type.