Reputation: 17
I have created a parser and a scanner containing some rules such as;
for flex file:
{tINT} return tINT ;
{tFLOAT} return tFLOAT ;
for bison file:
program : declarations statements
;
declarations: assignment declarations
| epsilon
;
assignment: tIDENT tASSIGN literal
;
literal: tINT
|tFLOAT
|tSTRING
|tTRUE
|tFALSE
|list
Now I have to check for some errors such as; undeclared variables, type mismatch in list, multiple declarations of a variable, wrong reassignment of a variable, type mismatch in comparable types, Type mismatch in if, elif statements, Type mismatch in for statements
The answer I am looking for of course not for all of them. I just need an idea to how to start. Thanks in advance.
Upvotes: 0
Views: 304
Reputation: 490623
Essentially everything you're asking about relates to type-checking.
The typical way to implement that involves building a symbol table so when (for example) you get a declaration saying that i
is an int
, you store that. Then when you get an assignment like i = j
, you can check that j
is an int
(or, depending on the conversion rules for your language, some other type that can implicitly convert to int
, if you allow implicit conversions).
As it stands right now, your grammar doesn't seem to have anything like a type declaration though--it has only assignments. To do much with that, you'll probably want to decide types based on the values assigned to them. For example:
i = 1 // i is an int
j = "something" // j is a string
Then you can get to:
i = j // type mismatch--not allowed.
So basically, for each new identifier you encounter in an assignment, you store some data about its type (based on the type of whatever's on the right side of the assignment). Then when you see another assignment to that variable, you check the type associated with the value on the right, and check that it's compatible with the existing type of the left side.
Since this is apparently the first time you're doing this, I'll add that the simplest definition of "compatible" is usually "identical"--i.e., it's easiest to just prohibit all conversions.
Upvotes: 1