Click here to Skip to main content
15,885,881 members
Articles / Containers / Virtual Machine

Parsing Expression Grammar Support for C# 3.0 Part 1 - PEG Lib and Parser Generator

Rate me:
Please Sign up or sign in to vote.
4.95/5 (49 votes)
7 Oct 2008CPOL40 min read 202.9K   2.1K   118  
Introduction to the parsing method PEG with library and parser generator
<<Grammar Name="calc0_direct">>
Top{ // semantic top level block using C# as host language
  double result;
  bool print_(){Console.WriteLine("{0}",result);return true;}
}
Expr:    S Sum   (!. print_ / FATAL<"following code not recognized">);
Sum
{  //semantic rule related block using C# as host language 
   double v;
   bool save_()  {v=  result;result=0; return true;}
   bool add_()   {v+= result;result=0;return true;}
   bool sub_()   {v-= result;result=0;return true;} 
   bool store_() {result= v; return true;}
}	:     
	Product save_
                ('+' S Product add_
		/'-' S Product sub_)* store_		;
Product
{ //semantic rule related block using C# as host language 
   double v;
   bool save_()  {v=  result;result=0; return true;}
   bool mul_()   {v*= result;result=0; return true;}
   bool div_()   {v/= result;result=0;return true;} 
   bool store_() {result= v;return true;}	
}	: 
	Value  save_
	        ('*' S Value mul_
		/'/' S Value div_)* store_		;  
Value:   Number S / '(' S Sum ')' S	;
Number
{ //semantic rule related block using C# as host language 
   string sNumber;
   bool store_(){double.TryParse(sNumber,out result);return true;}
}
	:  ([0-9]+ ('.' [0-9]+)?):sNumber store_	;
S:	 [ \n\r\t\v]*					;
<</Grammar>>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions