So I'm having trouble for days now. Basically, I'm making a compiler for a language i am creating using python. We got the sintax and lexic part down, now the directory procedure and the variable table (symbol table) is being created. In my Yacc file I have:
Yacc.py
import ply.yacc as yacc
import sys
tokens = Lex.tokens
#Global variables
procs = { }
current_fid = ""
# add new value to the procedure directory
def add_procs_to_dict(fid, ftipo, fparams, fdict):
proc_dict = {}
proc_dict[fid] = {
'Tipo' : ftipo,
'Params' : fparams,
'Var_dict' : fdict
}
return proc_dict
# add new variable value to the procedure directory
def add_vars_to_dict(vid, vtipo, vparams):
var_dict = {
'Nombre' : vid,
'Tipo' : vtipo,
'Params' : vparams
}
print(current_fid)
print(procs)
return proc_dict
# Parsing Rules
def p_juego(p):
'''Juego : JUEGO ID DOSP JuegoA JuegoB MainProgram'''
current_fid = p[2]
procs = add_procs_to_dict( p[2], p[1], 'void', {})
def p_vars(p):
'''Vars : VAR ID COR_I Exp COR_D VarSizeA Vars2 DOSP Tipo PCOMA'''
add_vars_to_dict( p[2], p[9], p[4])
The important thing to note here is that i'm creating a a variable that saves the current ID (named current_fid
which is the name of the last procedure being inserted in the dictionary) and a dictionary variable (named procs
which is the procedure/function directory) as a global scope.
When the parser enters the parsing rule p_juego(p):
(given that the code its being fed is correct, and it is I already run it alone) it suppose to set to the variables (current_fid
and procs
) the value it found on the parser process. It does set the values alright. I could print the variables inside the function and returns the expected values.
Once once the parser exits the function p_juego(p)
and enters another function like p_vars(p)
(this function writes on the dictionary the symbol table for the last procedure/function inserted on the global directory) the global variables (current_fid
and procs
) have no value inside them. There is 2 prints inside the p_vars(p)
that always displays null for the variables.
I'm relatively new to python and maybe i'm missing something about the language. My intention was if I define a variables before everything (at the top of the code), the functions that uses those "global" variable will update their values and always keep themt even if another function tries to access them. I tried adding the procedures in a new python file named Semantics.py but the value of the variables is always null outside the function that previously set the value.
What am I missing here?
To avoid scoping problems like this and to be more explicit I suggest you make use of a class. Then you can use self.variable to hold information between class method calls.