Help with a Perl expression parser...

Status
Not open for further replies.

Magus`

Ars Legatus Legionis
30,136
Subscriptor++
Ok, so I'm working on a lab for class, and I'm starting to run into spots where I'm totally stuck looking for ideas on where to go next, and some times where I'm not sure if the way I'm doing it is really as easy as I thought it would be...

So I'm looking for assistance, and hoping to find some here. I'm not after a solution or for someone to write my program for me, but for ideas. Suggestions, thoughts, ideas.

The lab writeup is here, and my current code is here.

Thanks in advance,
Magus`
 

EgalitarianBovine

Ars Tribunus Angusticlavius
8,086
There's a simple way of structuring your parsing functions so that precedence rules are enforced (this is for recursive descent parsing, which I think you're doing).

The main gist of it is that you call the function that parses the lowest precedence operator first. This function in turn calls functions that parse the next-lowest precedence operator. It's somewhat hard to explain, so I'll try to come up with pseudocode for a very simplified version of your problem.

-EB
 
I belive EB means that if you have something like:

X^2 + 2x + -3 - 4

Then you need to call your +/- parsing functions before your multiplication, and your multiplication before your exponentiation.

This example is not for a perl-like language, but you get the gist. This will make it so that when you get your AST, the lowest precedent operators are at the top (i.e. done last).

code:<HR>
Code:
def parsePlusMinus():
     // find the lhs and rhs of a + or - operation, and call
     // parseMultiplyDivide on each side, add to +/- node.

def parseMultiplyDivide():
     // Same as above, but parse for * or / and call parseExp()

def parseExp():
     // Parse an exponentiation, then parse out actual numbers.

def parseNumber():
     // Get a number, also handle unary minus...
 

EgalitarianBovine

Ars Tribunus Angusticlavius
8,086
Ok, here's a basic pseudocode example, with a simple grammer which contains the following tokens: +, -, *, /, IDENTIFIER, (, )

Where * and / are at the same precedence level.
Where + and - are at the same precedence level.
And (*, /) are higher precedence than (+, -)

code:<HR>
Code:
def parse():
    return parse_addsub()

def parse_addsub():
    expr = parse_muldiv()
    while not done:
        tok = next_token()
        if tok is EOF:
            done = true
        elif tok is + or -:
            expr2 = parse_muldiv()
            expr = new Node(tok, expr, expr2)
        else:
            push_back(tok)
            done = true
    return expr

def parse_muldiv():
    expr = parse_atom()
    while not done:
        tok = next_token()
        if tok is EOF:
            done = true
        elif tok is * or /:
            expr2 = parse_atom()
            expr = new Node(tok, expr, expr2)
        else:
            push_back(tok)
            done = true
    return expr

def parse_atom():
    tok = next_token()
    if tok is IDENTIFIER:
        return new Node(IDENTIFIER, tok)
    elif tok is (:
        expr = parse_addsub()
        tok = next_token()
        if tok is not ):
            ERROR
        else:
            return expr
    else:
        ERROR

next_token() returns the next token
push_back() pushes a token back onto the token stream, so the next time you call next_token() the token you pushed back will be read.

Anyway, the idea with this example is this, given an expression 'expr', you assume that it is an addition/subtraction expression, with 0 or more additions/subtractions.

addsubexpr = muldivexpr1 (+,-) muldivexpr2 (+,-) .... (+,-) muldivexprN

and you split up each muldivexpr into:

muldivexprI = atomexpr1 (*,/) atomexpr2 (*,/) ... (*,/) atomexprN

and each atomexpr can be:

atomexprI = ( addsubexpr ) OR identifier


That's the general idea. You'll have to modify it for your grammar. Good luck.


Edit:

Cobalt, that's exactly what I was thinking.


-EB
 
You can do if ... then ... else really easily if you're allowed to use Regular Expression. Just set your parseIfThenElse() function to grab the most possible text in-between an if and an else.

This will take care of if ... elses inside of other if conditionals.

EB and I have been talking of a pretty standard way to do simple expression parsing for context-free grammars: recursive decent. Think of the full parse tree you're trying to achive, and then make a function for each level of the tree essentially. Another way to think of it is that you'll need one function per <entry> in a BNF syntax specification. (I can't believe I forgot what the text in < and > are called...)

code:<HR>
Code:
def parseIfThenElse(string):
     // IF the first token is an "if":
          // Grab text between the if and the then, pass this to parseExpression().
          // Grab all the text between the then and the else or ";"
          // Pass this text to parseIfThenElse() again.
          // If you didn't get to a ";", grab all text after the else, pass it to parseIfThenElse()
     // ELSE: Pass the text to a non-conditional expression handler.  Perhaps an assignment handler?  This is where peeking at the next token or two is helpful.

edit: That pseudocode above will handle the following very nicely:

code:<HR>
Code:
if ... then
   if ... then
   ...
   else
   ...
else
...
 
Status
Not open for further replies.