<?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>lexer &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<atom:link href="https://blog.sephiroth.it/tag/lexer/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.sephiroth.it</link>
	<description>programmer by pure chance</description>
	<lastBuildDate>Mon, 21 Jun 2010 20:33:43 +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>lexer &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<link>https://blog.sephiroth.it</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>AsYacc &#8211; first alpha release</title>
		<link>https://blog.sephiroth.it/2009/01/15/asyacc-first-alpha-release/</link>
					<comments>https://blog.sephiroth.it/2009/01/15/asyacc-first-alpha-release/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Thu, 15 Jan 2009 15:35:48 +0000</pubDate>
				<category><![CDATA[actionscript]]></category>
		<category><![CDATA[asyacc]]></category>
		<category><![CDATA[compiler]]></category>
		<category><![CDATA[gnu flex]]></category>
		<category><![CDATA[lexer]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[yacc]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=271</guid>

					<description><![CDATA[Before going further with discussing how to add runtime scripting support to a Flash applications, I&#8217;d like to share with you the source code of a porting of Yacc I did a while ago. I did some simple modification to make Yacc able to generate ActionScript 3.0 source code instead of C. It works quite &#8230; <a href="https://blog.sephiroth.it/2009/01/15/asyacc-first-alpha-release/" class="more-link">Continue reading <span class="screen-reader-text">AsYacc &#8211; first alpha release</span></a>]]></description>
										<content:encoded><![CDATA[<p>Before going further with discussing how to add <a title="Runtime expression evaluation in ActionScript" href="https://blog.sephiroth.it/2008/04/19/runtime-expression-evaluation-in-actionscript/">runtime scripting support to a Flash applications</a>, I&#8217;d like to share with you the source code of a porting of <a href="http://en.wikipedia.org/wiki/Yacc">Yacc</a> I did a while ago. I did some simple modification to make Yacc able to <strong>generate ActionScript 3.0 source code</strong> instead of C. It works quite well and supports a lot standard Yacc features. There might be some issues &#8211; report them to me and I&#8217;ll try to fix them 🙂</p>
<p>You can easilly find documentation about Yacc searching Google (you can start <a href="http://dinosaur.compilertools.net/">here</a> for example).</p>
<p>Usually Yacc is used in conjunction with a <strong>Scanner generator</strong> (like <a href="http://en.wikipedia.org/wiki/Lex_programming_tool">Lex</a>/<a href="http://en.wikipedia.org/wiki/Flex_lexical_analyserx">Flex</a>), but I didn&#8217;t to any porting of commonly used Scanner generators yet.</p>
<p><a href="/wp-content/uploads/2009/01/AsYacc.zip">Here you can download the sources</a>. The <strong>source code should be portable</strong> and compilable on all the most common platform, but I didn&#8217;t tested it on Windows yet. To compile the source code on Mac or Linux, <em>cd</em> to the source code directory and type use:</p>
<pre>gcc *.c -o AsYacc</pre>
<p>Once you have the compiled binary file, you can run the Parser generator using:</p>
<pre>./AsYacc -Hpackage=it.sephiroth.test grammar.y</pre>
<p>Where <em>grammar.y</em> is a text file that contains the grammar of a language defined using the proper syntax (see the docs online for all the detailed information you may need).</p>
<p><a href="https://blog.sephiroth.it/wp-content/uploads/2009/01/TestAsYacc.zip">Here you can download a simple calculator example</a> that uses the RegexLexer <a title="Scripting Flash apps: scanning the input file" href="https://blog.sephiroth.it/2008/12/16/scripting-flash-apps-scanning-the-input-file/">described previously</a> to implement the Scanner. For the ones who might be interested, here is the grammar used:<br />
<code>/* Infix notation calculator. */<br />
%{<br />
%}<br />
%token NUM<br />
%left '-' '+'<br />
%left '*' '/'<br />
%left NEG<br />
%right '^' /* exponentiation */<br />
%%<br />
input:<br />
exp			{ trace( $1 ); }<br />
;<br />
exp:<br />
NUM 			{ $$ = $1; }<br />
| exp '+' exp 		{ $$ = $1 + $3; }<br />
| exp '-' exp 		{ $$ = $1 - $3; }<br />
| exp '*' exp 		{ $$ = $1 * $3; }<br />
| exp '/' exp 		{ $$ = $1 / $3; }<br />
| '-' exp %prec NEG 	{ $$ = -$2; }<br />
| exp '^' exp 		{ $$ = Math.pow( $1, $3 ); }<br />
| '(' exp ')' 		{ $$ = $2; }<br />
;<br />
%%</code></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2009/01/15/asyacc-first-alpha-release/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Scripting Flash apps: scanning the input file</title>
		<link>https://blog.sephiroth.it/2008/12/16/scripting-flash-apps-scanning-the-input-file/</link>
					<comments>https://blog.sephiroth.it/2008/12/16/scripting-flash-apps-scanning-the-input-file/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Tue, 16 Dec 2008 17:06:54 +0000</pubDate>
				<category><![CDATA[scripting languages]]></category>
		<category><![CDATA[aif]]></category>
		<category><![CDATA[lexer]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[scanner]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[token]]></category>
		<category><![CDATA[yacc]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=269</guid>

					<description><![CDATA[Here we go. I know that probably I should have started this new topic talking about the grammar of the language we are going to implement, but as long as I see grammar strictly related to parsing, I&#8217;ve preferred to talk about scanning first. We will go back to the grammar the next time, when &#8230; <a href="https://blog.sephiroth.it/2008/12/16/scripting-flash-apps-scanning-the-input-file/" class="more-link">Continue reading <span class="screen-reader-text">Scripting Flash apps: scanning the input file</span></a>]]></description>
										<content:encoded><![CDATA[<p>Here we go. I know that probably I should have started this new topic talking about the grammar of the language we are going to implement, but as long as I see grammar strictly related to parsing, I&#8217;ve preferred to talk about <strong>scanning</strong> first.</p>
<p>We will go back to the grammar the next time, when talking about how to parse an input file.</p>
<p>I wrote about scanning (or <strong>lexing</strong> if you prefer) a while ago, when blogging about expression evalution in ActionScript. Scanning an input file is quite always the same (although some languages might require unusual features), and what I wrote about expressions works also for a general language.</p>
<p>The goal of the scanning process is to group some characters together, skipping the ones that have no meaning for the language like spaces. Each group of characters is usually called <strong>token</strong>. So a <strong>Scanner</strong> converts a textual input into a stream of tokens, each one rappresenting a possible valid word for our language. While scanning you don&#8217;t take care about the meaning of what you are grouping or about the fact that a sequence of tokens is meaningful. This is a task for the <strong>Parser</strong> as we will see.</p>
<p>When talking about expressions, I showed a manual implementation for a Lexer. Now I want to take a different approach and show you a possible implementation for a simple dynamic scanner. This scanner will be based on <em>regular expressions</em>: each regular expression will rappresent a given token, and we will be able to assign callbacks to the scanner that will be executed each time a given token is extracted from the input.<br />
Writing a general and reusable scanner is usually a good practice. A common approach is to use some <strong>scanner generators</strong>, that are usually regular expression based too but are able to generate the code for a scanner at compile time. Our approach is different (and generates slower scanners) because regular expressions are evaluated at runtime; but it is fine for a test project.</p>
<p>You can download the source code for the regular expression based lexer (<em>RegexLexer</em>) <strong><a href="https://blog.sephiroth.it/wp-content/uploads/2008/12/scriptingflash.zip">here</a></strong>, as long as a simple usage example. Let&#8217;s see this example together so we can briefly discuss it (<em>PBLexer.as</em>):</p>
<p><span id="more-269"></span><br />
<code>package test<br />
{<br />
import it.sephiroth.scripting.utils.RegexLexer;<br />
import it.sephiroth.scripting.utils.RegexLexerContext;<br />
import it.sephiroth.scripting.utils.Token;<br />
public class PBLexer extends RegexLexer<br />
{<br />
private static const keyword_map: Object = {<br />
languageVersion:  TokensTable.LANGUAGE_VERSION,<br />
kernel:        TokensTable.KERNEL,<br />
parameter:      TokensTable.PARAMETER,<br />
input:        TokensTable.INPUT,<br />
image1:        TokensTable.IMAGE1,<br />
image2:        TokensTable.IMAGE2,<br />
image3:        TokensTable.IMAGE3,<br />
image4:        TokensTable.IMAGE4,<br />
"void":        TokensTable.VOID,<br />
output:        TokensTable.OUTPUT,<br />
evaluatePixel:    TokensTable.EVALUATE_PIXEL,<br />
"if":        TokensTable.IF,<br />
"else":        TokensTable.ELSE,<br />
"const":      TokensTable.CONST,<br />
"int":        TokensTable.INT,<br />
int2:        TokensTable.INT2,<br />
int3:        TokensTable.INT3,<br />
int4:        TokensTable.INT4,<br />
float:        TokensTable.FLOAT,<br />
float2:        TokensTable.FLOAT2,<br />
float3:        TokensTable.FLOAT3,<br />
float4:        TokensTable.FLOAT4,<br />
float2x2:      TokensTable.FLOAT2X2,<br />
float3x3:      TokensTable.FLOAT3X3,<br />
float4x4:      TokensTable.FLOAT4X4,<br />
pixel1:        TokensTable.PIXEL1,<br />
pixel2:        TokensTable.PIXEL2,<br />
pixel3:        TokensTable.PIXEL3,<br />
pixel4:        TokensTable.PIXEL4  };<br />
public function PBLexer( source_name: String, input: String )<br />
{<br />
super( source_name, input );<br />
addRule( "nl",      "\n",            -1,          RegexLexer.NL );<br />
addRule( "space",    "[ \t]+",           -1,          RegexLexer.SKIP );<br />
addRule( "comment",    "//.*",           -1,          RegexLexer.SKIP );<br />
addRule( "start_cmt",  "/\\*",           -1,          RegexLexer.START_EAT );<br />
addRule( "stop_cmt",  "\\*/",           -1,          RegexLexer.STOP_EAT );<br />
addRule( "ident",    "[a-zA-Z_][a-zA-Z_0-9]*",  TokensTable.IDENT,  onIdent );<br />
addRule( "number",    "0|([1-9][0-9]*(\\.[0-9]*)?)",  TokensTable.NUMBER, onNumber );<br />
addRule( "string",    "\"(\\\\\"|[^\"])+\"",    TokensTable.STRING, onString );<br />
addRule( "symbol",    "\\+\\+|\\-\\-|< =|>=|==|" +<br />
"!=|&amp;&amp;|\\|\\||\\*=|/=|" +<br />
"\\+=|\\-=|\\(|\\)|\\*|" +<br />
"\\+|,|\\-|\\.|/|:|;|#|" +<br />
"\\< |=|\\>|\\{|\\}|\\[|" +<br />
"\\]|\\?|!",          -1,          onSymbol );<br />
}<br />
private function onSymbol( context: RegexLexerContext ): void<br />
{<br />
var token: Token;<br />
token = new Token(<br />
context.token.value.charCodeAt( 0 ),<br />
context.token.value,<br />
context.token.sourceName,<br />
context.token.charno,<br />
context.token.lineno,<br />
context.token.columnno );<br />
context.token = token;<br />
}<br />
private function onIdent( context: RegexLexerContext ): void<br />
{<br />
var type: int;<br />
var token: Token;<br />
type = context.token.type;<br />
if( keyword_map[ context.token.value ] )<br />
{<br />
type = keyword_map[ context.token.value ];<br />
}<br />
token = new Token(<br />
type,<br />
context.token.value,<br />
context.token.sourceName,<br />
context.token.charno,<br />
context.token.lineno,<br />
context.token.columnno );<br />
context.token = token;<br />
}<br />
private function onNumber( context: RegexLexerContext ): void<br />
{<br />
var token: Token;<br />
var value: Number;<br />
value = parseFloat( context.token.value );<br />
token = new Token(<br />
context.token.type,<br />
value,<br />
context.token.sourceName,<br />
context.token.charno,<br />
context.token.lineno,<br />
context.token.columnno );<br />
context.token = token;<br />
}<br />
private function onString( context: RegexLexerContext ): void<br />
{<br />
var token: Token;<br />
var value: String;<br />
value = context.token.value.substr( 1, context.token.value.length - 2 );<br />
token = new Token(<br />
context.token.type,<br />
value,<br />
context.token.sourceName,<br />
context.token.charno,<br />
context.token.lineno,<br />
context.token.columnno );<br />
context.token = token;<br />
}<br />
}<br />
}</code><br />
As you may imagine, this example is a simple Lexer that is able to scan Pixel Bender input files. The Lexer is composed by a serie of rules registered using the function <em>addRule( name: String, regex: String, id: int, callback: Function )</em>. The callback function can be a user defined callback or a standard callback.<br />
There are some standard callbacks:</p>
<ul>
<li><strong>RegexLexer.NL</strong>: tells the Lexer that a new line token have been matched. This action increase an internal counter that keeps track of the line number;</li>
<li><strong>RegexLexer.SKIP</strong>: skip the current token;</li>
<li><strong>RegexLexer.START_EAT</strong>: start eating the tokens;</li>
<li><strong>RegexLexer.STOP_EAT</strong>: stop eating the tokens;</li>
</ul>
<p>Custom actions instead can be used to change the state of the Lexer or to generate a custom Token; take for instance the <em>onIdent</em> calback: each time an identifier is matched, we check if it is a keyword and if so, we generate the proper.</p>
<p>Here is an simple usage example:<br />
<code>package {<br />
import flash.display.Sprite;<br />
import it.sephiroth.scripting.utils.Token;<br />
import test.PBLexer;<br />
public class test extends Sprite<br />
{<br />
private static var INPUT: XML = <input />< ![CDATA[
/*****************************************************************************
*
* Copyright (C) 2008 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE:  All information contained  herein is,  and remains the property of
* Adobe Systems Incorporated and its suppliers, if any.  The intellectual and
* technical  concepts  contained  herein  are  proprietary  to  Adobe Systems
* Incorporated  and  its suppliers  and may  be covered  by U.S.  and Foreign
* Patents, patents in process, and are protected by trade secret or copyright
* law.  Dissemination of this information or reproduction of this material is
* strictly forbidden  unless prior  written permission is obtained from Adobe
* Systems Incorporated.
*
*****************************************************************************/
<languageVersion: 1.0;><br />
// basicBoxBlur: A simple example to demonstrate how to implement a 1<br />
//                iteration box blur.  The kernel is a good example to<br />
//                demonstrate how to implement a convolution using for loops.<br />
kernel basicBoxBlur<br />
< namespace : "AIF";
vendor : "Adobe Systems";
version : 2;
description : "variable Radius Box Blur"; ><br />
{<br />
// A parameter that represents the radius of the blur in both the X and Y<br />
// directions.<br />
parameter float blurRadius<br />
< minValue:float(0.0);
maxValue:float(25.0);
defaultValue:float(5.0);
>;<br />
// A dependent value.  These are calculated in the evaluateDependents()<br />
// function and save us from having to perform repetitive calculations<br />
// for each pixel.<br />
dependent int radiusAsInt;<br />
// evaluateDependents(): Built-in function to do any pre-processing of the<br />
//                       parameters.  Usage of this function helps avoid<br />
//                       repeating any necessary instructions per pixel.<br />
//                       In a filter as simple as this, the extra cycles<br />
//                       are probably not necessary, but it serves as a<br />
//                       good example.<br />
void<br />
evaluateDependents()<br />
{<br />
// Convert the dimension into a integer value for use in the iteration<br />
// over the kernel window.  All type conversions are required to be<br />
// explicit.<br />
radiusAsInt = int(ceil(blurRadius));<br />
}<br />
input image4 src;<br />
output float4 dst;<br />
// Region functions are not available in Flash targets, so we only define<br />
// the functions if we are executing on a different backend.<br />
#if !AIF_FLASH_TARGET<br />
// needed(): Indicates what area of the input is needed to fulfill the<br />
//           requested output region.  In this case, we consider a<br />
//           radius sized area of the input for each output pixel, so we<br />
//           need to outset the area by one.<br />
region needed(region outputRegion, imageRef inputRef)<br />
{<br />
float2 singlePixel = pixelSize(src);<br />
return outset(outputRegion, float2(singlePixel.x * ceil(blurRadius), singlePixel.y * ceil(blurRadius)));<br />
}<br />
// changed(): Indicates what area of the output is affected by the<br />
//            specified input.  In this case, we will blur out the image<br />
//            by the size of the radius, so the output is the input outset by<br />
//            one.<br />
region changed(region inputRegion, imageRef inputRef)<br />
{<br />
float2 singlePixel = pixelSize(src);<br />
return outset(inputRegion, float2(singlePixel.x * ceil(blurRadius), singlePixel.y * ceil(blurRadius)));<br />
}<br />
#endif<br />
// evaluatePixel(): The function of the filter that actually does the<br />
//                  processing of the image.  This function is called once<br />
//                  for each pixel of the output image.<br />
void<br />
evaluatePixel()<br />
{<br />
// Containers for both the accumulated color as well as the number of<br />
// pixels touched.<br />
float denominator = 0.0;<br />
float4 colorAccumulator = float4(0.0, 0.0, 0.0, 0.0);<br />
float2 singlePixel = pixelSize(src);<br />
// Iterate through the kernel window, adding up the samples in<br />
// that location.<br />
for(int i = -radiusAsInt; i < = radiusAsInt; i++)
{
for(int j = -radiusAsInt; j <= radiusAsInt; j++)
{
colorAccumulator += sampleNearest(src,
outCoord() + float2(float(i) * singlePixel.x, float(j) * singlePixel.y));
denominator++;
}
}
// calculate the resultant pixel value which is the accumulated color
// divided by the total number of pixels.
// In this case, the denominator is 9.
dst = colorAccumulator / denominator;
}
}
]]&gt;<br />
public function test()<br />
{<br />
super();<br />
var token: Token;<br />
var lexer: PBLexer;<br />
lexer = new PBLexer( "<file>", INPUT.text() );<br />
while( token = lexer.next() )<br />
{<br />
if( token.type == Token.EOF )<br />
{<br />
break;<br />
}<br />
trace( token );<br />
}<br />
}<br />
}<br />
}</file></code><br />
Next week we will move further and start discussing the grammar, implementing a simple Parser using a custom version of <a href="http://en.wikipedia.org/wiki/Yacc">Yacc</a> that generates ActionScript code.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2008/12/16/scripting-flash-apps-scanning-the-input-file/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>
