<?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>gnu flex &#8211; Alessandro Crugnola &#8211; sephiroth.it</title>
	<atom:link href="https://blog.sephiroth.it/tag/gnu-flex/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>gnu flex &#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>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>ActionScript Parsing, the YACC revenge :)</title>
		<link>https://blog.sephiroth.it/2006/12/10/actionscript-parsing-the-yacc-revenge/</link>
					<comments>https://blog.sephiroth.it/2006/12/10/actionscript-parsing-the-yacc-revenge/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Mon, 11 Dec 2006 00:47:30 +0000</pubDate>
				<category><![CDATA[actionscript]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[antlr]]></category>
		<category><![CDATA[bison]]></category>
		<category><![CDATA[ecma]]></category>
		<category><![CDATA[ecmascript]]></category>
		<category><![CDATA[elastic]]></category>
		<category><![CDATA[gnu flex]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[pyrex]]></category>
		<category><![CDATA[yacc]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=188</guid>

					<description><![CDATA[After my first <a target="_blank" href="http://www.sephiroth.it/weblog/archives/2006/12/an_experience_with_antlr_with_java_an.php">attempts with ANTLR</a> scanners in python/java I decided to start back with Bison/Flex again to see the difference in performances...
]]></description>
										<content:encoded><![CDATA[<p>After my first <a title="An experience with antlr, java and python" href="https://blog.sephiroth.it/2006/12/01/an-experience-with-antlr-java-and-python/" target="_blank">attempts with ANTLR</a> scanners in python/java I decided to start back with Bison/Flex again to see the difference in performances.<br />
So first I need to wrote from scratch the grammar/lexer files using only the <a href="http://www.mozilla.org/js/language/es4/" target="_blank">ECMAScript 4</a> specifications and much patience (the <a href="http://svn.berlios.de/wsvn/elastic/trunk/elastiC/src/elastic_p.y?op=file&amp;rev=0&amp;sc=0">elastic grammar file</a> help me a lot too).</p>
<p>After finishing a first version of the parser I tested it on the same file (75Kb actionscript file) which both java and python parsed in more than 1 second.<br />
The result was unbelievable: <span style="font-weight: bold;">0.02</span> seconds for that file!</p>
<p>Then I tested it on multiple files, and for about 320 files of the whole adobe corelib library it took 220ms</p>
<p>Ok, the parser it&#8217;s not yet complete and doesn&#8217;t care about regexp and xml syntax, but its performance convinced me enough&#8230;<br />
Now, the next step is to finish and test the parser and finally create a python library using <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" target="_blank">pyrex</a>, then a benchmark test again.</p>
<p>If someone is interested in testing the parser, <a href="https://blog.sephiroth.it/wp-content/uploads/2006/12/parser.exe">download it</a> (use &#8220;<span style="font-style: italic;">parser &#8211;help</span>&#8221; form the command line for usage help), but remember this is only a first test.. not really helpful right now (I just wanted to share my text/parsing experiences).</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2006/12/10/actionscript-parsing-the-yacc-revenge/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>An experience with antlr, java and python</title>
		<link>https://blog.sephiroth.it/2006/12/01/an-experience-with-antlr-java-and-python/</link>
					<comments>https://blog.sephiroth.it/2006/12/01/an-experience-with-antlr-java-and-python/#comments</comments>
		
		<dc:creator><![CDATA[Alessandro Crugnola]]></dc:creator>
		<pubDate>Fri, 01 Dec 2006 19:09:11 +0000</pubDate>
				<category><![CDATA[general]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[antlr]]></category>
		<category><![CDATA[asdt]]></category>
		<category><![CDATA[bison]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[ecma]]></category>
		<category><![CDATA[gnu flex]]></category>
		<category><![CDATA[grammar]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[profiler]]></category>
		<category><![CDATA[psyco]]></category>
		<guid isPermaLink="false">http://blog.sephiroth.it/?p=187</guid>

					<description><![CDATA[I just wanted to share a little experience with generating an AS3 parser using antlr and python.I was trying first to create the parser using...
]]></description>
										<content:encoded><![CDATA[<p>I just wanted to share a little experience with generating an AS3 parser using <a href="http://www.antlr.org">antlr</a> and <a href="http://www.python.org">python</a>.<br />
I was trying first to create the parser using GNU <a title="gnu flex" href="http://www.gnu.org/software/flex/" target="_blank">Flex</a> and <a title="gnu bison" href="http://www.gnu.org/software/bison/" target="_blank">Bison</a> in C, probably the best way for a very performancing parser.<br />
Yeah, that&#8217;s right.. but looking at the antlr syntax I realized that&#8217;s easier and easier.<br />
Moreover I start using this very useful <a title="antlrstudio" href="http://www.placidsystems.com/antlrstudio.aspx" target="_blank">eclipse plugin</a> for antlr debugging which made my life easier!</p>
<p>The grammar file I created is a compromise between the <a title="as3.g" href="http://www.google.com/codesearch?hl=it&amp;q=+file:%5C.g%24+as3.g+show:gFeBx72kxIk:XKFG9i76Jiw:mSlmdOLa2XQ&amp;sa=N&amp;cd=1&amp;ct=rc&amp;cs_p=:pserver:anonymous%40aseclipseplugin.cvs.sourceforge.net:/cvsroot/aseclipseplugin+org.asdt.astview&amp;cs_f=src/org/asdt/core/internal/antlr/as3.g#a0" target="_blank">asdt grammar</a> file and the <a title="ECMA-262 specifications" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" target="_blank">ECMA-262 grammar</a> specification.</p>
<p>Once finished working on my eclipse project I&#8217;ve managed to parse succesfully all the adobe corelibs files using this java test file:<br />
<code lang="java">package org.sepy.core.parsers.as3;<br />
import java.io.File;<br />
import java.io.FileInputStream;<br />
import java.io.FileNotFoundException;<br />
import antlr.CommonAST;<br />
import antlr.RecognitionException;<br />
import antlr.TokenStreamException;<br />
public class Application {<br />
public static void main(String argv[])<br />
{<br />
if(argv.length &gt; 0)<br />
{<br />
File file = new File(argv[0]);<br />
if(file.exists())<br />
{<br />
FileInputStream is = null;<br />
try {<br />
is = new FileInputStream(file);<br />
} catch (FileNotFoundException e) {<br />
// TODO Auto-generated catch block<br />
e.printStackTrace();<br />
}<br />
AS3Lexer L = new AS3Lexer(is);<br />
AS3Parser P = new AS3Parser(L);<br />
try {<br />
P.compilationUnit();<br />
} catch (RecognitionException e) {<br />
// TODO Auto-generated catch block<br />
System.out.println(" line=" + e.line + ", column="+ e.column);<br />
System.out.println(e.getMessage());<br />
e.printStackTrace(System.err);<br />
} catch (TokenStreamException e) {<br />
// TODO Auto-generated catch block<br />
System.out.println(" line=" + L.getLine() + ", column="+ L.getColumn());<br />
System.out.println(L.getGuessInfo());<br />
System.out.println(e.getMessage());<br />
e.printStackTrace(System.err);<br />
}<br />
CommonAST.setVerboseStringConversion(false, P.getTokenNames());<br />
CommonAST ast = (CommonAST) P.getAST();<br />
System.out.println("Tree:");<br />
System.out.println(ast.toStringTree());<br />
}<br />
}<br />
}<br />
}</code><br />
Ok, done that I decided to export the grammar file for python (thanks to antrl python export feature).<br />
Everything works fine also for python, but I realized that the python script were so much slower than the java one!<br />
<code lang="python">import sys<br />
import antlr<br />
import AS3Parser<br />
import AS3Lexer<br />
L = AS3Lexer.Lexer(filename);<br />
P = AS3Parser.Parser(L);<br />
P.setFilename(filename)<br />
try:<br />
   P.compilationUnit();<br />
   ast = P.getAST();<br />
except:<br />
   pass<br />
</code><br />
On a 75Kb actionscript file the python script took about 7 seconds to run, while the java application only 2 seconds. I know python interpreter caould be slower than many other languages, but I never thought so much slower.<br />
So I run the python <a href="http://docs.python.org/lib/module-hotshot.html" target="_blank">hotshot profiler</a> to see which could be the bottleneck in the python script and I found most of the problems were due to unuseless antlr (the python module) method&#8217;s calls.<br />
After making corrections to the antlr.py file the same script took exactly half of the time. Now 3 seconds. Wow 🙂<br />
But not fast enough.<br />
So I enabled for the antlr python script <a href="http://psyco.sourceforge.net/" target="_blank">psyco</a> module and this time the same script took <strong>only 1.6 seconds.</strong><br />
Now the python script is fast enough, even if I&#8217;m sure I can make more optimizations in the antlr module&#8230;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.sephiroth.it/2006/12/01/an-experience-with-antlr-java-and-python/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
	</channel>
</rss>
