API Documentation

Parsers API

This file contains the base logic for the parser generator. It declares a base class, Parser, from which every parsing primitive derives.

It contains both the public interface to the parsers (eg. the Rows, Opt, Or, etc.. classes), and the engine implementation that will actually emit the final code.

The way the code is generated is by recursively visiting the parser structure and emitting the code corresponding to the declared parser. For example, for the following rule definition:

if_stmt=Row("if", G.expression, "then", G.statements, "endif")

The row structure will be visited recursively, emitting the corresponding code.

The parser generator generates separate functions for every rule that is declared. It means that in the case of the previous example, a rule will be declared for if_stmt, and for the expression and statements rule, that are not defined in the example, but relied on explicitly.

class langkit.parsers.Cut(context: CompileCtx, location: Location)[source]

An instance of this parser will prevent backtracking from the point where the cut is inserted.

Diagnostics will be emitted (so the resulting analysis unit will necessarily be considered as being erroneous), the parser will return an incomplete error node, but will not return ``No_Token_Index``, and hence parsing will continue from the next token.

Note that in the general case, this behavior (parsing continuing), will just lead to an immediate failure, because the parser will start back from a point that makes no sense. But, combined with the use of Skip parsers, this can allow the user to continue parsing by skipping every token until it finds something that makes sense.

This parser is used to:

  1. Get better error messages. You are indicating the parser that if something fails past a certain point, it should not backtrack. That allows the parser to generate a specific error message for that branch, instead of a more generic error message later on.

    Note

    This is only half true for the moment. We can definitely further improve the quality of error messages Cuts produce.

  2. Get better error recovery. So far this is the primary reason the Cut parser is used. Associated with other error recovery primitives in Langkit, such as the Skip parser, this will allow you to generate more precise incomplete/incorrect nodes.

Here is an example of how to use the Cut parser. Let’s take the example of a very simple rule like the following:

fn=Fn("function", name, "is", stmts, "end")

In this case, if we try to parse the input "function end", it will fail completely, and not produce any node.

If we add a cut in the rule like so:

fn=Fn("function", Cut(), name, "is", stmts, "end")

Then, parsing the same input will produce an incomplete Fn node. Parsing will probably fail on the next token (end) anyway.

If you combine that with the use of the Skip parser, you can get a parser that can recover errors:

fn=Fn("function", Cut(), name, "is", stmts, "end")
typ=Typ("type", Cut(), name, "is", ..., "end")
decls=List(Or(fn, typ, Skip(ErrorDecl)))

With this parser, you can parse incomplete code such as:

type A             --  This will produce an incomplete node thanks to
                   --  the cut annotation, and parser will start back
                   --  from the "end" token.

end                --  This token will be skipped thanks to the
                   --  ``Skip`` parser.

function Foo is    --  This function decl will be parsed correctly
    print("lol")
end

Still in the perspective of better error recovery, a Cut parser is also allowed in an Opt parser in order to prevent backtracking even when an Opt parser fails. Here is an example of how to use the Cut parser in an Opt one:

body=Body(Opt("scope", identifier), "begin", stmts_list, "end")

In this case, if we try to parse the input "scope begin [stmts] end", it will fail because of the missing identifier field, the Opt parser will backtrack and the scope keyword will report an error. Nevertheless, it can be improved thanks to a Cut:

body=Body(Opt("scope", Cut(), identifier), "begin", stmts_list, "end")

Now, the parser will not backtrack and produce an incomplete node, taking into account the Opt part. The error will now concern the identifier field being absent instead of complaining about the scope keyword. This also means that on the simple input: "scope", the parser won’t backtrack and produce an incomplete Body node.

Note that the Cut parser only applies to the Opt parser it is defined in, therefore, the parser will backtrack on the following input: "begin end". Here, the parser will fail because of the missing stmts_list field. Several Cut parsers can be used to improve error recovery in that case. Rewriting the rule as:

body=Body(Opt("scope", Cut(), identifier),
          "begin", Cut(), stmts_list, "end")

will allow the parser to properly parse the incomplete input, reporting the missing stmts_list field. Moreover, if no Cut is defined in the Opt parser:

body=Body(Opt("scope", identifier), "begin", Cut(), stmts_list, "end")

The Cut in the Body parser has no effect in the Opt part, which means that the following input: "scope begin end", will produce a parsing error and won’t recover anything from the Opt parser: the identifier being absent, the Opt parser will fail and backtrack, the scope keyword will be reported as en error, and, the begin end will be incompletely parsed (no backtrack because of the Cut).

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

property discard: bool

Return whether the result of this parser must be discarded (i.e. whether it does not return a node).

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.Defer(context: CompileCtx, location: Location, rule_name: str, parser_fn: Callable[[], Parser])[source]

Stub parser used to implement forward references.

Create a stub parser.

Parameters:
  • rule_name (str) – the name of the deferred parser (used for pretty-printing).

  • parser_fn (callable) – must be a callable that returns the referenced parser.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.Discard(context: CompileCtx, location: Location, parser: Parser)[source]

Wrapper parser used to discard the match.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

property discard: bool

Return whether the result of this parser must be discarded (i.e. whether it does not return a node).

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.DontSkip(context: CompileCtx, location: Location, subparser: Parser, dontskip_parsers: list[Parser])[source]

This is used in the following way:

parser.dont_skip(other_parser)

This means that in the scope of parser, if a skip parser occurs, it will first run other_parser, and if other_parser is successful, then skip will fail (eg. not skip anything).

For more details about the use of this parser, check the documentation of Skip.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.GeneratedParser(name: Name, spec: str, body: str)[source]

Simple holder for generated parsers.

class langkit.parsers.Grammar(context: CompileCtx, location: Location, main_rule_name: str, extra_entry_points: set[str] | None = None, with_unparsers: bool = False)[source]

Holder for parsing rules.

Parsing rules can be added incrementally while referencing each other: this class will automatically resolve forward references when needed.

Parameters:
  • context – Compilatio context that owns this grammar.

  • location – Source location for the declaration of this grammar.

  • main_rule_name – Name of the main parsing rule.

  • entry_points – Set of rule names for parsing rules that are entry points. Entry points are used as “used roots” for unused rules detection. The main rule is automatically considered as an entry point.

  • with_unparsers – Whether to generate unparsers for this grammar.

add_rule(name: str, parser: Parser, doc: str = '') → None[source]

Add a rule to the grammar. The input parser is expected to have its location properly set at this point.

Parameters:
  • name – Name for the new parsing rule.

  • parser – Root parser for this rule.

  • doc – Documentation for this rule.

check_entry_points(context: CompileCtx) → None[source]

Emit an error if any of the entry points are missing.

compute_user_defined_rules(context: CompileCtx) → None[source]

Compute the list of rule names defined by the user.

get_unreferenced_rules() → set[str][source]

Return a set of names for all rules that are not transitively referenced by entry points.

rule_resolver(rule_name: str) → Callable[[], Parser][source]

Return a callable that returns the rule designated by rule_name.

rules: dict[str, Parser]

For each parsing rule, associate its name to its parser.

user_defined_rules: list[str]

List of rules names defined by the language spec.

user_defined_rules_docs: dict[str, str]

Mapping from rules defined by the language spec to the corresponding documentations.

user_defined_rules_indexes: dict[str, int]

Reverse mapping for user_defined_rules.

uses_external_properties

Whether a parsing rule uses an external property. If one does, generated code must use visibility.

warn_unreferenced_parsing_rules(context: CompileCtx) → None[source]

Emit a warning for unreferenced parsing rules.

class langkit.parsers.List(context: CompileCtx, location: Location, parser: Parser, sep: Parser | None = None, empty_valid: bool = False, list_cls: ASTNodeType | None = None, extra: ListSepExtra | None = None)[source]

Parser that matches a list. A sub-parser matches list items.

Create a parser that matches a list of elements.

Each element will be matched by parser. If sep is provided, it is a parser that is used to match separators between elements.

By default, this parser will not match empty sequences but it will if empty_valid is True.

Parameters:
  • sep – Parser or string corresponding to the token that is used to match separators between elements.

  • list_cls – If provided, it must be a ASTNodeType.list subtype to be used for the result of this parser.

  • empty_valid – Whether to match empty sequences or not.

  • extra – Whether this list parser allows extra separators.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

create_vars_before() → VarDef | None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to override the position variable for its sub-parsers, it should override this callback and return the new position variable.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.ListSepExtra(*values)[source]

Whether list parsers allow extra separators.

property ada_name: str

Return the name for this enum value, with the Ada casing.

allow_leading = 2

It accepts one optional list separator before the first element.

allow_none = 1

It accepts only separators between list elements.

allow_trailing = 3

It accepts one optional list separator after the last element.

class langkit.parsers.NoVarDef[source]

Substitute for VarDef instances to mean “no variable” when None already means “use the default”.

class langkit.parsers.Null(context: CompileCtx, location: Location, result_type: ASTNodeType)[source]

Parser that matches the empty sequence and that yields no AST node.

Create a new Null parser. result_type is either a CompiledType instance that defines what nullexpr this parser returns, either a Parser subclass’ instance. In the latter case, this parser will return the same type as the other parser.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

property for_bool_node: bool

Return whether this parser creates an “absent” bool node.

freeze_types() → None[source]

Initialize self.type with the result of the compute_types pass.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.Opt(context: CompileCtx, location: Location, parsers: list[Parser])[source]

Parser that matches something if possible or that matches an empty sequence otherwise.

Create a parser that matches parsers if possible or matches an empty sequence otherwise.

as_bool(dest: ASTNodeType) → Parser[source]

Return the self parser, modified to return dest nodes rather than the sub-parser result. dest must be a bool enum node: the parser result will be the “true” qualifier if the parse was successful, and the “false” qualifier otherwise.

This is typically useful to store specific tokens as attributes, for example in Ada, you’ll mark a subprogram as overriding with the “overriding” keyword, and we want to store that in the tree as a boolean attribute, so we’ll use:

Opt("overriding").as_bool(OverridingQualifier)
Parameters:

dest – An enum node with qualifier set to True. The result will be booleanized using this enum node type.

property booleanized_type: CompiledType

For parsers that return a boolean, return the actual result type to use in code generation.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

property discard: bool

Return whether the result of this parser must be discarded (i.e. whether it does not return a node).

error() → Parser[source]

Returns the self parser, modified to function as an error recovery parser.

The semantic of Opt in this case is that it will try to parse it’s sub parser, and when failing, it will add a diagnostic to the parser’s diagnostic list.

NOTE: There is no diagnostics backtracking if the parent parser is discarded. That means that you should only use this parser in cases in which you are sure that you are in a successfull branch of your parser. This is neither checked statically nor dynamically so use with care!

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.Or(context: CompileCtx, location: Location, parsers: list[Parser])[source]

Parser that matches what the first sub-parser accepts.

Create a parser that matches any thing that the first parser in parsers accepts.

property can_parse_token_node: bool

Return whether this parser can be used as a sub-parser to build token nodes.

Return type:

bool

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

property discard: bool

Return whether the result of this parser must be discarded (i.e. whether it does not return a node).

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.Parser(context: CompileCtx, location: Location)[source]

Base class for parsers building blocks.

