/****************************************************/
/* File: main.c                                     */
/* Main program for TINY compiler                   */
/* Compiler Construction: Principles and Practice   */
/* Kenneth C. Louden                                */
/****************************************************/

#include "GLOBALS.H"

/* set NO_PARSE to TRUE to get a scanner-only compiler */
#define NO_PARSE FALSE

#include "UTIL.H"
#if NO_PARSE
#include "scan.h"
#else
#include "PARSE.H"
#endif

/* allocate global variables */
int lineno = 0;
FILE * source;
FILE * listing;
FILE * code;

/* allocate and set tracing flags */
int EchoSource = TRUE;
int TraceScan = TRUE;
int TraceParse = TRUE;
int TraceCode = TRUE;

int Error = FALSE;

int main(int argc, char * argv[]) {
    TreeNode * syntaxTree;
    char pgm[120]; /* source code file name */
    if (argc != 2) {
        fprintf(stderr,"usage: %s <filename>\n",argv[0]);
        exit(1);
    }
    strcpy(pgm,argv[1]) ;
    if (strchr (pgm, '.') == NULL) {
        strcat(pgm,".tny");
    }
    source = fopen(pgm,"r");
    if (source==NULL) {
        fprintf(stderr,"File %s not found\n",pgm);
        exit(1);
    }
    listing = stdout; /* send listing to screen */
    fprintf(listing,"\nTINY COMPILATION: %s\n",pgm);
  #if NO_PARSE
    while (getToken() != ENDFILE);
  #else
    lexicalAnalysisHeader();
    syntaxTree = parse(); // 词法分析
    if (TraceParse) { //语法分析
        syntacticAnalysisHeader();
        fprintf(listing,"Syntax tree:\n");
        printTree(syntaxTree);
    }
    if (TraceCode) { //语义分析
        semanticAnalysisHeader();
        generateMidCode(syntaxTree);
    }
    footer();
    
  #endif
    fclose(source);
    return 0;
}
