ply concatenating strings on grammar

398 views Asked by At

So im writing a grammar on Ply that recognizes basic C statements, such as a variable declaration or a while statement. For now, what I want to do is to be able to concatenate all the tokens and then print it or have it propagate up the tree, like this:

def p_whileStmt(p):
    '''whileStmt : WHILE '(' condition ')' '{' stmt '}' '''
    p[0] += p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + p[7]

Is there a better way to concatenate all the tokens (I only need the character values, I only need to build a string) than the one I'm using?

EDIT: In certain cases I need to concatenate all the tokens except a few, like for example:

def p_whileStmt(p):
    '''whileStmt : WHILE '(' condition ')' '{' stmt '}' '''
    p[0] += p[1] + p[3] + p[5]
2

There are 2 answers

1
Bhargav Rao On BEST ANSWER

You can avoid += by using

p[0] = ''.join(p)

And for p[0] += p[1]+p[3]+p[5] you can do

p[0] += ''.join(p[1::2])
0
jjm On

In python when you have a list of strings, you usually want to use str.join, which is both simpler and more efficient. Here, you'd want something like:

p[0] += ''.join( p[1:] )

Assuming that p[0] is already a string.

If you need to concatenate particular tokens, your way of doing it is fine. It's a bit of a silly design on the part of ply to put every token in p, but the point is to be very close to the behaviour of yacc.