main.c

来自「SRI international 发布的OAA框架软件」· C语言 代码 · 共 1,748 行 · 第 1/4 页

C
1,748
字号
}

static void
#ifdef __USE_PROTOS
pMRhoist( char *s, char *t )
#else
pMRhoist(s,t)
char *s;
char *t;
#endif
{
	if ( ci_strequ(t,"on")) MRhoisting = 1;
	else if ( ci_strequ(t,"off")==0 ) MRhoisting = 0;
    if (MRhoisting) {
        fprintf(stderr,"Maintenance Release style hoisting enabled for predicates with lookahead depth = 1\n");
        fprintf(stderr,"  No longer considered experimental\n");
        fprintf(stderr,"  Can't consider suppression for predicates with lookahead depth > 1\n");
        fprintf(stderr,"  Implies -prc on but does *not* imply -mrhoistk for k>1 predicates\n");
        fprintf(stderr,"  This is a reminder, not a warning or error.\n");
    };
}

static void
#ifdef __USE_PROTOS
pMRhoistk( char *s, char *t )
#else
pMRhoistk(s,t)
char *s;
char *t;
#endif
{
	if ( ci_strequ(t,"on")) MRhoistingk = 1;
	else if ( ci_strequ(t,"off")==0 ) MRhoistingk = 0;
    if (MRhoistingk) {
        fprintf(stderr,"EXPERIMENTAL Maintenance Release style hoisting enabled\n");
        fprintf(stderr,"  Applies to predicates with lookahead depth > 1\n");
        fprintf(stderr,"  Implies -prc on and -mrhoist on\n");
    };
}

static void
#ifdef __USE_PROTOS
pTRes( char *s, char *t )
#else
pTRes( s, t )
char *s;
char *t;
#endif
{
	TreeResourceLimit = atoi(t);
	if ( TreeResourceLimit <= 0 )
	{
		warnNoFL("analysis resource limit (# of tree nodes) must be greater than 0");
		TreeResourceLimit = -1; /* set to no limit */
	}
}