add_symbol_literals() → None[source]

Register symbols literals used by this parser to “context”.

property base_name: Name

Return a simple name (names.Name instance) for this parser.

The result is used as a base name for the generated function name.

property can_parse_token_node: bool

Return whether this parser can be used as a sub-parser to build token nodes.

Return type:

bool

check_toplevel_rules() → None[source]

Make sure that top-level grammar rules yield nodes.

abstract property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

compile() → None[source]

Compile this parser tree.

Assuming that type inference on node parse fields already run, this performs general validation on parsers.

compute_types() → None[source]

Infer parse fields from this parser tree.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

create_vars_before() → VarDef | None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to override the position variable for its sub-parsers, it should override this callback and return the new position variable.

property discard: bool

Return whether the result of this parser must be discarded (i.e. whether it does not return a node).

property error_repr: str

Return a representation of the parser suitable for generated code’s error messages.

freeze_types() → None[source]

Initialize self.type with the result of the compute_types pass.

abstractmethod generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

init_vars(pos_var: VarDef | None = None, res_var: VarDef | NoVarDef | None = None) → None[source]

Set or create variables for code generation.

Parameters:
  • pos_var – If provided, variable to use as self.pos_var. Otherwise, create a new VarDef instance.

  • res_var – If provided, variable to use as self.res_var. Otherwise, create a new VarDef instance.

is_dont_skip_parser

Whether this parser is a parser generated as part of a DontSkip parser, to scan the input to see if input should be skipped or not.

is_left_recursive() → bool[source]

Return whether this parser is left-recursive.

loc_comment(prefix: str) → str[source]

Return an Ada comment including prefix to locate this parser in generated code.

no_backtrack: VarDef | None

If this variable is set, it indicates that this parser is part of a no_backtrack hierarchy, indicating that if there is a failure, the parsers should not try to backtrack, but instead return a failure node.

When compiling the parsers, we will check existence of this variable to know if there is a possibility of not backtracing. At runtime, parsers will check the value of this variable to know if they should backtrack or not.

classmethod parser_cls_name() → str[source]

Return a name for this parser class to be used for code generation.

pos_var: VarDef | None

Variable to contain a token index (T.Token) during code generation.

Before this parser runs, this contains the index of the first token to analyze. After it has run, it contains the next index after the last token that was consumed by this parser.

property precise_element_types: TypeSet

Return the precise set of nodes that the list nodes this parser return can contain.

property precise_types: TypeSet

Return the precise set of nodes that this parser can return.

This is valid only for parsers that return nodes.

render(template_name: str, **kwargs: Any) → str[source]

Shortcut for render for parsers, passing the parsers sub-path for templates, and self as “parser” in the template context.

render_parser(context: CompileCtx) → None[source]

Emit code for this parser as a function into the global context.

Parameters:

context (langkit.compile_context.CompileCtx) – Global context.

property repr_label: str

Return the “label” to use for this parser in __repr__.

By default, this just returns the name of this Parser’s class. Subclasses can override this to include more relevant information.

res_var: VarDef | None

Variable to contain the parser result (self.type) during code generation.

set_grammar(grammar: Grammar) → None[source]

Associate grammar to this parser and to all its children.

Parameters:

grammar (Grammar) – The grammar instance.

set_name(name: Name) → None[source]

Rename this parser and all its children so that name is part of the corresponding function in the generated code.

Parameters:

name – The name to include in the name of this parser tree.

property symbol_literals: set[str]

Return a list of strings for all symbol literals used by this parser and all its subparsers.

Subclasses must override this method to actually include their own symbol literals.

traverse_create_vars(start_pos: VarDef) → None[source]

This method will traverse the parser tree and create variables for every parser. When this has finished running, every parser should have a pos_var and a res_var.

It leverages two callbacks that can be implemented by Parser subclasses: create_vars_before and create_vars_after.

traverse_dontskip(grammar: Grammar) → None[source]

Traverse the parser, looking for DontSkip parsers. When finding one, create a dedicated separate rule for the parsers that should not be skipped, so that we can store references to those parsers as function pointers.

traverse_nobacktrack(nobt: VarDef | None = None) → VarDef | None[source]

This method will traverse the parser hierarchy and set the no_backtrack variable if necessary, indicating which parsers should not backtrack.

property type: CompiledType | None

Type that this parser creates.

This can be either an ASTNodeType subclass, the token type, or None if this parser does not yield a specific value itself (for instance Row parsers).

class langkit.parsers.Predicate(context: CompileCtx, location: Location, parser: Parser, property_ref: PropertyDef)[source]

This composite parser takes as parameters a sub parser and a property reference that will be used as predicate, and will test the predicate on the node resulting of parsing. If true, it will return the node, else, it will error.

Parameters:
  • parser – Sub-parser whose result is the predicate input.

  • property_ref – Property to use as the predicate.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

property property_name: str

Informal representation for the property reference that this predicate references.

class langkit.parsers.Skip(context: CompileCtx, location: Location, dest_node: ASTNodeType)[source]

This recovery parser will skip any token and produce an error node from it, generating an error along the way.

A common use of the Skip parser is to skip as many tokens as necessary for the parent parser to fallback into a state where it is able to parse something successfully.

An example would be to use it in a list of statements:

stmt=Or(
    call,
    assign,
    ...,
)

stmts=List(Or(stmt, Skip(ErrorDecl)))

This way, if the parsing of any of the statements reaches an unexpected token that cannot be parsed by any of the statements, it will eventually be handled by the Skip parser, and produce an error decl for each unexpected token.

Note that if you use that in a List parser like above, and that parser is itself in a parser, you will probably need to use the DontSkip parser to signal to the skip parser that it must not eat certain tokens. Let’s develop the example above:

stmt=Or(
    call,
    assign,
    ...,
)

stmts=List(Or(stmt, Skip(ErrorDecl)))

function=Fn("function", name, "is", stmts, "end")

In the example above, the stmts parser will eat any unexpected token, including the eventual “end” token that signals the end of the function, before the function parser has the opportunity to use it. To solve this, we’ll use the DontSkip parser as such:

function=Fn("function", name, "is", stmts.dont_skip("end"), "end")

With this modification, the nested Skip parser will skip anything but the “end” token, making thus sure that the function can be parsed correctly.

Note

As other things in Langkit parsers, those annotations could probably be statically derived from the grammar definition.

Parameters:

dest_node (CompiledType) – The error node to create.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.StopCut(context: CompileCtx, location: Location, parser: Parser)[source]

This parser is meant to be used in combination with the Cut parser, containing its effects, by making sure the parser backtracks, and cancelling eventual error messages that might have been emitted.

  • If parsing of StopCut’s subparser is successful, nothing happens.

  • If parsing of StopCut’s subparser fails because of a cut (so returning an incomplete node), then the result is discarded, and StopCut returns a null result and position, forcing the parent parser to backtrack.

  • If parsing of StopCut’s subparser fails completely (so returning null), then we still reset eventual error messages that might have been emitted in nested Cut parsers.

Here is an example of how to use the StopCut parser. Imagine you have the two following rules:

def1=Def("def", Cut(), ..., "end")
def2=Var("def", Cut(), ...)

So far, we imagine it’s fine to have cuts in each rule, because they’re not used in a context where they can clash. But then at some point you add the following rule to your parser:

block=Block("{", Or(def1, def2), "}")

Then it doesn’t work, because def2 can’t ever be parsed, and you will always get an error node out of def1 in cases where you try to parse def2. If you add a StopCut parser you can solve that problem:

block=Block("{", Or(StopCut(def1), def2), "}")

In this case, the parsing of def1 will fail rather than return an error node, and so the Or will backtrack on def2.

property children: list[Parser]

Parsers are combined to create new and more complex parsers. They make up a parser tree. Return a list of children for this parser.

Subclasses must override this method.

create_vars_after(start_pos: VarDef) → None[source]

This callback can be implemented by parser subclasses, to create variables needed for parsing. If the parser needs to use the start_pos variable for either pos_var or res_var, this callback is the way to do it.

generate_code() → str[source]

Return generated code for this parser into the global context.

Subclasses must override this method.

class langkit.parsers.VarDef(context: CompileCtx, base_name: str, type: str | CompiledType, create: bool = True, reinit: bool = False)[source]

Holder object for a variable in parsers. Creating an instance of vardef requires a context to exist already.

Creates a VarDef.

Parameters:
  • base_name – The string used as base for the name of the variable. A number will be appended in order to make the variable unique.

  • type – The type of the variable.

  • create – If true, the variable will be automatically added to the current variable context when created, and an unique name will be generated. If false, it is considered that the definition is done in the template, so the name used is the name passed, and the variable won’t be added to the context.

  • reinit – If true, the variable will be reinitialized to null expr if variable occurs in a left recursive parser, and left recursion is triggered.

langkit.parsers.add_var_context(context: CompileCtx) → Iterator[list[VarDef]][source]

Context manager that will push a variable context into the stack when compiling a parser.

langkit.parsers.always_make_progress(parser: Parser) → bool[source]

Return whether parser cannot match an empty sequence of tokens.

langkit.parsers.make_pick(context: CompileCtx, location: Location, parsers: Sequence[Parser], no_checks: bool = False) → Parser[source]

Return a parser to scan a sequence of sub-parsers, removing tokens and ignored sub-parsers and extracting the only significant sub-result.

Parameters:

no_checks – If left to false, check that only one parser in parsers generates an node. Otherwise, don’t do this check.

langkit.parsers.var_context(context: CompileCtx) → list[VarDef][source]

Returns the var context for the current parser.

Lexer API

class langkit.lexer.Action(location: Location)[source]

Base class for an action. An action specificies what to do with a given match.

matcher: Matcher | None

If this action is associated to a Literal matcher, this will be set to it.

class langkit.lexer.Alt(send: Action, match_size: int, prev_token_cond: Sequence[Action] | None = None)[source]

Holder class used to specify the alternatives to a Case rule. Can only be used in this context.

class langkit.lexer.Case(location: Location, matcher: Matcher, *alts: Alt)[source]

Special rule association that enables dispatching the action depending on the previously parsed token. The canonical example is the one for which this class was added: in the Ada language, a tick character can be used either as the start of a character literal, or as an attribute expression.

One way to disambiguate is by looking at the previous token. An attribute expression can only happen is the token to the left is an identifier or the “all” keyword. In the rest of the cases, a tick will correspond to a character literal, or be a lexing error.

We can express that with the case rule this way:

Case(Pattern("'.'"),
     Alt(prev_token_cond=(Token.Identifier, Token.All),
         send=Token.Tick,
         match_size=1),
     Alt(send=Token.Char, match_size=3)),

If the previous token is an Identifier or an All, then we send Token.Tick, with a match size of 1. We need to specify that because if the lexer arrived here, it matched one tick, any char, and another tick, so it needs to rewind back to the first tick.

Else, then we matched a regular character literal. We send it.

class CaseAction(location: Location, match_length: int, *alts: Alt)[source]
class langkit.lexer.Ignore(location: Location)[source]

Action. Basically ignore the matched text.

class langkit.lexer.Lexer(tokens_class: Type[LexerToken], track_indent: bool = False, pre_rules: Sequence[tuple[Matcher, Action] | RuleAssoc] = [], case_insensitive: bool = False)[source]

