예제 #1
0
int main() {
    symboltable *table;
    initTypeDescList();
    initPredefinedSymboltable();
    initScope();
    printSymbolTable(predefinedIdTable);
    
    printf("type %d\n", getType("integer"));
    
    entryAttr attr;
    scope *curScope = getCurScope();
    table = getCurSymboltable();
    registerSymbol(table, "a", NULL);
    registerSymbol(table, "test", NULL);
    
    printf("scopeid: %d \n", curScope->scopeId);
    printSymbolTable(getCurSymboltable());
    printf("\n");
    
    int addr = getSymbolEntry(getCurSymboltable(), "a");
    if(getType("integer") >= 0) {
        setSymbolTypeAttrDirec(getCurSymboltable(), addr, "integer", attr);
    }
    printf("scopeid: %d \n", curScope->scopeId);
    printSymbolTable(getCurSymboltable());

    printf("error: %d\n", setSymbolTypeAttrDirec(getCurSymboltable(), addr, "string", attr));
    
    attr.arrayInfo.boundLow = 1;
    attr.arrayInfo.boundUp = 10;
    attr.arrayInfo.typeEntry = 23;
    registerSymbol(getCurSymboltable(), "b", "array");
    printSymbolTable(getCurSymboltable());
    setSymbolTypeAttrDirec(getCurSymboltable(), getSymbolEntry(getCurSymboltable(), "b"), "array", attr);
    
    printSymbolTable(getCurSymboltable());
    
    attr.funcInfo.paramQty = 2;
    attr.funcInfo.retTypeEntry = 23;
    registerSymbol(getCurSymboltable(), "func1", "function");
    setSymbolTypeAttrDirec(getCurSymboltable(), getSymbolEntry(getCurSymboltable(), "func1"), "function", attr);
    
    newScopeAndPush(getSymbolEntry(getCurSymboltable(), "func1"));
    
    registerSymbol(getCurSymboltable(), "a", "integer");
    
    popScopeStack();
    
    registerSymbol(getCurSymboltable(), "var1", "string");
    
    printf("\n");
    printAllSymbolTable();
    return 0;
}
예제 #2
0
파일: ProblemSet1_2.c 프로젝트: dw6/NUS
int main() {
	readInput();
	if ( tokenize() ) {
		printSymbolTable();
	}
	
}
예제 #3
0
/**
 * Print the symbol table in the specified format.
 * @param list
 */
void printSymbolTable(STList list)
{
	int a = 0;
	STList readList = list;
	while(readList != NULL)
	{
		STable entry = readList->table;
		while(entry->data != NULL)
		{
			printf("%20s%16s(%2d-%2d)%16s",entry->data->value,readList->functionName,readList->startLineNumber,readList->endLineNumber,getTokenName(entry->data->type));
			if(entry->data->type == NUM || entry->data->type == INT)
			{
				printf("%s","    ");
				printf("%15d",a);
				a = a+2;
			}
			else if(entry->data->type == RNUM || entry->data->type == REAL)
			{
				printf("%s","    ");
				printf("%15d",a);
				a= a+4;
			}
			else if(entry->data->type == STR || entry->data->type == STRING)
			{
				printf("%s","    ");
				printf("%15d",a);
				a = a + findLength(entry->data->value,readList,0);
			}
			else if(entry->data->type == MATRIX)
			{
				matrixSizes mat = findMatrix(entry->data->value,readList);
				if(mat == NULL)
				{
					printf(",0,0");
				}
				else
				{
					printf(",%d,%d",mat->rows,mat->columns);
				}
			}
			printf("\n");
			entry = entry->nextEntry;
		}
		if(readList->childList != NULL)
			printSymbolTable(readList->childList);
		if(readList->sisterList != NULL)
			readList = readList->sisterList;
		else
			readList = NULL;
	}
}
예제 #4
0
파일: analyze.c 프로젝트: canslab/cminus
/* Function buildSymtab constructs the symbol 
 * table by preorder traversal of the syntax tree
 */
