<?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>expression &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<atom:link href="https://blog.sephiroth.it/tag/expression/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.sephiroth.it</link>
	<description>programmer by pure chance</description>
	<lastBuildDate>Mon, 21 Jun 2010 09:39:58 +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>expression &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<link>https://blog.sephiroth.it</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Expressions evaluation at (almost) native speed</title>
		<link>https://blog.sephiroth.it/2008/07/01/expressions-evaluation-at-almost-native-speed/</link>
					<comments>https://blog.sephiroth.it/2008/07/01/expressions-evaluation-at-almost-native-speed/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Wed, 02 Jul 2008 00:00:00 +0000</pubDate>
				<category><![CDATA[actionscript]]></category>
		<category><![CDATA[scripting languages]]></category>
		<category><![CDATA[applicationDomain]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[compiler]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[haxe]]></category>
		<category><![CDATA[HxASM]]></category>
		<category><![CDATA[swfcompiler]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=257</guid>

					<description><![CDATA[Finally I found a bit of time this weekend to do some other tests with expressions evaluation. The results are pretty interesting, even if obvious from some point of view. I took the ExpressionEvaluator I wrote as example for the first post about this topic, and then I edited a bit the code adding just &#8230; <a href="https://blog.sephiroth.it/2008/07/01/expressions-evaluation-at-almost-native-speed/" class="more-link">Continue reading <span class="screen-reader-text">Expressions evaluation at (almost) native speed</span></a>]]></description>
										<content:encoded><![CDATA[<p>Finally I found a bit of time this weekend to do some other tests with <strong>expressions evaluation</strong>.</p>
<p>The results are pretty interesting, even if obvious from some point of view. I took the ExpressionEvaluator I wrote as example for the <a title="Runtime expression evaluation in ActionScript" href="https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/">first post</a> about this topic, and then I edited a bit the code adding just in time <strong>AS Bytecode compilation</strong>.<br />
Thanks to that, expressions evaluation is much more fast and always safe because it runs in its own <em>ApplicationDomain</em>.</p>
<p>You can <a href="https://blog.sephiroth.it/wp-content/uploads/2008/07/ExpressionEvaluator_compiler.zip">download the sources here</a>, that includes the edited code and a test file. <strong>The test file runs 1 milion of iterations and may hang your browser or at worst case your system. Reduce the value of the ITERATIONS constant if you are not sure about the power of you machine</strong>.</p>
<p>If you want to read a bit more details about that, click on the link below to continue reading.</p>
<p><span id="more-257"></span></p>
<p>I did some simple modification to the existing classes:</p>
<ul>
<li>Added a <em>compile</em> method to the IExpression interface;</li>
<li>Added the <em>symbolNames</em> getter to the SymbolTable class, to retrieve a list of all the symbols defined inside the symbol table.</li>
<li>Converted hxasm to Actionscript (finxing some small issues to avoid to include all the Haxe support classes);</li>
<li>Implemented the <em>compile</em> method on all the AST nodes using HxASM;</li>
<li>Added an <em>SWFCompile</em> class that takes an IExpression and a SymbolTable and produces an SWF;</li>
<li>Edited the <em>CompiledExpression</em> class adding a <em>compile</em> method that generates an SWF starting from an <em>IExpression</em>.</li>
</ul>
<p>Adding just in time compilation was easy a really quick thanks to <a href="http://haxe.org/com/libs/hxasm">HxASM</a>. <strong>HxASM</strong> is an <a href="http://haxe.org">Haxe</a> library written by Haxe&#8217;s author (<strong>Nicolas Cannasse</strong>) that makes you able to write low level bytecode instructions in ActionScript an generate a <em>ByteArray</em> that contains an (hopefully) valid SWF. The SWF can then be loaded by <em>Loader.loadBytes</em> and executed.</p>
<p>It have been easy to port HxASM to ActionScript too, thanks again to the <strong>Haxe compiler which is able to generate AS3 code starting from Haxe code</strong>.</p>
<p>Compilation was achieved easilly because the expressions we are compiling are really simple. The compiler generates a class called <em>CompiledExpression</em> that has a method <em>execute</em> that can be called to execute the expression. All the values inside the symbol table are exposed as public properties.</p>
<p>Just to make you understand better, givin this expression:</p>
<p><code>sin( x * 10 + y - 11 )</code></p>
<p>SWFCompiler will generate the bytecode for this class:<br />
<code lang="actionscript">class CompiledExpression<br />
{<br />
public var sin: *;<br />
public var x: *;<br />
public var y: *;<br />
public function execute(): Number<br />
{<br />
return sin( x * 10 + y - 11 );<br />
}<br />
}</code><br />
As you can see the type of the class variables is generic, but you can improve the generator to understand if a variable should contain a number or a function.</p>
<p>The generated SWF can be loaded and run easilly:<br />
<code lang="actionscript">var loader: Loader = new Loader();<br />
var parser: Parser = new Parser(<br />
new Scanner( "sin( x / ( 4 / 2 * 2 - 2 + 2 * x / x ) ) * 100" ) );<br />
var compiled: CompiledExpression = parser.parse();<br />
var data: ByteArray = compiled.compile();<br />
loader.contentLoaderInfo.addEventListener( Event.COMPLETE,<br />
function( event: Event ): void<br />
{<br />
var info: LoaderInfo = ( event.target as LoaderInfo );<br />
var klass: Class = (<br />
info.applicationDomain.getDefinition( "CompiledExpression" ) as Class );<br />
var cp: Object = new klass();<br />
cp.x = 10;<br />
cp.sin = Math.sin;<br />
trace( "Result", cp.execute() );<br />
} );<br />
loader.loadBytes( data, new LoaderContext( false,<br />
new ApplicationDomain( ApplicationDomain.currentDomain ) ) );<br />
</code><br />
I build a simple test (shipped with the sources) that runs 1 milion times an expression using 3 methods: Evaluation, Compiled and Native.</p>
<p>Results (on my Mac Pro 8 Core, 4GB ram) are obvious:</p>
<pre>eval 1000000 iterations: 12939
<strong>compiled 1000000 iterations: 848</strong>
native 1000000 iterations: 371</pre>
<p>As you can see native execution is faster, but compiled version runs really well (you might want to optimize the generated code to make it run faster) and it is many times faster then AST evaluation.</p>
<p>If you want to run a complex expression many times and dont want to stress your Flash Plugin, you can use the compiled version.</p>
<p>Gotta run, see u next time!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2008/07/01/expressions-evaluation-at-almost-native-speed/feed/</wfw:commentRss>
			<slash:comments>8</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>