This is the main lexer object, through which you will define your Lexer. At initialization time, you will need to provide an enum class to it, that will be used to identify the different kinds of tokens that your lexer can generate. This is a simple example for a simple calculator’s lexer:

class Token(LexerToken):
    Plus = WithText()
    Minus = WithText()
    Times = WithText()
    Div = WithText()
    Number = WithText()

l = Lexer(Token)

You can add patterns to it, that are shortcuts to regex patterns, and that can refer to each others, like so:

l.add_patterns(
    ('digit',   r"[0-9]"),
    ('integer', r"{digit}(_?{digit})*"),
)

Note that this is not necessary, just a convenient shortcut. After that you’ll be able to define the match rules for your lexer, via the add_rules function:

l.add_rules((
    (Literal("+"),         Token.Plus),
    (Literal("-"),         Token.Minus),
    (Literal("*"),         Token.Times),
    (Literal("/"),         Token.Div),
    (Pattern('{integer}'), Token.Number),
))

After that, your lexer is complete! You can use it in your parser to generate parse trees.

Parameters:
  • tokens_class – The class for the lexer’s tokens.

  • track_indent – Whether to track indentation when lexing or not. If this is true, then the special Layout parsers can be used to do indentation sensitive parsing.

  • pre_rules – A list of rules to add before the built-in new-line rule, if track_indent is True. If track_indent is false, adding rules this way is the same as calling add_rules.

  • case_insensitive – Whether the language is supposed to be case insensitive. Note that this provides a default symbol canonicalizer that takes care of case folding symbols.

add_newline_after(*tokens: TokenAction) → None[source]

Add mandatory line break emission during unparsing after the given tokens.

add_pattern(name: str, regexp: str, location: Location) → None[source]

Like add_patterns, but add a single pattern.

add_rules(*rules: tuple[Matcher, Action] | RuleAssoc) → None[source]

Add the list of rules to the lexer’s internal list of rules. A rule is either:

  • A tuple of a Matcher and an Action to execute on this matcher. This is the common case;

  • An instance of a class derived from RuleAssoc. This is used to implement custom matching behaviour, such as in the case of Case.

Please note that the order of addition matters. It will determine which rules are tried first by the lexer, so you could in effect make some rules ‘dead’ if you are not careful.

Parameters:

rules – The list of rules to add.

add_spacing(*token_family_couples: tuple[TokenFamily, TokenFamily]) → None[source]

Add mandatory spacing rules for the given couples of token families.

For each given token families TF1 and TF2, state that during unparsing, a token that belongs to TF1 must be followed by space when a token that belongs to TF2 comes next. By default, no space is inserted.

build_dfa_code(context: CompileCtx) → DFACodeGenHolder[source]

Build the DFA that implements this lexer (self.dfa_code).

check_token_families(context: CompileCtx) → None[source]

Pass that checks that either there are no defined token families, or that they form a partition of existing tokens.

compile_rules(context: CompileCtx) → None[source]

Pass to turn the lexer DSL into our internal regexp objects.

get_token(location: Location, literal: str) → Action[source]

Return the action that is associated to the given literal string.

newline_after: set[TokenAction]

Set of tokens after which unparsing must emit a line break.

property sorted_tokens: list[TokenAction]

Return the list of token types sorted by their corresponding numeric values.

spacing_table: dict[TokenFamily, dict[TokenFamily, bool]]

Nested mapping that indicates whether two tokens must be separated by a space during unparsing.

A space must be inserted between two token T1 and T2 iff spacing_rules[T1.family][T2.family] is true.

class langkit.lexer.LexerToken(track_indent: bool = False)[source]

Base class from which your token class must derive. Every member needs to be an instanciation of a subclass of TokenAction, specifiying what is done with the resulting token.

class langkit.lexer.Literal(location: Location, to_match: str)[source]

Matcher. This matcher will match the string given in parameter, literally. This means that characters which would be special in a Pattern will be regular characters here:

Pattern("a+")   # Matches one or more a
Literal("a+")   # Matches "a" followed by "+"
property match_length: int

Return the number of characters this pattern will accept, or raise ValueError if it is variable.

property regexp: str

Return a regular expression (syntax for langkit.lexer.regexp) to implement this matcher.

class langkit.lexer.Matcher(location: Location)[source]

Base class for a matcher. A matcher specificies in which case a given input will trigger a match.

abstract property match_length: int

Return the number of characters this pattern will accept, or raise ValueError if it is variable.

abstract property regexp: str

Return a regular expression (syntax for langkit.lexer.regexp) to implement this matcher.

class langkit.lexer.NoCaseLit(location: Location, to_match: str)[source]

Same as Literal, but with case insensitivity.

property regexp: str

Return a regular expression (syntax for langkit.lexer.regexp) to implement this matcher.

class langkit.lexer.Pattern(location: Location, pattern: str)[source]

Regular-expression based matcher.

The following subset of regular expressions is supported:

  • A|B: match either the A pattern or the B one.

  • (A): match the A pattern. Useful to group patterns and change associativity.

  • [XYZ]: match either the X character, the Y one or the Z one.

  • [^XYZ]: match any character but the X character, the Y one or the Z one.

  • [A-Z]: match any character between A and Z.

  • {NAME}: reference to the pattern called NAME. See Lexer.add_patterns for how to add named patterns.

  • A*: match the A pattern zero, one or multiple times.

  • A+: match the A pattern one or multiple times.

  • A?: match the A pattern zero or one time.

  • .: match any character except the newline one. Equivalent to [^\n].

  • \p{CATEGORY}: match any character in the given Unicode general category.

  • \P{CATEGORY}: match any character not in the given Unicode general category.

Note that due to the intended use of these regular expressions, several traditional constructs are not supported:

  • ^ and $, to match the very beginning of the input and its end.

property match_length: int

Return the number of characters this pattern will accept, or raise ValueError if it is variable.

property regexp: str

Return a regular expression (syntax for langkit.lexer.regexp) to implement this matcher.

class langkit.lexer.RuleAssoc(location: Location, matcher: Matcher, action: Action)[source]

Base class for a matcher -> action association. This class should not be used directly, since you can provide a tuple to add_rules, that will be expanded to a RuleAssoc.

property tokens: list[TokenAction]

Return the list of all tokens that this rule association can yield.

class langkit.lexer.TokenAction(location: Location, start_ignore_layout: bool = False, end_ignore_layout: bool = False)[source]

Abstract Base class for an action that sends a token. Subclasses of TokenAction can only be used as the instantiation of a token kind, in the declaration of a LexerToken subclass, as in:

class MyToken(LexerToken):
    Identifier = WithSymbol()
    Keyword = WithText()

Create a new token action. This is meant to be called on subclasses of TokenAction.

Parameters:
  • start_ignore_layout – If True, the token associated with this token action will trigger the start of layout ignore, which means that indent, dedent, and newline tokens will not be emitted by the lexer.

  • end_ignore_layout – If True, the token associated with this token action will trigger the end of layout ignorance.

Note that layout ignore works in a nested fashion: If the lexer reads 3 tokens that starts layout ignore, it will need to read 3 tokens that ends it so that it is taken into account again. The lexer won’t handle proper pairing: This is up to the parser’s implementer.

property lkt_name: str

Name for this token as it appears in Lkt sources. To be used in diagnostics.

name: Name | None

Name user associated to this token.

class langkit.lexer.TokenFamily(location: Location, *tokens: TokenAction)[source]

Set of tokens.

All token families must form a partition on the set of tokens for a given lexer. They can then be used to define spacing rules for unparsing.

name: Name | None

Name for this family. Assigned in LexerToken’s constructor.

class langkit.lexer.WithSymbol(location: Location, start_ignore_layout: bool = False, end_ignore_layout: bool = False)[source]

TokenAction. When the associated token kind will be lexed, a token will be created with the text corresponding to the match, but as an internalized symbol, so that if you have two tokens with the same text, the text will be shared amongst both:

class MyToken(LexerToken):
    # Identifiers will keep an internalized version of the text
    Identifier = WithSymbol()

Create a new token action. This is meant to be called on subclasses of TokenAction.

Parameters:
  • start_ignore_layout – If True, the token associated with this token action will trigger the start of layout ignore, which means that indent, dedent, and newline tokens will not be emitted by the lexer.

  • end_ignore_layout – If True, the token associated with this token action will trigger the end of layout ignorance.

Note that layout ignore works in a nested fashion: If the lexer reads 3 tokens that starts layout ignore, it will need to read 3 tokens that ends it so that it is taken into account again. The lexer won’t handle proper pairing: This is up to the parser’s implementer.

class langkit.lexer.WithText(location: Location, start_ignore_layout: bool = False, end_ignore_layout: bool = False)[source]

TokenAction. The associated token kind will have the lexed text associated to it. A new string will be allocated by the parser each time. Suited for literals (numbers, strings, etc..):

class MyToken(LexerToken):
    # String tokens will keep the associated text when lexed
    StringLiteral = WithText()

Create a new token action. This is meant to be called on subclasses of TokenAction.

Parameters:
  • start_ignore_layout – If True, the token associated with this token action will trigger the start of layout ignore, which means that indent, dedent, and newline tokens will not be emitted by the lexer.

  • end_ignore_layout – If True, the token associated with this token action will trigger the end of layout ignorance.

Note that layout ignore works in a nested fashion: If the lexer reads 3 tokens that starts layout ignore, it will need to read 3 tokens that ends it so that it is taken into account again. The lexer won’t handle proper pairing: This is up to the parser’s implementer.

class langkit.lexer.WithTrivia(location: Location, start_ignore_layout: bool = False, end_ignore_layout: bool = False, comment: bool = False)[source]

TokenAction. The associated token kind will have the lexed text associated to it. A new string will be allocated by the parser each time. Suited for literals (numbers, strings, etc..):

class MyToken(LexerToken):
    # String tokens will keep the associated text when lexed
    StringLiteral = WithText()
Parameters:

comment – Whether unparsing must treat this token as a comment, i.e. a trivia to preserve in unparsed sources.

Compiled Types API

class langkit.compiled_types.ASTNodeType(context: CompileCtx, name: names.Name, location: Location, doc: str, base: ASTNodeType | None, env_spec: EnvSpec | None = None, element_type: ASTNodeType | None = None, annotations: Annotations | None = None, is_generic_list_type: bool = False, is_abstract: bool = False, is_synthetic: bool = False, with_abstract_list: bool = False, implements: Callable[[], Sequence[GenericInterface]] | None = None, is_enum_node: bool = False, is_bool_node: bool = False, is_token_node: bool = False, is_error_node: bool = False, lkt_name: str | None = None)[source]

Type for an AST node.

Parameters:
  • context – Compilation context that owns this type.

  • name – Name for this node.

  • location – Location of the declaration of this node.

  • doc – User documentation for this node.

  • base – ASTNodeType subclass corresponding to the base class for this node. None when creating the root node.

  • env_spec – Environment specification for this node, if any.

  • element_type – For root list types, this must be the ASTNodeType subclass that this list contains. Must be left to None in all other cases.

  • is_generic_list_type – Whether this subclass will materialize the generic list type.

  • is_abstract – Whether this node is abstract. Note that this can be changed later. This is forced to True for the generic list type and for root list types whose element type has the with_abstract_list attribute set to True.

  • is_synthetic – Whether this node is synthetic. Note that this can be changed later.

  • with_abstract_list – Whether the root list type for this node must be abstract. Node that this can be changed later, until the list type is actually created.

  • implements – If provided, callback that returns the list of generic interfaces that this node implements.

  • is_enum_node – Whether this node comes from the expansion of an enum node.

  • is_bool_node – Whether this node is a qualifier coming from the expansion of an enum node.

  • is_token_node – Whether this node only materializes a parsed token. If so, grammars that produce such nodes must parse only one token (.token_start must be equal to .token_end).

  • is_error_node – Whether this node only materializes a parsing error. If so, only Skip parsers can create this node.

  • lkt_name – Name used to represent this type in Lkt sources. Useful to format diagnostics.

property ada_kind_name: str

Return the name of the Ada enumerator to represent this kind of node.

property ada_kind_range_bounds: tuple[str, str]

Return the name of the Ada enumerators for the range bounds (first and last) of kinds that nodes of this type can have.

property ada_kind_range_name: str

Return the name of the Ada kind subtype to represent the set of node kinds that include self and all its subclasses.

add_list_element_parser(parser: Parser) → None[source]

Register parser as a parser that creates list elements.

Parameters:

parser – Parser to register.

add_transform(parser: _Transform) → None[source]

Register parser as a Transform parser that creates this node.

This also registers sub-parsers in node fields and keep track of field types, checking for consistencies.

Parameters:

parser – Transform parser to register.

property base: ASTNodeType | None

Return the base of this type, or None if there is no derivation involved.

builtin_properties(owner: CompiledType) → builtin_list[E.PropertyDef][source]

Return properties available for all AST nodes.

c_type(c_api_settings: CAPISettings) → CAPIType[source]

Return a CAPIType instance for this type.

check_inferred_field_types() → None[source]

Check that inferred field types from the grammar are consistent with annotations. If there was no type annotation, use the inferred type to assign a type to the parse field.

static common_ancestor(*nodes: ASTNodeType) → ASTNodeType[source]

Return the bottom-most common parent AST node for all nodes AST nodes.

Parameters:

nodes – List of AST node types for which we are looking for the common ancestor.

create_abstract_as_bool_cb(location: Location) → Callable[[], builtin_list[E.PropertyDef]][source]

Callback for deferred type members to build and return the abstract as_bool property for booleanized enum node base types.

create_concrete_as_bool_cb(is_present: bool, location: Location) → Callable[[], builtin_list[E.PropertyDef]][source]

Callback for deferred type members to build and return the abstract return the concrete as_bool property for booleanized enum node subclasses.

Parameters:

is_present – Whether the booleanized enum is considered to be present in this concrete property.

create_default_can_reach() → E.PropertyDef[source]

Build and return the default can_reach property.

This is meant to be used for the default node, when the language specification does not define this property.

property doc: str

Return the user documentation for this type, or None if there is no documentation.

property effective_env_spec: EnvSpec | None

Return the env spec, for this node, whether it’s defined on this node or inherited from a parent node.

env_spec: EnvSpec | None

EnvSpec instance corresponding to this node.

property equivalent_to_root: bool

Return whether this node type is equivalent to the root type.

For instance, if the root node has only one subclass, then this subclass is equivalent to the root type, as all concrete nodes belong to both types.

This property is useful to avoid emitting tautological kind checks during code generation.

fields_to_initialize(include_inherited: bool) → list[BaseField][source]

Return the list of fields to initialize for this node.

Parameters:

include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

fields_with_accessors() → list[AbstractNodeData][source]

Return a list of fields for which we must generate accessors in APIs.

This list excludes inherited/overriden fields so that they are not generated multiple times. This list also excludes private fields unless the context requires them to be public in the generated library.

generic_list_type: ASTNodeType

Root grammar class subclass. It is abstract, generated automatically when the root grammar class is known. All root list types subclass it.

get_parse_fields(predicate: Callable[[Field], bool] | None = None, include_inherited: bool = True) → list[Field][source]

Return the list of all the parse fields self has, including its parents’.

Parameters:
  • predicate – Predicate to filter fields if needed.

  • include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

list_element_parsers: list[Parser] | None

For list nodes, list of parsers that produce list elements. None for all other nodes.

property parser_allocator: str

Return the name of the function to call in parsers to allocate this node.

precise_list_element_types: TypeSet | None

For list nodes, precise set of types that this list can contain.

property public_type: CompiledType

Return the type to use when exposing values in public APIs.

This returns self for most types, but some (such as bare nodes) are automatically wrapped as entity.

repr_name() → str[source]

Return a name that will be used when serializing this AST node.

snaps(anchor_end: bool) → bool[source]

Whether this node type snaps. To see what this means, see documentation for Annotations.

Note that no node snaps if unparsers are not requested.

Parameters:

anchor_end – If true, return whether this node snaps at the end, otherwise return whether it snaps at the beginning.

subclasses: list[ASTNodeType]

List of subclasses. Overriden in the root grammar class and its children. This list is completed as ASTNodeType instances are created, and sorted in the “compute_types” compilation pass.

to_internal_expr(public_expr: str, context: str | None = None) → str[source]

Given public_expr, an expression that computes a public value, for this type return another expression that converts it to an internal value.

Parameters:

context – If this type requires the context for this conversion, this must be an expression that yields the context.

to_public_expr(internal_expr: str) → str[source]

Given internal_expr, an expression that computes an internal value, for this type return another expression that converts it to a public value.

token_kind: TokenAction | None

If this is a token node and if unparser generation is enabled, this must reference the only token kind that this node can be associated to. Must be None otherwise.

transform_parsers: list[_Transform]

List of Transform parsers that produce this node.

property type_set: list[ASTNodeType]

Return the list of all (direct or indirect) subclasses for self, including self as well, sorted by hierarchical name.

unparser: NodeUnparser | None

Unparser for this node. Computed during the NodesToParsers pass.

validate_fields() → None[source]

Perform various checks on this ASTNodeType’s fields.

In particular, make sure: * the AST node is type resolved (i.e. all fields have a type); * all fields are AST nodes themselves; * it does not hold homonym parse fields.

Emit errors when appropriate.

value_type_name

Name of the Ada type for the record that contains data for all nodes.

with_abstract_list: bool

Whether the automatically generated list type for this ASTNodeType (the “root list type”) is abstract.

class langkit.compiled_types.AbstractNodeData(owner: CompiledType, names: MemberNames, location: Location, type: CompiledType, public: bool = True, default_value: E.BindableLiteralExpr | None = None, abstract: bool = False, access_needs_incref: bool = False, internal_name: langkit.names.Name | None = None, access_constructor: Callable[[E.ExprDebugInfo | None, E.Expr, AbstractNodeData, list[E.Expr | None]], E.Expr] | None = None, final: bool = False, implements: Callable[[], InterfaceMethodProfile] | None = None)[source]

This class defines an abstract base class for fields and properties on AST nodes.

It defines the basis of what is needed to bind them in other languages bindings: a type and a name.

Parameters:
  • owner – Compiled type that owns this member.

  • names – Names for this member.

  • location – Source location of the declaration for this member.

  • type – Type for this member (fields) or return type (properties).

  • public –

    Whether this AbstractNodeData instance is supposed to be public or not.

    In the context of properties only, None is also allowed: in this case, inherit vibility from parents. If there is no property to override and None is passed, make the property private. This is computed in the “compute” pass.

  • default_value – Default value for this field, when omitted from New expressions.

  • abstract – Whether this member is abstract.

  • access_needs_incref – If True, field access evaluation does not create an ownership share: callers must call Inc_Ref themselves. See the eponym property.

  • internal_name – If provided, override the default name to use in code generation for this node data.

  • access_constructor – Optional callback to create a resolved expression that implements a DSL access to this field. If provided, this overrides the default code generation of EvalMemberExpr.

  • final – If True, this field/property cannot be overriden. This is possible only for concrete fields/properties.

  • implements – If provided, callback that returns the generic interface method that this member implements.

property abstract: bool

Return whether this field is abstract. This can be true only for properties and syntax fields.

property access_needs_incref: bool

Return whether field access evaluation does not create an ownership share. In this case, users must call Inc_Ref themselves. This returns always False for node data whose type is not ref-counted.

property accessor_basename: Name

Return the base name for the C API accessor we generate for this field.

Note that this is available only for fields attached to parse nodes.

property ada_default_value: str

Return the default value to use for the record component declaration that implements this field in generated code.

arguments: list[Argument]

Code generation-wise, all node data can be considered as functions which take at least a mandatory Self argument and return the corresponding data.

This is a list that describes all other arguments. Note that only Property instances accept other arguments.

property base: _Self | None

If this field overrides an inherited one in a base class, return the inherited one, otherwise return None.

c_type_or_error(capi: CAPISettings) → CAPIType[source]

Within a diagnostic context for this field, return its C API type.

property concrete_overridings: Sequence[_Self]

Return the list of concrete overridings for self.

abstract property doc: str

Documentation for the abstract node field.

field_set() → Sequence[_Self][source]

Return all fields associated with this fields in terms of overriding hierarchy.

implements: InterfaceMethodProfile | None

Generic interface method that this type member implements, if any.

property indexing_name: str

Name to use for this node data in structure field dicts.

For user fields created by users, this should be the lower case form that appears in Lkt sources. For fields created by the compilation process, this is arbitrary.

property internal_name: str

Name of the field in the generated code.

property is_internal: bool

Whether this property is internal.

property is_overriding: bool

Return whether this field overrides an inheritted one in a base class.

property is_private: bool

Whether this field is public.

This is a shortcut for:

not self.is_public
is_property: ClassVar[bool] = False

Whether this class is Property (to be overriden in the Property subclass).

property is_public: bool

Whether this field is private.

is_user_field: ClassVar[bool] = False

Whether this class is UserField.

kind_name: ClassVar[str]

Human-readable name for this kind of node data. Used to format diagnostics.

property natural_arguments: list[Argument]

Return the subset of “self.arguments” that are non-artificial arguments, that is to say the subset that users actually handle in expressions.

This property makes sense in user-facing layers.

property original_name: str

Name for this property as specified in Lkt sources.

For internal properties, we generally use impossible syntax (brackets, leading underscore, …) to avoid name clashes with user-defined properties.

property overridings: Sequence[_Self]

Return the list of fields that override self.

property qual_impl_name: str

Fully qualified name for the implementation of this property.

This is useful during code generation to avoid name clashes.

property qualname: str

Return the qualified name for this field, i.e. the name of the owning type plus the name of the field itself. This is useful for diagnostic messages.

Note that if expansion renamed this property, this will return the original (Lkt-level) name.

reset_inheritance_info() → None[source]

Reset memoization caches for inheritance-related information.

Must be called on the root field when modifying a tree of inherited fields.

property root: _Self

Return the ultimate field that self inherits.

This returns self itself if it is not overriding.

property uses_entity_info: bool

Return whether evaluating this field requires entity info.

