home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The World of Computer Software
/
World_Of_Computer_Software-02-385-Vol-1of3.iso
/
p
/
pccts.zip
/
antlr
/
main.c
< prev
next >
Wrap
C/C++ Source or Header
|
1992-12-08
|
13KB
|
500 lines
/*
* main.c -- main program for PCCTS ANTLR.
*
* SOFTWARE RIGHTS
*
* We reserve no LEGAL rights to the Purdue Compiler Construction Tool
* Set (PCCTS) -- PCCTS is in the public domain. An individual or
* company may do whatever they wish with source code distributed with
* PCCTS or the code generated by PCCTS, including the incorporation of
* PCCTS, or its output, into commerical software.
*
* We encourage users to develop software with PCCTS. However, we do ask
* that credit is given to us for developing PCCTS. By "credit",
* we mean that if you incorporate our source code into one of your
* programs (commercial product, research project, or otherwise) that you
* acknowledge this fact somewhere in the documentation, research report,
* etc... If you like PCCTS and have developed a nice tool with the
* output, please mention that you developed it using PCCTS. In
* addition, we ask that this header remain intact in our source code.
* As long as these guidelines are kept, we expect to continue enhancing
* this system and expect to make other tools available as they are
* completed.
*
* ANTLR 1.06
* Terence Parr
* Purdue University
* 1989-1992
*/
#include <stdio.h>
#include "set.h"
#include "syn.h"
#include "hash.h"
#include "generic.h"
#include "antlr.h"
#include "tokens.h"
#include "dlgdef.h"
#define MAX_INT_STACK 50
static int istack[MAX_INT_STACK]; /* Int stack */
static int isp = MAX_INT_STACK;
/* C m d - L i n e O p t i o n S t r u c t & F u n c s */
typedef struct _Opt {
char *option;
int arg;
void (*process)();
char *descr;
} Opt;
extern int ProcessArgs();
static void
pFile(s)
char *s;
{
if ( *s=='-' ) { warnNoFL( eMsg1("invalid option: '%s'",s) ); return; }
require(NumFiles<MaxNumFiles,"exceeded max # of input files");
FileStr[NumFiles++] = s;
}
static void
pLLK(s,t)
char *s,*t;
{
OutputLL_k = LL_k = atoi(t);
if ( LL_k <= 0 ) {
warnNoFL("must have at least one token of look-ahead (setting to 1)");
LL_k = 1;
}
if ( ((LL_k-1)&LL_k)!=0 ) { /* output ll(k) must be power of 2 */
int n;
for(n=1; n<LL_k; n<<=1) {;}
OutputLL_k = n;
}
}
static void pCGen() { CodeGen = FALSE; LexGen = FALSE; }
static void pLGen() { LexGen = FALSE; }
static void pTGen() { TraceGen = TRUE; }
static void pSGen() { GenExprSets = FALSE; }
static void pPrt() { PrintOut = TRUE; pCGen(); pLGen(); }
static void pPrtA() { PrintOut = TRUE; PrintAnnotate = TRUE; pCGen(); pLGen(); }
static void pAst() { GenAST = TRUE; }
static void pANSI() { GenANSI = TRUE; }
static void pCr() { GenCR = TRUE; }
static void pLI() { GenLineInfo = TRUE; }
static void pFe(s,t) char *s, *t; {ErrFileName = t;}
static void pFl(s,t) char *s, *t; {DlgFileName = t;}
static void pFt(s,t) char *s, *t; {DefFileName = t;}
static void pE1() { elevel = 1; }
static void pE2() { elevel = 2; }
static void pE3() { elevel = 3; }
static void pEGen() { GenEClasseForRules = 1; }
static void pDL() { DemandLookahead = 1; }
static void pGHdr() { GenStdPccts = 1; }
static void pPre(s,t) char *s, *t; { RulePrefix = t; }
static void pFHdr(s,t) char *s, *t; { stdpccts = t; pGHdr(); }
static void
pPred()
{
ParseWithPredicates = 1;
if ( DemandLookahead )
warnNoFL("-gk conflicts with -pr; -gk turned off");
DemandLookahead = 0;
}
static void pTRes(s,t)
char *s, *t;
{
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[] = {
{ "-cr", 0, pCr, "Generate cross reference (default=FALSE)"},
{ "-e1", 0, pE1, "Ambiguities/errors shown in low detail (default)"},
{ "-e2", 0, pE2, "Ambiguities/errors shown in more detail"},
{ "-e3", 0, pE3, "Ambiguities/errors shown in excrutiating detail"},
{ "-fe", 1, pFe, "Rename err.c"},
{ "-fh", 1, pFHdr, "Rename stdpccts.h header (turns on -gh)"},
{ "-fl", 1, pFl, "Rename lexical output--parser.dlg"},
{ "-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 'til needed"},
{ "-gl", 0, pLI, "Generate line info about grammar actions in C parser"},
{ "-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)"},
{ "-k", 1, pLLK, "Set k of LL(k) -- tokens of look-ahead (default==1)"},
{ "-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, "Turn on use of predicates in parsing decisions (alpha version)"},
{ "-rl", 1, pTRes, "Limit max # of tree nodes used by grammar analysis"},
{ "*", 0, pFile, "" }, /* anything else is a file */
{ NULL, 0, NULL }
};
void readDescr();
void cleanUp();
static void help(), init(), buildRulePtr();
/* M a i n */
main(argc,argv)
int argc;
char *argv[];
{
static char EPSTR[] = "[Ep]";
fprintf(stderr, "Antlr parser generator Version %s 1989-1992\n", Version);
if ( argc == 1 ) { help(); return 1; }
ProcessArgs(argc-1, &(argv[1]), options);
fpTrans = &(C_Trans[0]); /* Translate to C Language */
fpJTrans = &(C_JTrans[0]);
init();
lexclass(LexStartSymbol);
readDescr();
if ( CannotContinue ) {cleanUp(); return 1;}
if ( HdrAction == NULL ) warnNoFL("no #header action was found");
EpToken = addTname(EPSTR); /* add imaginary token epsilon */
set_size(NumWords(TokenNum-1));
if ( CodeGen ) genDefFile(); /* create tokens.h */
if ( LexGen ) genLexDescr(); /* create parser.dlg */
if ( GenStdPccts )
{
FILE *f = fopen(stdpccts, "w");
if ( f==NULL ) {warnNoFL( eMsg1("can't create %s",stdpccts) );}
else
{
genStdPCCTSIncludeFile(f);
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();
return 1;
}
else
{
ErrFile = fopen(ErrFileName, "w");
require(ErrFile != NULL, "main: can't open err file");
NewSetWd();
GenErrHdr();
TRANS(SynDiag); /* Translate to the target language */
DumpSetWd();
fclose( ErrFile );
}
}
if ( PrintOut )
{
if ( SynDiag == NULL ) {warnNoFL("no grammar description recognized");}
else PRINT(SynDiag);
}
cleanUp();
return 0; /* report all is well for make etc... */
}
static void
init()
{
Tname = newHashTable();
Rname = newHashTable();
Fcache = newHashTable();
Tcache = newHashTable();
TokenStr = (char **) calloc(TSChunk, sizeof(char *));
require(TokenStr!=NULL, "main: cannot allocate TokenStr");
FoStack = (int **) calloc(LL_k+1, sizeof(int *));
require(FoStack!=NULL, "main: cannot allocate FoStack");
FoTOS = (int **) calloc(LL_k+1, sizeof(int *));
require(FoTOS!=NULL, "main: cannot allocate FoTOS");
Cycles = (ListNode **) calloc(LL_k+1, sizeof(ListNode *));
require(Cycles!=NULL, "main: cannot allocate Cycles List");
}
static
void
help()
{
Opt *p = options;
fprintf(stderr, "antlr [options] f1 f2 ... fn\n");
while ( *(p->option) != '*' )
{
fprintf(stderr, "\t%s %s\t%s\n",
p->option,
(p->arg)?"___":" ",
p->descr);
p++;
}
}
/* The RulePtr array is filled in here. RulePtr exists primarily
* so that sets of rules can be maintained for the FOLLOW caching
* mechanism found in rJunc(). RulePtr maps a rule num from 1 to n
* to a pointer to its RuleBlk junction where n is the number of rules.
*/
static void
buildRulePtr()
{
int r=1;
Junction *p = SynDiag;
RulePtr = (Junction **) calloc(NumRules+1, sizeof(Junction *));
require(RulePtr!=NULL, "cannot allocate RulePtr array");
while ( p!=NULL )
{
require(r<=NumRules, "too many rules???");
RulePtr[r++] = p;
p = (Junction *)p->p2;
}
}
void
readDescr()
{
input = NextFile();
require(input!=NULL, "No grammar description found (exiting...)");
ANTLR(grammar(), input);
}
FILE *
NextFile()
{
FILE *f;
for (;;)
{
CurFile++;
if ( CurFile >= NumFiles ) return(NULL);
f = fopen(FileStr[CurFile], "r");
if ( f == NULL )
{
warnNoFL( eMsg1("file %s doesn't exist; ignored", FileStr[CurFile]) );
}
else
{
/* aSourceFile = FileStr[CurFile];
* Doesn't seem to be used
*/
return(f);
}
}
}
/*
* Return a string corresponding to the output file name associated
* with the input file name passed in.
*
* Observe the following rules:
*
* f.e --> f".c"
* f --> f".c"
* f. --> f".c"
* f.e.g --> f.e".c"
*
* Where f,e,g are arbitrarily long sequences of characters in a file
* name.
*
* In other words, if a ".x" appears on the end of a file name, make it
* ".c". If no ".x" appears, append ".c" to the end of the file name.
*
* Use malloc() for new string.
*/
char *
outname(fs)
char *fs;
{
static char buf[MaxFileName+1];
char *p;
p = buf;
strcpy(buf, fs);
while ( *p != '\0' ) {p++;} /* Stop on '\0' */
while ( *p != '.' && p != buf ) {--p;} /* Find '.' */
if ( p != buf ) *p = '\0'; /* Found '.' */
require(strlen(buf) + 2 < MaxFileName, "outname: filename too big");
strcat(buf, ".c");
return( buf );
}
void
fatalFL(err,f,l)
char *err, *f;
int l;
{
fprintf(stderr, ErrHdr, f, l);
fprintf(stderr, " %s\n", err);
cleanUp();
exit(-1);
}
void
cleanUp()
{
if ( DefFile != NULL) fclose( DefFile );
}
/* sprintf up to 3 strings */
char *
eMsg3(s,a1,a2,a3)
char *s, *a1, *a2, *a3;
{
static char buf[250]; /* DANGEROUS as hell !!!!!! */
sprintf(buf, s, a1, a2, a3);
return( buf );
}
/* sprintf a decimal */
char *
eMsgd(s,d)
char *s;
int d;
{
static char buf[250]; /* DANGEROUS as hell !!!!!! */
sprintf(buf, s, d);
return( buf );
}
void
s_fprT(f, e)
FILE *f;
set e;
{
register unsigned *p;
unsigned *q;
if ( set_nil(e) ) return;
if ( (q=p=set_pdq(e)) == NULL ) fatal("Can't alloc space for set_pdq");
fprintf(f, "{");
while ( *p != nil )
{
fprintf(f, " %s", TerminalString(*p));
p++;
}
fprintf(f, " }");
free(q);
}
/* Return the token name or regular expression for a token number. */
char *
TerminalString(token)
int token;
{
int j;
/* look in all lexclasses for the token */
if ( TokenStr[token] != NULL ) return TokenStr[token];
for (j=0; j<NumLexClasses; j++)
{
lexmode(j);
if ( ExprStr[token] != NULL ) return ExprStr[token];
}
require(j<NumLexClasses, eMsgd("No label or expr for token %d",token));
return "invalid";
}
/* S i m p l e I n t S t a c k */
void
pushint(i)
int i;
{
require(isp>0, "pushint: stack overflow");
istack[--isp] = i;
}
int
popint()
{
require(isp<MAX_INT_STACK, "popint: stack underflow");
return istack[isp++];
}
int
istacksize()
{
return MAX_INT_STACK-isp;
}
void
istackreset()
{
isp = MAX_INT_STACK;
}
int
istackempty()
{
return isp==MAX_INT_STACK;
}
int
topint()
{
require(isp<MAX_INT_STACK, "topint: stack underflow");
return istack[isp];
}
ProcessArgs(argc, argv, options)
int argc;
char **argv;
Opt *options;
{
Opt *p;
require(argv!=NULL, "ProcessArgs: command line NULL");
while ( argc-- > 0 )
{
p = options;
while ( p->option != NULL )
{
if ( strcmp(p->option, "*") == 0 ||
strcmp(p->option, *argv) == 0 )
{
if ( p->arg )
{
(*p->process)( *argv, *(argv+1) );
argv++;
argc--;
}
else
(*p->process)( *argv );
break;
}
p++;
}
argv++;
}
}