{"id":4005,"date":"2024-02-27T19:52:07","date_gmt":"2024-02-27T18:52:07","guid":{"rendered":"https:\/\/oopm.org\/?page_id=4005"},"modified":"2024-12-13T13:45:44","modified_gmt":"2024-12-13T12:45:44","slug":"10-1-3-an-abstract-syntax-tree","status":"publish","type":"page","link":"https:\/\/oopm.org\/?page_id=4005","title":{"rendered":"10.1.3 An abstract syntax tree"},"content":{"rendered":"<div class=\"pdfprnt-buttons pdfprnt-buttons-page pdfprnt-top-right\"><a href=\"https:\/\/oopm.org\/index.php?rest_route=wpv2pages4005&print=pdf\" class=\"pdfprnt-button pdfprnt-button-pdf\" target=\"_blank\"><img decoding=\"async\" src=\"https:\/\/oopm.org\/wp-content\/plugins\/pdf-print\/images\/pdf.png\" alt=\"image_pdf\" title=\"View PDF\" \/><\/a><a href=\"https:\/\/oopm.org\/index.php?rest_route=wpv2pages4005&print=print\" class=\"pdfprnt-button pdfprnt-button-print\" target=\"_blank\"><img decoding=\"async\" src=\"https:\/\/oopm.org\/wp-content\/plugins\/pdf-print\/images\/print.png\" alt=\"image_print\" title=\"Print Content\" \/><\/a><\/div>\n<p class=\"wp-block-paragraph\">In this section, we will show how to represent an expression by means of an abstract syntax tree. An <em>abstract syntax tree<\/em> (<em>AST<\/em>) or just <em>syntax tree<\/em> is a data structure that may represent the structure of a text described by a grammar. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The &#8220;<em>tree<\/em>&#8221; in AST refers to the fact that an AST is an example of a common data structure called a tree. A tree represents a hierarchical structure with a set of connected <em>nodes<\/em>. A node may have zero or more  <em>children<\/em> which are also nodes. A child has exactly one <em>parent<\/em>. Nodes that have no children are called <em>leaf nodes<\/em>. The top node in a tree is called the <em>root<\/em> and have no parent. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <em>binary tree <\/em>is a common used data structure where each parent has at most two children and the two nodes are often ordered in a <em>left<\/em> node and a <em>right<\/em> node.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For our expression grammar we will use a binary tree and the tree in the figure below shows a representation of the expression <code>\"10 + 11 * (1 + 9)\"<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img fetchpriority=\"high\" decoding=\"async\" width=\"623\" height=\"528\" src=\"https:\/\/oopm.org\/wp-content\/uploads\/2024\/03\/AST-A-2.jpg\" alt=\"\" class=\"wp-image-4514\" style=\"width:307px;height:auto\" srcset=\"https:\/\/oopm.org\/wp-content\/uploads\/2024\/03\/AST-A-2.jpg 623w, https:\/\/oopm.org\/wp-content\/uploads\/2024\/03\/AST-A-2-300x254.jpg 300w\" sizes=\"(max-width: 623px) 100vw, 623px\" \/><figcaption class=\"wp-element-caption\">An AST for \u201c10 + 11 * (1 + 9)\u201d<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In the following, we introduce classes to represent a binary AST for our expression grammar as shown in the figure. We start by introducing a general class being the superclass of all nodes of an AST:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>class<\/strong> Node(label: <strong>var<\/strong> char, left: <strong>ref<\/strong> Node, right: <strong>ref<\/strong> Node): \n   eval -&gt; v: var integer:&lt;\n      inner(eval)\n   print(ind: var integer):\n         ...<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Class <code>Node<\/code> has three parameters, the <code>label<\/code> of the node, and <code>left<\/code> and <code>right<\/code> representing the two children of the <code>Node<\/code>. In addition, a <code>Node<\/code> has an <code>eval<\/code>-method and a <code>print<\/code>-method. We return to these later in this section.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For each nonterminal except <code>&lt;Primary&gt;<\/code>, we have a subclass of <code>Node<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>class<\/strong> ExpNode: Node\n   eval::\n      v := left.eval + right.eval\n<strong>class<\/strong> TermNode: Node\n   eval::\n      v := left.eval * right.eval\n<strong>class<\/strong> NumberNode: Node\n   eval::\n      if (right == none) :then\n         v := left.eval\n      :else\n         v := (left.eval * 10) + right.eval\n<strong>class<\/strong> DigitNode: Node\n   eval::\n       v := label - '0'<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The next figure shows how the above tree representing <code>\"10 + 11 * (1 + 9)\"<\/code> may be represented as objects of these classes:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1024\" height=\"716\" src=\"https:\/\/oopm.org\/wp-content\/uploads\/2024\/10\/AST-b-1-1024x716.jpg\" alt=\"\" class=\"wp-image-8545\" srcset=\"https:\/\/oopm.org\/wp-content\/uploads\/2024\/10\/AST-b-1-1024x716.jpg 1024w, https:\/\/oopm.org\/wp-content\/uploads\/2024\/10\/AST-b-1-300x210.jpg 300w, https:\/\/oopm.org\/wp-content\/uploads\/2024\/10\/AST-b-1-768x537.jpg 768w, https:\/\/oopm.org\/wp-content\/uploads\/2024\/10\/AST-b-1.jpg 1217w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">AST-b\/An object diagram for \u201c10 + 11 * (1 + 9)\u201d<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>eval<\/code>-method performs a recursive traversal of the tree and evaluates the expression represented by the tree. If <code>root<\/code> is a reference to the root of the tree, <code>root.eval<\/code> will return the value 120.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Building the AST<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We now extend the parser to build the AST during parsing. Each method will then return the AST for the string being parsed by the method. Consider <code>exp<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>exp -&gt; N: <strong>ref<\/strong> Node:\n   N := term\n   addOp: do\n      if (ch = '+') :then\n         rN: <strong>ref<\/strong> Node\n         nextChar\n         rN := term\n         N := expNode('+',N,rN)\t\n         restart(addOp)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As can be seen the return value of <code>exp<\/code> is a <code>Node<\/code> represented by the reference variable <code>N<\/code>. The method <code>term<\/code> is assumed to return the AST representing the string parsed by <code>term<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If no <code>'+'<\/code> character is following the first call of <code>term<\/code> (<code>ch = '+'<\/code>) then <code>exp<\/code> just returns the <code>Node<\/code> returned by term. If a <code>'+'<\/code> character is met, <code>term<\/code> invoked again, and <code>exp<\/code> returns an <code>ExpNode<\/code> with the first argument being a <code>'+'<\/code>, and the second and third argument being the nodes returned by the first an second call of <code>term<\/code>. This is repeated as long as <code>ch = '+'.<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The revised methods <code>term<\/code> and <code>primary<\/code> may look as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>term -&gt;  N: <strong>ref<\/strong> node:\n   N := primary\n   multOp: do\n      if (ch = '*') :then\n         rN: <strong>ref<\/strong> Node\n         nextChar\n         rN := primary\t \n         N := termNode('*',N,rN)\n         restart(multOP)\nprimary -&gt; N: <strong>ref<\/strong> Node:\n   if (ch = '(') :then\n      nextChar        \n      N := exp\n      if (ch = ')') :then\n         nextChar\n      :else\n         syntaxError(1)\n   :else\n      N := number<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As can be seen, the structure of <code>term<\/code> similar to <code>exp<\/code> whereas <code>primary<\/code> just returns the <code>Node<\/code> returned by <code>exp<\/code> or <code>number<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next we show the revised versions of <code>number<\/code> and <code>digit<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>number -&gt; N: <strong>ref<\/strong> node:\n   N := digit\n   moreDigits: do\n      if (ascii.isDigit(ch)) :then\n         rN: ref Node\n         rN := digit\n         N := NumberNode('N',N,rN)\t    \n         restart(moreDigits)\n      :else\n         N := NumberNode('N',N,none)\ndigit -&gt; N: <strong>ref<\/strong> Node:\n   if (ascii.isDigit(ch)) :then\n      N:= digitNode(ch,none,none)\n      nextChar\n   :else\n       syntaxError(2)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These should be straightforward to understand. Note, however, that both may return a <code>Node<\/code> where the left and\/or right child is <code>none<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally we may show the new version of the <code>parse<\/code> method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>parse:\n   N: ref Node\n   inn :=  \"10 + 11 * (1 + 9)\"\n   console.print((\"\\nParse: \" + inn + \"\\n\")\n   nextChar\n   N := exp      \n   if (ch &lt;&gt; ascii.null) :then\n      syntaxError(3)\n   if (not hasSyntaxErrors) :then\n      console.print(\"\\nResulting AST:\\n\")\t  \n      console.print(N.print(0))\n      console.print(\"Evaluation of exp is: N.eval))<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If no syntax errors have happened during the <code>exp<\/code>-call, the resulting AST is printed and the result of evaluating it is also printed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We have not shown details of a <code>print<\/code>-method and leave this to the reader. The parameter of <code>print<\/code> is supposed to be the level of a given <code>Node<\/code> in an AST where the <code>root<\/code> is at level 0 and the children of the root at level 1, etc. This should make it easier to print an indented text version of the AST.<\/p>\n<div style=\"display:flex; gap:10px;justify-content:center\" class=\"wps-pgfw-pdf-generate-icon__wrapper-frontend\">\n\t\t<a  href=\"https:\/\/oopm.org?action=genpdf&amp;id=4005\" class=\"pgfw-single-pdf-download-button\" ><img src=\"https:\/\/oopm.org\/wp-content\/plugins\/pdf-generator-for-wp\/admin\/src\/images\/PDF_Tray.svg\" title=\"Generate PDF\" style=\"width:auto; height:45px;\"><\/a>\n\t\t<\/div>","protected":false},"excerpt":{"rendered":"<p>In this section, we will show how to represent an expression by means of an abstract syntax tree. An abstract syntax tree (AST) or just syntax tree is a data structure that may represent the structure of a text described by a grammar. The &#8220;tree&#8221; in AST refers to the fact that an AST is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1282,"menu_order":3,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-4005","page","type-page","status-publish","hentry"],"mb":[],"mfb_rest_fields":["title","gutenberg_elementor_mode"],"_links":{"self":[{"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/pages\/4005","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/oopm.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4005"}],"version-history":[{"count":43,"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/pages\/4005\/revisions"}],"predecessor-version":[{"id":10344,"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/pages\/4005\/revisions\/10344"}],"up":[{"embeddable":true,"href":"https:\/\/oopm.org\/index.php?rest_route=\/wp\/v2\/pages\/1282"}],"wp:attachment":[{"href":"https:\/\/oopm.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4005"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}