How to implement multiple assignment in an interpreter written in python?

I am writing an interpreter in python and I am following this example http://www.dabeaz.com/ply/example.html

I would like to know how I can implement multiple assignment, for example:

a=b=c=1 and a=(b=1)*1

I tried a few rules, but all in vain. I know that parsing should be something like this.

 abc 1 \ \ \/ \ \ / \ \ / \ / 

I'm just not sure how to write this with PLY.

+6
source share
1 answer

Most languages ​​go away from it by declaring assignment with an expression.

In your example, the assignment would be:

 def p_expression_assign(t): 'expression : NAME EQUALS expression' t[0] = names[t[1]] = t[3] 

I simply changed the “statement” to “expression” both in the function name and in the docstring syntax and “returned” (assigned t[0] ) the value that is assigned.

I say “leave with” because other languages ​​(like Python) go the extra mile because they allow multiple assignments, but forbid the use of the assignment result in any other expression.

But your second example a=(b=1)*1 tells me that you need the first, weaker (or C-like) multiple-use form.

+4
source

All Articles