Opt options[] = {
#ifdef __cplusplus
    { "-CC", 0, (void (*)(...)) pCC,	"Generate C++ output (default=FALSE)"},
    { "-ck", 1, (void (*)(...)) pCk,	"Set compressed lookahead depth; fast approximate lookahead"},
    { "-cr", 0, (void (*)(...)) pCr,	"Generate cross reference (default=FALSE)"},
    { "-e1", 0, (void (*)(...)) pE1,	"Ambiguities/errors shown in low detail (default)"},
    { "-e2", 0, (void (*)(...)) pE2,	"Ambiguities/errors shown in more detail"},
    { "-e3", 0, (void (*)(...)) pE3,
    	"Ambiguities for k>1 grammars shown with exact tuples (not lookahead sets)"},
    { "-f",  1, (void (*)(...)) pFileList,"Read names of grammar files from specified file"}, /* MR14 */
    { "-fe", 1, (void (*)(...)) pFe,	"Rename err.c"},
    { "-fh", 1, (void (*)(...)) pFHdr,	"Rename stdpccts.h header (turns on -gh)"},
    { "-fl", 1, (void (*)(...)) pFl,	"Rename lexical output--parser.dlg"},
    { "-fm", 1, (void (*)(...)) pFm,	"Rename mode.h"},
    { "-fr", 1, (void (*)(...)) pFr,	"Rename remap.h"},
    { "-ft", 1, (void (*)(...)) pFt,	"Rename tokens.h"},
    { "-ga", 0, (void (*)(...)) pANSI,	"Generate ANSI-compatible code (default=FALSE)"},
    { "-gc", 0, (void (*)(...)) pCGen,	"Do not generate output parser code (default=FALSE)"},
    { "-gd", 0, (void (*)(...)) pTGen,	"Generate code to trace rule invocation (default=FALSE)"},
    { "-ge", 0, (void (*)(...)) pEGen,	"Generate an error class for each non-terminal (default=FALSE)"},
    { "-gh", 0, (void (*)(...)) pGHdr,	"Generate stdpccts.h for non-ANTLR-generated-files to include"},
    { "-gk", 0, (void (*)(...)) pDL,	"Generate parsers that delay lookahead fetches until needed"},
    { "-gl", 0, (void (*)(...)) pLI,	"Generate line info about grammar actions in parser"},
    { "-glms", 0, (void (*)(...)) pLIms,"Like -gl but replace '\\' with '/' in #line filenames for MS C/C++ systems"},
    { "-gp", 1, (void (*)(...)) pPre,	"Prefix all generated rule functions with a string"},
    { "-gs", 0, (void (*)(...)) pSGen,	"Do not generate sets for token expression lists (default=FALSE)"},
    { "-gt", 0, (void (*)(...)) pAst,	"Generate code for Abstract-Syntax-Trees (default=FALSE)"},
    { "-gx", 0, (void (*)(...)) pLGen,	"Do not generate lexical (dlg-related) files (default=FALSE)"},
    { "-gxt",0, (void (*)(...)) pXTGen,	"Do not generate tokens.h (default=FALSE)"},
    { "-k",  1, (void (*)(...)) pLLK,	"Set full LL(k) lookahead depth (default==1)"},
    { "-o",  1, (void (*)(...)) pOut,	OutputDirectoryOption},
    { "-p",  0, (void (*)(...)) pPrt,	"Print out the grammar w/o actions (default=no)"},
    { "-pa", 0, (void (*)(...)) pPrtA,	"Print out the grammar w/o actions & w/FIRST sets (default=no)"},
    { "-pr",0, (void (*)(...)) pPred,	"no longer used; predicates employed if present"},
    { "-prc", 1, (void (*)(...)) pPredCtx,"Turn on/off computation of context for hoisted predicates"},
   	{ "-rl", 1, (void (*)(...)) pTRes,	"Limit max # of tree nodes used by grammar analysis"},
    { "-stdout",0,  (void (*)(...)) pStdout,"Send grammar.c/grammar.cpp to stdout"},           /* MR6 */
	{ "-tab", 1, (void (*)(...)) pTab,	"Width of tabs (1 to 8) for grammar.c/grammar.cpp files"}, /* MR6 */
	{ "-w1", 0, (void (*)(...)) pW1,	"Set the warning level to 1 (default)"},
	{ "-w2", 0, (void (*)(...)) pW2,	"Ambiguities yield warnings even if predicates or (...)? block"},
	{ "-",   0, (void (*)(...)) pStdin,	"Read grammar from stdin" },
    { "-mrhoist",1, (void (*)(...)) pMRhoist,                                                  /* MR9 */
                                        "Turn on/off k=1 Maintenance Release style hoisting"},  /* MR9 */
    { "-mrhoistk",1, (void (*)(...)) pMRhoistk,                                                  /* MR9 */
                                        "Turn on/off EXPERIMENTAL k>1 Maintenance Release style hoisting"},  /* MR13 */
    { "-aa"  , 1, (void (*)(...)) pAA,  "Ambiguity aid for a rule (rule name or line number)"},          /* MR11 */
    { "-aam" , 0, (void (*)(...)) pAAm,
                                         "Lookahead token may appear multiple times in -aa listing"},    /* MR11 */
    { "-aad" , 1, (void (*)(...)) pAAd,
                                         "Limits exp growth of -aa listing - default=1 (max=ck value)"}, /* MR11 */
	{ "-info", 1, (void (*)(...)) pInfo,
      "Extra info: p=pred t=tnodes f=first/follow m=monitor o=orphans 0=noop"},                          /* MR12 */
    { "-treport",1,(void (*)(...)) pTreport,
                        "Report when tnode usage exceeds value during ambiguity resolution"},            /* MR11 */
	{ "-newAST", 0, (void (*)(...)) pNewAST,
                 "In C++ mode use \"newAST(...)\" rather than \"new AST(...)\""},                        /* MR13 */
	{ "-tmake", 0, (void (*)(...)) ptmakeInParser,
                 "In C++ mode use parser's tmake method rather than \"ASTBase::tmake(...)\""},			 /* MR23 */
    { "-alpha",0,(void (*)(...)) pAlpha,
                 "Provide additional information for \"(alpha)? beta\" error messages"},                 /* MR14 */
    { "-mrblkerr",0,(void (*)(...)) pMR_BlkErr,                                        /* MR21 */
                 "EXPERIMENTAL change to (...)* and (...)+ syntax error sets"},        /* MR21 */
	{ "-nopurify",0,(void (*)(...)) pNOPURIFY,
		"Don't use the notorious PURIFY macro (replaced by MR23 initial value syntax) to zero return arguments of rules"},   /* MR23 */
    { "*",   0, (void (*)(...)) pFile, 	"" },	/* anything else is a file */
#else
    { "-CC", 0, pCC,	"Generate C++ output (default=FALSE)"},
    { "-cr", 0, pCr,	"Generate cross reference (default=FALSE)"},
    { "-ck", 1, pCk,	"Set compressed lookahead depth; fast approximate lookahead"},
    { "-e1", 0, pE1,	"Ambiguities/errors shown in low detail (default)"},
    { "-e2", 0, pE2,	"Ambiguities/errors shown in more detail"},
    { "-e3", 0, pE3,   	"Ambiguities for k>1 grammars shown with exact tuples (not lookahead sets)"},
    { "-f",  1, pFileList,"Read names of grammar files from specified file"},   /* MR14 */
    { "-fe", 1, pFe,	"Rename err.c"},
    { "-fh", 1, pFHdr,	"Rename stdpccts.h header (turns on -gh)"},
    { "-fl", 1, pFl,	"Rename lexical output--parser.dlg"},
    { "-fm", 1, pFm,	"Rename mode.h"},
    { "-fr", 1, pFr,	"Rename remap.h"},
    { "-ft", 1, pFt,	"Rename tokens.h"},
    { "-ga", 0, pANSI,	"Generate ANSI-compatible code (default=FALSE)"},
    { "-gc", 0, pCGen,	"Do not generate output parser code (default=FALSE)"},
    { "-gd", 0, pTGen,	"Generate code to trace rule invocation (default=FALSE)"},
    { "-ge", 0, pEGen,	"Generate an error class for each non-terminal (default=FALSE)"},
    { "-gh", 0, pGHdr,	"Generate stdpccts.h for non-ANTLR-generated-files to include"},
    { "-gk", 0, pDL,	"Generate parsers that delay lookahead fetches until needed"},
    { "-gl", 0, pLI,	"Generate line info about grammar actions in C parser"},
    { "-glms", 0, pLIms,"Like -gl but replace '\\' with '/' in #line filenames for MS C/C++ systems"},
    { "-gp", 1, pPre,	"Prefix all generated rule functions with a string"},
    { "-gs", 0, pSGen,	"Do not generate sets for token expression lists (default=FALSE)"},
    { "-gt", 0, pAst,	"Generate code for Abstract-Syntax-Trees (default=FALSE)"},
    { "-gx", 0, pLGen,	"Do not generate lexical (dlg-related) files (default=FALSE)"},
    { "-gxt",0, pXTGen,	"Do not generate tokens.h (default=FALSE)"},
    { "-k",  1, pLLK,	"Set full LL(k) lookahead depth (default==1)"},
    { "-o",  1, pOut,	OutputDirectoryOption},
    { "-p",  0, pPrt,	"Print out the grammar w/o actions (default=no)"},
    { "-pa", 0, pPrtA,	"Print out the grammar w/o actions & w/FIRST sets (default=no)"},
    { "-pr",0, pPred,	"no longer used; predicates employed if present"},
    { "-prc", 1, pPredCtx,"Turn on/off computation of context for hoisted predicates"},
    { "-rl", 1, pTRes,	"Limit max # of tree nodes used by grammar analysis"},
    { "-stdout",0, pStdout,	"Send grammar.c/grammar.cpp to stdout"},               /* MR6 */
    { "-tab", 1, pTab,	"Width of tabs (1 to 8) for grammar.c/grammar.cpp files"}, /* MR6 */
	{ "-w1", 0, pW1,	"Set the warning level to 1 (default)"},
	{ "-w2", 0, pW2,	"Ambiguities yield warnings even if predicates or (...)? block"},
    { "-mrhoist",1,pMRhoist,                                                       /* MR9 */
                         "Turn on/off k=1 Maintenance Release style hoisting"},  /* MR9 */
    { "-mrhoistk",1,pMRhoistk,                                                       /* MR13 */
                         "Turn on/off k>1 EXPERIMENTAL Maintenance Release style hoisting"},  /* MR13 */
    { "-aa"  ,1,pAA,     "Ambiguity aid for a rule (rule name or line number)"},          /* MR11 */
    { "-aam" ,0,pAAm,
                         "Lookahead token may appear multiple times in -aa listing"},     /* MR11 */
    { "-aad" ,1,pAAd,
                         "Limits exp growth of -aa listing - default=1 (max=ck value)"},  /* MR11 */
	{ "-info",1,pInfo,
      "Extra info: p=pred t=tnodes f=first/follow m=monitor o=orphans 0=noop"},           /* MR11 */
    { "-treport",1,pTreport,
                        "Report when tnode usage exceeds value during ambiguity resolution"},   /* MR11 */
	{ "-newAST", 0, pNewAST,
                 "In C++ mode use \"newAST(...)\" rather than \"new AST(...)\""},         /* MR13 */
	{ "-tmake", 0, ptmakeInParser,
                 "In C++ mode use parser's tmake method rather than \"ASTBase::tmake(...)\""},   /* MR23 */
    { "-alpha",0, pAlpha,
                 "Provide additional information for \"(alpha)? beta\" error messages"},  /* MR14 */
    { "-mrblkerr",0,pMR_BlkErr,                                                           /* MR21 */
                 "EXPERIMENTAL change to (...)* and (...)+ syntax error sets"},           /* MR21 */
	{ "-nopurify",0,pNOPURIFY,
		"Don't use the notorious PURIFY macro (replaced by MR23 initial value syntax) to zero return arguments of rules"},   /* MR23 */
	{ "-",   0, pStdin,	"Read grammar from stdin" },
	{ "*",   0, pFile, 	"" },	/* anything else is a file */
#endif
	{ NULL,  0, NULL }
 };