void buildSymtab(TreeNode * syntaxTree)
{
	// input & output already in symbol table
	insertBultinFunctions(&syntaxTree);

	traverse(syntaxTree, insertNode, nullProc);

	if (TraceAnalyze)
	{
		fprintf(listing, "\nSymbol table:\n\n");
		printSymbolTable(listing);
	}

	if (st_lookup_atCharScope("", "main") == NULL)
	{
		fprintf(listing, "\nThere should be main function !\n");
		exit(-4);
	}

}
예제 #5
0
int main(void)
{
	FILE *progFile,*outputFile,*opcode,*ADFile;
	
	progFile = fopen("input.txt","r");
	opcode = fopen("opcode.txt","r");
	outputFile = fopen("obj.o", "w");
	ADFile = fopen("AssemblyDirectives.txt","r");
	
	fgets(assemblyDirectives,30,ADFile);

	
	//int hexTest = 0x16;
	//hexTest = hexTest << 16;
	//int hexLocTest = 0x1033;
	//unsigned int opcodeTest = hexTest | hexLocTest;
	//printf("Opcode Test:%x",opcodeTest);
	populateOpcode(opcode);

	
	lineByLine(progFile);
	
	rewind(progFile);
	symbolAddresses(progFile);
	

	printSymbolTable();

	rewind(progFile);
	setSymbolAddresses(progFile);
	



	lineOp[lineNum-1] = 0;//End of the file has a 0x00 opcode
	rewind(progFile);
	writeObjFile(progFile,outputFile);
	fclose(progFile);
	fclose(outputFile);
	fclose(opcode);
}
예제 #6
0
void GLSLVisitor::printGlobalSymbolTable() {
    unsigned int depth = 0;

    std::list<GLSLSymbolMap*> children;
    GLSLSymbolMap* child = &globalSymbols_;
    while (child != 0)
    {
        const SymbolMap& symbols = child->getSymbolsMap();
        printSymbolTable(child->getName(), symbols, depth);

        const std::list<GLSLSymbolMap*>& c = child->getChildTables();
        if (! c.empty())
            children.insert(children.end(), c.begin(), c.end());

        if (! children.empty())
        {
            child = children.front();
            children.pop_front();
        }
        else
            child = 0;
    }
}
예제 #7
0
//enters a new symbol into the symbol table
// kind: const = 1, var = 2, proc = 3
void ENTER(int kind)
{
    //ensures a symbol is in the symbol table once
    int i;
    for(i = 0; i < numOfSymbols; i++)
    {
        if(strcmp(symbol_table[i].name, IDENTIFIER) == 0 && symbol_table[i].level == lexiLevel)
        {
            printf("%s %d\n", IDENTIFIER, lexiLevel);
            printSymbolTable();
            ERROR("Error number 27, an identifier has been declared multiple times.");
        }
    }

    symbol_table[numOfSymbols].kind = kind;
    strcpy(symbol_table[numOfSymbols].name, IDENTIFIER);
    symbol_table[numOfSymbols].level = lexiLevel;

    if(kind == 1)
    {
        symbol_table[numOfSymbols].val = NUMBER;
        symbol_table[numOfSymbols].addr = 0;
    }
    if(kind == 2)
    {
        symbol_table[numOfSymbols].addr = 4 + numOfVariablesInLexiLevel();
    }
    if(kind == 3)
    {
        //lines + 1 because of the jmp statement
        symbol_table[numOfSymbols].addr = lines+1;
    }

    numOfSymbols++;

}
예제 #8
0
int main(int argc, char** argv)
{

	////////////////Basic Printing/////////////////////////
	//printf("Submitted by Batch No. 06:\n%30s\t(%s)\n%30s\t(%s)\n\n\n", "Abhinav Bhatia", "2011A7PS371P", "Mukul Bhutani ", "2011A7PS343P");
	
	printf("LEVEL %d: %s", 3, "AST/Symbol Table/Type checking/Symantic Rules modules work\n");
	printf("Code generation implemented for most constructs\n\n");
	////////////////Basic Printing End/////////////////////

	FILE* pSourceFile = NULL;
	int choice;
	int isParsed = PARSER_NOT_INVOKED;


	if (argc > 1)
	{
		pSourceFile = fopen(argv[1], "r");
	}
	else if (argc == 1)
	{
		printf("\nLess number of arguments ...Two arguments required....\n");
		printf("1. Source Code File.\n");
		printf("2. File for printing parse tree.\n");

		char c;
		scanf("%c", &c);
		return 0;
	}

	if (pSourceFile == NULL)
	{
		printf("\nError: No Input File!\nExiting...........");
		char c;
		scanf("%c", &c);
		return -1;
	}

	FILE* pKeywordsFile = fopen(KEYWORDS_INPUT_FILENAME, "r");
	if (!pKeywordsFile)
	{
		printf("\nError: keywords file \"%s\" not found.\nExiting..........", KEYWORDS_INPUT_FILENAME);
		char c;
		scanf("%c", &c);
		return -1;
	}
	FILE* grammarInputFile = fopen(GRAMMAR_INPUT_FILENAME, "r");
	if (!grammarInputFile)
	{
		printf("\nError: Grammar file \"%s\" not found.\nExiting..........", GRAMMAR_INPUT_FILENAME);
		char c;
		scanf("%c", &c);
		return -1;
	}
	FILE* astRulesFile = fopen(AST_RULES_FILENAME, "r");
	if (!astRulesFile)
	{
		printf("\nError: AST Rules file \"%s\" not found.\nExiting..........", AST_RULES_FILENAME);
		char c;
		scanf("%c", &c);
		return -1;
	}

	Parser parser;
	Lexer lex = lexer_createNew(pSourceFile, pKeywordsFile);


	printf("\n\nPlease enter your choice\n");
	printf("1. Print list of tokens.\n");
	printf("2. Verify syntactic correctness of input source code.\n");
	printf("3. Print Abstract Syntax Tree.\n");
	printf("4. Print Symbol Table.\n");
	printf("5. Verify syntactic and semantic correctness.\n");
	printf("6. Produce Assembly Code.\n");
	printf("7. Exit.\n");

	char flushChar;
	scanf("%d%c", &choice, &flushChar);
	switch (choice)
	{
	case 1:
		lexer_runLexicalAnalyses(lex);
		break;
	case 2:
		parser = parser_initialise(grammarInputFile, astRulesFile);

		isParsed = printOnlyParsetree(&parser, lex, DEFAULT_OUTPUT_PARSE_TREE_FILE, isParsed);
		break;
	case 3:
		parser = parser_initialise(grammarInputFile, astRulesFile);
		isParsed = parseOnlySourceCode(&parser, lex);
		if (isParsed == PARSED_SUCCESSFULLY)
		{
			Tree ast = createAst(parser);
			printAST(ast);
		}
		break;
	case 4:
		parser = parser_initialise(grammarInputFile, astRulesFile);
		isParsed = parseOnlySourceCode(&parser, lex);
		if (isParsed == PARSED_SUCCESSFULLY)
		{
			Tree ast = createAst(parser);
			createSymbolTables(ast);
			turnOnReportingSemanticErrors(FALSE);
			typeExtractorandChecker(ast);
			printSymbolTable();
		}
		break;
	case 5:
		parser = parser_initialise(grammarInputFile, astRulesFile);
		isParsed = parseOnlySourceCode(&parser, lex);
		if (isParsed == PARSED_SUCCESSFULLY)
		{
			Tree ast = createAst(parser);
			createSymbolTables(ast);
			printf("\n\nRunning semantic analysis....");
			turnOnReportingSemanticErrors(TRUE);
			if (typeExtractorandChecker(ast))
			{
				printf("\n\nCode compiles successfully..........:)");
			}
		}
		break;
	case 6:
		parser = parser_initialise(grammarInputFile, astRulesFile);
		isParsed = parseOnlySourceCode(&parser, lex);
		if (isParsed == PARSED_SUCCESSFULLY)
		{
			Tree ast = createAst(parser);
			createSymbolTables(ast);
			turnOnReportingSemanticErrors(TRUE);
			if (typeExtractorandChecker(ast))
			{
				printf("\n\nCode compiles successfully..........:)");
				printf("\n\nGenerating Code......");
				FILE* asmm = fopen(argv[2], "w");
				generateCode(ast, asmm);
				printf("\n\nFinished code generation.");
				//Call code generation here
			}
		}
		break;
	case 7:
		return 0;
		break;
	default:
		printf("Invalid Choice...please enter correct choice (1-7)");
		break;
	}

	char c;
	scanf("%c", &c);
	return 0;
}
예제 #9
0
/**
 * Second compiler transition is building the code array and locating the extrens/entries usages
 * Algorithm
 * 1. reset ic = 0
 * 2. read next line
 * 3. ignore label on the beginning of line
 * 4. is it .data/.string go to step 2
 * 5. is it .extern or .entry (if not go to step 7)
 * 6. if it's .entry order mark is as entry in the symbols table and return to step 2
 * 7. calculate the command code byte and the oprand/s byte/s
 * 8. store the command & operand/s next bytes in the code AssemblyBytes
 * 8.1 in case of 2 operands with REGISTER addressing they share the same byte in the code AssemblyBytes
 * 9. in crease the ic by the calulated amount
 * 10. return to step 2
 *
 * In case of a failure in the second transitions stop the file processing.
 *
 * @param fileContent
 * @param assembly final struct to fill with symbols and bytes, should be FULL by the end of the method
 * @return Status (Pass/Fail)
 */
