home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / nethack-3.1 / sys / unix / cpp2.shr / cpp4.c < prev   
Encoding:
C/C++ Source or Header  |  1993-01-26  |  16.0 KB  |  589 lines

  1. /*
  2.  *                C P P 4 . C
  3.  *        M a c r o  D e f i n i t i o n s
  4.  *
  5.  * Edit History
  6.  * 31-Aug-84    MM    USENET net.sources release
  7.  * 04-Oct-84    MM    __LINE__ and __FILE__ must call ungetstring()
  8.  *            so they work correctly with token concatenation.
  9.  *            Added string formal recognition.
  10.  * 25-Oct-84    MM    "Short-circuit" evaluate #if's so that we
  11.  *            don't print unnecessary error messages for
  12.  *            #if !defined(FOO) && FOO != 0 && 10 / FOO ...
  13.  * 31-Oct-84    ado/MM    Added token concatenation
  14.  *  6-Nov-84    MM    Split off eval stuff
  15.  */
  16.  
  17. #include    <stdio.h>
  18. #include    <ctype.h>
  19. #include    "cppdef.h"
  20. #include    "cpp.h"
  21. /*
  22.  * parm[], parmp, and parlist[] are used to store #define() argument
  23.  * lists.  nargs contains the actual number of parameters stored.
  24.  */
  25. static char    parm[NPARMWORK + 1];    /* define param work buffer     */
  26. static char    *parmp;            /* Free space in parm        */
  27. static char    *parlist[LASTPARM];    /* -> start of each parameter    */
  28. static int    nargs;            /* Parameters for this macro    */
  29.  
  30. dodefine()
  31. /*
  32.  * Called from control when a #define is scanned.  This module
  33.  * parses formal parameters and the replacement string.  When
  34.  * the formal parameter name is encountered in the replacement
  35.  * string, it is replaced by a character in the range 128 to
  36.  * 128+NPARAM (this allows up to 32 parameters within the
  37.  * Dec Multinational range).  If cpp is ported to an EBCDIC
  38.  * machine, you will have to make other arrangements.
  39.  *
  40.  * There is some special case code to distinguish
  41.  *    #define foo    bar
  42.  * from    #define foo()    bar
  43.  *
  44.  * Also, we make sure that
  45.  *    #define    foo    foo
  46.  * expands to "foo" but doesn't put cpp into an infinite loop.
  47.  *
  48.  * A warning message is printed if you redefine a symbol to a
  49.  * different text.  I.e,
  50.  *    #define    foo    123
  51.  *    #define foo    123
  52.  * is ok, but
  53.  *    #define foo    123
  54.  *    #define    foo    +123
  55.  * is not.
  56.  *
  57.  * The following subroutines are called from define():
  58.  * checkparm    called when a token is scanned.  It checks through the
  59.  *        array of formal parameters.  If a match is found, the
  60.  *        token is replaced by a control byte which will be used
  61.  *        to locate the parameter when the macro is expanded.
  62.  * textput    puts a string in the macro work area (parm[]), updating
  63.  *        parmp to point to the first free byte in parm[].
  64.  *        textput() tests for work buffer overflow.
  65.  * charput    puts a single character in the macro work area (parm[])
  66.  *        in a manner analogous to textput().
  67.  */
  68. {
  69.     register int        c;
  70.     register DEFBUF        *dp;        /* -> new definition    */
  71.     int            isredefine;    /* TRUE if redefined    */
  72.     char            *old;        /* Remember redefined    */
  73.     extern int        save();        /* Save char in work[]    */
  74.  
  75.     if (type[(c = skipws())] != LET)
  76.         goto bad_define;
  77.     isredefine = FALSE;            /* Set if redefining    */
  78.     if ((dp = lookid(c)) == NULL)        /* If not known now    */
  79.         dp = defendel(token, FALSE);    /* Save the name    */
  80.     else {                    /* It's known:        */
  81.         isredefine = TRUE;            /* Remember this fact    */
  82.         old = dp->repl;            /* Remember replacement    */
  83.         dp->repl = NULL;            /* No replacement now    */
  84.     }
  85.     parlist[0] = parmp = parm;        /* Setup parm buffer    */
  86.     if ((c = get()) == '(') {        /* With arguments?    */
  87.         nargs = 0;                /* Init formals counter    */
  88.         do {                /* Collect formal parms    */
  89.         if (nargs >= LASTPARM)
  90.             cfatal("Too many arguments for macro", NULLST);
  91.         else if ((c = skipws()) == ')')
  92.             break;            /* Got them all        */
  93.         else if (type[c] != LET)    /* Bad formal syntax    */
  94.             goto bad_define;
  95.         scanid(c);            /* Get the formal param    */
  96.         parlist[nargs++] = parmp;    /* Save its start    */
  97.         textput(token);            /* Save text in parm[]    */
  98.         } while ((c = skipws()) == ',');    /* Get another argument    */
  99.         if (c != ')')            /* Must end at )    */
  100.         goto bad_define;
  101.         c = ' ';                /* Will skip to body    */
  102.     }
  103.     else {
  104.         /*
  105.          * DEF_NOARGS is needed to distinguish between
  106.          * "#define foo" and "#define foo()".
  107.          */
  108.         nargs = DEF_NOARGS;            /* No () parameters    */
  109.     }
  110.     if (type[c] == SPA)            /* At whitespace?    */
  111.         c = skipws();            /* Not any more.    */
  112.     workp = work;                /* Replacement put here    */
  113.     inmacro = TRUE;                /* Keep \<newline> now    */
  114.     while (c != EOF_CHAR && c != '\n') {    /* Compile macro body    */
  115. #if OK_CONCAT
  116.         if (c == '#') {            /* Token concatenation?    */
  117.         while (workp > work && type[workp[-1]] == SPA)
  118.             --workp;            /* Erase leading spaces    */
  119.         save(TOK_SEP);            /* Stuff a delimiter    */
  120.         c = skipws();            /* Eat whitespace    */
  121.         if (type[c] == LET)        /* Another token here?    */
  122.             ;                /* Stuff it normally    */
  123.         else if (type[c] == DIG) {    /* Digit string after?    */
  124.             while (type[c] == DIG) {    /* Stuff the digits    */
  125.             save(c);
  126.             c = get();
  127.             }
  128.             save(TOK_SEP);        /* Delimit 2nd token    */
  129.         }
  130.         else {
  131.             ciwarn("Strange character after # (%d.)", c);
  132.         }
  133.         continue;
  134.         }
  135. #endif
  136.         switch (type[c]) {
  137.         case LET:
  138.         checkparm(c, dp);        /* Might be a formal    */
  139.         break;
  140.  
  141.         case DIG:                /* Number in mac. body    */
  142.         case DOT:                /* Maybe a float number    */
  143.         scannumber(c, save);        /* Scan it off        */
  144.         break;
  145.  
  146.         case QUO:                /* String in mac. body    */
  147. #if STRING_FORMAL
  148.         stparmscan(c, dp);        /* Do string magic    */
  149. #else
  150.         stparmscan(c);
  151. #endif
  152.         break;
  153.  
  154.         case BSH:                /* Backslash        */
  155.         save('\\');
  156.         if ((c = get()) == '\n')
  157.             wrongline = TRUE;
  158.         save(c);
  159.         break;
  160.  
  161.         case SPA:                /* Absorb whitespace    */
  162.         /*
  163.          * Note: the "end of comment" marker is passed on
  164.          * to allow comments to separate tokens.
  165.          */
  166.         if (workp[-1] == ' ')        /* Absorb multiple    */
  167.             break;            /* spaces        */
  168.         else if (c == '\t')
  169.             c = ' ';            /* Normalize tabs    */
  170.         /* Fall through to store character            */
  171.         default:                /* Other character    */
  172.         save(c);
  173.         break;
  174.         }
  175.         c = get();
  176.     }
  177.     inmacro = FALSE;            /* Stop newline hack    */
  178.     unget();                /* For control check    */
  179.     if (workp > work && workp[-1] == ' ')    /* Drop trailing blank    */
  180.         workp--;
  181.     *workp = EOS;                /* Terminate work    */
  182.     dp->repl = savestring(work);        /* Save the string    */
  183.     dp->nargs = nargs;            /* Save arg count    */
  184. #if DEBUG
  185.     if (debug)
  186.         dumpadef("macro definition", dp);
  187. #endif
  188.     if (isredefine) {            /* Error if redefined    */
  189.         if ((old != NULL && dp->repl != NULL && !streq(old, dp->repl))
  190.          || (old == NULL && dp->repl != NULL)
  191.          || (old != NULL && dp->repl == NULL)) {
  192.         cerror("Redefining defined variable \"%s\"", dp->name);
  193.         }
  194.         if (old != NULL)            /* We don't need the    */
  195.         free(old);            /* old definition now.    */
  196.     }     
  197.     return;
  198.  
  199. bad_define:
  200.     cerror("#define syntax error", NULLST);
  201.     inmacro = FALSE;            /* Stop <newline> hack    */
  202. }
  203.  
  204. checkparm(c, dp)
  205. register int    c;
  206. DEFBUF        *dp;
  207. /*
  208.  * Replace this param if it's defined.  Note that the macro name is a
  209.  * possible replacement token.  We stuff DEF_MAGIC in front of the token
  210.  * which is treated as a LETTER by the token scanner and eaten by
  211.  * the output routine.  This prevents the macro expander from
  212.  * looping if someone writes "#define foo foo".
  213.  */
  214. {
  215.     register int        i;
  216.     register char        *cp;
  217.  
  218.     scanid(c);                /* Get parm to token[]    */
  219.     for (i = 0; i < nargs; i++) {        /* For each argument    */
  220.         if (streq(parlist[i], token)) {    /* If it's known    */
  221.         save(i + MAC_PARM);        /* Save a magic cookie    */
  222.         return;                /* And exit the search    */
  223.         }
  224.     }
  225.     if (streq(dp->name, token))        /* Macro name in body?    */
  226.         save(DEF_MAGIC);            /* Save magic marker    */
  227.     for (cp = token; *cp != EOS;)        /* And save        */
  228.         save(*cp++);            /* The token itself    */
  229. }
  230.  
  231. #if STRING_FORMAL
  232. stparmscan(delim, dp)
  233. int        delim;
  234. register DEFBUF    *dp;
  235. /*
  236.  * Scan the string (starting with the given delimiter).
  237.  * The token is replaced if it is the only text in this string or
  238.  * character constant.  The algorithm follows checkparm() above.
  239.  * Note that scanstring() has approved of the string.
  240.  */
  241. {
  242.     register int        c;
  243.  
  244.     /*
  245.      * Warning -- this code hasn't been tested for a while.
  246.      * It exists only to preserve compatibility with earlier
  247.      * implementations of cpp.  It is not part of the Draft
  248.      * ANSI Standard C language.
  249.      */
  250.     save(delim);
  251.     instring = TRUE;
  252.     while ((c = get()) != delim
  253.          && c != '\n'
  254.          && c != EOF_CHAR) {
  255.         if (type[c] == LET)            /* Maybe formal parm    */
  256.         checkparm(c, dp);
  257.         else {
  258.         save(c);
  259.         if (c == '\\')
  260.             save(get());
  261.         }
  262.     }
  263.     instring = FALSE;
  264.     if (c != delim)
  265.         cerror("Unterminated string in macro body", NULLST);
  266.     save(c);
  267. }
  268. #else
  269. stparmscan(delim)
  270. int        delim;
  271. /*
  272.  * Normal string parameter scan.
  273.  */
  274. {
  275.     register char        *wp;
  276.     register int        i;
  277.     extern int        save();
  278.  
  279.     wp = workp;            /* Here's where it starts    */
  280.     if (!scanstring(delim, save))
  281.         return;            /* Exit on scanstring error    */
  282.     workp[-1] = EOS;        /* Erase trailing quote        */
  283.     wp++;                /* -> first string content byte    */ 
  284.     for (i = 0; i < nargs; i++) {
  285.         if (streq(parlist[i], wp)) {
  286.         *wp++ = MAC_PARM + PAR_MAC;    /* Stuff a magic marker    */
  287.         *wp++ = (i + MAC_PARM);        /* Make a formal marker    */
  288.         *wp = wp[-3];            /* Add on closing quote    */
  289.         workp = wp + 1;            /* Reset string end    */
  290.         return;
  291.         }
  292.     }
  293.     workp[-1] = wp[-1];        /* Nope, reset end quote.    */
  294. }
  295. #endif
  296.  
  297. doundef()
  298. /*
  299.  * Remove the symbol from the defined list.
  300.  * Called from the #control processor.
  301.  */
  302. {
  303.     register int        c;
  304.  
  305.     if (type[(c = skipws())] != LET)
  306.         cerror("Illegal #undef argument", NULLST);
  307.     else {
  308.         scanid(c);                /* Get name to token[]    */
  309.         if (defendel(token, TRUE) == NULL) {
  310.         cwarn("Symbol \"%s\" not defined in #undef", token);
  311.         }
  312.     }
  313. }
  314.  
  315. textput(text)
  316. char        *text;
  317. /*
  318.  * Put the string in the parm[] buffer.
  319.  */
  320. {
  321.     register int    size;
  322.  
  323.     size = strlen(text) + 1;
  324.     if ((parmp + size) >= &parm[NPARMWORK])
  325.         cfatal("Macro work area overflow", NULLST);
  326.     else {
  327.         strcpy(parmp, text);
  328.         parmp += size;
  329.     }
  330. }
  331.  
  332. charput(c)
  333. register int    c;
  334. /*
  335.  * Put the byte in the parm[] buffer.
  336.  */
  337. {
  338.     if (parmp >= &parm[NPARMWORK])
  339.         cfatal("Macro work area overflow", NULLST);
  340.     else {
  341.         *parmp++ = c;
  342.     }
  343. }
  344.  
  345. /*
  346.  *        M a c r o   E x p a n s i o n
  347.  */
  348.  
  349. static DEFBUF    *macro;        /* Catches start of infinite macro    */
  350.  
  351. expand(tokenp)
  352. register DEFBUF    *tokenp;
  353. /*
  354.  * Expand a macro.  Called from the cpp mainline routine (via subroutine
  355.  * macroid()) when a token is found in the symbol table.  It calls
  356.  * expcollect() to parse actual parameters, checking for the correct number.
  357.  * It then creates a "file" containing a single line containing the
  358.  * macro with actual parameters inserted appropriately.  This is
  359.  * "pushed back" onto the input stream.  (When the get() routine runs
  360.  * off the end of the macro line, it will dismiss the macro itself.)
  361.  */
  362. {
  363.     register int        c;
  364.     register FILEINFO    *file;
  365.     extern FILEINFO        *getfile();
  366.  
  367. #if DEBUG
  368.     if (debug)
  369.         dumpadef("expand entry", tokenp);
  370. #endif
  371.     /*
  372.      * If no macro is pending, save the name of this macro
  373.      * for an eventual error message.
  374.      */
  375.     if (recursion++ == 0)
  376.         macro = tokenp;
  377.     else if (recursion == RECURSION_LIMIT) {
  378.         cerror("Recursive macro definition of \"%s\"", tokenp->name);
  379.         fprintf(stderr, "(Defined by \"%s\")\n", macro->name);
  380.         if (rec_recover) {
  381.         do {
  382.             c = get();
  383.         } while (infile != NULL && infile->fp == NULL);
  384.         unget();
  385.         recursion = 0;
  386.         return;
  387.         }
  388.     }
  389.     /*
  390.      * Here's a macro to expand.
  391.      */
  392.     nargs = 0;                /* Formals counter    */
  393.     parmp = parm;                /* Setup parm buffer    */
  394.     switch (tokenp->nargs) {
  395.     case (-2):                /* __LINE__        */
  396.         sprintf(work, "%d", line);
  397.         ungetstring(work);
  398.         break;
  399.  
  400.     case (-3):                /* __FILE__        */
  401.         for (file = infile; file != NULL; file = file->parent) {
  402.         if (file->fp != NULL) {
  403.             sprintf(work, "\"%s\"", (file->progname != NULL)
  404.             ? file->progname : file->filename);
  405.             ungetstring(work);
  406.             break;
  407.         }
  408.         }
  409.         break;
  410.  
  411.     default:
  412.         /*
  413.          * Nothing funny about this macro.
  414.          */
  415.         if (tokenp->nargs < 0)
  416.         cfatal("Bug: Illegal __ macro \"%s\"", tokenp->name);
  417.         while ((c = skipws()) == '\n')    /* Look for (, skipping    */
  418.         wrongline = TRUE;        /* spaces and newlines    */
  419.         if (c != '(') {
  420.         /*
  421.          * If the programmer writes
  422.          *    #define foo() ...
  423.          *    ...
  424.          *    foo [no ()]
  425.          * just write foo to the output stream.
  426.          */
  427.         unget();
  428.         cwarn("Macro \"%s\" needs arguments", tokenp->name);
  429.         fputs(tokenp->name, stdout);
  430.         return;
  431.         }
  432.         else if (expcollect()) {        /* Collect arguments    */
  433.         if (tokenp->nargs != nargs) {    /* Should be an error?    */
  434.             cwarn("Wrong number of macro arguments for \"%s\"",
  435.             tokenp->name);
  436.         }
  437. #if DEBUG
  438.         if (debug)
  439.             dumpparm("expand");
  440. #endif
  441.         }                /* Collect arguments        */
  442.     case DEF_NOARGS:        /* No parameters just stuffs    */
  443.         expstuff(tokenp);        /* Do actual parameters        */
  444.     }                /* nargs switch            */
  445. }
  446.  
  447. FILE_LOCAL int
  448. expcollect()
  449. /*
  450.  * Collect the actual parameters for this macro.  TRUE if ok.
  451.  */
  452. {
  453.     register int    c;
  454.     register int    paren;            /* For embedded ()'s    */
  455.     extern int    charput();
  456.  
  457.     for (;;) {
  458.         paren = 0;                /* Collect next arg.    */
  459.         while ((c = skipws()) == '\n')    /* Skip over whitespace    */
  460.         wrongline = TRUE;        /* and newlines.    */
  461.         if (c == ')') {            /* At end of all args?    */
  462.         /*
  463.          * Note that there is a guard byte in parm[]
  464.          * so we don't have to check for overflow here.
  465.          */
  466.         *parmp = EOS;            /* Make sure terminated    */
  467.         break;                /* Exit collection loop    */
  468.         }
  469.         else if (nargs >= LASTPARM)
  470.         cfatal("Too many arguments in macro expansion", NULLST);
  471.         parlist[nargs++] = parmp;        /* At start of new arg    */
  472.         for (;; c = cget()) {        /* Collect arg's bytes    */
  473.         if (c == EOF_CHAR) {
  474.             cerror("end of file within macro argument", NULLST);
  475.             return (FALSE);        /* Sorry.        */
  476.         }
  477.         else if (c == '\\') {        /* Quote next character    */
  478.             charput(c);            /* Save the \ for later    */
  479.             charput(cget());        /* Save the next char.    */
  480.             continue;            /* And go get another    */
  481.         }
  482.         else if (type[c] == QUO) {    /* Start of string?    */
  483.             scanstring(c, charput);    /* Scan it off        */
  484.             continue;            /* Go get next char    */
  485.         }
  486.         else if (c == '(')        /* Worry about balance    */
  487.             paren++;            /* To know about commas    */
  488.         else if (c == ')') {        /* Other side too    */
  489.             if (paren == 0) {        /* At the end?        */
  490.             unget();        /* Look at it later    */
  491.             break;            /* Exit arg getter.    */
  492.             }
  493.             paren--;            /* More to come.    */
  494.         }
  495.         else if (c == ',' && paren == 0) /* Comma delimits args    */
  496.             break;
  497.         else if (c == '\n')        /* Newline inside arg?    */
  498.             wrongline = TRUE;        /* We'll need a #line    */
  499.         charput(c);            /* Store this one    */
  500.         }                    /* Collect an argument    */
  501.         charput(EOS);            /* Terminate argument    */
  502. #if DEBUG
  503.         if (debug)
  504.             printf("parm[%d] = \"%s\"\n", nargs, parlist[nargs - 1]);
  505. #endif
  506.     }                    /* Collect all args.    */
  507.     return (TRUE);                /* Normal return    */
  508. }
  509.  
  510. FILE_LOCAL
  511. expstuff(tokenp)
  512. DEFBUF        *tokenp;        /* Current macro being expanded    */
  513. /*
  514.  * Stuff the macro body, replacing formal parameters by actual parameters.
  515.  */
  516. {
  517.     register int    c;            /* Current character    */
  518.     register char    *inp;            /* -> repl string    */
  519.     register char    *defp;            /* -> macro output buff    */
  520.     int        size;            /* Actual parm. size    */
  521.     char        *defend;        /* -> output buff end    */
  522.     int        string_magic;        /* String formal hack    */
  523.     FILEINFO    *file;            /* Funny #include    */
  524.     extern FILEINFO    *getfile();
  525.  
  526.     file = getfile(NBUFF, tokenp->name);
  527.     inp = tokenp->repl;            /* -> macro replacement    */
  528.     defp = file->buffer;            /* -> output buffer    */
  529.     defend = defp + (NBUFF - 1);        /* Note its end        */
  530.     if (inp != NULL) {
  531.         while ((c = (*inp++ & 0xFF)) != EOS) {
  532.         if (c >= MAC_PARM && c <= (MAC_PARM + PAR_MAC)) {
  533.             string_magic = (c == (MAC_PARM + PAR_MAC));
  534.             if (string_magic)
  535.              c = (*inp++ & 0xFF);
  536.             /*
  537.              * Replace formal parameter by actual parameter string.
  538.              */
  539.             if ((c -= MAC_PARM) < nargs) {
  540.             size = strlen(parlist[c]);
  541.             if ((defp + size) >= defend)
  542.                 goto nospace;
  543.             /*
  544.              * Erase the extra set of quotes.
  545.              */
  546.             if (string_magic && defp[-1] == parlist[c][0]) {
  547.                 strcpy(defp-1, parlist[c]);
  548.                 defp += (size - 2);
  549.             }
  550.             else {
  551.                 strcpy(defp, parlist[c]);
  552.                 defp += size;
  553.             }
  554.             }
  555.         }
  556.         else if (defp >= defend) {
  557. nospace:        cfatal("Out of space in macro \"%s\" arg expansion",
  558.             tokenp->name);
  559.         }
  560.         else {
  561.             *defp++ = c;
  562.         }
  563.         }
  564.     }
  565.     *defp = EOS;
  566. #if DEBUG
  567.     if (debug > 1)
  568.         printf("macroline: \"%s\"\n", file->buffer);
  569. #endif
  570. }
  571.  
  572. #if DEBUG
  573. dumpparm(why)
  574. char        *why;
  575. /*
  576.  * Dump parameter list.
  577.  */
  578. {
  579.     register int    i;
  580.  
  581.     printf("dump of %d parameters (%d bytes total) %s\n",
  582.         nargs, parmp - parm, why);
  583.     for (i = 0; i < nargs; i++) {
  584.         printf("parm[%d] (%d) = \"%s\"\n",
  585.         i + 1, strlen(parlist[i]), parlist[i]);
  586.     }
  587. }
  588. #endif
  589.