What’s the difference between parse trees and abstract syntax trees (ASTs)?

This is based on the Expression Evaluator grammar by Terrence Parr. The grammar for this example: grammar Expr002; options { output=AST; ASTLabelType=CommonTree; // type of $stat.tree ref etc… } prog : ( stat )+ ; stat : expr NEWLINE -> expr | ID ‘=’ expr NEWLINE -> ^(‘=’ ID expr) | NEWLINE -> ; expr … Read more

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code … Read more

Python 3, Are there any known security holes in ast.literal_eval(node_or_string)?

The documentation states it is safe, and there is no bug relative to security of literal_eval in the bug tracker, so you can probably assume it is safe. Also, according to the source, literal_eval parses the string to a python AST (source tree), and returns only if it is a literal. The code is never … Read more

Constructing an Abstract Syntax Tree with a list of Tokens

The fundamental trick is to recognize that parsing, however accomplished, happens in incremental steps, including the reading of the tokens one by one. At each incremental step, there is an opportunity to build part of the AST by combining AST fragments built by other incremental steps. This is a recursive idea, and it bottoms out … Read more

What would an AST (abstract syntax tree) for an object-oriented programming language look like?

AST is an abstraction of the CST (concrete syntax tree, or, parse tree). The concrete syntax tree is the tree resulting from the productions (in the grammar) used to parse the file. So your AST is basically derived from your grammar definition, but has for transformed Exp / | \ / | \ * Ident … Read more

What is the difference between an Abstract Syntax Tree and a Concrete Syntax Tree?

A concrete syntax tree represents the source text exactly in parsed form. In general, it conforms to the context-free grammar defining the source language. However, the concrete grammar and tree have a lot of things that are necessary to make source text unambiguously parseable, but do not contribute to actual meaning. For example, to implement … Read more