Click here to Skip to main content
Click here to Skip to main content

Tokenizer and analyzer package supporting precedence prioritized rules

By , 1 Jan 2002
 

grammarIDE   Evaluation

Introduction

This library has its origin in some study project I am currently working on. All source code is covered by the LGPL - this means you can freely use the code in any project (commercial or non-commercial).

How it works

The tokenizer uses a hierarchical map structure to store the tokens, and should be as fast as the paragon lexx (at least n*O(lexx) :-). The analyzer does not have the restriction of being a LALR(1) analyzer (if used correctly), has some caching capabilities and allows resolution of literal tokens. It also supports a precedence prioritized rule set.

All projects make heavy use of the STL. Because the STL implementation shipped with MSVC6 is not the best option, you should download the STL Port 4.5.1 implementation freely available at www.stlport.org. I have now managed to get rid most of the C4786 warnings (hint: switch /FI).

How to setup the analyzer/tokenizer

A typical rule definition for a simple expression evaluator looks like this:

std::tstringstream init(
    "[seperators]\n"
    "200:+\n"       "201:-\n"
    "202:*\n"       "203:/\n"
    "204:^\n"       "205:;\n"
    "206:(\n"       "207:)\n"
    "' Whitespace tokens:\n"
    "0: \n"         "0:\t\n"
    "0:\\n\n"       "0:\\r\n"
    "[rules]\n"
    "300:numbers\n"
    "[grammar]\n"
    "401:{.expr}=100:{.expr}{$+}{.expr}\n"
    "402:{.expr}=100:{.expr}{$-}{.expr}\n"
    "403:{.expr}=99:{.expr}{$*}{.expr}\n"
    "404:{.expr}=99:{.expr}{$/}{.expr}\n"
    "405:{.expr}=98:{.expr}{$^}{.expr}\n"
    "406:{.expr}=0:{$(}{.expr}{$)}\n"
    "400:{.expr}=0:{!number}\n"
    "500:{.line}=0:{.expr}{$;}\n");

This initializes the tokenizer to recognize the separators '+', '-', '*', '/', '^', ';', '(', ')' and to skip the usual white space characters, and initializes the analyzer to recognize the math rules '+,*,-,/,^' and declares that '*' has a higher priority than '+', for example.

The interface class

Usually you have to deal only with one class, cxtPackage. This class exports all methods needed to access the library. Some of them are:

  • vSetInputStream() - sets the input stream :)
  • vSetDelimeterIDs() - can be used to set the end-of-statement tokens, in C++ this could be ';'
  • nReadUntilDelimeter() - parses the input stream until the next delimiting token is found or the end of the input stream is reached
  • papbCheckForRule() - analyzes the token stream for a given rule and returns a parse tree (if successful)
  • vRebalance() - rearranges the parse tree according to the precedence priority rules

Those are the most important ones. For more details please see the sample project or check the page http://www.subground.cc/devel which will have some minimal documentation on the classes available for download soon.

New: The grammar IDE

The new grammar IDE included in the complete download provides a environment to develop and test analyzer rulesets. It has some syntax-highlighting features, shows errors by marking the lines in the editor and has an integrated test environment to live-check the results of the ruleset. I have no documentation yet and the IDE is still early beta and it has some cosmetic bugs (for example, it is possible to insert via clipboard RTF-formatted text into the editor :-), but most of it is already usable.

The sample projects

There are two sample projects included in the complete download. One is an almost-empty sample application you can easily use to explore the library, and the other project, simpleCalc, shows how to use the library to build a simple expression evaluator in 200 lines. A step-by-step explanation on how the sample works is here.

How to use it in own projects

Make sure to insert the projects cxTokenizer, cxAnalyzer and cxtPackage in the workspace of your project. Adjust the dependencies of your project to depend on cxtPackage (which itself depends on cxAnalyzer, which in turn depends on cxTokenizer). If your project doesn't use the MFC, you have to include the file common.cpp which is located in the base directory of the project files in your project. If you have problems or questions, feel free to mail them to alexander-berthold@web.de. For the most recent updates, see also http://www.subground.cc/devel

Updates

  • 2002-01-02
    C++ (w/o templates and pre-processor) grammar is now included. See also here.
  • 2001-12-29
    Fixed small bug in analyzer. IDE download now includes a not yet complete C grammar.
  • 2001-12-27
    Updated Homepage-URL to ad-free host.
  • 2001-12-26
    Uploaded new release including the grammarIDE and some enhancements in the analyzer.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alexander Berthold
Web Developer
Germany Germany
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalbroken linkmemberAli Khanlarkhani17 Dec '02 - 0:52 
http://www.subground.cc/devel ?Mad | :mad:
Generalrepresneting grammars and parse treessussSteven Corkey2 Dec '02 - 8:14 
I am working on projects that perform operations on grammars and parse trees.
 
