Skip to content

API

The aspen project.

__main__

The main entry point for the application.

main() -> None

Run the main function.

cli

Command line commands exposing AspenTree's reify and transform functionality.

cmd_reify(args: Namespace) -> None

Run the aspen reify subcommand: parse one or more SOURCE[@LANG] sources and print their combined reified ASP fact representation to stdout.

cmd_transform(args: Namespace) -> None

Run the aspen transform subcommand: parse one or more SOURCE[@LANG][:DEST] sources, apply a transformation meta-encoding to them, and either write out each source's transformed text to its own DEST (the default, via AspenTree.write()) or print the combined fact base to stdout (--facts).

resolve_language(name: str) -> ts.Language

Load a tree-sitter Language by short name: "clingo" loads the installed tree_sitter_clingo package, and so on for any other installed tree-sitter grammar.

messages

Module rendering the templates derived by transformation meta-encodings, and messages about nodes of the sources.

NodeFormatter

Renders templates and messages about nodes, using locate_node to find the source and tree-sitter node of a node(Id) symbol (which returns None if the symbol is not the identifier of a node), and locate_original_node to find them in the sources as they were at the start of the current transformation step.

describe_edit(edit_symb: Symbol) -> str

Describe an edit symbol by its kind and the text it inserts (or its template, if it cannot be converted to text).

locate_target(target_symb: Symbol, original: bool = False) -> tuple[Source, list[ts.Node]]

The source and nodes of a node(Id) symbol, or of a span(node(N), node(M)) symbol, whose nodes are N and its next siblings up to M. If original is set, they are located in the sources as they were at the start of the transformation step. Raises a ValueError if a node is not known, or M is not N or a later sibling of it.

node_message(node_symb: Symbol, text: str) -> str

Message about the node with the given node(Id) symbol (or the nodes of a span(node(N), node(M)) symbol), consisting of its location in the source, the text, and the part of the source spanned by the node. If the node is not known (e.g. as the symbol is not the identifier of a node, which is reported separately), the symbol is shown instead.

node_position(node_symb: Symbol) -> tuple[str, int]

Key to sort node(Id) (and span) symbols by their position in the sources.

template_symb2str(symb: Symbol) -> str

Convert template symbol to python str.

A template is a string, or one of: - node(N): the current text of node N, i.e. including the edits of it and its descendants applied so far (which the transformation encoding orders before the edit using the template); - span(node(N), node(M)): the current text from the start of node N to the end of node M, which must be N or a later sibling of N; - original(node(N)), original(span(node(N), node(M))): the text of node N (or the span) at the start of the current transformation step, before any edits; - format(S, L) and join(S, L): the format string S with the templates of the list L inserted, or the templates of the list L joined by S; - mutate(B, E): the text of B, which is node(N), a span, or either of them wrapped in original(...), with the edits E applied, without changing the source. E is an edit or a list of edits of the form replace(T, S), append(node(M), S) or prepend(node(M), S), where T is node(M) or a span, and the nodes are in B or descendants of nodes in B, see _mutate_text; - syntax_error(node(N)): a description of the syntax error at node N.

cons_list_symb2py(l: Symbol) -> list[Symbol]

Convert symbolic cons list consisting of nested tuples into a python list of symbols.

is_span(symb: Symbol) -> bool

Whether symb is of the form span(node(N), node(M)).

is_target(symb: Symbol) -> bool

Whether symb is of the form node(N) or span(node(N), node(M)).

loc_prefix(source: Source, start_p: ts.Point, end_p: ts.Point) -> str

The location prefix of the part of a source between two points for error and log messages.

source

Module defining the sources processed by an AspenTree.

Source dataclass

Source processed by an AspenTree.

source_str(source: Source) -> str

The identifier to show for a source in error/log messages: its file path when read from one, or its source id otherwise (e.g. for stdin, or any other in-memory source).

tree

Module defining the AspenTree class.

AspenTree

A tree that wraps a tree-sitter tree and it's representation as a set ASP facts.

The class further defined various transformation operations on both representations, and syncs the two in case of changes. Transformations to the tree-sitter tree can be made via the wrapped tree's API, while trasformations on the ASP fact reperesentation can be defined via a logic program, which deriving special transformation predicates in it's answer sets with the fact representation of the tree as input.

facts: List[Symbol] property writable

The fact representation of the sources.

If re-reification was skipped after the last step of a transformation (see the skip_final_re_reify option of transform()), the sources are reified anew on first access.

parse(source: SourceInput, *, language: Optional[ts.Language] = None, encoding: Optional[StringEncoding] = None, included_ranges: Optional[Sequence[ts.Range]] = None, identifier: Optional[Symbol] = None, destination: Optional[Path] = None) -> Symbol

Parse input strings, and generate fact representation.

destination associates this source with where its text should be written by a later call to write(): a path, or None (the default) for stdout.

transform(*, meta_files: Optional[Sequence[Path]] = None, meta_string: Optional[str] = None, initial_program: tuple[str, Sequence[Symbol]] = ('base', ()), control_options: Optional[Sequence[str]] = None, skip_final_re_reify: bool = False) -> None

