[2] | 1 | #include "lookup.h"
|
---|
| 2 | #include "messages.h"
|
---|
| 3 | #include "types.h"
|
---|
| 4 | #include "Node.h"
|
---|
| 5 | #include "SyntaxTree.h"
|
---|
| 6 | #include "Symbol.h"
|
---|
| 7 | #include "SymbolTable.h"
|
---|
| 8 | #include <assert.h>
|
---|
| 9 |
|
---|
| 10 | /* declared in comp.l */
|
---|
| 11 | extern int lineno;
|
---|
| 12 |
|
---|
| 13 | /* declared in comp.y */
|
---|
| 14 | extern SyntaxTree *tree;
|
---|
| 15 | extern SymbolTable *symtab;
|
---|
| 16 | extern Messages messages;
|
---|
| 17 | extern string mainScopeName;
|
---|
| 18 |
|
---|
| 19 | Symbol *lookup(const string& id, SymbolType default_type)
|
---|
| 20 | {
|
---|
| 21 | /* Lookup ID */
|
---|
| 22 | Symbol *symbol = symtab->GetSymbol(id);
|
---|
| 23 | if (symbol == NULL) {
|
---|
| 24 | /* Symbol not found */
|
---|
| 25 | messages.UndeclaredIdError(lineno, id);
|
---|
| 26 |
|
---|
| 27 | /* Add ID with return type error to avoid triggering error again */
|
---|
| 28 | symbol = new Symbol();
|
---|
| 29 | symbol->SetSymbolType(default_type);
|
---|
| 30 | symbol->SetName(id);
|
---|
| 31 | symbol->SetLine(lineno);
|
---|
| 32 | symbol->SetReturnType(RT_ERROR);
|
---|
| 33 | symtab->AddSymbol(symbol);
|
---|
| 34 | }
|
---|
| 35 | return symbol;
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | /* Checks if the id already exists and gives an error if it does */
|
---|
| 39 | void check_id(const string& id)
|
---|
| 40 | {
|
---|
| 41 | /* check for program name */
|
---|
| 42 | if (id == mainScopeName) {
|
---|
| 43 | messages.DeclaredIdError(lineno, id, 0);
|
---|
| 44 | return;
|
---|
| 45 | }
|
---|
| 46 | /* check for local identifiers */
|
---|
| 47 | Symbol *symbol = symtab->GetSymbol(symtab->GetCurrentScopeName(), id, false);
|
---|
| 48 | if (symbol != NULL) {
|
---|
| 49 | messages.DeclaredIdError(lineno, id, symbol->GetLine());
|
---|
| 50 | return;
|
---|
| 51 | }
|
---|
| 52 | /* check for global identifiers */
|
---|
| 53 | symbol = symtab->GetSymbol(id);
|
---|
| 54 | if (symbol != NULL) {
|
---|
| 55 | SymbolType symboltype = symbol->GetSymbolType();
|
---|
| 56 | if (symboltype == ST_FUNCTION || symboltype == ST_PROCEDURE) {
|
---|
| 57 | messages.DeclaredIdError(lineno, id, symbol->GetLine());
|
---|
| 58 | return;
|
---|
| 59 | }
|
---|
| 60 | }
|
---|
| 61 | }
|
---|