1

I'm writing a .NET program that does a lot of string validation of text files. I want to allow the user to be able to set up validation rules so I don't have to hard code lots of edge cases. For example I envision something like the following (caps are items in drop downs to limit user operations and items in quotes are user written):

IF KEY IS "X" AND VALUE IS "Y" RETURN NOTIFICATION

(IF KEY IS "X" OR VALUE IS "Y") AND (IF SECTIONNAME IS "I") REPLACE "Y" WITH "J"

So as you can see above I want to be able to group things with parens, use logical AND and OR and process IF statements which will all evaluate to some True/False value to perform some action. My question is what's the best way to parse the data so that I know the right operations to perform and in the correct groupings. Through Google it seems that perhaps I'm wanting to create an abstract syntax tree, if that's the case I've not been able to find some simple examples to really get me started.

Any help is greatly appreciated!

competent_tech
  • 44,465
  • 11
  • 90
  • 113
Roger
  • 107
  • 6

2 Answers2

1

I'm a big fan of parser generators (see my bio) but they are sometimes overkill.

For expresssions this simple (boolean logic) and a small set of actions (such as you have shown), a recursive descent parser should do just fine. If you weave semantic actions into the parsing, you don't need an AST; you can compute the result of the boolean equation on the fly, and use the result to decide if you should execute the parsed action, before you even parse it, since recursive descent parsers work from left to right. Thus you can can store your rules as text and simply execute them on demand, and your users can type them in on the spot.

See this SO answer on how to build a recursive descent parser by hand

Community
  • 1
  • 1
Ira Baxter
  • 93,541
  • 22
  • 172
  • 341
  • All the answers so far are mighty appreciated but this is the one I was looking for! I don't try to reinvent the wheel if a tool exists to do something but I prefer to understand what's going on and do it myself just for experience sake. Thanks mate! – Roger Dec 13 '11 at 00:45
0

You can do this in C# by creating a Domain Specific Language... basically you build up a set up rules for what the grammar of the language will look like and what the language is allowed to do, and a correct parser is written for you.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794