0

Trying to modify a value already pushed to the stack of a PLY/Yacc parser. I'm using ply on python 3.

Basically I want to invert the previous two values when a token SWAP is used.

Imagine we have this stack:

1, 2, 3, 4, SWAP

I need it to reduce to:

1, 2, 4, 3

the value you write to p[0] will be pushed to the stack, but how can I push more then one value?

# this fails because it consume two values and pushes only one
# results into: `1`, `2`, `4`
def p_swap(p):
   'value : value value SWAP'
   p[0] = p[2]

# this was just a try... fails as well
def p_swap(p):
   'value : value value SWAP'
   p[0] = p[2]
   p[1] = p[1]

# this locked as a good idea since consumes only only value and modify the second in place
# it fails because the stack (negative indexes) are immutable:
# https://github.com/dabeaz/ply/blob/master/ply/yacc.py#L234
# results into: `1`, `2`, `3`, `3`
def p_swap(p):
   'value : value SWAP'
   p[0] = p[-1]
   p[-1] = p[1] # this is a NOP

p is an instance of this class

I guess it was designed to be immutable to enforce the parsing to be done a certain way (the correct way), but I'm missing it: what's the correct way to modify the stack or to design a parser?

1 Answer 1

2

It sounds like you're trying to create a stack-based language like Forth or Joy. If so, you shouldn't need a bottom-up parser, and you shouldn't be surprised that a bottom-up parser-generator doesn't work the way you want it to.

Stack-based languages are mostly simply streams of tokens. Each token has some kind of stack effect, and they are just applied in sequence; there's usually little or no syntactic structure beyond that. Consequently, the languages really aren't parsed; at best, they are tokenised.

Most stack-based languages contain some kind of nested control structures which are not strictly conformant with the above (but not all; see Postscript, for example). But even these are so simple that a real parser is unnecessary.

Of course, nothing stops you from using a generated parser to parse a trivial language. But if you do that, you should certainly not expect to be able to gain access to the parser's internal datastructures. The parser stack is used by the parser in ways which might not be fully obvious, and which certainly must not be interfered with. If you want to implement a stack-based language interpreter, you need to use your own value stack. (Or stacks; many stack-based languages have several different stacks, each with its own semantics.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.