Abstract syntax tree: Difference between revisions
imported>OAbot m Open access bot: url-access=subscription updated in citation with #oabot. |
imported>Linguistics-Expert m very minor corrections |
||
| Line 2: | Line 2: | ||
{{For|the trees used in linguistics|parse tree}} | {{For|the trees used in linguistics|parse tree}} | ||
{{no footnotes|date=February 2013}} | {{no footnotes|date=February 2013}} | ||
[[File:Abstract syntax tree for Euclidean algorithm.svg|thumb|400px|An abstract syntax tree for the following code for the [[Euclidean algorithm]]:<syntaxhighlight lang=" | [[File:Abstract syntax tree for Euclidean algorithm.svg|thumb|400px|An abstract syntax tree for the following code for the [[Euclidean algorithm]]:<syntaxhighlight lang="php">while b != 0: | ||
while b | |||
if a > b: | if a > b: | ||
a := a - b | a := a - b | ||
else: | else: | ||
b := b - a | b := b - a | ||
return a | return a</syntaxhighlight>]] | ||
</syntaxhighlight>]] | |||
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 (data structure)|tree]] representation of the [[abstract syntax|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'''. | 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 (data structure)|tree]] representation of the [[abstract syntax|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'''. | ||
| Line 20: | Line 18: | ||
== Application in compilers == | == 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 | 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 affect on the final output of the compiler. | ||
=== Motivation === | === Motivation === | ||
An AST has several properties that aid the | 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. | * 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 | * 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. | * 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 [[syntactic ambiguity|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 | Languages are often [[syntactic ambiguity|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 === | === Design === | ||
| Line 42: | Line 40: | ||
These requirements can be used to design the data structure for the AST. | 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 quick addition of an unknown quantity of children. | 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. | 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. | ||
| Line 48: | Line 46: | ||
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. | 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 == | == Other usages == | ||
| Line 55: | Line 54: | ||
=== Clone detection === | === Clone detection === | ||
An AST is a powerful abstraction to perform code [[clone detection]].<ref>{{Cite book |last1=Koschke |first1=Rainer |last2=Falke |first2=Raimar |last3=Frenzel |first3=Pierre |title=2006 13th Working Conference on Reverse Engineering |chapter=Clone Detection Using Abstract Syntax Suffix Trees |date=2006 |chapter-url=http://dx.doi.org/10.1109/wcre.2006.18 |pages=253–262 |publisher=IEEE |doi=10.1109/wcre.2006.18|isbn=0-7695-2719-1 |s2cid=6985484 }}</ref> | An AST is a powerful abstraction to perform code [[clone detection]].<ref>{{Cite book |last1=Koschke |first1=Rainer |last2=Falke |first2=Raimar |last3=Frenzel |first3=Pierre |title=2006 13th Working Conference on Reverse Engineering |chapter=Clone Detection Using Abstract Syntax Suffix Trees |date=2006 |chapter-url=http://dx.doi.org/10.1109/wcre.2006.18 |pages=253–262 |publisher=IEEE |doi=10.1109/wcre.2006.18|isbn=0-7695-2719-1 |s2cid=6985484 }}</ref> | ||
== Definition == | |||
=== Arities === | |||
Let <math>S</math> be a set of ''sorts'', an ''arity is a tuple'' <math>(s_1,\dots,s_n,s)</math>, for <math>s1,\dots,s_n,s\in S</math>, also written as <math>(s_1,\dots,s_n)s</math>. More precisely, <math>\mathrm{Arity}(S) := \coprod_{n \in \mathbb{N}} S^{n + 1}</math>. | |||
Let <math>\mathcal{O} = \{ \mathcal{O_\alpha} \}_{\alpha \in \mathrm{Arity}(S)}</math> be an <math>\mathrm{Arity}(S)</math>-indexed family of disjoint sets of ''operators''. If <math>o</math> is an operator arity <math>(s_1,\dots,s_n)s</math> we say that <math>o</math> has sort <math>s</math> and has <math>n</math> arguments of sorts <math>s_1,\dots,s_n</math>. | |||
=== ASTs === | |||
Fix <math>S</math> be a finite set of sorts, and <math>\mathcal{O}</math> an <math>\mathrm{Arity}(S)</math>-indexed family of disjoint sets of ''operators''. Let <math>\mathcal{X} = \{ \mathcal{X}_s \}_{s \in S}</math> be an <math>S</math>-indexed family of disjoint sets of variables. The family <math>\mathcal{A}[\mathcal{X}] = \{ \mathcal{A}[\mathcal{X}]_s \}_{s\in S}</math> of '''''abstract syntax trees''''', or '''''AST'''''s, is the smallest <math>S</math>-indexed family of disjoint sets closed under the following conditions: | |||
# '''Variables are ASTs:''' if <math>x \in \mathcal{X}_s</math>, then <math>x \in \mathcal{A}[\mathcal{X}]_s</math>. | |||
# '''Operators combine ASTs:''' If <math>o</math> is an operator of arity <math>(s_1,\dots,s_n)s</math>, and <math>a_i\in \mathcal{A}[\mathcal{X}]_{s_i}</math> for all <math>1 \leq i \leq n</math>, then <math>o(a_1;\dots;a_n) \in \mathcal{A}[\mathcal{X}]_s</math>. | |||
== See also == | == See also == | ||
| Line 70: | Line 82: | ||
* [[Symbol table]] | * [[Symbol table]] | ||
* [[TreeDL]] | * [[TreeDL]] | ||
* [[ | * [[Interpreter_(computing)#Variations|Abstract Syntax Tree Interpreters]] | ||
== References == | == References == | ||
| Line 76: | Line 88: | ||
== Further reading == | == Further reading == | ||
* {{cite web |last=Jones |first=Joel |title=Abstract Syntax Tree Implementation Idioms |url=http://www.hillside.net/plop/plop2003/Papers/Jones-ImplementingASTs.pdf |url-status=dead |archive-url= | * {{cite web |last=Jones |first=Joel |title=Abstract Syntax Tree Implementation Idioms |url=http://www.hillside.net/plop/plop2003/Papers/Jones-ImplementingASTs.pdf |url-status=dead |archive-url=https://web.archive.org/web/20240721094334/http://hillside.net/plop/plop2003/Papers/Jones-ImplementingASTs.pdf |archive-date=21 July 2024 |access-date=9 November 2011 }} (overview of AST implementation in various language families) | ||
* {{cite conference |last1=Neamtiu |first1=Iulian |last2=Foster |first2=Jeffrey S. |last3=Hicks |first3=Michael |date=May 17, 2005 |title=Understanding Source Code Evolution Using Abstract Syntax Tree Matching |conference=MSR'05 |location=Saint Louis, Missouri |publisher=ACM |citeseerx=10.1.1.88.5815}} | * {{cite conference |last1=Neamtiu |first1=Iulian |last2=Foster |first2=Jeffrey S. |last3=Hicks |first3=Michael |date=May 17, 2005 |title=Understanding Source Code Evolution Using Abstract Syntax Tree Matching |conference=MSR'05 |location=Saint Louis, Missouri |publisher=ACM |citeseerx=10.1.1.88.5815}} | ||
* {{cite thesis |last=Würsch |first=Michael |degree=Diploma |title=Improving Abstract Syntax Tree based Source Code Change Detection |url=http://www.ifi.uzh.ch/seal/research/tools/archive/changeDetection.html}} | * {{cite thesis |last=Würsch |first=Michael |degree=Diploma |title=Improving Abstract Syntax Tree based Source Code Change Detection |url=http://www.ifi.uzh.ch/seal/research/tools/archive/changeDetection.html}} | ||
* {{cite web |last=Lucas |first=Jason |title=Thoughts on the Visual C++ Abstract Syntax Tree (AST) |date=16 August 2006 |url=https://devblogs.microsoft.com/cppblog/thoughts-on-the-visual-c-abstract-syntax-tree-ast/}} | * {{cite web |last=Lucas |first=Jason |title=Thoughts on the Visual C++ Abstract Syntax Tree (AST) |date=16 August 2006 |url=https://devblogs.microsoft.com/cppblog/thoughts-on-the-visual-c-abstract-syntax-tree-ast/}} | ||
* [[Robert Harper (computer scientist)|Robert Harper]] (2016). ''[https://www.cs.cmu.edu/~rwh/pfpl/ Practical Foundations for Programming Languages] (Second Edition). Cambridge University Press.'' | |||
==External links== | ==External links== | ||
| Line 86: | Line 99: | ||
*{{cite web|url=http://www.eclipse.org/articles/Article-JavaCodeManipulation_AST/index.html|title=Abstract Syntax Tree and Java Code Manipulation in the Eclipse IDE|work=eclipse.org}} | *{{cite web|url=http://www.eclipse.org/articles/Article-JavaCodeManipulation_AST/index.html|title=Abstract Syntax Tree and Java Code Manipulation in the Eclipse IDE|work=eclipse.org}} | ||
*{{cite web|url=http://www.cs.utah.edu/flux/flick/current/doc/guts/gutsch6.html|title=CAST representation|work=cs.utah.edu}} | *{{cite web|url=http://www.cs.utah.edu/flux/flick/current/doc/guts/gutsch6.html|title=CAST representation|work=cs.utah.edu}} | ||
*[ | *[https://eli-project.sourceforge.net/elionline/idem_3.html eli project]: Abstract Syntax Tree [[Unparsing]] | ||
*{{cite web | url = http://www.omg.org/spec/ASTM/ | title = Architecture‑Driven Modernization — ADM: Abstract Syntax Tree Metamodeling — ASTM }} ([[Object Management Group|OMG]] standard). | *{{cite web | url = http://www.omg.org/spec/ASTM/ | title = Architecture‑Driven Modernization — ADM: Abstract Syntax Tree Metamodeling — ASTM }} ([[Object Management Group|OMG]] standard). | ||
*[https://javaparser.org JavaParser]: The JavaParser library provides you with an Abstract Syntax Tree of your Java code. The AST structure then allows you to work with your Java code in an easy programmatic way. | *[https://javaparser.org JavaParser]: The JavaParser library provides you with an Abstract Syntax Tree of your Java code. The AST structure then allows you to work with your Java code in an easy programmatic way. | ||
Latest revision as of 08:00, 29 October 2025
Template:Short description Script error: No such module "For". Template:No footnotes
while b != 0:
if a > b:
a := a - b
else:
b := b - a
return a
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 affect 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.[1] 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.[2]
Definition
Arities
Let be a set of sorts, an arity is a tuple , for , also written as . More precisely, .
Let be an -indexed family of disjoint sets of operators. If is an operator arity we say that has sort and has arguments of sorts .
ASTs
Fix be a finite set of sorts, and an -indexed family of disjoint sets of operators. Let be an -indexed family of disjoint sets of variables. The family of abstract syntax trees, or ASTs, is the smallest -indexed family of disjoint sets closed under the following conditions:
- Variables are ASTs: if , then .
- Operators combine ASTs: If is an operator of arity , and for all , then .
See also
- Abstract semantic graph (ASG), also called term graph
- Composite pattern
- Control-flow graph
- Directed acyclic graph (DAG)
- Document Object Model (DOM)
- Expression tree
- Extended Backus–Naur form
- Lisp, a family of languages written in trees, with macros to manipulate code trees
- Parse tree, also known as concrete syntax tree
- Semantic resolution tree (SRT)
- Shunting-yard algorithm
- Symbol table
- TreeDL
- Abstract Syntax Tree Interpreters
References
Further reading
- Script error: No such module "citation/CS1". (overview of AST implementation in various language families)
- Script error: No such module "citation/CS1".
- Template:Cite thesis
- Script error: No such module "citation/CS1".
- Robert Harper (2016). Practical Foundations for Programming Languages (Second Edition). Cambridge University Press.
External links
- AST View: an Eclipse plugin to visualize a Java abstract syntax tree
- Script error: No such module "citation/CS1".
- Script error: No such module "citation/CS1".
- eli project: Abstract Syntax Tree Unparsing
- Script error: No such module "citation/CS1". (OMG standard).
- JavaParser: The JavaParser library provides you with an Abstract Syntax Tree of your Java code. The AST structure then allows you to work with your Java code in an easy programmatic way.
- Spoon: A library to analyze, transform, rewrite, and transpile Java source code. It parses source files to build a well-designed AST with powerful analysis and transformation API.
- AST Explorer: A website to help visualize ASTs in several popular languages such as Go, Python, Java, and JavaScript.