class langkit.compiled_types.AnalysisUnitType(context: CompileCtx)[source]
Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property to_internal_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes a public value and returns an internal one. Return None otherwise.

property to_public_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes an internal value and returns a public one. Return None otherwise.

class langkit.compiled_types.Argument(location: Location, name: names.Name, type: CompiledType, is_artificial: bool = False, default_value: E.BindableLiteralExpr | None = None, local_var: E.LocalVars.LocalVar | None = None)[source]

Holder for properties arguments.

Parameters:
  • name – Argument name.

  • type – Argument type.

  • is_artificial – Whether the argument was automatically created by Langkit, i.e. the language specification did not mention it.

  • default_value – If None, there is no default value associated to this argument. Otherwise, it is the default value to use when generating code for the corresponding property argument.

  • local_var – For properties only. If provided, local variable that expressions in the property body must use to access the dynamic variable binding made during the property call. If not provided, a local variable is automatically created when adding this argument to its owning property.

local_var: E.LocalVars.LocalVar

Local variable instance to refer to this argument from inside its property.

If not set at Argument instantiation time, this attribute it set as soon as the argument is added to its owning property.

property public_default_value: E.Expr

Assuming this argument has a default value, return the default value to use in public APIs, according to the type exposed in public.

set_local_var(var: E.LocalVars.LocalVar) → None[source]

Initialize the local_var attribute for this Argument instance.

This may not be done at instantiation time as, for convenience when creating built-in properties, Argument objects can be created before their owning property.

property var: E.VariableExpr

Expression to refer to this argument from inside its property.

class langkit.compiled_types.ArrayType(context: CompileCtx, element_type: CompiledType)[source]

Base class for array types.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property api_access_name: Name

Name of the access type for public arrays. Used as internals for array struct fields.

property api_name: Name

Name of the public array type. This is the same as array_type_name for public types (such as booleans, integers, analysis units, etc.) but we have a different one for “wrapped” types, such as entities.

property array_type_name: Name

Name of the Ada array type.

builtin_properties(owner: CompiledType) → list[E.PropertyDef][source]

Return properties available for all array types.

c_create(capi: CAPISettings) → str[source]

Name of the C API function to create an array value.

c_dec_ref(capi: CAPISettings) → str[source]

Name of the C API function to dec-ref an array value.

c_inc_ref(capi: CAPISettings) → str[source]

Name of the C API function to inc-ref an array value.

c_type(c_api_settings: CAPISettings) → CAPIType[source]

Return a CAPIType instance for this type.

property constructor_name: Name

Name of the internal Ada functions to instantiate this array.

property emit_c_type: bool

Return whether to emit a C type for this type.

See StructType.emit_c_type.

property exposed_types: list[CompiledType]

Return the list of types that self exposes when it is itself exposed.

property has_early_decl: bool

Return whether declarations for this type in the internal Ada API happen earlier than usual.

Some types (for instance the metadata struct) have special constraints regarding code generation, so their type declaration must happen earlier than if they were more regular types.

index_type() → str[source]

Name of the index type for this array type.

property lkt_name: str

Type name as it appears in Lkt source code. To be used in diagnostics.

property name: Name

Name of the type for general values in the Ada generated code.

property pkg_vector: Name

Name of the Langkit_Support.Vectors package instantiation corresponding to this element_type.

property pointed: Name

Name of the type for values that are pointed to by general values.

property public_requires_boxing: bool

Whether the public type in the Ada API for this requires some boxing to be embedded in a record. This is true for all unbounded types (i.e. arrays).

property py_converter: str

Name of the Python class used to convert back and forth between user-facing values (lists) and C API values (pointers to array records).

require_hash_function() → None[source]

Tag this type as requiring a hash function.

property requires_to_iterator_property: bool

Return whether the to_iterator property of this array type should be emitted during codegen. This will be true only if the property is ever called from within the DSL, since the property is private.

property to_internal_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes a public value and returns an internal one. Return None otherwise.

property to_public_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes an internal value and returns a public one. Return None otherwise.

vector() → str[source]

Name of the type for vector values.

class langkit.compiled_types.BaseField(owner: CompiledType, names: MemberNames, location: Location, type: CompiledType, repr: bool = True, doc: str = '', default_value: E.BindableLiteralExpr | None = None, abstract: bool = False, access_needs_incref: bool = False, null: bool = False, nullable: bool | None = None, implements: Callable[[], InterfaceMethodProfile] | None = None)[source]

Base class for node fields and structure fields.

Create an AST node field.

Parameters:
  • owner – Compiled type that owns this member.

  • names – Names for this member.

  • location – Source location of the declaration for this member.

  • type – Type for this field.

  • repr – If true, the field will be displayed when pretty-printing the embedding AST node.

  • doc – User documentation for this field.

  • default_value – Default value for this field, when omitted from New expressions.

  • abstract – Whether this member is abstract.

  • access_needs_incref – See AbstractNodeData’s constructor.

  • null – Whether this field is always supposed to be null.

  • nullable – None if the language spec does not defines whether this field can be null in the absence of parsing error (i.e. when it is inferred). True/False otherwise (whether it can be null).

  • implements – If provided, callback that returns the generic interface method that this member implements.

concrete: ClassVar[bool] = False

Field used to prevent instantiation of the class. Concrete descendants of BaseField must put that field to True in their definition.

property doc: str

Documentation for the abstract node field.

property null: bool

Return whether this field is always supposed to be null.

property nullable: bool

Whether this field can be null in the absence of parsing error.

nullable_from_spec

Whether this field has the @nullable annotation.

set_synthetized() → None[source]

Tag this field and its ancestors as being initialized by node synthetization in properties.

should_emit

Subclasses can change that variable to trigger wether the field should be emitted or not.

property synthetized: bool

Whether this field is initialized by node synthetization in properties.

class langkit.compiled_types.BaseStructType(context: CompileCtx, name: names.Name, location: Location, doc: str = '', base: _Self | None = None, fields: Callable[[BaseStructType], Sequence[AbstractNodeData]] | None = None, implements: Callable[[], Sequence[GenericInterface]] | None = None, is_ptr: bool = True, is_list_type: bool = False, is_entity_type: bool = False, exposed: bool = False, c_type_name: str | None = None, external: bool = False, null_allowed: bool = False, is_ada_record: bool = False, is_refcounted: bool = False, nullexpr: str | None = None, py_nullexpr: str | None = None, java_nullexpr: str | None = None, element_type: CompiledType | None = None, hashable: bool = False, has_equivalent_function: bool = False, type_repo_name: str | None = None, api_name: str | names.Name | None = None, lkt_name: str | None = None, conversion_requires_context: bool = False)[source]

Base class to share common behavior between StructType and ASTNodeType.

See CompiledType.__init__ for a description of the other arguments.

Parameters:

implements – If provided, callback that returns the list of generic interfaces that this node/struct implements.

add_internal_user_field(name: names.Name, type: CompiledType, default_value: E.BindableLiteralExpr | None, doc: str = '') → UserField[source]

Create an internal (not public) UserField for this struct type.

This method takes care of creating the UserField instance, registering it as a field of self and then returns the instance.

See UserField’s constructor for argument semantics.

Note that default_value is a mandatory argument that can be None as we need to allow None values because None is the exception rather than the rule: users cannot assign a value to these fields, and thus we need most of the time to assign a default value to them.

implemented_interfaces(include_parents: bool = True) → list[GenericInterface][source]

Return the interfaces implemented by this node, including its parents’ if include_parents is true.

property py_nullexpr: str

Return a string to be used in Python code gen for “null” expressions.

Must be overridden in subclasses… for which we need the Python null expression.

property required_fields_in_exprs: dict[str, BaseField]

Return all fields that must be involved in the property DSL.

This returns a mapping from DSL field names to fields for all fields that must be considered when building structs in the property DSL.

class langkit.compiled_types.BigIntegerType(context: CompileCtx)[source]
Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property to_internal_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes a public value and returns an internal one. Return None otherwise.

property to_public_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes an internal value and returns a public one. Return None otherwise.

class langkit.compiled_types.BuiltinField(owner: CompiledType, names: MemberNames, type: CompiledType, repr: bool = False, doc: str = '', public: bool = True, default_value: E.BindableLiteralExpr | None = None, access_needs_incref: bool = True)[source]

A built-in field is just like a UserField, except that its name has no prefix. It is typically used for fields of built-in structs.

See inherited doc. In this version we just ensure that a type is passed because it is mandatory for data fields. We also set repr to False because most of the time you don’t want User fields to show up in the pretty printer.

Parameters:
  • names – Names for this member.

  • is_public – Whether this field is public in the generated APIs.

  • access_needs_incref – See AbstractNodeData’s constructor.

  • default_value – Default value for this field, when omitted from New expressions.

  • implements – If provided, callback that returns the generic interface method that this member implements.

class langkit.compiled_types.CompiledType(context: CompileCtx, name: str | names.Name, location: Location, doc: str = '', base: _Self | None = None, fields: Callable[[CompiledType], Sequence[AbstractNodeData]] | None = None, is_ptr: bool = True, has_special_storage: bool = False, is_list_type: bool = False, is_entity_type: bool = False, exposed: bool = False, c_type_name: str | None = None, external: bool = False, null_allowed: bool = False, is_ada_record: bool = False, is_refcounted: bool = False, nullexpr: str | None = None, py_nullexpr: str | None = None, java_nullexpr: str | None = None, element_type: CompiledType | None = None, hashable: bool = False, has_equivalent_function: bool = False, type_repo_name: str | None = None, api_name: str | names.Name | None = None, lkt_name: str | None = None, conversion_requires_context: bool = False)[source]

Descriptor for a type in the generated code.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

add_as_memoization_key(context: CompileCtx) → None[source]

Add self to the set of types that are used as keys in the hashed maps used to implement properties memoization. It has to be hashable.

add_as_memoization_value(context: CompileCtx) → None[source]

Add self to the set of types that are used as values in the hashed maps used to implement properties memoization.

property api_name: Name

Name of public type. By default, it is the same as name.

property base: _Self | None

Return the base of this type, or None if there is no derivation involved.

c_name(capi: CAPISettings, suffix: str) → str[source]

Return a name derived from the name of this type in the C API.

Parameters:

suffix – Lower-case suffix to add to the C API type name.

c_type(capi: CAPISettings) → CAPIType[source]

Return a CAPIType instance for this type.

convert_to_storage_expr(node_expr: str, base_expr: str) → str[source]

Turn a public value into a storage value. See documentation for has_special_storage.

Parameters:
  • node_expr (str) – Expression that yields the node that will own the resulting storage value.

  • base_expr – Expression that yields the public value:

Returns:

An expression that yields the storage value.

create_iterator(used: bool) → IteratorType[source]

Create, if needed, the iterator type for “self”.

This creates the iterator type if it does not exist yet, and return the existing one otherwise.

Parameters:

used – Whether the returned iterator type must be considered as used (i.e. required for code generation).

derivations: set[CompiledType]

Set of types that derive from self.

property doc: str

Return the user documentation for this type, or None if there is no documentation.

property element_type: CompiledType

Assuming this is a collection type (array, iterator, list) or an entity, return the corresponding element type.

property exposed_types: list[CompiledType]

