I have to visit parse tree and build symbol tables for functions by Antlr4.
I have to add some codes at SymbolTableVisitor class given behind with a skeleton code in B2CMain.cpp.
// collection of per-function symbol tables accessed by function name
// symbol table in global scope can be accessed with special name defined in GlobalFuncName
map<string, SymbolTable*> symTabs;
class SymbolTableVisitor : public BBaseVisitor {
private:
int scopeLevel;
string curFuncName;
int blockCounter; // 추가 코드
public:
SymbolTableVisitor(): scopeLevel(0), blockCounter(1) {}; // 추가 코드
// Building symbol tables by visiting tree
Assistant
any visitProgram(BParser::ProgramContext *ctx) override {
scopeLevel = 0; // global scope
// prepare symbol table for global scope
SymbolTable* globalSymTab = new SymbolTable();
curFuncName = _GlobalFuncName_;
symTabs[curFuncName] = globalSymTab;
// visit children
for (int i=0; i< ctx->children.size(); i++) {
visit(ctx->children[i]);
}
// print all symbol tables
for (auto& pair : symTabs) {
cout << "--- Symbol Table --- " << pair.first << endl; // function name
pair.second->printSymbols(); // per-function symbol table
cout << "";
}
return nullptr;
}
any visitDefinition(BParser::DefinitionContext *ctx) override {
visit(ctx->children[0]);
return nullptr;
}
any visitAutostmt(BParser::AutostmtContext *ctx) override {
// get current symbol table
SymbolTable *stab = symTabs[curFuncName];
// You can retrieve the variable names and constants using ctx->name(i) and ctx->constant(i)
for (int i=0, j=0; i < ctx->name().size(); i++) {
string varName = ctx->name(i)->getText();
enum Types varType = tyAUTO; // default type
// if initialized, get constant type
int idx_assn = 1 + i*2 + j*2 + 1; // auto name (= const)?, name (= const)?, ...
if (ctx->children[idx_assn]->getText().compare("=") == 0) {
if (ctx->constant(j)) {
varType = any_cast<Types>( visit(ctx->constant(j)) ); // returns init constant type
j++;
}
}
stab->addSymbol(varName, {varType});
}
return nullptr;
}
/* 추가 시작 ------------------------------------------------------------------------------------------ */
any visitBlockstmt(BParser::BlockstmtContext *ctx) override {
scopeLevel++;
string blockName = curFuncName + "_$" + to_string(blockCounter++);
SymbolTable* blockSymTab = new SymbolTable();
symTabs[blockName] = blockSymTab;
for (auto stmt : ctx->statement())
visit(stmt);
scopeLevel--;
return nullptr;
}
any visitIfstmt(BParser::IfstmtContext *ctx) override {
visit(ctx->expr());
visit(ctx->statement(0));
if (ctx->ELSE())
visit(ctx->statement(1));
return nullptr;
}
any visitWhilestmt(BParser::WhilestmtContext *ctx) override {
visit(ctx->expr());
visit(ctx->statement());
return nullptr;
}
any visitFuncdef(BParser::FuncdefContext *ctx) override {
string functionName = ctx->name(0)->getText();
curFuncName = functionName; // 현재 함수 이름
// Symbol Table 위한 type 저장하기
vector<Types> retArgTypes;
retArgTypes.push_back(tyAUTO);
for (int i = 1; i < ctx->name().size(); i++)
retArgTypes.push_back(tyAUTO);
// global의 Symbol Table
SymbolTable* globalSymTab = symTabs[_GlobalFuncName_];
globalSymTab->addSymbol(functionName, {tyFUNCTION, retArgTypes});
// 현재 함수의 Symbol Table
SymbolTable* funcSymTab = new SymbolTable();
symTabs[functionName] = funcSymTab;
visit(ctx->blockstmt()); // visit blockstmt
curFuncName = _GlobalFuncName_; // 함수 종료, Global로 돌아가기
return nullptr;
}
/* 추가 종료 ------------------------------------------------------------------------------------------ */
any visitConstant(BParser::ConstantContext *ctx) override {
if (ctx->INT()) return tyINT;
else if (ctx->REAL()) return tyDOUBLE;
else if (ctx->STRING()) return tySTRING;
else if (ctx->BOOL()) return tyBOOL;
else if (ctx->CHAR()) return tyCHAR;
cout << "[ERROR] unrecognizable constant is used for initialization: " << ctx->children[0]->getText() << endl;
exit(-1);
return nullptr;
}
};
/*
STEP 2. infer type
*/
class TypeAnalysisVisitor : public BBaseVisitor {
public:
// infer types for 'auto' variables and functions
// ...
};
/*
STEP 3. print code
*/
class PrintTreeVisitor : public BBaseVisitor {
public:
any visitProgram(BParser::ProgramContext *ctx) override {
// Perform some actions when visiting the program
for (int i=0; i< ctx->children.size(); i++) {
visit(ctx->children[i]);
}
return nullptr;
}
any visitDefinition(BParser::DefinitionContext *ctx) override {
visit(ctx->children[0]);
return nullptr;
}
any visitFuncdef(BParser::FuncdefContext *ctx) override {
// Handle function definition
string functionName = ctx->name(0)->getText();
cout << "auto " << functionName << "(" ;
// You can retrieve and visit the parameter list using ctx->name(i)
for (int i=1; i < ctx->name().size(); i++) {
if (i != 1) cout << ", ";
cout << "auto " << ctx->name(i)->getText();
}
cout << ")";
any visitStatement(BParser::StatementContext *ctx) override {
visit(ctx->children[0]);
return nullptr;
}
any visitAutostmt(BParser::AutostmtContext *ctx) override {
// You can retrieve the variable names and constants using ctx->name(i) and ctx->constant(i)
cout << "auto ";
for (int i=0, j=0; i < ctx->name().size(); i++) {
if (i != 0) cout << " ,";
cout << ctx->name(i)->getText();
int idx_assn = 1 + i*2 + j*2 + 1; // auto name (= const)?, name (= const)?, ...
if (ctx->children[idx_assn]->getText().compare("=") == 0) {
if (ctx->constant(j)) {
cout << " = ";
visit(ctx->constant(j));
j++;
}
}
}
cout << ";" << endl;
return nullptr;
// You can retrieve and visit the parameter type list
for (int i=1; i < ctx->AUTO().size(); i++) {
if (i != 1) cout << ", ";
cout << "auto ";
}
cout << ");" << endl;
return nullptr;
}
any visitBlockstmt(BParser::BlockstmtContext *ctx) override {
// Perform some actions when visiting a block statement
cout << "{" << endl;
for (auto stmt : ctx->statement()) {
visit(stmt);
}
cout << "}" << endl;
return nullptr;
}
class ProgramContext;
class DirectiveContext;
class DefinitionContext;
class AutostmtContext;
class DeclstmtContext;
class FuncdefContext;
class BlockstmtContext;
class StatementContext;
class IfstmtContext;
class WhilestmtContext;
class ExpressionstmtContext;
class ReturnstmtContext;
class NullstmtContext;
class ExprContext;
class AtomContext;
class ExpressionContext;
class FuncinvocationContext;
class ConstantContext;
class NameContext;
// By default the static state used to implement the parser is lazily initialized during the first
// call to the constructor. You can call this function if you wish to initialize the static state
// ahead of time.
static void initialize();
private:
};
This is a content of input0.b .
/* input0.b */
auto a, b = 10;
auto fn(auto, auto);
auto main()
{
auto i, j, phi = 3.14;
auto a;
{
auto x;
}
while(true) {
auto y;
if (y) {
auto z;
} else {
}
}
}
auto fn(auto x, auto y) {
}
When I execute this code with ./b2c input0.b ,
--- Symbol Table --- _global_
(name) a, (type) auto
(name) b, (type) int
(name) fn, (type) function | auto(auto, auto)
(name) main, (type) function | auto()
--- Symbol Table --- fn
--- Symbol Table --- fn_6
--- Symbol Table --- main
(name) a, (type) auto
(name) i, (type) auto
(name) j, (type) auto
(name) phi, (type) double
(name) x, (type) auto
(name) y, (type) auto
(name) z, (type) auto
--- Symbol Table --- main_1
--- Symbol Table --- main_2
--- Symbol Table --- main_3
--- Symbol Table --- main_4
--- Symbol Table --- main_5
is printed in Step 1.
I should modify the code to print the output
--- Symbol Table --- _global_
(name) a, (type) auto
(name) b, (type) int
(name) fn, (type) function | auto (auto, auto)
(name) main, (type) function | auto ()
--- Symbol Table --- main
(name) i, (type) auto
(name) j, (type) auto
(name) phi, (type) double
(name) a, (type) auto
--- Symbol Table --- main_$1
(name) x, (type) auto
--- Symbol Table --- main_$2
(name) y, (type) auto
--- Symbol Table --- main_$2_1
(name) z, (type) auto
--- Symbol Table --- main_$2_2
--- Symbol Table --- fn
(name) x, (type) auto
(name) y, (type) auto
to be printed in Step 1.
I think I have to control all the scopes (such as if statement, while statement, {}, ...) in making symbol table. How can I modify this SymbolTableVisitor class code to activate the output in Step 1 correctly?
To achieve the correct output in Step 1 as per your requirement, modifications are needed in SymbolTableVisitor class, specifically in how you handle scopes such as if statements, while statements, and blocks {} to properly maintain hierarchical scoping and naming of the symbol tables.
Here's an approach to achieve this:
General Idea:
Use a stack to keep track of the current scope. Push a new scope onto the stack when entering a new block ({}), if statement, or while statement, and pop it when exiting those blocks. This helps you to know the current scope at any given point and assists in finding or creating the correct symbol tables.
Augment block names by appending the count of blocks as a suffix and reset this count when needed. Additionally, differentiate between different kinds of blocks (normal blocks, if blocks, while blocks) to form the correct hierarchy.
Modifications:
Scope Tracking: Introduce a stack to track scope names. This will help in building hierarchical names for nested scopes.
Hierarchical Naming for Scopes: Modify the visitBlockstmt, visitIfstmt, and visitWhilestmt methods to create hierarchical names and symbol tables correctly.
Here's how you can implement these suggestions:
Scope Stack:
First, add a stack<string> scopeNames; to your SymbolTableVisitor class to track the scope names. Initialize this stack with a global scope entry in the constructor.
class SymbolTableVisitor : public BBaseVisitor {
private:
stack<string> scopeNames;
//... existing members ...
public:
SymbolTableVisitor() {
// Initialize scope with global scope
scopeNames.push(_GlobalFuncName_);
}
//... existing methods ...
};
Handling Scopes:
Modify the visitBlockstmt, visitIfstmt, and visitWhilestmt methods and anywhere you need to manage scopes.
For the visitBlockstmt method:
any visitBlockstmt(BParser::BlockstmtContext *ctx) override {
// Generate hierarchical scope name
string parentScope = scopeNames.top();
string currentScope = parentScope + "_$" + to_string(blockCounter++);
scopeNames.push(currentScope);
SymbolTable* blockSymTab = new SymbolTable();
symTabs[currentScope] = blockSymTab;
for (auto stmt : ctx->statement())
visit(stmt);
scopeNames.pop(); // Exiting the block
return nullptr;
}
Adapt Other Methods:
Similar to the visitBlockstmt, for visitIfstmt and visitWhilestmt, you need to track entry and exit from these scopes by manipulating the scopeNames stack and blockCounter accordingly. Also, ensure to create symbol tables for each scope encountered during traversal.
To manage this better, create utility functions for entering/exiting scopes if the code gets repetitive.
Important Note:
The modifications provided here are conceptual and might need adjustments according to your actual grammar definitions in ANTLR and the specific requirements of your implementation (like handling the visitFuncdef method correctly with scopes).
Remember, managing scope names with stack operations is crucial for achieving hierarchical naming convention as per your output requirements. This involves careful handling when entering new scopes (pushing to scopeNames stack) and exiting them (popping from scopeNames stack).