<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>abstract syntax tree &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<atom:link href="https://blog.sephiroth.it/tag/abstract-syntax-tree/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.sephiroth.it</link>
	<description>programmer by pure chance</description>
	<lastBuildDate>Sun, 20 Jun 2010 16:18:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.sephiroth.it/wp-content/uploads/2019/03/cropped-sepy-big-32x32.png</url>
	<title>abstract syntax tree &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<link>https://blog.sephiroth.it</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Top Down or Bottom Up for Expression Evaluation ?</title>
		<link>https://blog.sephiroth.it/2008/05/03/top-down-or-bottom-up-for-expression-evaluation/</link>
					<comments>https://blog.sephiroth.it/2008/05/03/top-down-or-bottom-up-for-expression-evaluation/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Sun, 04 May 2008 01:00:35 +0000</pubDate>
				<category><![CDATA[actionscript]]></category>
		<category><![CDATA[scripting languages]]></category>
		<category><![CDATA[abstract syntax tree]]></category>
		<category><![CDATA[ast]]></category>
		<category><![CDATA[byacc]]></category>
		<category><![CDATA[gnu flex]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[yacc]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=252</guid>

					<description><![CDATA[Last time I wrote about Top Down parsing, a technique for parsing that can be easilly implemented manually using function recursion. Today it is time to talk about one of the other ways of parsing, called Bottom Up parsing. This technique try to find the most important units first and then, based on a language &#8230; <a href="https://blog.sephiroth.it/2008/05/03/top-down-or-bottom-up-for-expression-evaluation/" class="more-link">Continue reading <span class="screen-reader-text">Top Down or Bottom Up for Expression Evaluation ?</span></a>]]></description>
										<content:encoded><![CDATA[<p><a title="Runtime expression evaluation in ActionScript" href="https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/">Last time</a> I wrote about <a href="http://en.wikipedia.org/wiki/Top-down_parsing">Top Down</a> parsing, a technique for parsing that can be easilly implemented manually using function recursion.</p>
<p>Today it is time to talk about one of the other ways of parsing, called <a href="http://en.wikipedia.org/wiki/Bottom-up_parsing">Bottom Up</a> parsing. This technique try to find the most important units first and then, based on a language grammar and a set of rules, try to infer higher order structures starting from them. Bottom Up parsers are the common output of <a href="http://en.wikipedia.org/wiki/Parser_generator">Parser Generators</a> (you can find a good comparison of parser generators <a href="http://en.wikipedia.org/wiki/Comparison_of_parser_generators">here</a>) as they are easier to generate automatically then recursive parser because they can be implemented using sets of tables and simple state based machines.</p>
<p>Writing down manually a bottom up parser is quite a tedious task and require quite a lot of time; moreover, this kind of parsers are difficult to maintain and are usually not really expandable or portable. This is why for my tests I decided to port <a href="http://invisible-island.net/byacc/byacc.html">bYacc</a> (a parser generator that usually generates C code) and edit it so it generates ActionScript code starting from Yacc-compatible input grammars. Having this kind of tool makes things a lot easier, because maintaining a grammar (that usually is composed by a few lines) is less time expensive than working with the generated code (that usually is many lines long).<br />
I will not release today the port because actually I had not time to make sure it is bugfree and I&#8217;ve only a working version for Mac, but I plan to release it shortly if you will ever need it for your own tasks. My goal for today was to compare the speed of the parser I wrote with an automatically generated bottom up parser, to see which is the faster approach.</p>
<p>I created a bottom up parser which is able to execute the same expressions accepted by the expression evaluator I wrote last time. There are anyways some differences that &#8211; as you will probably and hopefully understand in the future &#8211; that make those parsers really different. Some will be disussed shortly here.</p>
<p>To do that I created a Yacc grammar and some support classes.<br />
The parser grammar is really simple and really readable:<br />
<code>%{<br />
%}<br />
%token NUMBER SYMBOL<br />
%left '+' '-'<br />
%left '*' '/'<br />
%left NEG<br />
%%<br />
program<br />
: expr                { Vars.result = $1; }<br />
;<br />
expr<br />
: expr '+' expr       { $$ = $1 + $3; }<br />
| expr '-' expr       { $$ = $1 - $3; }<br />
| expr '*' expr       { $$ = $1 * $3; }<br />
| expr '/' expr       { $$ = $1 / $3; }<br />
| '-' expr %prec NEG  { $$ = -$2; }<br />
| '(' expr ')'        { $$ = $2; }<br />
| SYMBOL '(' expr ')' {<br />
if( Vars.SYMBOL_TABLE[ $1 ] )<br />
{<br />
$$ = Vars.SYMBOL_TABLE[ $1 ]( $3 );<br />
} else<br />
{<br />
trace( "can't find function" );<br />
}<br />
}<br />
| SYMBOL              {<br />
if( Vars.SYMBOL_TABLE[ $1 ] )<br />
{<br />
$$ = Vars.SYMBOL_TABLE[ $1 ];<br />
} else<br />
{<br />
trace( "can't find symbol" );<br />
}<br />
}<br />
| NUMBER              { $$ = yyval; }<br />
;<br />
%%</code><br />
<strong>Continue reading the extended entry to see the results.<span id="more-252"></span></strong></p>
<p>It defined a simple expression grammar which includes addition, subtraction, multiplication, negation, division, variables, function calls and sub expressions. The tokens accepted are numbers (integers or simple floating point numbers), symbols and all the punctuation and operands needed.</p>
<p>The grammar uses a simple support class (called <em>Vars</em>) which is used to store a global symbol table and the result of the evaluation.<br />
As you might have noted there is a really big difference about how the expression will be evaluated here and how do I evaluate it in my original expression parser: the expression is executed as soon as a rule is matched, and it is not compiled into an intermediate <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">abstract syntax tree</a>.<br />
Usually those kind of tools are used in conjunction with a lexer generator (<a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser">Flex</a> is a good example of lexer generator &#8211; don&#8217;t confuse it with Adobe Flex!! :D), that is able to automatically generate the code for a scanner based in a set of rules usually defined by regular expressions. I didn&#8217;t ported this kind of tool because I was already having a working scanner for my needs that is a porting of the scanner used in the expression evaluator library:</p>
<p><code lang="actionscript"><br />
package it.sephiroth.expr2<br />
{<br />
	public class Lexer<br />
	{<br />
		private var _pos: int;<br />
		private var _pool: Array;<br />
		private var _source: String;<br />
		public function Lexer( source: String )<br />
		{<br />
			_pos = 0;<br />
			_source = source;<br />
			_pool = new Array();<br />
		}<br />
		public function scan(): Object<br />
		{<br />
			if( _pool.length > 0 )<br />
			{<br />
				return _pool.shift();<br />
			}<br />
			skipWhites();<br />
			if( isEOF() )<br />
			{<br />
				return null;<br />
			}<br />
			var c: String = _source.charAt( _pos++ );<br />
			switch( c )<br />
			{<br />
				case '+':<br />
				case '-':<br />
				case '*':<br />
				case '/':<br />
				case '(':<br />
				case ')':<br />
				case ',':  return  { type: c.charCodeAt( 0 ), val: c };<br />
				default:<br />
					var buf: String = "";<br />
					var code: int = c.charCodeAt( 0 );<br />
					if( isNumber( code ) )<br />
					{<br />
						var num: Number;<br />
						while( isNumber( code ) )<br />
						{<br />
							buf += c;<br />
							if( isEOF() )<br />
							{<br />
								++_pos;<br />
								break;<br />
							}<br />
							c  = _source.charAt( _pos++ );<br />
							code = c.charCodeAt( 0 );<br />
						}<br />
						if( c == '.' )<br />
						{<br />
							buf += c;<br />
							c  = _source.charAt( _pos++ );<br />
							code = c.charCodeAt( 0 );<br />
							while( isNumber( code ) )<br />
							{<br />
								buf += c;<br />
								if( isEOF() )<br />
								{<br />
									++_pos;<br />
									break;<br />
								}<br />
								c  = _source.charAt( _pos++ );<br />
								code = c.charCodeAt( 0 );<br />
							}<br />
							num = parseFloat( buf );<br />
						}else<br />
						{<br />
							num = parseInt( buf );<br />
						}<br />
						--_pos;<br />
						return  { type: Token.NUMBER, val: num };<br />
					}<br />
					if( isAlpha( code ) || ( c == '_' ) )<br />
					{<br />
						while( isAlpha( code ) || ( c == '_' ) || isNumber( code ) )<br />
						{<br />
							buf += c;<br />
							if( isEOF() )<br />
							{<br />
								++_pos;<br />
								break;<br />
							}<br />
							c  = _source.charAt( _pos++ );<br />
							code = c.charCodeAt( 0 );<br />
						}<br />
						--_pos;<br />
						return  { type: Token.SYMBOL, val: buf };<br />
					}<br />
					break;<br />
			}<br />
			return null;<br />
		}<br />
		public function pushBack( token: Token ): void<br />
		{<br />
			_pool.push( token );<br />
		}<br />
		protected function isNumber( c: int ): Boolean<br />
		{<br />
			return ( c >= 48 ) && ( c < = 57 );
		}
		protected function isAlpha( c: int ): Boolean
		{
			return ( ( c >= 97 ) && ( c < = 122 ) ) || ( ( c >= 65 ) && ( c < = 90 ) );
		}
		protected function isEOF(): Boolean
		{
			return ( _pos >= _source.length );<br />
		}<br />
		protected function skipWhites(): void<br />
		{<br />
			while( !isEOF() )<br />
			{<br />
				var c: String = _source.charAt( _pos++ );<br />
				if( ( c != " " ) && ( c != "\t" ) )<br />
				{<br />
					--_pos;<br />
					break;<br />
				}<br />
			}<br />
		}<br />
	}<br />
}<br />
</code></p>
<p>After compiling the grammar with my parser generator and having written some support code we can use to do our tests, I finally had my small comparison test suite.  A quick note about the parser: It should be used only for testing and if you want to have a fast and safe expressions evaluator I suggest you to build your own or &#8211; if you can wait &#8211; wait a bit more 😉  The test can be easilly run from the command line without the need fo having Flex Builder (but you need the Flex SDK that you can freely download from the <a href="http://opensource.adobe.com/wiki/display/flexsdk/">Adobe Open Source Website</a>); I choose a quite long expression to make the execution and parsing time a bit high.  Here is the test I ran:</p>
<p><code><br />
package {<br />
	import flash.display.Sprite;<br />
	import flash.utils.getTimer;<br />
	import it.sephiroth.expr.CompiledExpression;<br />
	import it.sephiroth.expr.Parser;<br />
	import it.sephiroth.expr.Scanner;<br />
	import it.sephiroth.expr2.Vars;<br />
	public class TestExprEval extends Sprite<br />
	{<br />
		public static const ITERATIONS: int = 10000;<br />
		public static const EXPRESSION: String = "sin( x / ( 4 / 2.0 * 2 + (- 2.12345 + 2.12345) * x / x ) ) * 100 - ( sin( x / ( 4 / 2.0 * 2 + (- 2.12345 + 2.12345) * x / x ) ) * 100 )";<br />
		public function TestExprEval()<br />
		{<br />
			runTests();<br />
		}<br />
		private function runTests(): void<br />
		{<br />
			trace( "Running tests (this may take a while)" );<br />
			runTopDown();<br />
			runBottomUp();<br />
		}<br />
		private function runTopDown(): void<br />
		{<br />
			var sum: Number = 0;<br />
			for( var i: int = 0; i < ITERATIONS; ++i )
			{
				var t: Number = getTimer();
				var scanner: Scanner = new Scanner( EXPRESSION );
				var parser: Parser = new Parser( scanner );
				var compiled: CompiledExpression = parser.parse();
				compiled.execute( {
					'x'    : Math.random(),
					'sin'  : Math.sin,
					'cos'  : Math.cos
				} );
				sum += ( getTimer() - t );
			}
			trace( "Top Down parser:", sum / ITERATIONS );
		}
		private function runBottomUp(): void
		{
			var sum: Number = 0;
			Vars.symbolTable.sin = Math.sin;
			for( var i: int = 0; i < ITERATIONS; ++i )
			{
				Vars.symbolTable.x = Math.random();
				var t: Number = getTimer();
				var myparser: TestBottomUpParser = new TestBottomUpParser();
				myparser.yyparse()
				sum += ( getTimer() - t );
			}
			trace( "Bottom Up parser:", sum / ITERATIONS );
		}
	}
}
import it.sephiroth.expr2.BottomUpParser;
import it.sephiroth.expr2.Lexer;
class TestBottomUpParser extends BottomUpParser
{
	private var _lexer: Lexer;
	public function TestBottomUpParser()
	{
		super();
		_lexer = new Lexer( TestExprEval.EXPRESSION );
	}
	override public function yylex(): int
	{
		var value: Object = _lexer.scan();
		if( value == null )
		{
			return 0;
		}
		set_yylval( value.val );
		return value.type;
	}
}
</code></p>
<p>As you can see the test includes also the instantiation of all the objects needed. Running that from the command line, I obtained this result:<br />
</code><code>$ mxmlc -debug=true TestExprEval.as<br />
Loading configuration file /Applications/Adobe Flex Builder 3 Plug-in/sdks/3.0.0/frameworks/flex-config.xml<br />
/Users/gabriele/Desktop/TestExprParsers/src/TestExprEval.swf (11647 bytes)<br />
$ fdb TestExprEval.swf<br />
Adobe fdb (Flash Player Debugger) [build 3.0.0.477]<br />
Copyright (c) 2004-2007 Adobe, Inc. All rights reserved.<br />
Attempting to launch and connect to Player using URL<br />
TestExprEval.swf<br />
Player connected; session starting.<br />
Set breakpoints and then type 'continue' to resume the session.<br />
[SWF] Users:gabriele:Desktop:TestExprParsers:src:TestExprEval.swf - 25.942 bytes after decompression<br />
(fdb) continue<br />
[trace] Running tests (this may take a while)<br />
[trace] Top Down parser: 0.6979<br />
[trace] Bottom Up parser: 0.9063<br />
(fdb) quit</code><br />
This is not totally unexpected for such a simple grammar, but the execution time is much more better (around 20%) using a manually written top down parser than using an autogenerated bottom up parser; I say it is not totally unexpected because the performances should change as the grammar becames more complex, but in our situation this is what we get. And we can also achive a better result if we precompile the expression into an AST and the execute it. Add this code to your test and add the function call inside the <em>runTests</em> method:<br />
<code><br />
private function runTopDownCompiled(): void<br />
{<br />
	var sum: Number = 0;<br />
	var scanner: Scanner = new Scanner( EXPRESSION );<br />
	var parser: Parser = new Parser( scanner );<br />
	var compiled: CompiledExpression = parser.parse();<br />
	for( var i: int = 0; i < ITERATIONS; ++i )
	{
		var t: Number = getTimer();
		compiled.execute( {
			'x':     Math.random(),
			'sin'  : Math.sin,
			'cos'  : Math.cos
		} );
		sum += ( getTimer() - t );
	}
	trace( "Top Down parser (precompiled):", sum / ITERATIONS );
}
</code><br />
And then run again to see the result:<br />
</code><code>$ mxmlc -debug=true TestExprEval.as<br />
Loading configuration file /Applications/Adobe Flex Builder 3 Plug-in/sdks/3.0.0/frameworks/flex-config.xml<br />
/Users/gabriele/Desktop/TestExprParsers/src/TestExprEval.swf (11794 bytes)<br />
$ fdb TestExprEval.swf<br />
Adobe fdb (Flash Player Debugger) [build 3.0.0.477]<br />
Copyright (c) 2004-2007 Adobe, Inc. All rights reserved.<br />
Attempting to launch and connect to Player using URL<br />
TestExprEval.swf<br />
Player connected; session starting.<br />
Set breakpoints and then type 'continue' to resume the session.<br />
[SWF] Users:gabriele:Desktop:TestExprParsers:src:TestExprEval.swf - 26.272 bytes after decompression<br />
(fdb) continue<br />
[trace] Running tests (this may take a while)<br />
[trace] Top Down parser: 0.698<br />
[trace] Bottom Up parser: 0.9001<br />
[trace] Top Down parser (precompiled): 0.0315</code><br />
This is really a good thing: as we can see, the most of the time is taken by the parser and the scanner, and if we remove their execution from the loop and just evaluate the generated AST, we get a great speed improvment. As far as I know this is quite good if you have a set of expressions that does not vary and do you want to execute them many times.</p>
<p>And this is why quite all the languages precompile their source code into bytecode before execution.</p>
<p>Unfortunately it is time to go now, but I&#8217;ve really a lot of stuff to show you next week (the parser generator, a way to &#8211; try to &#8211; write an expression evaluator that evaluate expressions at near-native speed &#8230;) so stay tuned as usual!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2008/05/03/top-down-or-bottom-up-for-expression-evaluation/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Runtime expression evaluation in ActionScript</title>
		<link>https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/</link>
					<comments>https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Sat, 19 Apr 2008 15:00:00 +0000</pubDate>
				<category><![CDATA[actionscript]]></category>
		<category><![CDATA[scripting languages]]></category>
		<category><![CDATA[abstract syntax tree]]></category>
		<category><![CDATA[ast]]></category>
		<category><![CDATA[evaluation]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[lexer]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[postfix]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=250</guid>

					<description><![CDATA[Finally I have a bit of free time to write down this post. Some days ago a guy on the forum asked about how to evaluate at runtime simple mathematical expressions with support for symbols and function calls. Now that the eval function have been removed from the language for reasons I&#8217;ve not enought time &#8230; <a href="https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/" class="more-link">Continue reading <span class="screen-reader-text">Runtime expression evaluation in ActionScript</span></a>]]></description>
										<content:encoded><![CDATA[<p>Finally I have a bit of free time to write down this post.<br />
Some days ago a guy on the <a href="http://sephiroth.it/phpBB/">forum</a> asked about how to <strong>evaluate at runtime simple mathematical expressions</strong> with support for symbols and function calls.</p>
<p>Now that the <em>eval</em> function have been removed from the language for reasons I&#8217;ve not enought time to talk about, we need to parse and execute those expressions manually.</p>
<p>I built a simple Actionscript library that can be used to parse mathematical expressions: it has support for function calls, for variables and it is able to convert the expression into a postfix rappresentation if you may need it. The expression parser is quite simple and have been built manually following some concepts related to programming language compilers; it includes a <a href="http://en.wikipedia.org/wiki/Lexical_analysis">Scanner</a> (or lexer &#8211; however you want to call it) to tokenize the expression, a <a href="http://en.wikipedia.org/wiki/Parser">Parser</a> that convert the expression into an <a href="http://en.wikipedia.org/wiki/Abstract_Syntax_Tree">Abstract Syntax Tree</a> and a simple routine that evaluates that AST using a <a href="http://en.wikipedia.org/wiki/Symbol_table">Symbol Table</a> as evaluation context.</p>
<p>There are no comments inside the code right now; I hope to find a little bit of time to write an in depth discussion about this topic. In the mean time you can continue reading the entry for a general explanation about how does the code works and for some examples that may be useful.</p>
<p>Here is a simple example that shows how does the code works:<br />
<code lang="actionscript"><br />
import it.sephiroth.expr.CompiledExpression;<br />
import it.sephiroth.expr.Parser;<br />
import it.sephiroth.expr.Scanner;<br />
public class Example<br />
{<br />
public static function run(): void<br />
{<br />
var expression: String = "sin( x / ( 8 / 2 + (-0.12 + 2.3) * x / x ) ) * 100";<br />
var scanner: Scanner = new Scanner( expression );<br />
var parser: Parser = new Parser( scanner );<br />
var compiled: CompiledExpression = parser.parse();<br />
var context: Object = {<br />
x:    100,<br />
sin:   Math.sin,<br />
cos:  Math.cos<br />
};<br />
trace( 'Postfix:', compiled.toString() );<br />
trace( 'Result:', compiled.execute( context ) );<br />
}<br />
}<br />
</code><br />
Before I forgot, you can download the source code here with a simple example included.</p>
<p><span id="more-250"></span></p>
<p>Building an expression parser and evaluator is quite a simple task if you don&#8217;t plan to write a superfast library or a superpowerful engine. The steps are something like <em>predefined</em> and can be subdivided into tree groups:</p>
<ul>
<li><strong>Lexical analysis</strong></li>
<li><strong>Parsing</strong></li>
<li><strong>Evaluation</strong></li>
</ul>
<p>My code simply follow those steps to make you able to evaluate an expression. Before starting with the code anyways it is really important to define a set of rules and functionalities our expression evaluator will include. This is foundamental because based on the features the operations performed during the tree steps above may vary.</p>
<p>In my code I simply want to accept integer and float numbers (float numbers defined using the simple <em>dot syntax</em>), negative numbers, variables, function calls, basic operations (subtract, add, multiply, divide and negate) and parethesis for grouping.</p>
<h3>Lexical Analysis</h3>
<p>During Lexical analysis the <strong>input string is analyzed</strong> to provide the parser a set of chunks, called <strong>tokens</strong>, that can be <strong>interpreted easilly by our code</strong>. The main goal of the lexical analysis is just to group togheter some characters and give them a meaning (for instance: 1 is a number, / the divide operation and so on), discarding the unuseful ones (like spaces). At this stage there is <strong>no validation of the input</strong>, because the lexical analyzer (<em>Scanner.as</em>) doesn&#8217;t know anything about how does the input will be interpreted.<br />
The lexical analyzer generates a stream of tokens (<em>Token.as</em>) of different type (<em>TokenType.as</em>) which are then feeded to the Parser.</p>
<h3>Parsing</h3>
<p>The Parsing phase is one of the most important and is when the program starts to take a streams of token and give a meaning to a set of them. During this step the Parser (<em>Parser.as</em>) <strong>reads from the Scanner the tokens</strong> as needed and, given a defined Grammar, is able to group them togheter and <strong>understand if the input is grammatically correct</strong> or not.<br />
In our sitatuation the grammar is implicit: the expression must be formatted correctly, every open parenthesis must match a closed one and function calls allows one or more arguments. When working on more complex parsers, the grammar may became much more complex (think about a whatever language parser for instance), and so the technique I used (called <a href="http://en.wikipedia.org/wiki/Recursive_descent_parser">Recursive Descent Parsing</a>) risk to become too difficult to use, too time and memory consuming. At this stage may be helpful to use <strong>parser generators</strong>, but I&#8217;ll talk about that the next time because I&#8217;ve something interestingto show you.<br />
During this phase the input is validated but also other two really important tasks are performed: the first one is that <strong>all the identifiers found inside the input are recorded inside a Symbol Table</strong> (<em>SymbolTable.as</em>), than later will be filled at runtime with valid values for the indetifiers to execute the expression correctly. The second one is that <strong>the input is translated into an intermediate form</strong> that is <strong>easier for a computer language to deal with</strong>: the Abstract Syntax Tree (<em>it.sephiroth.expr.ast.*</em> package). The <strong>AST</strong> is a tree structure where each node rappresents a portion of code that then can be analyzed easilly using a tree walker or other means. When evaluating expressions an AST is not always useful because <strong>expressions evaluation may be performed using a stack based direct execution</strong>.</p>
<h3>Evaluation</h3>
<p>When the AST is ready, we are sure that the expression is syntactically valid and can be executed providing the right <strong>context</strong>. A context is simply the variables and functions that are needed by the expression to return a value, and are assigned to the identified included inside the Symbol Table. When the expression is executing, it requests from the symbol table the values needed. In my code the evaluation is performed by each AST node itself, but we may use also a tree walker to walk each node and execute it based on its type.</p>
<p>This is a super general introduction about how does the code works, hope to have a bit of free time to go more in depth about this. Just to show you something working, here is a simple Flex examples that plots an expression. The potting is not accurate, but the example can be used to give you an idea about how does the code may be used. With the separation provided, we will be able to replace the single parts of the code with improved versions, obtaining anyway a correct result.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/feed/</wfw:commentRss>
			<slash:comments>25</slash:comments>
		
		
			</item>
	</channel>
</rss>