Return the list of types that self exposes when it is itself exposed.

extract_from_storage_expr(node_expr: str, base_expr: str) → str[source]

Turn a storage value into a public value. See documentation for has_special_storage.

Parameters:
  • node_expr – Expression that yields the node that owns the storage value.

  • base_expr – Expression that yields the storage value.

Returns:

An expression that yields the public value.

get_abstract_node_data(predicate: ~typing.Callable[[~langkit.compiled_types.AbstractNodeData], bool] | None = None, include_inherited: bool = True, field_class: ~typing.Type[~langkit.compiled_types.AbstractNodeData] = <class 'langkit.compiled_types.AbstractNodeData'>) → list[AbstractNodeData][source]

Get all BaseField instances for the class.

Parameters:
  • predicate – Predicate to filter fields if needed.

  • include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

  • field_class – The field class to use to filter fields.

get_abstract_node_data_dict(include_inherited: bool = True, field_class: ~typing.Type[~langkit.compiled_types.AbstractNodeData] = <class 'langkit.compiled_types.AbstractNodeData'>) → dict[str, AbstractNodeData][source]

Get all BaseField instances for the class.

Parameters:
  • include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

  • field_class – The field class to use to filter fields.

get_fields(predicate: Callable[[BaseField], bool] | None = None, include_inherited: bool = True) → list[BaseField][source]

Return the list of all the fields self has, including its parents’.

Parameters:
  • predicate – Predicate to filter fields if needed.

  • include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

get_inheritance_chain() → list[_Self][source]

Return the chain of types following the base link as a list. Root-most types come first.

get_properties(predicate: Callable[[E.PropertyDef], bool] | None = None, include_inherited: bool = True) → list[E.PropertyDef][source]

Return the list of all the fields self has.

Parameters:
  • predicate – Predicate to filter fields if needed.

  • include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

get_user_fields(predicate: Callable[[UserField], bool] | None = None, include_inherited: bool = True) → list[UserField][source]

Return the list of all the user fields self has, including its parents’.

Parameters:
  • predicate – Predicate to filter fields if needed.

  • include_inherited – If true, include inheritted fields in the returned list. Return only fields that were part of the declaration of this node otherwise.

property has_early_decl: bool

Return whether declarations for this type in the internal Ada API happen earlier than usual.

Some types (for instance the metadata struct) have special constraints regarding code generation, so their type declaration must happen earlier than if they were more regular types.

property has_nullexpr: bool

Return whether this type has a null expression.

property is_analysis_unit_kind: bool

Return whether this is the analysis unit kind type.

property is_analysis_unit_type: bool

Return whether this is the analysis unit type.

property is_array_type: bool

Return whether this is an instance of ArrayType.

property is_big_int_type: bool

Return whether this is the big integer type.

property is_big_integer_type: bool

Return whether this is a big integer type.

property is_bool_type: bool

Return whether this is the boolean type.

property is_character_type: bool

Return whether this is a character type.

property is_collection: bool

Return whether this is a collection type.

property is_enum_type: bool

Return whether this is an enumeration type.

property is_env_rebindings_type: bool

Return whether this is the env rebindings type.

property is_equation_type: bool

Return whether this is the equation type.

property is_int_type: bool

Return whether this is the integer type.

property is_iterator_type: bool

Return whether this is an instance of IteratorType.

property is_lexical_env_type: bool

Return whether this is the lexical environment type.

property is_logic_var_type: bool

Return whether this is an instance of LogicVarType.

property is_long_type: bool

Return whether this is a integer type.

property is_refcounted: bool

Return whether this type matters for the ref-counting mechanism.

This returns whether this type is dynamically allocated and thus ref-counted, or whether it owns ref-counted values. “dynamically” in this context means: with a lifetime that is different from the owning analysis unit.

If it is ref-counted, there must exist Inc_Ref and Dec_Ref primitives. The Dec_Ref primitive must handle null values correctly (i.e. ignore them).

property is_root_node: bool

Return whether this is the root node.

property is_set_type: bool

Return whether this is an instance of SetType.

property is_source_location_type: bool

Return whether this is a source location type.

property is_string_type: bool

Return whether this is the string type.

property is_symbol_type: bool

Return whether this is a symbol type.

property is_token_type: bool

Return whether this is a token type.

property iterator: IteratorType

Create an iterator type whose element type is self.

property java_nullexpr: str

Return a string representing the null expression in generated Java code.

Must be overridden in subclasses… for which we need the Java null expression.

property lkt_name: str

Type name as it appears in Lkt source code. To be used in diagnostics.

matches(formal: CompiledType) → bool[source]

Return whether self matches formal.

This is mere equality for all types but AST nodes, in which self is allowed to be a subtype for formal.

Parameters:

formal – Type to match. self is checked to be a subtype of it.

property memoization_kind: str

Return the enumerator name that corresponds to this type for the discriminated record to materialize memoization keys/values.

property mypy_type_hint: str

Type hint to use for this type when generating Mypy stub files for the Python bindings.

property name: Name

Name of the type for general values in the Ada generated code.

property nullexpr: str

Return a string to be used in code generation for “null” expressions.

Must be overriden in subclasses.

property public_requires_boxing: bool

Whether the public type in the Ada API for this requires some boxing to be embedded in a record. This is true for all unbounded types (i.e. arrays).

property public_type: CompiledType

Return the type to use when exposing values in public APIs.

This returns self for most types, but some (such as bare nodes) are automatically wrapped as entity.

property py_nullexpr: str

Return a string to be used in Python code gen for “null” expressions.

Must be overridden in subclasses… for which we need the Python null expression.

property qualified_api_name: str

Return the Ada qualified name to use for this type in public APIs.

require_hash_function() → None[source]

Tag this type as requiring a hash function.

property requires_hash_function: bool

Return whether code generation must produce a Hash function for this type.

property storage_nullexpr: str

Return the nullexpr that is used for fields of this type in structs and ASTNodes. See documentation for has_special_storage.

property storage_type_name: Name

Return the name of the type that is used to store instances of this type in structs and AST nodes. See documentation for has_special_storage.

property to_internal_converter: Name | None

If this type requires a conversion in public properties, return the name of the function that takes a public value and returns an internal one. Return None otherwise.

to_internal_expr(public_expr: str, context: str | None = None) → str[source]

Given public_expr, an expression that computes a public value, for this type return another expression that converts it to an internal value.

Parameters:

context – If this type requires the context for this conversion, this must be an expression that yields the context.

property to_public_converter: Name | None

If this type requires a conversion in public properties, return the name of the function that takes an internal value and returns a public one. Return None otherwise.

to_public_expr(internal_expr: str) → str[source]

Given internal_expr, an expression that computes an internal value, for this type return another expression that converts it to a public value.

unify(other: _Self, error_location: Location | L.LktNode, error_msg: str | None = None) → _Self[source]

If self and other are types that match, return the most general type to cover both. Create an error diagnostic if they don’t match.

Parameters:
  • other – Type to unify with self.

  • error_location – Location for the error diagnostic.

  • error_msg – Diagnostic message for mismatching types. If None, a generic one is used, otherwise, we call .format on it with the self and other keys being the names of mismatching types.

used_in_public_struct

Whether this type is used as a field in a struct that belongs to the public API.

class langkit.compiled_types.CompiledTypeRepo[source]

Namespace class: Repository for every compiled type. This is used to have a comprehensive list of every compiled type instance, so that you can use a TypeRepo instance to refer to any compiled type.

classmethod reset() → None[source]

Make this holder empty again. Useful to use Langkit multiple times in a process.

type_dict: dict[str, CompiledType] = {}

Mapping: type name -> CompiledType instance. Used in TypeRepo for type lookup by name.

class langkit.compiled_types.EntityType(context: CompileCtx, astnode: ASTNodeType)[source]

Subclass of StructType dedicated to entity types.

Parameters:
  • name – See CompiledType.__init__.

  • implements – If provided, callback that returns the list of generic interfaces that this struct implements.

property api_name: Name

Type name to use in the public API.

property base: EntityType | None

Return the entity type that self overrides, or None for the root.

c_type(capi: CAPISettings) → CAPIType[source]

Return a CAPIType instance for this type.

property constructor_name: Name

Name of the internal Ada functions to instantiate this array.

property element_type: ASTNodeType

Assuming this is a collection type (array, iterator, list) or an entity, return the corresponding element type.

property is_root_type: bool

Return whether this entity type correspond to the AST node root type.

property lkt_name: str

Type name as it appears in Lkt source code. To be used in diagnostics.

to_internal_expr(public_expr: str, context: str | None = None) → str[source]

Given public_expr, an expression that computes a public value, for this type return another expression that converts it to an internal value.

Parameters:

context – If this type requires the context for this conversion, this must be an expression that yields the context.

to_public_expr(internal_expr: str) → str[source]

Given internal_expr, an expression that computes an internal value, for this type return another expression that converts it to a public value.

class langkit.compiled_types.EnumNodeAlternative(base_name: Name, enum_node: ASTNodeType, alt_node: ASTNodeType | None, location: Location)[source]

Synthetic description of an enum node alternative.

alt_node: ASTNodeType | None

Node that implements this alternative.

This is None when the EnumNodeAlternative object was just created, as the corresponding ASTNodeType is instantiated only after that.

base_name: Name

Name of the alternative, as found in the language spec.

enum_node: ASTNodeType

Enum node that owns this alternative.

property full_name: Name

Name of the node that implements this alternative. This is the node of the enum node, suffixed with the base name.

location: Location

Location in the language spec where this alternative was created. This is the location of the enum node declaration itself for alternatives synthetized by the @qualifier annotation.

class langkit.compiled_types.EnumType(context: CompileCtx, name: str | Name, location: Location, doc: str, value_names: list[Name], default_val_name: Name | None = None)[source]

Ada-like enumeration type.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

default_val_name

Name of the default value for this enum, if any.

property py_helper: str

Name of the class helper in the Python binding layer to convert values for this enumeration back and forth between C and Python-level values.

resolve_value(debug_info: E.ExprDebugInfo | None, value_name: str) → E.Expr[source]

Return an expression corresponding to the given value name.

Parameters:
  • debug_info – Debug info for the returned expression.

  • value_name – Lower-case name of the value to process.

values_dict: dict[Name, EnumValue]

Lookup dictionnary for enumeration values, by name.

class langkit.compiled_types.EnumValue(enum_type: EnumType, name: Name, index: int)[source]

Possible value for an enumeration type.

property ada_name: str

Return the identifier used in Ada to designate this value.

c_name(c_api_settings: CAPISettings) → str[source]

Return the identifier used in C to designate this value.

Parameters:

c_api_settings – The settings for the C API.

create_ref_expr(debug_info: E.ExprDebugInfo | None) → E.Expr[source]

Create an expression wrapping this enumeration value.

Parameters:

debug_info – Debug info for the returned expression.

index

Index for this enumeration value. Each enumeration values in a given enumeration type are assigned an index, incrementing from 0.

property lkt_name: str

Return the Lkt name for this enumeration value.

name

Name for this enumeration value.

type

Enumeration type that owns this enumeration value.

class langkit.compiled_types.EnvRebindingsType(context: CompileCtx)[source]

