• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
BeanDog

Recursive-descent parsing: Handling left-associativity?

8 posts in this topic

I'm writing a small language parser. Addition and subtraction are left-associative. In other words, 3+3+3 means (3+3)+3. In my grammar, it's basically this:
Expression ::= Expression + Term  |  Term
I'm having trouble getting my mind around this problem. If it was right-associative, my parsing function for this rule would be something like this:
Expression ParseExpression() {
  Term tLeft = ParseTerm();
  if(NextToken().Type == Plus)
    return new Addition(tLeft, ParseExpression());
  else
    return tLeft;
}
In fact, I originally wrote the function that way, and it worked great--except that my additions were all right-associative instead of left-associative. The problem, of course, is that my function would get into an infinite loop if I tried to do this instead:
Expression ParseExpression() {
  Expression eLeft = ParseExpression();
  if(NextToken().Type == Plus)
    return new Addition(eLeft, ParseTerm());
  else
    return eLeft;
}
So, what do I have to change to implement left-associativity? [edit: Fixed grammar] Thanks, [Edited by - BeanDog on September 27, 2006 6:28:13 PM]
0

Share this post


Link to post
Share on other sites
Note: Fixed original grammar in OP.

Unfortunately, changing the grammar as you suggested makes answers incorrect. You would make the operator right-associative. Although additions would work correctly, consider divisions. 1/2/3 would be 1/(2/3) = 3/2 instead of (1/2)/3 = 1/6. So I've got to figure out a way to do it with my original grammar (or come up with an equivalent grammar that's easier to implement).
0

Share this post


Link to post
Share on other sites
Recursive descent parsers CANNOT handle left associativity (or right associativity, if they start parsing from the right :) ).

Fortunately, every left-associative BNF grammar can be rewritten into a non-left-associative, equivalent grammar. I believe Zahlman was giving an example, not a solution. So experiment with new ways of writing BNF for arithmetic (and remember, even if no particular RULE is left-recursive, the BNF might still be (cycles in the BNF rules).
0

Share this post


Link to post
Share on other sites
Usually a better way to parse expressions of this type is to use only 1 recursive call per operator level/precedence. Normally you handle all operators (not just 1) of the same level in a single parsing function, while accumulating the result of this level in the return variable. In practice this means that your function ParseExpression should look something like this:

Expression ParseExpression() {
Term tLeft = ParseTerm();
while (NextToken().Type == Plus) {
tLeft = new Addition(tLeft, ParseTerm());
}

return tLeft;
}
Notice that three things have changed:
1. The if-statement was replaced with a while-statement,
2. The call to Addition now uses ParseTerm as the second parameter, instead of ParseExpression (the function ParseExpression is now only called once per operator level, and the next level [ParseTerm] is invoked directly rather than through a recursive ParseExpression call),
3. The result is now accumulated in tLeft, which is returned from the function when there are no more operators of this level in the input string.

If you do all your arithmetics like this you get left-associativity for free, while also reducing recursion depth and making the code more understandable. Btw, the grammar this is parsing is: Expression = Term {"+" Term}.

P.S. I am not a C programmer so the code snippet I posted above might contain errors!

[Edited by - Devilogic on September 28, 2006 6:36:57 AM]
2

Share this post


Link to post
Share on other sites
Sorry, my rewrite was equivalent to the right-associative parser you illustrated. For some reason I was thinking of the interpretation process as somehow decoupled from the construct ;)

You might find this useful though. Or search for yourself :)

Edit: NM, it's still all the same: the techniques for removing left-recursion also flip the natural associativity. You additionally need to do something like what Devilogic said. Alternatively, keep the recursion but transform as you go:


Expression ParseExpression() {
Term tLeft = ParseTerm();
if(NextToken().Type == Plus) {
Addition right(ParseExpression());
// Hmm... not sure about this at all, actually :P
return Addition(Addition(tLeft, right.lhs), right.rhs);
} else return tLeft;
}


[Edited by - Zahlman on September 27, 2006 11:55:37 PM]
0

Share this post


Link to post
Share on other sites
For example, if you have a grammar like this:



expr = expr * expr
| expr / expr
| expr + expr
| expr - expr
| <...>





It can be refactored to something like the following to eliminate left recursion:



expr = factor * factor
| factor / factor

factor = term + term
| term - term

term = number
| ( expr )





I did a small(sorta) scripting language in Boost.Spirit, which is a recursive descent parser framework.
0

Share this post


Link to post
Share on other sites
Daerid: Unfortunately your example refactored grammar eliminates *all* recursion, making something like 1/2/3 impossible.

Devilogic: Rating++ for helping me understand what I'd found on Google. They said that left-recursion should be done in a loop, exiting the loop if the next operator is a lower precedence and continuing the loop if the operator is equal or higher precedence. Didn't make much sense at first, but I see your quick pseudocode would do what I need.

Thanks all!
0

Share this post


Link to post
Share on other sites
Quote:
Original post by BeanDog
Daerid: Unfortunately your example refactored grammar eliminates *all* recursion, making something like 1/2/3 impossible.


oh, right.. sorry. the correct grammar would be:



expr = factor * expr
| factor / expr
| factor

factor = term + factor
| term - factor
| term

term = number
| ( expr )






I was thinking with a spirit grammar, which has a nice little kleene star operator, like so:


add_expr
= mul_expr >> *(add_op >> mul_expr)
;

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0