prodigy.pgcl.parser

Parser

A Lark-based parser for pGCL.

For more details on what syntax is accepted for pGCL programs, you can view the formal grammar used for the parser.

Notes on the parsing algorithm

For most of the grammar, a simple run of the Lark parser suffices. The only slightly tricky part is parsing of categorical choice expressions. To avoid ambiguous grammar, we parse those as normal expressions of PLUS operators. Individual weights attached to probabilities are saved in a temporary LikelyExpr type which associates a single expression with a probability. Later we collect all LikelyExpr and flatten them into a single CategoricalExpr. LikelyExpr never occur outside of this parser.

parse_pgcl(code)[source]

Parse a pGCL program with an optional prodigy.pgcl.ast.ProgramConfig.

>>> parse_pgcl("x := y")
Program(variables={}, constants={}, parameters={}, functions={}, instructions=[AsgnInstr(lhs='x', rhs=VarExpr('y'))])

>>> parse_pgcl("x := unif(5, 17)").instructions[0]
AsgnInstr(lhs='x', rhs=FunctionCallExpr(function='unif', params=([NatLitExpr(5), NatLitExpr(17)], {})))

>>> parse_pgcl("x := x : 1/3 + y : 2/3").instructions[0]
AsgnInstr(lhs='x', rhs=CategoricalExpr(exprs=[(VarExpr('x'), RealLitExpr("1/3")), (VarExpr('y'), RealLitExpr("2/3"))]))
Parameters:

code (str)

Return type:

Program

parse_expr(code)[source]

Parse a pGCL expression.

As a program expression, it may not contain Iverson bracket expressions.

>>> parse_expr("x < y & z")
BinopExpr(operator=Binop.AND, lhs=BinopExpr(operator=Binop.LT, lhs=VarExpr('x'), rhs=VarExpr('y')), rhs=VarExpr('z'))

>>> parse_expr("[x]")
Traceback (most recent call last):
    ...
Exception: parse_expr: Expression may not contain an Iverson bracket expression.
Parameters:

code (str)

Return type:

VarExpr | BoolLitExpr | NatLitExpr | RealLitExpr | UnopExpr | BinopExpr | CategoricalExpr | SubstExpr | TickExpr | FunctionCallExpr | InferExpr | SampleExpr

parse_expectation(code)[source]

Parse a pGCL expectation. This allows all kind of expressions.

>>> parse_expectation("[x]")
UnopExpr(operator=Unop.IVERSON, expr=VarExpr('x'))

>>> parse_expectation("0.2")
RealLitExpr("0.2")

>>> parse_expectation("1/3")
RealLitExpr("1/3")

>>> parse_expectation("∞")
RealLitExpr("Infinity")
Parameters:

code (str)

Return type:

VarExpr | BoolLitExpr | NatLitExpr | RealLitExpr | UnopExpr | BinopExpr | CategoricalExpr | SubstExpr | TickExpr | FunctionCallExpr | InferExpr | SampleExpr