I asked a question earlier, but I don’t think I was clear enough about the sort of answers I was hoping for, so let me provide a more concrete example:
class Program
{
private static bool State;
static void Main(string[] args)
{
State = false;
Console.WriteLine(And());
Console.ReadLine();
}
static bool And()
{
return Or() && C();
}
static bool Or()
{
return A() || AB();
}
static bool C()
{
return State;
}
static bool A()
{
return true;
}
static bool AB()
{
State = true;
return true;
}
}
The flow of this program looks like:
- And() gets called
- And() calls Or()
- Or() calls A()
- A() returns true
- Flow returns to Or(), which returns true (lazy evaluation)
- Flow returns to And(), And() calls C()
- C() returns false
- Flow returns to And(), which returns false
Now if Or() did not perform lazy evaluation (I change || to |), the program will return true. However, I don’t want AB() to executed unless the result of the entire parse fails (And() returns false).
So what I’d like to do, is somewhere in the Or() function, save the current state on a stack (static variable) so that if And() returns false, I can pop an item off the stack and try the alternative.
How would I accomplish this in C#?
It strikes me as being fairly trivial- just rearrange the calls:
Or am I missing something? Maybe
C()has side effects such that it should not be called twice?EDIT: Now I understand what you are trying to do. Do yourself a favor. Listen to the suggestions you’ve gotten, get a copy of GPPG, or (probably much simpler) ANTLR, with ANTLRWorks. It is so, so much easier and less error prone than attempting to roll a parser by hand, and you still get C# at the end.