Status runSecondTransition(FileContent *fileContent, AssemblyStructure *assembly) {
    int i;
    FileLine line;
    assembly->ic = ASSEMBLY_CODE_START_ADDRESS;

    for (i=0; i < fileContent->size; i++) { /* For every line in file */
        line = fileContent->line[i];

        if(DEBUG) {
            printSymbolTable(assembly->symbolsTable);
            printSymbolTable(assembly->externs);
            printAssemblyByte(assembly->codeArray);
            printAssemblyByte(assembly->dataArray);
        }

        /* Step: 4 */
        if (line.actionType == DATA || line.actionType == STRING) {
            /* do nothing */
            continue;
        }

        /* Step: 5 */
        if (line.actionType == EXTERN || line.actionType == ENTRY) {
            if (line.actionType == ENTRY) {
                if (setLabelIsEntryInTable(assembly->symbolsTable, line.firstOperValue->entryOrExtern) == false) {
                    printCompileError(errMessage(ERR_LABEL_NOT_DEFINED, line.firstOperValue->entryOrExtern), fileContent->filename, line.lineNumber);
                    return Fail;
                }
            }
        }
        /* handle command */
        else {
            /*  101 - num of command operands (2b) - command opcode (4b) - src addressing type (2b) - dest addressing type (2b) - E,R,A (2b) */
            char* errStr;
            int binCmd = buildBinaryCommand(line);
            bool isMemAllocOk = pushByteFromInt(assembly->codeArray, binCmd); /* add cmd to code array */
            assembly->ic++;
            /*  0000000000000-00 (data 13b - E,R,A (2b)) */
            /* Building Code Array */
            if (line.numOfCommandOprands == 1){ /* if one operand */
                int binData = 0;
                errStr = buildBinaryData(&binData, line.firstOperValue, assembly->symbolsTable, assembly->externs, true, assembly->ic);
                if (errStr != NULL) { /* if there was an issue in building binary data of first operand, throw error */
                    printCompileError(errStr, fileContent->filename, line.lineNumber);
                    return Fail;
                }
                isMemAllocOk &= pushByteFromInt(assembly->codeArray, binData); /* add first operand byte array to code array */
                assembly->ic++;
            }
            else if (line.numOfCommandOprands == 2) { /* if 2 operands */
                int firstBinData = 0, secondBinData = 0;
                errStr = buildBinaryData(&firstBinData, line.firstOperValue, assembly->symbolsTable, assembly->externs, false, assembly->ic); /* calculate first operand byte array */
                if (errStr != NULL) { /* if there was an issue in building binary data of first operand, throw error */
                    printCompileError(errStr, fileContent->filename, line.lineNumber);
                    return Fail;
                }
                errStr = buildBinaryData(&secondBinData, line.secondOperValue, assembly->symbolsTable, assembly->externs, true, assembly->ic+1); /* calculate second operand byte array */
                if (errStr != NULL) { /* if there was an issue in building binary data of first operand, throw error */
                    printCompileError(errStr, fileContent->filename, line.lineNumber);
                    return Fail;
                }
                if (line.firstOperValue->addressingType == REGISTER && line.secondOperValue->addressingType == REGISTER){ /* if both operands are registers, they share a byte array */
                    isMemAllocOk &= pushByteFromInt(assembly->codeArray, firstBinData + secondBinData);
                    assembly->ic++;
                }
                else{
                    isMemAllocOk &= pushByteFromInt(assembly->codeArray, firstBinData);
                    isMemAllocOk &= pushByteFromInt(assembly->codeArray, secondBinData);
                    assembly->ic += 2;
                }
            }

            if(isMemAllocOk == false){ /* if there is an issue with memory allocation, throw error */
                printInternalError(ERR_CODE_RAM_OVERFLOW, fileContent->filename);
                return Fail;
            }
        }

    }
    return Pass; /* Done and ready to save assembly files! */
}