void readDescr();
void cleanUp();

#ifdef __USE_PROTOS
static void buildRulePtr( void );
static void help( void );
static void init( void );
static void CompleteTokenSetRefs( void );
static void ensure_no_C_file_collisions(char *);
static void CompleteContextGuards(void);
#else
static void buildRulePtr( );
static void help( );
static void init( );
static void CompleteTokenSetRefs( );
static void ensure_no_C_file_collisions();
static void CompleteContextGuards();
#endif

static void
#ifdef __USE_PROTOS  /* <BJS> */
report_numericPredLabels(ActionNode *a)
#else
report_numericPredLabels(a)
ActionNode *a;
#endif
{                                                                           /* MR10 */
  warnFL("numeric references to attributes (e.g. $i or $i.j) in semantic pred will be null during guess mode",  /* MR10 */
            FileStr[a->file],a->line);                                      /* MR10 */
}                                                                           /* MR10 */

								/* M a i n */

int
#ifdef __USE_PROTOS
main( int argc, char *argv[] )
#else
main( argc, argv )
int argc;
char *argv[];
#endif
{
	int i;
	static char EPSTR[] = "[Ep]";

    Save_argc=argc;                                                  /* MR10 */
    Save_argv=argv;                                                  /* MR10 */

/*	malloc_debug(8);*/

#ifdef SPECIAL_INITS
    special_inits();                                                 /* MR1 */
#endif
	fprintf(stderr, "Antlr parser generator   Version %s   1989-2001\n", Version);
	if ( argc == 1 ) { help(); zzDIE; }
	ProcessArgs(argc-1, &(argv[1]), options);

/* MR14 */    if (MR_AmbAidRule && AlphaBetaTrace) {
/* MR14 */       fatal("Can't specify both -aa (ambiguity aid) and -alpha (\"(alpha)? beta\" aid)");
/* MR14 */    }

    if (MRhoistingk) {              /* MR13 */
      HoistPredicateContext=1;      /* MR13 */
      MRhoisting=1;                 /* MR13 */
    };                              /* MR13 */
    if (MRhoisting && ! HoistPredicateContext) {
/***      warnNoFL("Using \"-mrhoist\" forces \"-prc on\"");    ***/
      HoistPredicateContext=1;
    };
    if (HoistPredicateContext && ! MRhoisting) {
        warnNoFL("When using predicate context (-prc on) -mrhoist on is recommended");
    }
	/* Fix lookahead depth */
	/* Compressed lookahead must always be larger than or equal to full lookahead */
	if ( CLL_k < LL_k  && CLL_k>0 )
	{
		warnNoFL("must have compressed lookahead >= full LL(k) lookahead (setting -ck to -k)");
		CLL_k = LL_k;
	}
	if ( CLL_k == -1 ) CLL_k = LL_k;
	OutputLL_k = CLL_k;
	if ( ((CLL_k-1)&CLL_k)!=0 ) { /* output ll(k) must be power of 2 */
		int n;
		for(n=1; n<CLL_k; n<<=1) {;}
		OutputLL_k = n;
	};

	if (MR_BlkErr) {
		warnNoFL("The -mrblkerr option is EXPERIMENTAL");
        if (LL_k > 1) {
    		warnNoFL("The -mrblkerr option is designed only for k=1 ck=1 grammars");
        }
	};

    if ( ! ambAidDepthSpecified) {
      MR_AmbAidDepth=1;
    } else {
      if (MR_AmbAidDepth > CLL_k || MR_AmbAidDepth <= 0) {
        warnNoFL(eMsgd(
            "Ambiguity aid depth (\"-aad ...\") must be a number between 1 and max(k,ck)=%d",CLL_k));
        MR_AmbAidDepth=1;
      };
      if (MR_AmbAidDepth == 0) {
        MR_AmbAidDepth=2;
      };
    };

    if (MR_AmbAidRule != NULL) MR_AmbAidLine=atoi(MR_AmbAidRule);

	fpTrans = &(C_Trans[0]);		/* Translate to C Language */
	fpJTrans = &(C_JTrans[0]);
	init();
	lexclass(LexStartSymbol);

	readDescr();
	LastTokenCounted = TokenNum;
	RemapForcedTokens();
	if ( CannotContinue ) {cleanUp(); zzDIE;}
	if ( GenCC && no_classes_found ) fatal("required grammar class not found (exiting...)");
	if ( WarningLevel>1 && HdrAction == NULL )
	   warnNoFL("no #header action was found");
	if ( FoundAtOperator && ! FoundExceptionGroup) {
	   warnNoFL("found the exception operator '@' - but no exception group was found");
	};
	EpToken = addTname(EPSTR);		/* add imaginary token epsilon */
	set_orel(EpToken, &imag_tokens);

	/* this won't work for hand-built scanners since EofToken is not
	 * known.  Forces EOF to be token type 1.
	 */
	set_orel(EofToken, &imag_tokens);

	set_size(NumWords(TokenNum-1));

	/* compute the set of all known token types
	 * It represents the set of tokens from 1 to last_token_num + the
	 * reserved positions above that (if any).  Don't include the set of
	 * imaginary tokens such as the token/error classes or EOF.
	 */
	{
		set a;
		a = set_dup(reserved_positions);
		for (i=1; i<TokenNum; i++) { set_orel(i, &a); }
		all_tokens = set_dif(a, imag_tokens);
		set_free(a);
	}

	ComputeTokSets();				/* Compute #tokclass sets */
	CompleteTokenSetRefs();			/* Change complex nodes in syn diag */
    CompleteContextGuards();        /* MR13 */

	if ( CodeGen ) genDefFile();	/* create tokens.h */
	if ( LexGen ) genLexDescr();	/* create parser.dlg */

	if ( GenStdPccts )
	{
		FILE *f = fopen(OutMetaName(stdpccts), "w");
		if ( f==NULL ) {warnNoFL( eMsg1("can't create %s",OutMetaName(stdpccts)) );}
		else
		{
#ifdef SPECIAL_FOPEN
			special_fopen_actions(OutMetaName(stdpccts));            /* MR1 */
#endif
            if (strcmp(stdpccts,"stdpccts.h") == 0) {                /* MR10 */
 	  	      genStdPCCTSIncludeFile(f,NULL);                        /* MR10 */
            } else {                                                 /* MR10 */
 	  	      genStdPCCTSIncludeFile(f,pcctsBaseName(stdpccts));     /* MR32 */
            };
			fclose(f);
		}
	}

	buildRulePtr();					/* create mapping from rule # to RuleBlk junction */
	ComputeErrorSets();
	FoLink( (Node *)SynDiag );		/* add follow links to end of all rules */
	
	if ( GenCR ) GenCrossRef( SynDiag );

	if ( CodeGen )
	{
		if ( SynDiag == NULL )
		{
			warnNoFL("no grammar description recognized");
			cleanUp();
			zzDIE;
		}
		else if ( !GenCC ) {
			ErrFile = fopen(OutMetaName(ErrFileName), "w");
			require(ErrFile != NULL, "main: can't open err file");
#ifdef SPECIAL_FOPEN
	              special_fopen_actions(OutMetaName(ErrFileName));   /* MR1 */
#endif
			NewSetWd();
			GenErrHdr();
			TRANS(SynDiag);			/* Translate to the target language */
			DumpSetWd();
			DumpRemainingTokSets();
			fclose( ErrFile );
		}
		else {
			strcpy(Parser_h_Name, CurrentClassName);
			strcat(Parser_h_Name, ".h");
			strcpy(Parser_c_Name, CurrentClassName);
			strcat(Parser_c_Name, CPP_FILE_SUFFIX);
			ensure_no_C_file_collisions(Parser_c_Name);
			Parser_h = fopen(OutMetaName(Parser_h_Name), "w");
			require(Parser_h != NULL, "main: can't open class Parserx.h file");
#ifdef SPECIAL_FOPEN
		    special_fopen_actions(OutMetaName(Parser_h_Name));       /* MR1 */
#endif
			Parser_c = fopen(OutMetaName(Parser_c_Name), "w");
			require(Parser_c != NULL, "main: can't open class Parserx.c file");
#ifdef SPECIAL_FOPEN
		    special_fopen_actions(OutMetaName(Parser_c_Name));       /* MR1 */
#endif
			GenParser_h_Hdr();
			if ( class_before_actions != NULL )
			{
				ListNode *p;
				for (p = class_before_actions->next; p!=NULL; p=p->next)
				{
					UserAction *ua = (UserAction *)p->elem;
					dumpAction( ua->action, Parser_h, 0, ua->file, ua->line, 1);
				}
			}
			GenParser_c_Hdr();
			fprintf(Parser_h, "protected:\n");  /* MR20 */
			NewSetWd();
			TRANS(SynDiag);			/* Translate to the target language */
			DumpSetWd();
			GenRuleMemberDeclarationsForCC(Parser_h, SynDiag);
			if ( class_after_actions != NULL )
			{
				ListNode *p;
				for (p = class_after_actions->next; p!=NULL; p=p->next)
				{
					UserAction *ua = (UserAction *)p->elem;
					dumpAction( ua->action, Parser_h, 0, ua->file, ua->line, 1);
				}
			}
			DumpRemainingTokSets();
			fprintf(Parser_h, "};\n");
			fprintf(Parser_h, "\n#endif /* %s_h */\n", CurrentClassName);
			fclose( Parser_h );
			fclose( Parser_c );
		}
	}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?