Singleton for the environment rebinding type.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

class langkit.compiled_types.Field(owner: CompiledType, names: MemberNames, location: Location, type: CompiledType, repr: bool = True, doc: str = '', abstract: bool = False, null: bool = False, nullable: bool | None = None, implements: Callable[[], InterfaceMethodProfile] | None = None)[source]

Fields that are meant to store parsing results. Can be used only on subclasses of ASTNodeType.

Create an AST node field.

Parameters:
  • owner – Compiled type that owns this member.

  • names – Names for this member.

  • location – Source location of the declaration for this member.

  • type – Type for this field.

  • repr – If true, the field will be displayed when pretty-printing the embedding AST node.

  • doc – User documentation for this field.

  • default_value – Default value for this field, when omitted from New expressions.

  • abstract – Whether this member is abstract.

  • access_needs_incref – See AbstractNodeData’s constructor.

  • null – Whether this field is always supposed to be null.

  • nullable – None if the language spec does not defines whether this field can be null in the absence of parsing error (i.e. when it is inferred). True/False otherwise (whether it can be null).

  • implements – If provided, callback that returns the generic interface method that this member implements.

concrete: ClassVar[bool] = True

Field used to prevent instantiation of the class. Concrete descendants of BaseField must put that field to True in their definition.

property doc: str

Documentation for the abstract node field.

property index: int

Return the 0-based index of this parsing field in the owning AST node’s children list. Only non-null concrete fields have an index.

kind_name: ClassVar[str] = 'field'

Human-readable name for this kind of node data. Used to format diagnostics.

parsers_from_transform: list[Parser]

List of parsers that provide a value for this field. Such parsers are children of Transform parsers.

property precise_element_types: TypeSet

For fields that contain lists, return the precise set of types that these list can contain.

property precise_types: TypeSet

Return the precise set of types that this field can contain.

This is the same as TypeSet([self.type]) except for nodes created during parsing: for these, self.type might be too general.

types_from_synthesis: TypeSet[ASTNodeType]

Set of types coming from node synthetization in properties.

class langkit.compiled_types.IteratorType(context: CompileCtx, element_type: CompiledType)[source]

Base class for iterator types.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property api_name: Name

Name of the public iterator type.

c_dec_ref(capi: CAPISettings) → str[source]

Name of the C API function to dec-ref an iterator value.

c_inc_ref(capi: CAPISettings) → str[source]

Name of the C API function to inc-ref an iterator value.

c_next(capi: CAPISettings) → str[source]

Name of the C API function to get the next value out of the iterator.

c_type(c_api_settings: CAPISettings) → CAPIType[source]

Return a CAPIType instance for this type.

property emit_c_type: bool

Return whether to emit a C type for this type.

See StructType.emit_c_type.

property exposed_types: list[CompiledType]

Return the list of types that self exposes when it is itself exposed.

property has_early_decl: bool

Return whether declarations for this type in the internal Ada API happen earlier than usual.

Some types (for instance the metadata struct) have special constraints regarding code generation, so their type declaration must happen earlier than if they were more regular types.

property is_used: bool

Return whether this iterator type is actually used, and thus whether we will emit code for it.

property iterator_type_name: Name

Name of the Ada iterator type.

property lkt_name: str

Type name as it appears in Lkt source code. To be used in diagnostics.

property name: Name

Name of the type for general values in the Ada generated code.

property to_internal_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes a public value and returns an internal one. Return None otherwise.

property to_public_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes an internal value and returns a public one. Return None otherwise.

class langkit.compiled_types.LogicVarType(context: CompileCtx)[source]

Singleton for the logic variable type.

This type represents a logical variable. A logical variable is a reference, that can take a specific value when it is bound to a specific Equation, and that equation is solved for a certain problem set.

It is a special type in Langkit at this point, in that its value is initially undefined, and is mutated after the solve of an equation to a specific value. It is thus the only type in Langkit for the moment for which variables of the type can be mutated after creation.

TODO: For the moment a logic variable is necessarily a holder around an ASTNodeType. At some point we might want to make it generic, like list and array types.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

convert_to_storage_expr(node_expr: str, base_expr: str) → str[source]

Turn a public value into a storage value. See documentation for has_special_storage.

Parameters:
  • node_expr (str) – Expression that yields the node that will own the resulting storage value.

  • base_expr – Expression that yields the public value:

Returns:

An expression that yields the storage value.

extract_from_storage_expr(node_expr: str, base_expr: str) → str[source]

Turn a storage value into a public value. See documentation for has_special_storage.

Parameters:
  • node_expr – Expression that yields the node that owns the storage value.

  • base_expr – Expression that yields the storage value.

Returns:

An expression that yields the public value.

property storage_nullexpr: str

Return the nullexpr that is used for fields of this type in structs and ASTNodes. See documentation for has_special_storage.

property storage_type_name: Name

Return the name of the type that is used to store instances of this type in structs and AST nodes. See documentation for has_special_storage.

class langkit.compiled_types.MemberNames(index: str, codegen: str, spec: Name | None = None, api: Name | None = None)[source]

Set of names for a given compiled type member (field, property, …).

api: Name | None = None

Public members need to have a name, to be used in generated APIs.

codegen: str

Internal name to be used in code generation (Ada implementation packages): function name for properties/lazy fields, component name for fields, …

static for_internal(context: CompileCtx, radix: str) → MemberNames[source]

Return names for an internal member.

Internal members are not accessible from language spec code: the index is not a valid identifier and there is no spec/API name.

Parameters:
  • context – Compilation conetxt that will own this member.

  • radix – Radix used to create unique index/code generation names. In principle a simple counter would do, but including a meaningful radix in the names makes it easier to understand generated code, and simplifies debugging in general: better “env_mappings_42” than “internal_prop_42”.

static for_lazy_field(owner: CompiledType, spec: Name | str) → MemberNames[source]

Return names for a lazy field.

Parameters:
  • owner – Compiled type that owns the member.

  • spec – Lower case (if str) name for this field, as declared in the language specification.

static for_node_field(owner: CompiledType, spec: Name | str) → MemberNames[source]

Return names for a parse node field.

Parameters:
  • owner – Compiled type that owns the member.

  • spec – Lower case (if str) name for this field, as declared in the language specification.

static for_property(owner: CompiledType, spec: Name | str, builtin: bool = False) → MemberNames[source]

Return names for a property.

Parameters:
  • owner – Compiled type that owns the member.

  • spec – Lower case (if str) name for this field, as declared in the language specification.

  • builtin – Whether this is a builtin property.

static for_struct_field(spec: Name | str, codegen: str | None = None) → MemberNames[source]

Return names for a struct field.

Parameters:
  • spec – Lower case (if str) name for this field, as declared in the language specification.

  • codegen – Camel-with-underscores name to use for code generation. If left to None, an automatic one is generated.

index: str

Name used as an index in compiled type-level member lookup tables.

This must be the lower-cased version of spec if spec is defined, so that .foo references in Lkt code correctly resolve to the foo member. For internal members, this should contain invalid identifier names so that Lkt code cannot reference them.

An overriding member must have the same index name as its base member, so that consolidated lookup tables have only one entry for the full overriding hierarchy.

spec: Name | None = None

Name as defined in the language spec. This can be None for internal members, that are not meant to be accessed from the language spec itself.

class langkit.compiled_types.MetadataField(owner: CompiledType, names: MemberNames, location: Location, type: CompiledType, use_in_equality: bool, repr: bool = False, doc: str = '', public: bool = True, default_value: E.BindableLiteralExpr | None = None, access_needs_incref: bool = True)[source]

Field for metadata struct. Can be used only there, and requires the user to specify whether the field shall be taken into account when processing identity related properties.

See inherited doc. In this version we just ensure that a type is passed because it is mandatory for data fields. We also set repr to False because most of the time you don’t want User fields to show up in the pretty printer.

Parameters:
  • names – Names for this member.

  • is_public – Whether this field is public in the generated APIs.

  • access_needs_incref – See AbstractNodeData’s constructor.

  • default_value – Default value for this field, when omitted from New expressions.

  • implements – If provided, callback that returns the generic interface method that this member implements.

class langkit.compiled_types.NoCompiledType(context: CompileCtx, name: str | names.Name, location: Location, doc: str = '', base: _Self | None = None, fields: Callable[[CompiledType], Sequence[AbstractNodeData]] | None = None, is_ptr: bool = True, has_special_storage: bool = False, is_list_type: bool = False, is_entity_type: bool = False, exposed: bool = False, c_type_name: str | None = None, external: bool = False, null_allowed: bool = False, is_ada_record: bool = False, is_refcounted: bool = False, nullexpr: str | None = None, py_nullexpr: str | None = None, java_nullexpr: str | None = None, element_type: CompiledType | None = None, hashable: bool = False, has_equivalent_function: bool = False, type_repo_name: str | None = None, api_name: str | names.Name | None = None, lkt_name: str | None = None, conversion_requires_context: bool = False)[source]

Special CompiledType singleton. Used to mean the absence of type. This is useful in special resolved expressions.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property is_refcounted: bool

Return whether this type matters for the ref-counting mechanism.

This returns whether this type is dynamically allocated and thus ref-counted, or whether it owns ref-counted values. “dynamically” in this context means: with a lifetime that is different from the owning analysis unit.

If it is ref-counted, there must exist Inc_Ref and Dec_Ref primitives. The Dec_Ref primitive must handle null values correctly (i.e. ignore them).

exception langkit.compiled_types.NoNullexprError[source]

Exception raised by “nullexpr” properties when no null expression is available.

class langkit.compiled_types.NodeBuilderType(context: CompileCtx, node_type: ASTNodeType)[source]

Base class for node builder types.

Parameters:

node_type – Node type that this builder creates.

class ConstructorArgument(codegen_name: str, type: CompiledType, field: BaseField | None)[source]

Description of a constructor argument for a synthetizing node builder.

codegen_name: str

Ada identifier for argument, to be used in code generation.

field: BaseField | None

If this argument is used to initialize a field in the node to synthetize, reference to that field.

Note that in the case of parse fields, the argument type is a node builder, which is why field.type and type can be different.

There is only one argument that maps to no particular field: the constructor argument that contains node builders corresponding to the children of list node. When present, this argument always comes first.

type: CompiledType

Type for this argument.

property access_type: str

Return the name of the Ada record access type that implements this node builder type.

builtin_properties(owner: CompiledType) → list[E.PropertyDef][source]

Return properties available for all node builder types.

property record_type: str

Return the name of the Ada record type that implements this node builder type.

property synth_constructor: str

Return the name of the Ada function that creates a synthetizing node builder.

property synth_constructor_args: list[ConstructorArgument]

Return the list of arguments for the Ada function that creates a synthetizing node builder.

synth_node_builder_needed

Whether we need to generate code to create synthetizing node builders for this type in Ada.

class langkit.compiled_types.SetType(context: CompileCtx, element_type: CompiledType)[source]

Base class for set types.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property hashed_sets_pkg_name: Name

Name of the instance of Ada.Containers.Hashed_Sets used by this set type to store its elements.

property lkt_name: str

Type name as it appears in Lkt source code. To be used in diagnostics.

property name: Name

Name of the type for general values in the Ada generated code.

