ArticleslgStudy

computer science

Abstract syntax tree

Abstract syntax tree is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Abstract syntax tree rather than just read about it. In short: An abstract syntax tree (AST) is a data structure used in computer science to represent the structure of a program or code snippet. It is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language.

Abstract syntax tree — main illustration
Abstract syntax tree — illustration

Key takeaways

  • Abstract syntax tree belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Abstract syntax tree to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Abstract syntax tree from memory before moving on to harder problems.

Reference excerpt

An abstract syntax tree (AST) is a data structure used in computer science to represent the structure of a program or code snippet. It is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurring in the text. It is sometimes called just a syntax tree. The syntax is "abstract" in the sense that it does not represent every detail appearing in the real syntax, but rather just the structural or content-related details. For instance, grouping parentheses are implicit in the tree structure, so these do not have to be represented as separate nodes. Likewise, a syntactic construct like an if-condition-then statement may be denoted by means of a single node with three branches. This distinguishes abstract syntax trees from concrete syntax trees, traditionally designated parse trees. Parse trees are typically built by a parser during the source code translation and compiling process. Once built, additional information is added to the AST by means of subsequent processing, e.g., contextual analysis. Abstract syntax trees are also used in program analysis and program transformation systems.

Application in compilers Abstract syntax trees are data structures widely used in compilers to represent the structure of program code. An AST is usually the result of the syntax analysis phase of a compiler. It often serves as an intermediate representation of the program through several stages that the compiler requires, and has a strong effect on the final output of the compiler.

Motivation An AST has several properties that aid in the additional steps of the compilation process:

An AST can be edited and enhanced with information such as properties and annotations for every element it contains. Such editing and annotation is impossible with the source code of a program, since it would imply changing it. Compared to the source code, an AST does not include nonessential punctuation and delimiters (braces, semicolons, parentheses, etc.). An AST usually contains extra information about the program, due to the consecutive stages of analysis by the compiler. For example, it may store the position of each element in the source code, allowing the compiler to print useful error messages. Languages are often ambiguous by nature. In order to avoid this ambiguity, programming languages are often specified as a context-free grammar (CFG). However, there are often aspects of programming languages that a CFG can't express, but are part of the language and are documented in its specification. These are details that require a context to determine their validity and behavior. For example, if a language allows new types to be declared, a CFG cannot predict the names of such types nor the way in which they should be used. Even if a language has a predefined set of types, enforcing proper usage usually requires some context. Another example is duck typing, where the type of an element can change depending on context. Operator overloading is yet another case where correct usage and final function are context-dependent.

Design The design of an AST is often closely linked with the design of a compiler and its expected features. Core requirements include the following:

Variable types must be preserved, as well as the location of each declaration in source code. The order of executable statements must be explicitly represented and well defined. Left and right components of binary operations must be stored and correctly identified. Identifiers and their assigned values must be stored for assignment statements. These requirements can be used to design the data structure for the AST. Some operations will always require two elements, such as the two terms for addition. However, some language constructs require an arbitrarily large number of children, such as argument lists passed to programs from the command shell. As a result, an AST used to represent code written in such a language has to also be flexible enough to allow for the quick addition of an unknown quantity of children. To support compiler verification it should be possible to unparse an AST into source code form. The source code produced should be sufficiently similar to the original in appearance and identical in execution, upon recompilation. The AST is used intensively during semantic analysis, where the compiler checks for correct usage of the elements of the program and the language. The compiler also generates symbol tables based on the AST during semantic analysis. A complete traversal of the tree allows verification of the correctness of the program. After verifying correctness, the AST serves as the base for code generation. The AST is often used to generate an intermediate representation (IR), sometimes called an intermediate language, for the code generation.

Other usages

AST differencing AST differencing, or for short tree differencing, consists of computing the list of differences between two ASTs. This list of differences is typically called an edit script. The edit script directly refers to the AST of the code. For instance, an edit action may result in the addition of a new AST node representing a function.

Clone detection An AST is a powerful abstraction to perform code clone detection.

Definition

Arities Let S be a set of sorts, an arity is a tuple (s1,…,sn,s), for s1,…,sn,s∈S, also written as (s1,…,sn)s. More precisely, Arity(S):=∐n∈ℕSn+1. Let 𝒪={𝒪α}α∈Arity(S) be an Arity(S)-indexed family of disjoint sets of operators. If o is an operator arity (s1,…,sn)s we say that o has sort s and has n arguments of sorts s1,…,sn.

ASTs Fix S be a finite set of sorts, and 𝒪 an Arity(S)-indexed family of disjoint sets of operators. Let 𝒳={𝒳s}s∈S be an S-indexed family of disjoint sets of variables. The family 𝒜[𝒳]={𝒜[𝒳]s}s∈S of abstract syntax trees, or ASTs, is the smallest S-indexed family of disjoint sets closed under the following conditions:

Variables are ASTs: if x∈𝒳s, then x∈𝒜[𝒳]s. Operators combine ASTs: If o is an operator of arity (s1,…,sn)s, and ai∈𝒜[𝒳]si for all 1≤i≤n, then o(a1;…;an)∈𝒜[𝒳]s.

See also

References

… excerpt ends here. Continue reading the full article.

Illustrations

Abstract syntax tree: An abstract syntax tree for the following code for the Euclidean algorithm:while b != 0:
    if a > b:
        a := a - b
    else:
        b := b - a
return a
An abstract syntax tree for the following code for the Euclidean algorithm:while b != 0: if a > b: a := a - b else: b := b - a return a

Worked examples

Example 1 — a first encounter with Abstract syntax tree

Start with the simplest possible case. Write down what Abstract syntax tree claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Abstract syntax tree before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Abstract syntax tree ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Abstract syntax tree

In research
Abstract syntax tree appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Abstract syntax tree in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Abstract syntax tree is common in secondary-school and first-year university syllabi. It links to neighbouring topics Formal languages, Trees (data structures), so understanding it makes those chapters shorter.
In everyday life
Look for Abstract syntax tree outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Abstract syntax tree” →

How to study Abstract syntax tree in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Abstract syntax tree means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Abstract syntax tree out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Abstract syntax tree in simple terms?

An abstract syntax tree (AST) is a data structure used in computer science to represent the structure of a program or code snippet. It is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language.

Why does Abstract syntax tree matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Abstract syntax tree?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Abstract syntax tree.

Tags

  • Formal languages
  • Trees (data structures)

Keep exploring