Transform fact base via a meta-encoding.

If skip_final_re_reify is set, the sources edited in the last step of the transformation (the one not deriving aspen(next_program(...))) are re-parsed, but not re-reified, which saves time when the resulting facts are not needed. Syntax errors introduced by the edits are still detected. If the facts are accessed afterwards, all sources are reified anew.

write() -> None

Write every source's current text to its associated destination, in the order they were parsed: a source with no destination (the default) is printed to stdout. A newline is added to text not ending with one.

The text is written as is, without translating newlines (in text mode, Python would write the \r\n line endings of a source as \r\r\n on Windows): files are written in the encoding of the source, and stdout is written to via its binary buffer, if it has one.

TransformError

Bases: Exception

Exception raised when a transformation meta-encoding derives an error.

id_counter(start: int = 0, step: int = 1) -> Generator[Symbol, None, None]

Simple infinite generator that yields clingo Numbers, starting from start, with increment given by step.

utils

Utilities.

include_resolver

Resolve the '@aspen/...' include convention, which lets a user-authored meta-encoding reference aspen's own bundled ASP utility library (shipped under asp/utils) without needing to know where aspen itself is installed, e.g.:

#include "@aspen/clingo/derived_predicates/symbol_signature.lp".

clingo's own #include only understands paths relative to the file containing the directive (or absolute paths), with no library search path of its own - and no amount of relative '../..' climbing can express "wherever aspen happens to be installed", since that varies per installation. So the '@aspen/' prefix has to be rewritten to an absolute path before the file ever reaches clingo; that is what this module does, recursively following local (non-'@aspen/') #include-s so that a user's own file three levels deep can use '@aspen/' too.

resolve_meta_encoding_file(path: Path, cache_root: Path, bundled_utils_path: Path) -> Path

The file aspen should load into clingo in place of path: path itself, unchanged, if neither it nor anything it (transitively, locally) #include-s uses the '@aspen/' convention; otherwise a rewritten copy, mirrored under cache_root at the same absolute-path-derived layout, so that unrelated local #include-s between mirrored files keep resolving exactly as they did from path's original location.

rewrite_includes(text: str, bundled_utils_path: PurePath) -> str

Rewrite every #include "@aspen/foo.lp" in text to the real, absolute location of foo.lp under bundled_utils_path. Other

include targets are left untouched.

log

Setup project wide loggers.

This is a thin wrapper around Python's logging module. It supports colored logging.

LoggerRedirector

Class with methods to update the stream on the log handler to point to the buffer unittest has set up for capturing the test output, as well as to reset them after test has run.

all_loggers() -> list[logging.Logger] staticmethod

Store all loggers.

redirect_loggers(fake_stdout: Optional[TextIO] = None, fake_stderr: Optional[TextIO] = None) -> None classmethod

Redirect loggers before test.

reset_loggers(fake_stdout: Optional[TextIO] = None, fake_stderr: Optional[TextIO] = None) -> None classmethod

Reset loggers after test

SingleLevelFilter

Bases: Filter

Filter levels.

TestCaseWithRedirectedLogs

Bases: TestCase

A TestCase subclass that redirects stdin and stderr in such a fashion as to redirect log handlers to the buffer unittest uses. This allows us to display logs when a test fails.

configure_logging(stream: TextIO, level: int, use_color: bool) -> None

Configure application logging.

get_clingo_logger(logger: logging.Logger) -> Callable[[MessageCode, str], None]

Return a callback function to be used by a clingo.Control object to log to input logger.

get_logger(name: str) -> logging.Logger

Get a logger with the given name.

get_ts_logger(logger: logging.Logger) -> Callable[[ts.LogType, str], None]

Return a callback function to be used when initializing a clingo.core.Library object to log to input logger.

log_clingo_message(message_code: MessageCode, message: str, logger: logging.Logger) -> None

Log clingo message at the appropriate level

log_ts_message(logtype: ts.LogType, message: str, logger: logging.Logger) -> None

Log tree-sitter message.

parser

The command line parser for the project.

get_parser() -> ArgumentParser

Return the parser for command line options.

testing

Utilities for testing.

AspenTestCase

Bases: TestCaseWithRedirectedLogs

Base class for building test cases related to AspenTree class.

assert_parse_equals_file(language: Language, source: SourceInput, path: Path, additional_expected_facts: Optional[list[Symbol]] = None, raise_syntax_errors: bool = True) -> None

Assert that parsing string of the given language results in symbols contained in the given file.

assert_transform_isomorphic(*, language: Language, sources: Sequence[SourceInput], expected_sources: Sequence[str | Path], meta_files: Optional[Sequence[Path]] = None, meta_string: Optional[str] = None, initial_program: tuple[str, Sequence[Symbol]] = ('base', ()), control_options: Optional[Sequence[str]] = None, skip_final_re_reify: bool = False) -> None

Assert that transformation results in expected string, and check that reified representation is isomorphic.