The project does not require any parsing.
 
I need data structures that represent parse trees and unrestricted grammars (open source).
 
I need to be able to represent rules that represent modifying an existing parse tree (changing leaves, changing ordering of non leaf branches, changing structures of branches, removing a branch, removing a branch and replacing it with another instance of that abstract branch type).
 
The operations I need to perform are given a word and parse tree perform mutations involving the word and its parse tree. I perform mutations based on rules that might need to use knowledge of its parse tree.
 
If anyone can give a lead to references or source code it would be appreciated.
GeneralParse TreesussEd Deighton4 Aug '02 - 3:17 
This software seems excelent to me. I dont understand the comparisons with flex / bison since with them you cannot obtain a parse tree. Surely the great thing about this is being able to parse user input expressions, and then evaluate them at a later triger point.
 
I was wondering if you had any facility to convert the parse tree to a post fix array or any other routines that could enable making it easier to actually invoke the tree resolving symbols to data or functions in the a program.
 
Clearly for most applications, its only the evaluation time thats relevant.
 
Ed.
QuestionWebsite links broken ?memberJerry Evans20 May '02 - 8:12 
I keep getting a 403 error
AnswerRe: Website links broken ?memberrealfly28 Jul '02 - 20:36 
http://absd.hypermart.net/
 
i am realfly8)
GeneralResults of comparison vs bison/flex parsermemberMatt Wigdahl8 Jan '02 - 12:10 
I have some preliminary results to share. I wrote a lex-based calculator very similar to Alexander's simpleCalc program. I then wrote a program called genfile that can generate arbitrarily-long mathematical expressions with arbitrary and random parenthesis nesting for the calculators to work on. I generated a file that was 10 MB in size with a maximum nesting depth of 20. I ran this file through my bison/flex calculator and it took 13.7 seconds for the file to parse and evaluate the expression. I then ran the file through Alexander's simpleCalc program. It is still running as I write this, 42 minutes later.
 
I have provided full source and projects to Alexander so that he can perform additional tests/comparisons, but it seems obvious that this system performs several orders of magnitude worse than bison/flex for an equivalent implementation.
 
Matthew L. Wigdahl
Software Engineer
matt@scriptpro.com
GeneralRe: Results of comparison vs bison/flex parsermemberMartin.Holzherr18 May '05 - 5:04 
Hi,
your comparision might be quite missleading.
If Alexander's package builds a parse tree, this tree will use at least 20 to 50 times more memory than your comparable bison/flex program. The long running time in your test may therefore be a result of swapping.
Right?
 
The point is, does a simple calculator need a parse tree? Probably not!
 
Best Regards
Martin
GeneralRe: Results of comparison vs bison/flex parsermemberMatt Wigdahl18 May '05 - 7:29 
Wow, a response 3 years after the fact!
 
You are correct, of course. The calculator is an oversimplified example. Obviously it doesn't need a parse tree as I was able to write my version completely in flex.
 
As best I can recall from the testing, no hard drive swapping was involved. I ran both programs on a development server with 1 GB of RAM. The real problem seemed to be the dynamic lexing in Alexander's program. My point was just to demonstrate that his program was not speed-neutral to or faster than equivalent parsers built using standard tools, where those tools were applicable.
 
There are certainly other cases where the extra features of Alexander's program make possible parsers that can't be done (easily, efficiently or even at all) in bison/flex. But for nontrivial inputs in equivalent problem domain implementations, I'm confident that properly-implemented bison/flex will outperform this package every time, often by considerable margins.
 
Matt
GeneralDefining grammarmemberRay Hayes2 Jan '02 - 5:27 
Hi,
 
this class looks interesting to me, but I can't find any links to how the rules/grammar is defined!
 
What would a basic XML(/HTML) parser rule-set look like?
 
Regards,
Ray
QuestionSeriously, why not just use lex???memberMatt Wigdahl28 Dec '01 - 9:50 
Granted lex and yacc (really, flex and bison) produce pretty ugly code.   But you should never need to even look at that code.   In my MFC projects that need parsing I include the clean, understandable .l and .yy files in my project with custom build steps that invoke flex and bison on them.   The resultant files are included in the build without my ever needing to see them.  
 
The advantages of using the existing tools are:   Flex and bison are free, available today, extremely fast, portable and almost completely rock-stable; their behavior is well-defined and lots of people know how to use them.   Contrast this to your yacc replacement, which will be buggy, and will have non-standard syntax.
 
Really, we should all be happy that flex produces ugly code.   It's that static, ugly code that makes it so screamingly fast since the token map is implemented in compilable, optimizable, C code.   Your solution implements lexing dynamically which almost guarantees that it will be drastically slower than flex for equivalent tasks.

 
Matthew L. Wigdahl
Software Engineer
matt@scriptpro.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 2 Jan 2002
Article Copyright 2001 by Alexander Berthold
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid