home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / TOP / USR / SRC / cpp.decus.t.Z / cpp.decus.t / cpp4.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-03-06  |  16.1 KB  |  593 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. #ifdef OSK
  193.         cwarn("Redefining defined variable \"%s\"", dp->name);
  194. #else
  195.         cerror("Redefining defined variable \"%s\"", dp->name);
  196. #endif
  197.         }
  198.         if (old != NULL)            /* We don't need the    */
  199.         free(old);            /* old definition now.    */
  200.     }     
  201.     return;
  202.  
  203. bad_define:
  204.     cerror("#define syntax error", NULLST);
  205.     inmacro = FALSE;            /* Stop <newline> hack    */
  206. }
  207.  
  208. checkparm(c, dp)
  209. register int    c;
  210. DEFBUF        *dp;
  211. /*
  212.  * Replace this param if it's defined.  Note that the macro name is a
  213.  * possible replacement token.  We stuff DEF_MAGIC in front of the token
  214.  * which is treated as a LETTER by the token scanner and eaten by
  215.  * the output routine.  This prevents the macro expander from
  216.  * looping if someone writes "#define foo foo".
  217.  */
  218. {
  219.     register int        i;
  220.     register char        *cp;
  221.  
  222.     scanid(c);                /* Get parm to token[]    */
  223.     for (i = 0; i < nargs; i++) {        /* For each argument    */
  224.         if (streq(parlist[i], token)) {    /* If it's known    */
  225.         save(i + MAC_PARM);        /* Save a magic cookie    */
  226.         return;                /* And exit the search    */
  227.         }
  228.     }
  229.     if (streq(dp->name, token))        /* Macro name in body?    */
  230.         save(DEF_MAGIC);            /* Save magic marker    */
  231.     for (cp = token; *cp != EOS;)        /* And save        */
  232.         save(*cp++);            /* The token itself    */
  233. }
  234.  
  235. #if STRING_FORMAL
  236. stparmscan(delim, dp)
  237. int        delim;
  238. register DEFBUF    *dp;
  239. /*
  240.  * Scan the string (starting with the given delimiter).
  241.  * The token is replaced if it is the only text in this string or
  242.  * character constant.  The algorithm follows checkparm() above.
  243.  * Note that scanstring() has approved of the string.
  244.  */
  245. {
  246.     register int        c;
  247.  
  248.     /*
  249.      * Warning -- this code hasn't been tested for a while.
  250.      * It exists only to preserve compatibility with earlier
  251.      * implementations of cpp.  It is not part of the Draft
  252.      * ANSI Standard C language.
  253.      */
  254.     save(delim);
  255.     instring = TRUE;
  256.     while ((c = get()) != delim
  257.          && c != '\n'
  258.          && c != EOF_CHAR) {
  259.         if (type[c] == LET)            /* Maybe formal parm    */
  260.         checkparm(c, dp);
  261.         else {
  262.         save(c);
  263.         if (c == '\\')
  264.             save(get());
  265.         }
  266.     }
  267.     instring = FALSE;
  268.     if (c != delim)
  269.         cerror("Unterminated string in macro body", NULLST);
  270.     save(c);
  271. }
  272. #else
  273. stparmscan(delim)
  274. int        delim;
  275. /*
  276.  * Normal string parameter scan.
  277.  */
  278. {
  279.     register char        *wp;
  280.     register int        i;
  281.     extern int        save();
  282.  
  283.     wp = workp;            /* Here's where it starts    */
  284.     if (!scanstring(delim, save))
  285.         return;            /* Exit on scanstring error    */
  286.     workp[-1] = EOS;        /* Erase trailing quote        */
  287.     wp++;                /* -> first string content byte    */ 
  288.     for (i = 0; i < nargs; i++) {
  289.         if (streq(parlist[i], wp)) {
  290.         *wp++ = MAC_PARM + PAR_MAC;    /* Stuff a magic marker    */
  291.         *wp++ = (i + MAC_PARM);        /* Make a formal marker    */
  292.         *wp = wp[-3];            /* Add on closing quote    */
  293.         workp = wp + 1;            /* Reset string end    */
  294.         return;
  295.         }
  296.     }
  297.     workp[-1] = wp[-1];        /* Nope, reset end quote.    */
  298. }
  299. #endif
  300.  
  301. doundef()
  302. /*
  303.  * Remove the symbol from the defined list.
  304.  * Called from the #control processor.
  305.  */
  306. {
  307.     register int        c;
  308.  
  309.     if (type[(c = skipws())] != LET)
  310.         cerror("Illegal #undef argument", NULLST);
  311.     else {
  312.         scanid(c);                /* Get name to token[]    */
  313.         if (defendel(token, TRUE) == NULL) {
  314.         cwarn("Symbol \"%s\" not defined in #undef", token);
  315.         }
  316.     }
  317. }
  318.  
  319. textput(text)
  320. char        *text;
  321. /*
  322.  * Put the string in the parm[] buffer.
  323.  */
  324. {
  325.     register int    size;
  326.  
  327.     size = strlen(text) + 1;
  328.     if ((parmp + size) >= &parm[NPARMWORK])
  329.         cfatal("Macro work area overflow", NULLST);
  330.     else {
  331.         strcpy(parmp, text);
  332.         parmp += size;
  333.     }
  334. }
  335.  
  336. charput(c)
  337. register int    c;
  338. /*
  339.  * Put the byte in the parm[] buffer.
  340.  */
  341. {
  342.     if (parmp >= &parm[NPARMWORK])
  343.         cfatal("Macro work area overflow", NULLST);
  344.     else {
  345.         *parmp++ = c;
  346.     }
  347. }
  348.  
  349. /*
  350.  *        M a c r o   E x p a n s i o n
  351.  */
  352.  
  353. static DEFBUF    *macro;        /* Catches start of infinite macro    */
  354.  
  355. expand(tokenp)
  356. register DEFBUF    *tokenp;
  357. /*
  358.  * Expand a macro.  Called from the cpp mainline routine (via subroutine
  359.  * macroid()) when a token is found in the symbol table.  It calls
  360.  * expcollect() to parse actual parameters, checking for the correct number.
  361.  * It then creates a "file" containing a single line containing the
  362.  * macro with actual parameters inserted appropriately.  This is
  363.  * "pushed back" onto the input stream.  (When the get() routine runs
  364.  * off the end of the macro line, it will dismiss the macro itself.)
  365.  */
  366. {
  367.     register int        c;
  368.     register FILEINFO    *file;
  369.     extern FILEINFO        *getfile();
  370.  
  371. #if DEBUG
  372.     if (debug)
  373.         dumpadef("expand entry", tokenp);
  374. #endif
  375.     /*
  376.      * If no macro is pending, save the name of this macro
  377.      * for an eventual error message.
  378.      */
  379.     if (recursion++ == 0)
  380.         macro = tokenp;
  381.     else if (recursion == RECURSION_LIMIT) {
  382.         cerror("Recursive macro definition of \"%s\"", tokenp->name);
  383.         fprintf(stderr, "(Defined by \"%s\")\n", macro->name);
  384.         if (rec_recover) {
  385.         do {
  386.             c = get();
  387.         } while (infile != NULL && infile->fp == NULL);
  388.         unget();
  389.         recursion = 0;
  390.         return;
  391.         }
  392.     }
  393.     /*
  394.      * Here's a macro to expand.
  395.      */
  396.     nargs = 0;                /* Formals counter    */
  397.     parmp = parm;                /* Setup parm buffer    */
  398.     switch (tokenp->nargs) {
  399.     case (-2):                /* __LINE__        */
  400.         sprintf(work, "%d", line);
  401.         ungetstring(work);
  402.         break;
  403.  
  404.     case (-3):                /* __FILE__        */
  405.         for (file = infile; file != NULL; file = file->parent) {
  406.         if (file->fp != NULL) {
  407.             sprintf(work, "\"%s\"", (file->progname != NULL)
  408.             ? file->progname : file->filename);
  409.             ungetstring(work);
  410.             break;
  411.         }
  412.         }
  413.         break;
  414.  
  415.     default:
  416.         /*
  417.          * Nothing funny about this macro.
  418.          */
  419.         if (tokenp->nargs < 0)
  420.         cfatal("Bug: Illegal __ macro \"%s\"", tokenp->name);
  421.         while ((c = skipws()) == '\n')    /* Look for (, skipping    */
  422.         wrongline = TRUE;        /* spaces and newlines    */
  423.         if (c != '(') {
  424.         /*
  425.          * If the programmer writes
  426.          *    #define foo() ...
  427.          *    ...
  428.          *    foo [no ()]
  429.          * just write foo to the output stream.
  430.          */
  431.         unget();
  432.         cwarn("Macro \"%s\" needs arguments", tokenp->name);
  433.         fputs(tokenp->name, stdout);
  434.         return;
  435.         }
  436.         else if (expcollect()) {        /* Collect arguments    */
  437.         if (tokenp->nargs != nargs) {    /* Should be an error?    */
  438.             cwarn("Wrong number of macro arguments for \"%s\"",
  439.             tokenp->name);
  440.         }
  441. #if DEBUG
  442.         if (debug)
  443.             dumpparm("expand");
  444. #endif
  445.         }                /* Collect arguments        */
  446.     case DEF_NOARGS:        /* No parameters just stuffs    */
  447.         expstuff(tokenp);        /* Do actual parameters        */
  448.     }                /* nargs switch            */
  449. }
  450.  
  451. FILE_LOCAL int
  452. expcollect()
  453. /*
  454.  * Collect the actual parameters for this macro.  TRUE if ok.
  455.  */
  456. {
  457.     register int    c;
  458.     register int    paren;            /* For embedded ()'s    */
  459.     extern int    charput();
  460.  
  461.     for (;;) {
  462.         paren = 0;                /* Collect next arg.    */
  463.         while ((c = skipws()) == '\n')    /* Skip over whitespace    */
  464.         wrongline = TRUE;        /* and newlines.    */
  465.         if (c == ')') {            /* At end of all args?    */
  466.         /*
  467.          * Note that there is a guard byte in parm[]
  468.          * so we don't have to check for overflow here.
  469.          */
  470.         *parmp = EOS;            /* Make sure terminated    */
  471.         break;                /* Exit collection loop    */
  472.         }
  473.         else if (nargs >= LASTPARM)
  474.         cfatal("Too many arguments in macro expansion", NULLST);
  475.         parlist[nargs++] = parmp;        /* At start of new arg    */
  476.         for (;; c = cget()) {        /* Collect arg's bytes    */
  477.         if (c == EOF_CHAR) {
  478.             cerror("end of file within macro argument", NULLST);
  479.             return (FALSE);        /* Sorry.        */
  480.         }
  481.         else if (c == '\\') {        /* Quote next character    */
  482.             charput(c);            /* Save the \ for later    */
  483.             charput(cget());        /* Save the next char.    */
  484.             continue;            /* And go get another    */
  485.         }
  486.         else if (type[c] == QUO) {    /* Start of string?    */
  487.             scanstring(c, charput);    /* Scan it off        */
  488.             continue;            /* Go get next char    */
  489.         }
  490.         else if (c == '(')        /* Worry about balance    */
  491.             paren++;            /* To know about commas    */
  492.         else if (c == ')') {        /* Other side too    */
  493.             if (paren == 0) {        /* At the end?        */
  494.             unget();        /* Look at it later    */
  495.             break;            /* Exit arg getter.    */
  496.             }
  497.             paren--;            /* More to come.    */
  498.         }
  499.         else if (c == ',' && paren == 0) /* Comma delimits args    */
  500.             break;
  501.         else if (c == '\n')        /* Newline inside arg?    */
  502.             wrongline = TRUE;        /* We'll need a #line    */
  503.         charput(c);            /* Store this one    */
  504.         }                    /* Collect an argument    */
  505.         charput(EOS);            /* Terminate argument    */
  506. #if DEBUG
  507.         if (debug)
  508.             printf("parm[%d] = \"%s\"\n", nargs, parlist[nargs - 1]);
  509. #endif
  510.     }                    /* Collect all args.    */
  511.     return (TRUE);                /* Normal return    */
  512. }
  513.  
  514. FILE_LOCAL
  515. expstuff(tokenp)
  516. DEFBUF        *tokenp;        /* Current macro being expanded    */
  517. /*
  518.  * Stuff the macro body, replacing formal parameters by actual parameters.
  519.  */
  520. {
  521.     register int    c;            /* Current character    */
  522.     register char    *inp;            /* -> repl string    */
  523.     register char    *defp;            /* -> macro output buff    */
  524.     int        size;            /* Actual parm. size    */
  525.     char        *defend;        /* -> output buff end    */
  526.     int        string_magic;        /* String formal hack    */
  527.     FILEINFO    *file;            /* Funny #include    */
  528.     extern FILEINFO    *getfile();
  529.  
  530.     file = getfile(NBUFF, tokenp->name);
  531.     inp = tokenp->repl;            /* -> macro replacement    */
  532.     defp = file->buffer;            /* -> output buffer    */
  533.     defend = defp + (NBUFF - 1);        /* Note its end        */
  534.     if (inp != NULL) {
  535.         while ((c = (*inp++ & 0xFF)) != EOS) {
  536.         if (c >= MAC_PARM && c <= (MAC_PARM + PAR_MAC)) {
  537.             string_magic = (c == (MAC_PARM + PAR_MAC));
  538.             if (string_magic)
  539.              c = (*inp++ & 0xFF);
  540.             /*
  541.              * Replace formal parameter by actual parameter string.
  542.              */
  543.             if ((c -= MAC_PARM) < nargs) {
  544.             size = strlen(parlist[c]);
  545.             if ((defp + size) >= defend)
  546.                 goto nospace;
  547.             /*
  548.              * Erase the extra set of quotes.
  549.              */
  550.             if (string_magic && defp[-1] == parlist[c][0]) {
  551.                 strcpy(defp-1, parlist[c]);
  552.                 defp += (size - 2);
  553.             }
  554.             else {
  555.                 strcpy(defp, parlist[c]);
  556.                 defp += size;
  557.             }
  558.             }
  559.         }
  560.         else if (defp >= defend) {
  561. nospace:        cfatal("Out of space in macro \"%s\" arg expansion",
  562.             tokenp->name);
  563.         }
  564.         else {
  565.             *defp++ = c;
  566.         }
  567.         }
  568.     }
  569.     *defp = EOS;
  570. #if DEBUG
  571.     if (debug > 1)
  572.         printf("macroline: \"%s\"\n", file->buffer);
  573. #endif
  574. }
  575.  
  576. #if DEBUG
  577. dumpparm(why)
  578. char        *why;
  579. /*
  580.  * Dump parameter list.
  581.  */
  582. {
  583.     register int    i;
  584.  
  585.     printf("dump of %d parameters (%d bytes total) %s\n",
  586.         nargs, parmp - parm, why);
  587.     for (i = 0; i < nargs; i++) {
  588.         printf("parm[%d] (%d) = \"%s\"\n",
  589.         i + 1, strlen(parlist[i]), parlist[i]);
  590.     }
  591. }
  592. #endif
  593.