property pointed: Name

Name of the type for values that are pointed to by general values.

property set_type_name: Name

Name of the Ada set type.

class langkit.compiled_types.StringType(context: CompileCtx)[source]
Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

property api_access_name: Name

Name of the access type for public strings. Used as internals for array struct fields.

property public_requires_boxing: bool

Whether the public type in the Ada API for this requires some boxing to be embedded in a record. This is true for all unbounded types (i.e. arrays).

to_internal_expr(public_expr: str, context: str | None = None) → str[source]

Given public_expr, an expression that computes a public value, for this type return another expression that converts it to an internal value.

Parameters:

context – If this type requires the context for this conversion, this must be an expression that yields the context.

to_public_expr(internal_expr: str) → str[source]

Given internal_expr, an expression that computes an internal value, for this type return another expression that converts it to a public value.

class langkit.compiled_types.StructType(context: CompileCtx, name: names.Name, location: Location, doc: str = '', fields: Callable[[StructType], Sequence[AbstractNodeData]] | None = None, implements: Callable[[], Sequence[GenericInterface]] | None = None, is_list_type: bool = False, is_entity_type: bool = False, c_type_name: str | None = None, external: bool = False, py_nullexpr: str | None = None, java_nullexpr: str | None = None, element_type: CompiledType | None = None, has_equivalent_function: bool = False, type_repo_name: str | None = None, conversion_requires_context: bool = False)[source]

POD composite type.

Parameters:
  • name – See CompiledType.__init__.

  • implements – If provided, callback that returns the list of generic interfaces that this struct implements.

add_as_memoization_key(context: CompileCtx) → None[source]

Add self to the set of types that are used as keys in the hashed maps used to implement properties memoization. It has to be hashable.

c_dec_ref(capi: CAPISettings) → str[source]

Name of the C API function to dec-ref structure value.

Parameters:

capi – Settings for the C API.

c_inc_ref(capi: CAPISettings) → str[source]

Name of the C API function to inc-ref structure value.

Parameters:

capi – Settings for the C API.

property contains_boxed_fields: bool

Return if at least one field requires boxing in the public API.

property emit_c_type: bool

Return whether to emit a C type for this type.

This is used to filter out all entity types except the root one. All entity types are compatible from an ABI point of view, so this reduces the amount of code emitted for them.

property exposed_types: list[CompiledType]

Return the list of types that self exposes when it is itself exposed.

property has_early_decl: bool

Return whether declarations for this type in the internal Ada API happen earlier than usual.

Some types (for instance the metadata struct) have special constraints regarding code generation, so their type declaration must happen earlier than if they were more regular types.

property is_predeclared: bool

Whether this struct type is to be considered as pre-declared in templates for the internal Ada API.

Note that except for the type declaration itself (“type … is”) and the “nullexpr” constant, declarations for this type must still be emitted (Hash function, …).

property is_refcounted: bool

Return whether this type matters for the ref-counting mechanism.

This returns whether this type is dynamically allocated and thus ref-counted, or whether it owns ref-counted values. “dynamically” in this context means: with a lifetime that is different from the owning analysis unit.

If it is ref-counted, there must exist Inc_Ref and Dec_Ref primitives. The Dec_Ref primitive must handle null values correctly (i.e. ignore them).

property public_record_type: Name

Name of the Ada record type used to expose this struct in the public API.

require_hash_function() → None[source]

Tag this type as requiring a hash function.

property to_internal_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes a public value and returns an internal one. Return None otherwise.

property to_public_converter: Name

If this type requires a conversion in public properties, return the name of the function that takes an internal value and returns a public one. Return None otherwise.

class langkit.compiled_types.SymbolType(context: CompileCtx)[source]
Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

to_internal_expr(public_expr: str, context: str | None = None) → str[source]

Given public_expr, an expression that computes a public value, for this type return another expression that converts it to an internal value.

Parameters:

context – If this type requires the context for this conversion, this must be an expression that yields the context.

to_public_expr(internal_expr: str) → str[source]

Given internal_expr, an expression that computes an internal value, for this type return another expression that converts it to a public value.

langkit.compiled_types.T = <langkit.compiled_types.TypeRepo object>

Default type repository instance, to be used to refer to a type before its declaration.

class langkit.compiled_types.TokenType(context: CompileCtx)[source]

Singleton for the token data type.

Parameters:
  • context – Compilation context that owns this type.

  • name – Type name. If a string, it must be camel-case.

  • location – Location of the declaration of this compiled type.

  • doc (str) – User documentation for this type.

  • base – If this type derives from another type T, this is T.

  • fields – Callback that takes the compiled type instance and returns a list of fields to include for this type. The callback is evaluated as soon as all named types are known.

  • is_ptr – Whether this type is handled through pointers only in the generated code.

  • has_special_storage –

    Whether this type uses a special type for storage in structs and AST nodes. If this is true, the following methods may be overriden:

    • storage_type_name;

    • storage_nullexpr;

    • extract_from_storage_expr;

    • convert_to_storage_expr.

  • is_list_type – Whether this type is an AST node that is a list of AST nodes.

  • is_entity_type – Whether this type represents an entity type.

  • exposed – Whether the type should be exposed to the C and Python APIs. Note that all types are exposed anyway when the current context has the “library_all_fields_public” attribute set to True.

  • c_type_name – Name for the type as it will appear in the C API. If left to None, name will be used instead.

  • external – See CAPIType.__init__: this will be forwarded to it.

  • null_allowed – Whether a client is allowed to create a null value for this type. Note that a type might have a nullexpr and still have null disallowed, because nullexpr might make sense for initialization purposes in the parsers, but not as a real null value.

  • is_ada_record – Whether the type used in the C API is implemented as an Ada record. If so, we must pass them by reference in for C API interface functions.

  • is_refcounted – Return whether this type matters for the ref-counting mechanism. See the “is_refcounted” method.

  • nullexpr – Null expression to use in Ada for this type. See the “nullexpr” method.

  • py_nullexpr – Null expression to use in Python for this type. See the “py_nullexpr” method.

  • java_nullexpr – Null expression to use in Java for this type. See the java_nullexpr method.

  • element_type – If this is a collection type, must be the corresponding element type. Must be None otherwise.

  • hashable – Whether this type has a Hash primitive, so that it can be used as a key in hashed maps/sets.

  • has_equivalent_function – Whether testing equivalence for two values of this type must go through an Equivalent function. If not, code generation will use its “=” operator.

  • type_repo_name – Name to use for registration in TypeRepo. The camel-case of “name” is used if left to None.

  • api_name – If not None, must be the name of the type to use in the public Ada API. Strings are interpreted as camel case.

  • lkt_name – If provided, name used to represent this type at the Lkt level. Useful to format diagnostics.

  • conversion_requires_context – Whether converting this type from public to internal values requires an analysis context.

convert_to_storage_expr(node_expr: str, base_expr: str) → str[source]

Turn a public value into a storage value. See documentation for has_special_storage.

Parameters:
  • node_expr (str) – Expression that yields the node that will own the resulting storage value.

  • base_expr – Expression that yields the public value:

Returns:

An expression that yields the storage value.

extract_from_storage_expr(node_expr: str, base_expr: str) → str[source]

Turn a storage value into a public value. See documentation for has_special_storage.

Parameters:
  • node_expr – Expression that yields the node that owns the storage value.

  • base_expr – Expression that yields the storage value.

Returns:

An expression that yields the public value.

property mypy_type_hint: str

Type hint to use for this type when generating Mypy stub files for the Python bindings.

property storage_nullexpr: str

Return the nullexpr that is used for fields of this type in structs and ASTNodes. See documentation for has_special_storage.

property storage_type_name: Name

Return the name of the type that is used to store instances of this type in structs and AST nodes. See documentation for has_special_storage.

class langkit.compiled_types.TypeRepo[source]

Repository of types. Used to be able to do early references to not yet declared types, in this fashion:

T = TypeRepo()

class A(ASTNode):
    p = AbstractProperty(type=T.B)

class B(ASTNode):
    pass

Only Struct and AST node types are reachable through the type repository.

property all_types: ValuesView[CompiledType]

Return all compiled types created so far.

property entity: EntityType

This property returns the root type used to describe an AST node with semantic information attached.

property env_md: StructType

Shortcut to get the lexical environment metadata type.

property root_node: ASTNodeType

Shortcut to get the root AST node.

class langkit.compiled_types.UserField(owner: CompiledType, names: MemberNames, location: Location, type: CompiledType, repr: bool = False, doc: str = '', public: bool = True, default_value: E.BindableLiteralExpr | None = None, access_needs_incref: bool = True, implements: Callable[[], InterfaceMethodProfile] | None = None)[source]

Fields that are not meant to store parsing results. Can be used on any Node type, will be ignored by the parsing code.

See inherited doc. In this version we just ensure that a type is passed because it is mandatory for data fields. We also set repr to False because most of the time you don’t want User fields to show up in the pretty printer.

Parameters:
  • names – Names for this member.

  • is_public – Whether this field is public in the generated APIs.

  • access_needs_incref – See AbstractNodeData’s constructor.

  • default_value – Default value for this field, when omitted from New expressions.

  • implements – If provided, callback that returns the generic interface method that this member implements.

concrete: ClassVar[bool] = True

Field used to prevent instantiation of the class. Concrete descendants of BaseField must put that field to True in their definition.

classmethod for_struct(owner: StructType, name: str, location: Location, type: CompiledType, doc: str = '', default_value: E.BindableLiteralExpr | None = None, implements: Callable[[], InterfaceMethodProfile] | None = None) → UserField[source]

Create a struct field.

Parameters:
  • name – Lower-case name for this field, as declared in the language specification.

  • location – Source location for this field.

  • type – Type for this field.

  • doc – Documentation for this field, or empty string if not documented.

  • default_value – If this field has a default initialization, expression for the default initialization value.

  • implements – If provided, callback that returns the generic interface method that this member implements.

is_user_field: ClassVar[bool] = True

Whether this class is UserField.

langkit.compiled_types.create_builtin_types(context: CompileCtx) → None[source]

Create CompiledType instances for all built-in types. This will automatically register them in the current CompiledTypeRepo.

langkit.compiled_types.fields_callback_wrapper(ct: Type[_OwnerType], callback: Callable[[_OwnerType], Sequence[AbstractNodeData]]) → Callable[[CompiledType], Sequence[AbstractNodeData]][source]
langkit.compiled_types.fields_callback_wrapper(ct: Type[_OwnerType], callback: None) → None

Wrap a fields callback from a member class constructor.

CompiledType.__init__ takes (1) a callback that accepts CompiledType instances, however we want subclasses like StructType.__init__ to take (2) callbacks that accept BaseStructType values.

Since function types are contravariant in types of arguments, (2) is not a subtype of (1), so for type checking, this function returns a wrapper for (2) callbacks that matches (1).

langkit.compiled_types.gdb_helper(*args: str) → str[source]

Format given arguments into a special Ada comment for GDB helpers.

Parameters:

args (list[str]) – Elements of the special comment.

langkit.compiled_types.type_ref_list_doc(types: Sequence[CompiledType]) → str[source]

Helper to format a list of type references for the Sphinx documentation.