assert_transform_logs(*, log_level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR'], message2num_matches: dict[str, int], language: Language, source: SourceInput, meta_files: Optional[Sequence[Path]] = None, meta_string: Optional[str] = None, initial_program: tuple[str, Sequence[Symbol]] = ('base', ()), control_options: Optional[Sequence[str]] = None) -> None

Assert that transformation logs messages, or raises error.

assert_transform_raises(*, message_regex: str, language: Language, sources: Optional[Sequence[SourceInput]], meta_files: Optional[Sequence[Path]] = None, meta_string: Optional[str] = None, initial_program: tuple[str, Sequence[Symbol]] = ('base', ()), control_options: Optional[Sequence[str]] = None, skip_final_re_reify: bool = False) -> None

Assert that transformation raises error.

tree_sitter_utils

Utilities related to tree-sitter.

calc_edit_range(start_byte: int, old_end_byte: int, start_point: ts.Point, old_end_point: ts.Point, replacement: bytes) -> EditRange

Calculate start/end bytes and points for an arbitrary replacement

calc_node_append_range(node: ts.Node, to_append: bytes) -> EditRange

Calculate start/end bytes and points for appending text after node.

calc_node_edit_range(node: ts.Node, replacement: bytes) -> EditRange

Calculate start/end bytes and points for a node edit.

calc_node_prepend_range(node: ts.Node, to_prepend: bytes) -> EditRange

Calculate start/end bytes and points for prepending text before node.

edit_tree(tree: ts.Tree, edit_range: EditRange, replacement: bytes, old_source: Optional[bytes] = None) -> bytes

Edit a node in the tree by replacing with the given text.

Note that this function does not re-parse the tree.

expected_symbols(language: ts.Language, node: ts.Node) -> list[str]

What the grammar would have accepted at node's position.

This follows tree-sitter's own recommendation (see Language.lookahead_iterator's docstring), which differs by node kind: for an ERROR node, use the lookahead iterator on its own first leaf's parse_state - that leaf is the token the parser actually choked on, so its state captures exactly where things went wrong. A MISSING node has no such leaf of its own, so the next best thing is the last real, non-extra leaf before it, using that leaf's next_parse_state. Anything that's neither ERROR nor MISSING falls back to the same preceding-leaf approach as MISSING, as the more general "what's valid at this position" query.

Separately, tree-sitter merges "compatible" parse states that are reused across multiple unrelated grammar contexts (see https://github.com/tree-sitter/tree-sitter/issues/4711), which can inflate this list with symbols only valid in some other context. There's no way to filter those out from here; --disable-optimizations at grammar-generation time is the only fix, at the cost of a larger parse table, which we choose not to do for now.

format_node_span(node: ts.Node, source_bytes: bytes, encoding: str) -> str

Render the source line(s) spanned by node, with the span underlined by carets, see format_point_span.

format_point_span(start: ts.Point, end: ts.Point, source_bytes: bytes, encoding: str) -> str

Render the source line(s) between the start and end points, with the span underlined by carets.

A span within a single line gets that line, followed by one caret-underlined line. A span crossing multiple lines shows its first line (underlined from the start column to the end of that line) and its last line (underlined from the start of that line to the end column), with a single '...' line in between when the span covers more than two lines.

format_syntax_error(node: ts.Node, source_bytes: bytes, encoding: str, language: ts.Language, source_str: str) -> str

Render a tree-sitter ERROR/MISSING node as a human-readable message: which source it came from (a file path, or a source id such as 's(0)' for stdin or any other in-memory source), its location, the offending source line(s) with the span underlined (see format_node_span), and - for ERROR nodes only, when there's a short and specific enough hint to be worth it (see _expected_hint) - a note of what the parser would have accepted instead.

get_node_at_path(tree: ts.Tree, path: list[int], reverse: bool = False) -> ts.Node

Given an input tree and a path, represented as a sequence of integer indices (in reverse order by default), retrieve the node found at the path in the tree.

get_path_of_node(node: ts.Node) -> list[int]

Given an input node, calculate it's path in the tree, represented as a list of indices to traverse to reach the node from the root, in reverse order.

get_tree_changes(old_tree: ts.Tree, new_tree: ts.Tree) -> list[Change]

Given an old tree, and a new tree that has just been re-parsed from the old one, calculate the changes that need to be made to old_tree (and data structures derived from old_tree) to get a tree isomorphic to new_tree.

The necessary changes are returned a list of pairs. Each pair in turn contains two lists of sibling nodes, the first one from the old tree and the second one from the new tree. By replacing the old siblings with the new siblings in the old tree for each such pair in the returned list, the old tree becomes isomorphic to the new tree.

pprint_node(ts_node: ts.Node) -> None

Pretty-prints the string representation of a tree-sitter Tree.

print_changed_ranges(old_tree: ts.Tree, new_tree: ts.Tree) -> None

Print changed ranges after editing tree.

print_supertypes(lang: ts.Language) -> None

Prints all supertype and their respective subtypes defined in a grammar.