LMPTHW ex34: world.variables assignment vs reference

My analyzer is working. However, I’m just now realizing that my parser must somehow distinguish between variable assignment and reference/expression (ie, initializing, setting and getting variables).

Does this usually get handled by the parser or the analyzer? Should I write new productions to handle variable reference or assignment?

Here’s my productions script:

    script = [
        FuncDef("hello",
                Params([
                        ExprVariable('x'), ExprVariable('y')
                        ]),
                Body([
                    FuncCall("print",
                            Params([
                                ExprPlus(ExprVariable('x'), ExprVariable('y'))
                                ])
                            )
                    ])),
        FuncCall("hello",
                Params([ExprNumber(10), ExprNumber(20)])
                )
            ]

Here’s some output from my analyzer:

>>>     variables:  {'x': None, 'y': None}
>>>     functions: {'hello': 
<FUNCDEF>
 name: hello 
 params: 
<PARAMS>
 parameters: [
<EXPRVAR>
 identifier: x
</EXPRVAR>, 
<EXPRVAR>
 identifier: y
</EXPRVAR>]
</PARAMS> 
 body: 
<BODY indent: 0 >
 contents: [
<FUNCCALL>
 name: print
 params: 
<PARAMS>
 parameters: [
<EXPRPLUS>
 left: 
<EXPRVAR>
 identifier: x
</EXPRVAR>
 right: 
<EXPRVAR>
 identifier: y
</EXPRVAR>
</EXPRPLUS>]
</PARAMS>
</FUNCCALL>]
</BODY>
</FUNCDEF>}

Yes, so you always have the parser identify what each production is, but the analyzer uses that to create the environment and fix things up. That means if your analyzer has no way of knowing the difference between a variable assignment production and a variable usage expression then your parser is doing it wrong. What should happen is your parser parses the assignment into an AssignmentProduction, and expressions are parsed into their various expression production. Then when your analyzer goes through it will use the AssignmentProduction to fix up the world.

Now, in some simple languages you can have the parser register all the assignments in the world, but this becomes difficult when you start to get into nested scopes. The parser doesn’t really have enough information to know about assignment inside a function vs. inside a script, or inside an if-statement so it’s hard to track. The Analyzer though can keep track of this, or you can even shove this off to the interpreter/compiler stage.