Abstract Syntax Tree#
Kork
parses the code into the following AST https://github.com/langchain-ai/kork/blob/main/kork/ast.py.
Below we’ll show a few of the utilities to parse and print the ast.
Parse#
from kork.parser import parse
parse("x")
Program(stmts=(Variable(name='x'),))
parse("x = 1")
Program(stmts=(Assign(name='x', value=Literal(value=1)),))
parse(
"""
extern fn foo() -> Any # Comment
x = 1; // Comment
y = x * x + foo()
"""
)
Program(stmts=(ExternFunctionDef(name='foo', params=ParamList(params=[]), return_type='Any', implementation=None, doc_string=''), Assign(name='x', value=Literal(value=1)), Assign(name='y', value=Binary(left=Binary(left=Variable(name='x'), operator='*', right=Variable(name='x')), operator='+', right=FunctionCall(name='foo', args=[])))))
AstPrinter#
The AST printer can be used to translate AST syntax into a string representation of the program.
This functionality is used to generate the prompt for the LLM as we’ll see later in the docs.
from kork import AstPrinter
program = parse(
"""
extern fn foo() -> Any # Comment
x=1; // Comment
y=x*x + foo()
"""
)
program.stmts[0].params
ParamList(params=[])
print(AstPrinter().visit(program))
extern fn foo() -> Any
x = 1
y = x * x + foo()
Nodes#
The nodes in the ast are in the ast
module.
from kork.ast import FunctionCall, FunctionDef
?FunctionCall
Init signature: FunctionCall(name: 'str', args: 'Sequence[Expr]') -> None
Docstring: Represent a function call.
File: ~/src/kork/kork/ast.py
Type: ABCMeta
Subclasses:
?FunctionDef
Init signature:
FunctionDef(
name: 'str',
params: 'ParamList',
body: 'Sequence[Union[Stmt, Expr]]',
return_type: 'str',
) -> None
Docstring: Represent a function definition with an implementation.
File: ~/src/kork/kork/ast.py
Type: ABCMeta
Subclasses: