home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume1 / cpp / part2 < prev    next >
Encoding:
Internet Message Format  |  1986-11-30  |  49.5 KB

  1. From: decvax!minow
  2. Date: Tue, 8 Jan 85 00:05:37 est
  3. Subject: cpp2.arc
  4.  
  5. -h- cpp1.c    Mon Jan  7 23:59:31 1985    cpp1.c
  6. /*
  7.  * CPP main program.
  8.  *
  9.  * Edit history
  10.  * 21-May-84    MM    "Field test" release
  11.  * 23-May-84    MM    Some minor hacks.
  12.  * 30-May-84    ARF    Didn't get enough memory for __DATE__
  13.  *            Added code to read stdin if no input
  14.  *            files are provided.
  15.  * 29-Jun-84    MM    Added ARF's suggestions, Unixifying cpp.
  16.  * 11-Jul-84    MM    "Official" first release (that's what I thought!)
  17.  * 22-Jul-84    MM/ARF/SCK Fixed line number bugs, added cpp recognition
  18.  *            of #line, fixed problems with #include.
  19.  * 23-Jul-84    MM    More (minor) include hacking, some documentation.
  20.  *            Also, redid cpp's #include files
  21.  * 25-Jul-84    MM    #line filename isn't used for #include searchlist
  22.  *            #line format is <number> <optional name>
  23.  * 25-Jul-84    ARF/MM    Various bugs, mostly serious.  Removed homemade doprint
  24.  * 01-Aug-84    MM    Fixed recursion bug, remove extra newlines and
  25.  *            leading whitespace from cpp output.
  26.  * 02-Aug-84    MM    Hacked (i.e. optimized) out blank lines and unneeded
  27.  *            whitespace in general.  Cleaned up unget()'s.
  28.  * 03-Aug-84    Keie    Several bug fixes from Ed Keizer, Vrije Universitet.
  29.  *            -- corrected arg. count in -D and pre-defined
  30.  *            macros.  Also, allow \n inside macro actual parameter
  31.  *            lists.
  32.  * 06-Aug-84    MM    If debugging, dump the preset vector at startup.
  33.  * 12-Aug-84    MM/SCK    Some small changes from Sam Kendall
  34.  * 15-Aug-84    Keie/MM    cerror, cwarn, etc. take a single string arg.
  35.  *            cierror, etc. take a single int. arg.
  36.  *            changed LINE_PREFIX slightly so it can be
  37.  *            changed in the makefile.
  38.  * 31-Aug-84    MM    USENET net.sources release.
  39.  *  7-Sep-84    SCH/ado Lint complaints
  40.  * 10-Sep-84    Keie    Char's can't be signed in some implementations
  41.  * 11-Sep-84    ado    Added -C flag, pathological line number fix
  42.  * 13-Sep-84    ado    Added -E flag (does nothing) and "-" file for stdin.
  43.  * 14-Sep-84    MM    Allow # 123 as a synonym for #line 123
  44.  * 19-Sep-84    MM    scanid always reads to token, make sure #line is
  45.  *            written to a new line, even if -C switch given.
  46.  *            Also, cpp - - reads stdin, writes stdout.
  47.  * 03-Oct-84    ado/MM    Several changes to line counting and keepcomments
  48.  *            stuff.  Also a rewritten control() hasher -- much
  49.  *            simpler and no less "perfect". Note also changes
  50.  *            in cpp3.c to fix numeric scanning.
  51.  * 04-Oct-84    MM    Added recognition of macro formal parameters if
  52.  *            they are the only thing in a string, per the
  53.  *            draft standard.
  54.  * 08-Oct-84    MM    One more attack on scannumber
  55.  * 15-Oct-84    MM/ado    Added -N to disable predefined symbols.  Fixed
  56.  *            linecount if COMMENT_INVISIBLE enabled.
  57.  * 22-Oct-84    MM    Don't evaluate the #if/#ifdef argument if
  58.  *            compilation is supressed.  This prevents
  59.  *            unnecessary error messages in sequences such as
  60.  *                #ifdef FOO        -- undefined
  61.  *                #if FOO == 10    -- shouldn't print warning
  62.  * 25-Oct-84    MM    Fixed bug in false ifdef supression.  On vms,
  63.  *            #include <foo> should open foo.h -- this duplicates
  64.  *            the behavior of Vax-C
  65.  * 31-Oct-84    ado/MM    Parametized $ in indentifiers.  Added a better
  66.  *            token concatenator and took out the trial
  67.  *            concatenation code.  Also improved #ifdef code
  68.  *            and cleaned up the macro recursion tester.
  69.  *  2-Nov-84    MM/ado    Some bug fixes in token concatenation, also
  70.  *            a variety of minor (uninteresting) hacks.
  71.  *  6-Nov-84    MM    Happy Birthday.  Broke into 4 files and added
  72.  *            #if sizeof (basic_types)
  73.  *  9-Nov-84    MM    Added -S* for pointer type sizes
  74.  * 13-Nov-84    MM    Split cpp1.c, added vms defaulting
  75.  * 23-Nov-84    MM/ado    -E supresses error exit, added CPP_INCLUDE,
  76.  *            fixed strncpy bug.
  77.  *  3-Dec-84    ado/MM    Added OLD_PREPROCESSOR
  78.  *  7-Dec-84    MM    Stuff in Nov 12 Draft Standard
  79.  * 17-Dec-84    george    Fixed problems with recursive macros
  80.  * 17-Dec-84    MM    Yet another attack on #if's (f/t)level removed.
  81.  * 07-Jan-85    ado    Init defines before doing command line options
  82.  *            so -Uunix works.
  83.  */
  84.  
  85. /*)BUILD
  86.     $(PROGRAM)    = cpp
  87.     $(FILES)    = { cpp1 cpp2 cpp3 cpp4 cpp5 cpp6 }
  88.     $(INCLUDE)    = { cppdef.h cpp.h }
  89.     $(STACK)    = 2000
  90.     $(TKBOPTIONS)    = {
  91.         STACK    = 2000
  92.     }
  93. */
  94.  
  95. #ifdef    DOCUMENTATION
  96.  
  97. title    cpp        C Pre-Processor
  98. index            C pre-processor
  99.  
  100. synopsis
  101.     .s.nf
  102.     cpp [-options] [infile [outfile]]
  103.     .s.f
  104. description
  105.  
  106.     CPP reads a C source file, expands macros and include
  107.     files, and writes an input file for the C compiler.
  108.     If no file arguments are given, CPP reads from stdin
  109.     and writes to stdout.  If one file argument is given,
  110.     it will define the input file, while two file arguments
  111.     define both input and output files.  The file name "-"
  112.     is a synonym for stdin or stdout as appropriate.
  113.  
  114.     The following options are supported.  Options may
  115.     be given in either case.
  116.     .lm +16
  117.     .p -16
  118.     -C        If set, source-file comments are written
  119.     to the output file.  This allows the output of CPP to be
  120.     used as the input to a program, such as lint, that expects
  121.     commands embedded in specially-formatted comments.
  122.     .p -16
  123.     -Dname=value    Define the name as if the programmer wrote
  124.  
  125.         #define name value
  126.  
  127.     at the start of the first file.  If "=value" is not
  128.     given, a value of "1" will be used.
  129.  
  130.     On non-unix systems, all alphabetic text will be forced
  131.     to upper-case.
  132.     .p -16
  133.     -E        Always return "success" to the operating
  134.     system, even if errors were detected.  Note that some fatal
  135.     errors, such as a missing #include file, will terminate
  136.     CPP, returning "failure" even if the -E option is given.
  137.     .p -16
  138.     -Idirectory    Add this directory to the list of
  139.     directories searched for #include "..." and #include <...>
  140.     commands.  Note that there is no space between the
  141.     "-I" and the directory string.  More than one -I command
  142.     is permitted.  On non-Unix systems "directory" is forced
  143.     to upper-case.
  144.     .p -16
  145.     -N        CPP normally predefines some symbols defining
  146.     the target computer and operating system.  If -N is specified,
  147.     no symbols will be predefined.  If -N -N is specified, the
  148.     "always present" symbols, __LINE__, __FILE__, and __DATE__
  149.     are not defined.
  150.     .p -16
  151.     -Stext        CPP normally assumes that the size of
  152.     the target computer's basic variable types is the same as the size
  153.     of these types of the host computer.  (This can be overridden
  154.     when CPP is compiled, however.)  The -S option allows dynamic
  155.     respecification of these values.  "text" is a string of
  156.     numbers, separated by commas, that specifies correct sizes.
  157.     The sizes must be specified in the exact order:
  158.  
  159.         char short int long float double
  160.  
  161.     If you specify the option as "-S*text", pointers to these
  162.     types will be specified.  -S* takes one additional argument
  163.     for pointer to function (e.g. int (*)())
  164.  
  165.     For example, to specify sizes appropriate for a PDP-11,
  166.     you would write:
  167.  
  168.            c s i l f d func
  169.          -S1,2,2,2,4,8,
  170.         -S*2,2,2,2,2,2,2
  171.  
  172.     Note that all values must be specified.
  173.     .p -16
  174.     -Uname        Undefine the name as if
  175.  
  176.         #undef name
  177.  
  178.     were given.  On non-Unix systems, "name" will be forced to
  179.     upper-case.
  180.     .p -16
  181.     -Xnumber    Enable debugging code.  If no value is
  182.     given, a value of 1 will be used.  (For maintenence of
  183.     CPP only.)
  184.     .s.lm -16
  185.  
  186. Pre-Defined Variables
  187.  
  188.     When CPP begins processing, the following variables will
  189.     have been defined (unless the -N option is specified):
  190.     .s
  191.     Target computer (as appropriate):
  192.     .s
  193.         pdp11, vax, M68000 m68000 m68k
  194.     .s
  195.     Target operating system (as appropriate):
  196.     .s
  197.         rsx, rt11, vms, unix
  198.     .s
  199.     Target compiler (as appropriate):
  200.     .s
  201.         decus, vax11c
  202.     .s
  203.     The implementor may add definitions to this list.
  204.     The default definitions match the definition of the
  205.     host computer, operating system, and C compiler.
  206.     .s
  207.     The following are always available unless undefined (or
  208.     -N was specified twice):
  209.     .lm +16
  210.     .p -12
  211.     __FILE__    The input (or #include) file being compiled
  212.     (as a quoted string).
  213.     .p -12
  214.     __LINE__    The line number being compiled.
  215.     .p -12
  216.     __DATE__    The date and time of compilation as
  217.     a Unix ctime quoted string (the trailing newline is removed).
  218.     Thus,
  219.     .s
  220.         printf("Bug at line %s,", __LINE__);
  221.         printf(" source file %s", __FILE__);
  222.         printf(" compiled on %s", __DATE__);
  223.     .s.lm -16
  224.  
  225. Draft Proposed Ansi Standard Considerations
  226.  
  227.     The current version of the Draft Proposed Standard
  228.     explicitly states that "readers are requested not to specify
  229.     or claim conformance to this draft."  Readers and users
  230.     of Decus CPP should not assume that Decus CPP conforms
  231.     to the standard, or that it will conform to the actual
  232.     C Language Standard.
  233.  
  234.     When CPP is itself compiled, many features of the Draft
  235.     Proposed Standard that are incompatible with existing
  236.     preprocessors may be disabled.  See the comments in CPP's
  237.     source for details.
  238.  
  239.     The latest version of the Draft Proposed Standard (as reflected
  240.     in Decus CPP) is dated November 12, 1984.
  241.  
  242.     Comments are removed from the input text.  The comment
  243.     is replaced by a single space character.  The -C option
  244.     preserves comments, writing them to the output file.
  245.  
  246.     The '$' character is considered to be a letter.  This is
  247.     a permitted extension.
  248.  
  249.     The following new features of C are processed by CPP:
  250.     .s.comment Note: significant spaces, not tabs, .br quotes #if, #elif
  251.     .br;####_#elif expression    (_#else _#if)
  252.     .br;####'_\xNNN'             (Hexadecimal constant)
  253.     .br;####'_\a'                (Ascii BELL)
  254.     .br;####'_\v'                (Ascii Vertical Tab)
  255.     .br;####_#if defined NAME    1 if defined, 0 if not
  256.     .br;####_#if defined (NAME)  1 if defined, 0 if not  
  257.     .br;####_#if sizeof (basic type)
  258.     .br;####unary +
  259.     .br;####123U, 123LU          Unsigned ints and longs.
  260.     .br;####12.3L                Long double numbers
  261.     .br;####token_#token         Token concatenation
  262.     .br;####_#include token      Expands to filename
  263.  
  264.     The Draft Proposed Standard has extended C, adding a constant
  265.     string concatenation operator, where
  266.  
  267.         "foo" "bar"
  268.  
  269.     is regarded as the single string "foobar".  (This does not
  270.     affect CPP's processing but does permit a limited form of
  271.     macro argument substitution into strings as will be discussed.)
  272.  
  273.     The Standard Committee plans to add token concatenation
  274.     to #define command lines.  One suggested implementation
  275.     is as follows:  the sequence "Token1#Token2" is treated
  276.     as if the programmer wrote "Token1Token2".  This could
  277.     be used as follows:
  278.  
  279.         #line 123
  280.         #define ATLINE foo#__LINE__
  281.  
  282.     ATLINE would be defined as foo123.
  283.  
  284.     Note that "Token2" must either have the format of an
  285.     identifier or be a string of digits.  Thus, the string
  286.  
  287.         #define ATLINE foo#1x3
  288.  
  289.     generates two tokens: "foo1" and "x3".
  290.  
  291.     If the tokens T1 and T2 are concatenated into T3,
  292.     this implementation operates as follows:
  293.  
  294.       1. Expand T1 if it is a macro.
  295.       2. Expand T2 if it is a macro.
  296.       3. Join the tokens, forming T3.
  297.       4. Expand T3 if it is a macro.
  298.  
  299.     A macro formal parameter will be substituted into a string
  300.     or character constant if it is the only component of that
  301.     constant:
  302.  
  303.         #define VECSIZE 123
  304.         #define vprint(name, size) \
  305.           printf("name" "[" "size" "] = {\n")
  306.           ... vprint(vector, VECSIZE);
  307.  
  308.     expands (effectively) to
  309.  
  310.           vprint("vector[123] = {\n");
  311.  
  312.     Note that this will be useful if your C compiler supports
  313.     the new string concatenation operation noted above.
  314.     As implemented here, if you write
  315.  
  316.         #define string(arg) "arg"
  317.           ... string("foo") ...
  318.  
  319.     This implementation generates "foo", rather than the strictly
  320.     correct ""foo"" (which will probably generate an error message).
  321.     This is, strictly speaking, an error in CPP and may be removed
  322.     from future releases.
  323.  
  324. error messages
  325.  
  326.     Many.  CPP prints warning or error messages if you try to
  327.     use multiple-byte character constants (non-transportable)
  328.     if you #undef a symbol that was not defined, or if your
  329.     program has potentially nested comments.
  330.  
  331. author
  332.  
  333.     Martin Minow
  334.  
  335. bugs
  336.  
  337.     The #if expression processor uses signed integers only.
  338.     I.e, #if 0xFFFFu < 0 may be TRUE.
  339.  
  340. #endif
  341.  
  342. #include    <stdio.h>
  343. #include    <ctype.h>
  344. #include    "cppdef.h"
  345. #include    "cpp.h"
  346.  
  347. /*
  348.  * Commonly used global variables:
  349.  * line        is the current input line number.
  350.  * wrongline    is set in many places when the actual output
  351.  *        line is out of sync with the numbering, e.g,
  352.  *        when expanding a macro with an embedded newline.
  353.  *
  354.  * token    holds the last identifier scanned (which might
  355.  *        be a candidate for macro expansion).
  356.  * errors    is the running cpp error counter.
  357.  * infile    is the head of a linked list of input files (extended by
  358.  *        #include and macros being expanded).  infile always points
  359.  *        to the current file/macro.  infile->parent to the includer,
  360.  *        etc.  infile->fd is NULL if this input stream is a macro.
  361.  */
  362. int        line;            /* Current line number        */
  363. int        wrongline;        /* Force #line to compiler    */
  364. char        token[IDMAX + 1];    /* Current input token        */
  365. int        errors;            /* cpp error counter        */
  366. FILEINFO    *infile = NULL;        /* Current input file        */
  367. #if DEBUG
  368. int        debug;            /* TRUE if debugging now    */
  369. #endif
  370. /*
  371.  * This counter is incremented when a macro expansion is initiated.
  372.  * If it exceeds a built-in value, the expansion stops -- this tests
  373.  * for a runaway condition:
  374.  *    #define X Y
  375.  *    #define Y X
  376.  *    X
  377.  * This can be disabled by falsifying rec_recover.  (Nothing does this
  378.  * currently: it is a hook for an eventual invocation flag.)
  379.  */
  380. int        recursion;        /* Infinite recursion counter    */
  381. int        rec_recover = TRUE;    /* Unwind recursive macros    */
  382.  
  383. /*
  384.  * instring is set TRUE when a string is scanned.  It modifies the
  385.  * behavior of the "get next character" routine, causing all characters
  386.  * to be passed to the caller (except <DEF_MAGIC>).  Note especially that
  387.  * comments and \<newline> are not removed from the source.  (This
  388.  * prevents cpp output lines from being arbitrarily long).
  389.  *
  390.  * inmacro is set by #define -- it absorbs comments and converts
  391.  * form-feed and vertical-tab to space, but returns \<newline>
  392.  * to the caller.  Strictly speaking, this is a bug as \<newline>
  393.  * shouldn't delimit tokens, but we'll worry about that some other
  394.  * time -- it is more important to prevent infinitly long output lines.
  395.  *
  396.  * instring and inmarcor are parameters to the get() routine which
  397.  * were made global for speed.
  398.  */
  399. int        instring = FALSE;    /* TRUE if scanning string    */
  400. int        inmacro = FALSE;    /* TRUE if #defining a macro    */
  401.  
  402. /*
  403.  * work[] and workp are used to store one piece of text in a temporay
  404.  * buffer.  To initialize storage, set workp = work.  To store one
  405.  * character, call save(c);  (This will fatally exit if there isn't
  406.  * room.)  To terminate the string, call save(EOS).  Note that
  407.  * the work buffer is used by several subroutines -- be sure your
  408.  * data won't be overwritten.  The extra byte in the allocation is
  409.  * needed for string formal replacement.
  410.  */
  411. char        work[NWORK + 1];    /* Work buffer            */
  412. char        *workp;            /* Work buffer pointer        */
  413.  
  414. /*
  415.  * keepcomments is set TRUE by the -C option.  If TRUE, comments
  416.  * are written directly to the output stream.  This is needed if
  417.  * the output from cpp is to be passed to lint (which uses commands
  418.  * embedded in comments).  cflag contains the permanent state of the
  419.  * -C flag.  keepcomments is always falsified when processing #control
  420.  * commands and when compilation is supressed by a false #if
  421.  *
  422.  * If eflag is set, CPP returns "success" even if non-fatal errors
  423.  * were detected.
  424.  *
  425.  * If nflag is non-zero, no symbols are predefined except __LINE__.
  426.  * __FILE__, and __DATE__.  If nflag > 1, absolutely no symbols
  427.  * are predefined.
  428.  */
  429. int        keepcomments = FALSE;    /* Write out comments flag    */
  430. int        cflag = FALSE;        /* -C option (keep comments)    */
  431. int        eflag = FALSE;        /* -E option (never fail)    */
  432. int        nflag = 0;        /* -N option (no predefines)    */
  433.  
  434. /*
  435.  * ifstack[] holds information about nested #if's.  It is always
  436.  * accessed via *ifptr.  The information is as follows:
  437.  *    WAS_COMPILING    state of compiling flag at outer level.
  438.  *    ELSE_SEEN    set TRUE when #else seen to prevent 2nd #else.
  439.  *    TRUE_SEEN    set TRUE when #if or #elif succeeds
  440.  * ifstack[0] holds the compiling flag.  It is TRUE if compilation
  441.  * is currently enabled.  Note that this must be initialized TRUE.
  442.  */
  443. char        ifstack[BLK_NEST] = { TRUE };    /* #if information    */
  444. char        *ifptr = ifstack;        /* -> current ifstack[] */
  445.  
  446. /*
  447.  * incdir[] stores the -i directories (and the system-specific
  448.  * #include <...> directories.
  449.  */
  450. char    *incdir[NINCLUDE];        /* -i directories        */
  451. char    **incend = incdir;        /* -> free space in incdir[]    */
  452.  
  453. /*
  454.  * This is the table used to predefine target machine and operating
  455.  * system designators.  It may need hacking for specific circumstances.
  456.  * Note: it is not clear that this is part of the Ansi Standard.
  457.  * The -N option supresses preset definitions.
  458.  */
  459. char    *preset[] = {            /* names defined at cpp start    */
  460. #ifdef    MACHINE
  461.     MACHINE,
  462. #endif
  463. #ifdef    SYSTEM
  464.     SYSTEM,
  465. #endif
  466. #ifdef    COMPILER
  467.     COMPILER,
  468. #endif
  469. #if    DEBUG
  470.     "decus_cpp",            /* Ourselves!            */
  471. #endif
  472.     NULL                /* Must be last            */
  473. };
  474.  
  475. /*
  476.  * The value of these predefined symbols must be recomputed whenever
  477.  * they are evaluated.  The order must not be changed.
  478.  */
  479. char    *magic[] = {            /* Note: order is important    */
  480.     "__LINE__",
  481.     "__FILE__",
  482.     NULL                /* Must be last            */
  483. };
  484.  
  485. main(argc, argv)
  486. int        argc;
  487. char        *argv[];
  488. {
  489.     register int    i;
  490.  
  491. #if HOST == SYS_VMS
  492.     argc = getredirection(argc, argv);    /* vms >file and <file    */
  493. #endif
  494.     initdefines();                /* O.S. specific def's    */
  495.     i = dooptions(argc, argv);        /* Command line -flags    */
  496.     switch (i) {
  497.     case 3:
  498.         /*
  499.          * Get output file, "-" means use stdout.
  500.          */
  501.         if (!streq(argv[2], "-")) {
  502. #if HOST == SYS_VMS
  503.         /*
  504.          * On vms, reopen stdout with "vanilla rms" attributes.
  505.          */
  506.         if ((i = creat(argv[2], 0, "rat=cr", "rfm=var")) == -1
  507.          || dup2(i, fileno(stdout)) == -1) {
  508. #else
  509.         if (freopen(argv[2], "w", stdout) == NULL) {
  510. #endif
  511.             perror(argv[2]);
  512.             cerror("Can't open output file \"%s\"", argv[2]);
  513.             exit(IO_ERROR);
  514.         }
  515.         }                /* Continue by opening input    */
  516.     case 2:                /* One file -> stdin        */
  517.         /*
  518.          * Open input file, "-" means use stdin.
  519.          */
  520.         if (!streq(argv[1], "-")) {
  521.         if (freopen(argv[1], "r", stdin) == NULL) {
  522.             perror(argv[1]);
  523.             cerror("Can't open input file \"%s\"", argv[1]);
  524.             exit(IO_ERROR);
  525.         }
  526.         strcpy(work, argv[1]);    /* Remember input filename    */
  527.         break;
  528.         }                /* Else, just get stdin        */
  529.     case 0:                /* No args?            */
  530.     case 1:                /* No files, stdin -> stdout    */
  531. #if HOST == SYS_UNIX
  532.         work[0] = EOS;        /* Unix can't find stdin name    */
  533. #else
  534.         fgetname(stdin, work);    /* Vax-11C, Decus C know name    */
  535. #endif
  536.         break;
  537.  
  538.     default:
  539.         exit(IO_ERROR);        /* Can't happen            */
  540.     }
  541.     setincdirs();            /* Setup -I include directories    */
  542.     addfile(stdin, work);        /* "open" main input file    */
  543. #if DEBUG
  544.     if (debug > 0)
  545.         dumpdef("preset #define symbols");
  546. #endif
  547.     cppmain();            /* Process main file        */
  548.     if ((i = (ifptr - &ifstack[0])) != 0) {
  549. #if OLD_PREPROCESSOR
  550.         ciwarn("Inside #ifdef block at end of input, depth = %d", i);
  551. #else
  552.         cierror("Inside #ifdef block at end of input, depth = %d", i);
  553. #endif
  554.     }
  555.     fclose(stdout);
  556.     if (errors > 0) {
  557.         fprintf(stderr, (errors == 1)
  558.         ? "%d error in preprocessor\n"
  559.         : "%d errors in preprocessor\n", errors);
  560.         if (!eflag)
  561.         exit(IO_ERROR);
  562.     }
  563.     exit(IO_NORMAL);        /* No errors or -E option set    */
  564. }
  565.  
  566. FILE_LOCAL
  567. cppmain()
  568. /*
  569.  * Main process for cpp -- copies tokens from the current input
  570.  * stream (main file, include file, or a macro) to the output
  571.  * file.
  572.  */
  573. {
  574.     register int        c;        /* Current character    */
  575.     register int        counter;    /* newlines and spaces    */
  576.     extern int        output();    /* Output one character    */
  577.  
  578.     /*
  579.      * Explicitly output a #line at the start of cpp output so
  580.      * that lint (etc.) knows the name of the original source
  581.      * file.  If we don't do this explicitly, we may get
  582.      * the name of the first #include file instead.
  583.      */
  584.     sharp();
  585.     /*
  586.      * This loop is started "from the top" at the beginning of each line
  587.      * wrongline is set TRUE in many places if it is necessary to write
  588.      * a #line record.  (But we don't write them when expanding macros.)
  589.      *
  590.      * The counter variable has two different uses:  at
  591.      * the start of a line, it counts the number of blank lines that
  592.      * have been skipped over.  These are then either output via
  593.      * #line records or by outputting explicit blank lines.
  594.       * When expanding tokens within a line, the counter remembers
  595.      * whether a blank/tab has been output.  These are dropped
  596.      * at the end of the line, and replaced by a single blank
  597.      * within lines.
  598.      */
  599.     for (;;) {
  600.         counter = 0;            /* Count empty lines    */
  601.         for (;;) {                /* For each line, ...    */
  602.         while (type[(c = get())] == SPA) /* Skip leading blanks    */
  603.             ;                /* in this line.    */
  604.         if (c == '\n')            /* If line's all blank,    */
  605.             ++counter;            /* Do nothing now    */
  606.         else if (c == '#') {        /* Is 1st non-space '#'    */
  607.             keepcomments = FALSE;    /* Don't pass comments    */
  608.             counter = control(counter);    /* Yes, do a #command    */
  609.             keepcomments = (cflag && compiling);
  610.         }
  611.         else if (c == EOF_CHAR)        /* At end of file?    */
  612.             break;
  613.         else if (!compiling) {        /* #ifdef false?    */
  614.             skipnl();            /* Skip to newline    */
  615.             counter++;            /* Count it, too.    */
  616.         }
  617.         else {
  618.             break;            /* Actual token        */
  619.         }
  620.         }
  621.         if (c == EOF_CHAR)            /* Exit process at    */
  622.         break;                /* End of file        */
  623.         /*
  624.          * If the loop didn't terminate because of end of file, we
  625.          * know there is a token to compile.  First, clean up after
  626.          * absorbing newlines.  counter has the number we skipped.
  627.          */
  628.         if ((wrongline && infile->fp != NULL) || counter > 4)
  629.         sharp();            /* Output # line number    */
  630.         else {                /* If just a few, stuff    */
  631.         while (--counter >= 0)        /* them out ourselves    */
  632.             putchar('\n');
  633.         }
  634.         /*
  635.          * Process each token on this line.
  636.          */
  637.         unget();                /* Reread the char.    */
  638.         for (;;) {                /* For the whole line,    */
  639.         do {                /* Token concat. loop    */
  640.             for (counter = 0; (type[(c = get())] == SPA);) {
  641. #if COMMENT_INVISIBLE
  642.             if (c != COM_SEP)
  643.                 counter++;
  644. #else
  645.             counter++;        /* Skip over blanks    */
  646. #endif
  647.             }
  648.             if (c == EOF_CHAR || c == '\n')
  649.             goto end_line;        /* Exit line loop    */
  650.             else if (counter > 0)    /* If we got any spaces    */
  651.             putchar(' ');        /* Output one space    */
  652.             c = macroid(c);        /* Grab the token    */
  653.         } while (type[c] == LET && catenate());
  654.         if (c == EOF_CHAR || c == '\n')    /* From macro exp error    */
  655.             goto end_line;        /* Exit line loop    */
  656.         switch (type[c]) {
  657.         case LET:
  658.             fputs(token, stdout);    /* Quite ordinary token    */
  659.             break;
  660.  
  661.  
  662.         case DIG:            /* Output a number    */
  663.         case DOT:            /* Dot may begin floats    */
  664.             scannumber(c, output);
  665.             break;
  666.  
  667.         case QUO:            /* char or string const    */
  668.             scanstring(c, output);    /* Copy it to output    */
  669.             break;
  670.  
  671.         default:            /* Some other character    */
  672.             cput(c);            /* Just output it    */
  673.             break;
  674.         }                /* Switch ends        */
  675.         }                    /* Line for loop    */
  676. end_line:   if (c == '\n') {            /* Compiling at EOL?    */
  677.         putchar('\n');            /* Output newline, if    */
  678.         if (infile->fp == NULL)        /* Expanding a macro,    */
  679.             wrongline = TRUE;        /* Output # line later    */
  680.         }
  681.     }                    /* Continue until EOF    */
  682. }
  683.  
  684. output(c)
  685. int        c;
  686. /*
  687.  * Output one character to stdout -- output() is passed as an
  688.  * argument to scanstring()
  689.  */
  690. {
  691. #if COMMENT_INVISIBLE
  692.     if (c != TOK_SEP && c != COM_SEP)
  693. #else
  694.     if (c != TOK_SEP)
  695. #endif
  696.         putchar(c);
  697. }
  698.  
  699. static char    *sharpfilename = NULL;
  700.  
  701. FILE_LOCAL
  702. sharp()
  703. /*
  704.  * Output a line number line.
  705.  */
  706. {
  707.     register char        *name;
  708.  
  709.     if (keepcomments)            /* Make sure # comes on    */
  710.         putchar('\n');            /* a fresh, new line.    */
  711.     printf("#%s %d", LINE_PREFIX, line);
  712.     if (infile->fp != NULL) {
  713.         name = (infile->progname != NULL)
  714.         ? infile->progname : infile->filename;
  715.         if (sharpfilename == NULL
  716.          || sharpfilename != NULL && !streq(name, sharpfilename)) {
  717.         if (sharpfilename != NULL)
  718.             free(sharpfilename);
  719.         sharpfilename = savestring(name);
  720.         printf(" \"%s\"", name);
  721.          }
  722.     }
  723.     putchar('\n');
  724.     wrongline = FALSE;
  725. }
  726. -h- cpp2.c    Mon Jan  7 23:59:31 1985    cpp2.c
  727. /*
  728.  *                C P P 2 . C
  729.  *
  730.  *               Process #control lines
  731.  *
  732.  * Edit history
  733.  * 13-Nov-84    MM    Split from cpp1.c
  734.  */
  735.  
  736. #include    <stdio.h>
  737. #include    <ctype.h>
  738. #include    "cppdef.h"
  739. #include    "cpp.h"
  740. #if HOST == SYS_VMS
  741. /*
  742.  * Include the rms stuff.  (We can't just include rms.h as it uses the
  743.  * VaxC-specific library include syntax that Decus CPP doesn't support.
  744.  * By including things by hand, we can CPP ourself.)
  745.  */
  746. #include    <nam.h>
  747. #include    <fab.h>
  748. #include    <rab.h>
  749. #include    <rmsdef.h>
  750. #endif
  751.  
  752. /*
  753.  * Generate (by hand-inspection) a set of unique values for each control
  754.  * operator.  Note that this is not guaranteed to work for non-Ascii
  755.  * machines.  CPP won't compile if there are hash conflicts.
  756.  */
  757.  
  758. #define    L_assert    ('a' + ('s' << 1))
  759. #define    L_define    ('d' + ('f' << 1))
  760. #define    L_elif        ('e' + ('i' << 1))
  761. #define    L_else        ('e' + ('s' << 1))
  762. #define    L_endif        ('e' + ('d' << 1))
  763. #define    L_if        ('i' + (EOS << 1))
  764. #define    L_ifdef        ('i' + ('d' << 1))
  765. #define    L_ifndef    ('i' + ('n' << 1))
  766. #define    L_include    ('i' + ('c' << 1))
  767. #define    L_line        ('l' + ('n' << 1))
  768. #define    L_nogood    (EOS + (EOS << 1))    /* To catch #i        */
  769. #define    L_pragma    ('p' + ('a' << 1))
  770. #define L_undef        ('u' + ('d' << 1))
  771. #if DEBUG
  772. #define    L_debug        ('d' + ('b' << 1))    /* #debug        */
  773. #define    L_nodebug    ('n' + ('d' << 1))    /* #nodebug        */
  774. #endif
  775.  
  776. int
  777. control(counter)
  778. int        counter;    /* Pending newline counter        */
  779. /*
  780.  * Process #control lines.  Simple commands are processed inline,
  781.  * while complex commands have their own subroutines.
  782.  *
  783.  * The counter is used to force out a newline before #line, and
  784.  * #pragma commands.  This prevents these commands from ending up at
  785.  * the end of the previous line if cpp is invoked with the -C option.
  786.  */
  787. {
  788.     register int        c;
  789.     register char        *tp;
  790.     register int        hash;
  791.     char            *ep;
  792.  
  793.     c = skipws();
  794.     if (c == '\n' || c == EOF_CHAR)
  795.         return (counter + 1);
  796.     if (!isdigit(c))
  797.         scanid(c);            /* Get #word to token[]        */
  798.     else {
  799.         unget();            /* Hack -- allow #123 as a    */
  800.         strcpy(token, "line");    /* synonym for #line 123    */
  801.     }
  802.     hash = (token[1] == EOS) ? L_nogood : (token[0] + (token[2] << 1));
  803.     switch (hash) {
  804.     case L_assert:    tp = "assert";        break;
  805.     case L_define:    tp = "define";        break;
  806.     case L_elif:    tp = "elif";        break;
  807.     case L_else:    tp = "else";        break;
  808.     case L_endif:    tp = "endif";        break;
  809.     case L_if:    tp = "if";        break;
  810.     case L_ifdef:    tp = "ifdef";        break;
  811.     case L_ifndef:    tp = "ifndef";        break;
  812.     case L_include:    tp = "include";        break;
  813.     case L_line:    tp = "line";        break;
  814.     case L_pragma:    tp = "pragma";        break;
  815.     case L_undef:    tp = "undef";        break;
  816. #if DEBUG
  817.     case L_debug:    tp = "debug";        break;
  818.     case L_nodebug:    tp = "nodebug";        break;
  819. #endif
  820.     default:    hash = L_nogood;
  821.     case L_nogood:    tp = "";        break;
  822.     }
  823.     if (!streq(tp, token))
  824.         hash = L_nogood;
  825.     /*
  826.      * hash is set to a unique value corresponding to the
  827.      * control keyword (or L_nogood if we think it's nonsense).
  828.      */
  829.     if (infile->fp == NULL)
  830.         cwarn("Control line \"%s\" within macro expansion", token);
  831.     if (!compiling) {            /* Not compiling now    */
  832.         switch (hash) {
  833.         case L_if:                /* These can't turn    */
  834.         case L_ifdef:            /*  compilation on, but    */
  835.         case L_ifndef:            /*   we must nest #if's    */
  836.         if (++ifptr >= &ifstack[BLK_NEST])
  837.             goto if_nest_err;
  838.         *ifptr = 0;            /* !WAS_COMPILING    */
  839.         case L_line:            /* Many            */
  840.         /*
  841.          * Are pragma's always processed?
  842.          */
  843.         case L_pragma:            /*  options        */
  844.         case L_include:            /*   are uninteresting    */
  845.         case L_define:            /*    if we        */
  846.         case L_undef:            /*     aren't        */
  847.         case L_assert:            /*      compiling.    */
  848. dump_line:    skipnl();            /* Ignore rest of line    */
  849.         return (counter + 1);
  850.         }
  851.     }
  852.     /*
  853.      * Make sure that #line and #pragma are output on a fresh line.
  854.      */
  855.     if (counter > 0 && (hash == L_line || hash == L_pragma)) {
  856.         putchar('\n');
  857.         counter--;
  858.     }
  859.     switch (hash) {
  860.     case L_line:
  861.         /*
  862.          * Parse the line to update the line number and "progname"
  863.          * field and line number for the next input line.
  864.          * Set wrongline to force it out later.
  865.          */
  866.         c = skipws();
  867.         workp = work;            /* Save name in work    */
  868.         while (c != '\n' && c != EOF_CHAR) {
  869.         save(c);
  870.         c = get();
  871.         }
  872.         unget();
  873.         save(EOS);
  874.         /*
  875.          * Split #line argument into <line-number> and <name>
  876.          * We subtract 1 as we want the number of the next line.
  877.          */
  878.         line = atoi(work) - 1;        /* Reset line number    */
  879.         for (tp = work; isdigit(*tp) || type[*tp] == SPA; tp++)
  880.         ;                /* Skip over digits    */
  881.         if (*tp != EOS) {            /* Got a filename, so:    */
  882.         if (*tp == '"' && (ep = strrchr(tp + 1, '"')) != NULL) {
  883.             tp++;            /* Skip over left quote    */
  884.             *ep = EOS;            /* And ignore right one    */
  885.         }
  886.         if (infile->progname != NULL)    /* Give up the old name    */
  887.             free(infile->progname);    /* if it's allocated.    */
  888.             infile->progname = savestring(tp);
  889.         }
  890.         wrongline = TRUE;            /* Force output later    */
  891.         break;
  892.  
  893.     case L_include:
  894.         doinclude();
  895.         break;
  896.  
  897.     case L_define:
  898.         dodefine();
  899.         break;
  900.  
  901.     case L_undef:
  902.         doundef();
  903.         break;
  904.  
  905.     case L_else:
  906.         if (ifptr == &ifstack[0])
  907.         goto nest_err;
  908.         else if ((*ifptr & ELSE_SEEN) != 0)
  909.         goto else_seen_err;
  910.         *ifptr |= ELSE_SEEN;
  911.         if ((*ifptr & WAS_COMPILING) != 0) {
  912.         if (compiling || (*ifptr & TRUE_SEEN) != 0)
  913.             compiling = FALSE;
  914.         else {
  915.             compiling = TRUE;
  916.         }
  917.         }
  918.         break;
  919.  
  920.     case L_elif:
  921.         if (ifptr == &ifstack[0])
  922.         goto nest_err;
  923.         else if ((*ifptr & ELSE_SEEN) != 0) {
  924. else_seen_err:    cerror("#%s may not follow #else", token);
  925.         goto dump_line;
  926.         }
  927.         if ((*ifptr & (WAS_COMPILING | TRUE_SEEN)) != WAS_COMPILING) {
  928.         compiling = FALSE;        /* Done compiling stuff    */
  929.         goto dump_line;            /* Skip this clause    */
  930.         }
  931.         doif(L_if);
  932.         break;
  933.  
  934.     case L_if:
  935.     case L_ifdef:
  936.     case L_ifndef:
  937.         if (++ifptr >= &ifstack[BLK_NEST])
  938. if_nest_err:    cfatal("Too many nested #%s statements", token);
  939.         *ifptr = WAS_COMPILING;
  940.         doif(hash);
  941.         break;
  942.  
  943.     case L_endif:
  944.         if (ifptr == &ifstack[0]) {
  945. nest_err:    cerror("#%s must be in an #if", token);
  946.         goto dump_line;
  947.         }
  948.         if (!compiling && (*ifptr & WAS_COMPILING) != 0)
  949.         wrongline = TRUE;
  950.         compiling = ((*ifptr & WAS_COMPILING) != 0);
  951.         --ifptr;
  952.         break;
  953.  
  954.     case L_assert:
  955.         if (eval() == 0)
  956.         cerror("Preprocessor assertion failure", NULLST);
  957.         break;
  958.  
  959.     case L_pragma:
  960.         /*
  961.          * #pragma is provided to pass "options" to later
  962.          * passes of the compiler.  cpp doesn't have any yet.
  963.          */
  964.         printf("#pragma ");
  965.         while ((c = get()) != '\n' && c != EOF_CHAR)
  966.         cput(c);
  967.         unget();
  968.         break;
  969.  
  970. #if DEBUG
  971.     case L_debug:
  972.         if (debug == 0)
  973.         dumpdef("debug set on");
  974.         debug++;
  975.         break;
  976.  
  977.     case L_nodebug:
  978.         debug--;
  979.         break;
  980. #endif
  981.  
  982.     default:
  983.         /*
  984.          * Undefined #control keyword.
  985.          * Note: the correct behavior may be to warn and
  986.          * pass the line to a subsequent compiler pass.
  987.          * This would allow #asm or similar extensions.
  988.          */
  989.         cerror("Illegal # command \"%s\"", token);
  990.         break;
  991.     }
  992.     if (hash != L_include) {
  993. #if OLD_PREPROCESSOR
  994.         /*
  995.          * Ignore the rest of the #control line so you can write
  996.          *        #if    foo
  997.          *        #endif    foo
  998.          */
  999.         goto dump_line;            /* Take common exit    */
  1000. #else
  1001.         if (skipws() != '\n') {
  1002.         cwarn("Unexpected text in #control line ignored", NULLST);
  1003.         skipnl();
  1004.         }
  1005. #endif
  1006.     }
  1007.     return (counter + 1);
  1008. }
  1009.  
  1010. FILE_LOCAL
  1011. doif(hash)
  1012. int        hash;
  1013. /*
  1014.  * Process an #if, #ifdef, or #ifndef.  The latter two are straightforward,
  1015.  * while #if needs a subroutine of its own to evaluate the expression.
  1016.  *
  1017.  * doif() is called only if compiling is TRUE.  If false, compilation
  1018.  * is always supressed, so we don't need to evaluate anything.  This
  1019.  * supresses unnecessary warnings.
  1020.  */
  1021. {
  1022.     register int        c;
  1023.     register int        found;
  1024.  
  1025.     if ((c = skipws()) == '\n' || c == EOF_CHAR) {
  1026.         unget();
  1027.         goto badif;
  1028.     }
  1029.     if (hash == L_if) {
  1030.         unget();
  1031.         found = (eval() != 0);    /* Evaluate expr, != 0 is  TRUE    */
  1032.         hash = L_ifdef;        /* #if is now like #ifdef    */
  1033.     }
  1034.     else {
  1035.         if (type[c] != LET)        /* Next non-blank isn't letter    */
  1036.         goto badif;        /* ... is an error        */
  1037.         found = (lookid(c) != NULL); /* Look for it in symbol table    */
  1038.     }
  1039.     if (found == (hash == L_ifdef)) {
  1040.         compiling = TRUE;
  1041.         *ifptr |= TRUE_SEEN;
  1042.     }
  1043.     else {
  1044.         compiling = FALSE;
  1045.     }
  1046.     return;
  1047.  
  1048. badif:    cerror("#if, #ifdef, or #ifndef without an argument", NULLST);
  1049. #if !OLD_PREPROCESSOR
  1050.     skipnl();                /* Prevent an extra    */
  1051.     unget();                /* Error message    */
  1052. #endif
  1053.     return;
  1054. }
  1055.  
  1056. FILE_LOCAL
  1057. doinclude()
  1058. /*
  1059.  * Process the #include control line.
  1060.  * There are three variations:
  1061.  *    #include "file"        search somewhere relative to the
  1062.  *                current source file, if not found,
  1063.  *                treat as #include <file>.
  1064.  *    #include <file>        Search in an implementation-dependent
  1065.  *                list of places.
  1066.  *    #include token        Expand the token, it must be one of
  1067.  *                "file" or <file>, process as such.
  1068.  *
  1069.  * Note: the November 12 draft forbids '>' in the #include <file> format.
  1070.  * This restriction is unnecessary and not implemented.
  1071.  */
  1072. {
  1073.     register int        c;
  1074.     register int        delim;
  1075. #if HOST == SYS_VMS
  1076.     char            def_filename[NAM$C_MAXRSS + 1];
  1077. #endif
  1078.  
  1079.     delim = macroid(skipws());
  1080.     if (delim != '<' && delim != '"')
  1081.         goto incerr;
  1082.     if (delim == '<')
  1083.         delim = '>';
  1084.     workp = work;
  1085.     instring = TRUE;        /* Accept all characters    */
  1086.     while ((c = get()) != '\n' && c != EOF_CHAR)
  1087.         save(c);            /* Put it away.            */
  1088.     unget();            /* Force nl after includee    */
  1089.     /*
  1090.      * The draft is unclear if the following should be done.
  1091.      */
  1092.     while (--workp >= work && *workp == ' ')
  1093.         ;                /* Trim blanks from filename    */
  1094.     if (*workp != delim)
  1095.         goto incerr;
  1096.     *workp = EOS;            /* Terminate filename        */
  1097.     instring = FALSE;
  1098. #if HOST == SYS_VMS
  1099.     /*
  1100.      * Assume the default .h filetype.
  1101.      */
  1102.     if (!vmsparse(work, ".H", def_filename)) {
  1103.         perror(work);        /* Oops.            */
  1104.         goto incerr;
  1105.     }
  1106.     else if (openinclude(def_filename, (delim == '"')))
  1107.         return;
  1108. #else
  1109.     if (openinclude(work, (delim == '"')))
  1110.         return;
  1111. #endif
  1112.     /*
  1113.      * No sense continuing if #include file isn't there.
  1114.      */
  1115.     cfatal("Cannot open include file \"%s\"", work);
  1116.  
  1117. incerr:    cerror("#include syntax error", NULLST);
  1118.     return;
  1119. }
  1120.  
  1121. FILE_LOCAL int
  1122. openinclude(filename, searchlocal)
  1123. char        *filename;        /* Input file name        */
  1124. int        searchlocal;        /* TRUE if #include "file"    */
  1125. /*
  1126.  * Actually open an include file.  This routine is only called from
  1127.  * doinclude() above, but was written as a separate subroutine for
  1128.  * programmer convenience.  It searches the list of directories
  1129.  * and actually opens the file, linking it into the list of
  1130.  * active files.  Returns TRUE if the file was opened, FALSE
  1131.  * if openinclude() fails.  No error message is printed.
  1132.  */
  1133. {
  1134.     register char        **incptr;
  1135. #if HOST == SYS_VMS
  1136. #if NWORK < (NAM$C_MAXRSS + 1)
  1137.     << error, NWORK isn't greater than NAM$C_MAXRSS >>
  1138. #endif
  1139. #endif
  1140.     char            tmpname[NWORK];    /* Filename work area    */
  1141.  
  1142.     if (searchlocal) {
  1143.         /*
  1144.          * Look in local directory first
  1145.          */
  1146. #if HOST == SYS_UNIX
  1147.         /*
  1148.          * Try to open filename relative to the directory of the current
  1149.          * source file (as opposed to the current directory). (ARF, SCK).
  1150.          */
  1151.         if (filename[0] != '/'
  1152.          && hasdirectory(infile->filename, tmpname))
  1153.         strcat(tmpname, filename);
  1154.         else {
  1155.         strcpy(tmpname, filename);
  1156.         }
  1157. #else
  1158.         if (!hasdirectory(filename, tmpname)
  1159.          && hasdirectory(infile->filename, tmpname))
  1160.         strcat(tmpname, filename);
  1161.         else {
  1162.         strcpy(tmpname, filename);
  1163.         }
  1164. #endif
  1165.         if (openfile(tmpname))
  1166.         return (TRUE);
  1167.     }
  1168.     /*
  1169.      * Look in any directories specified by -I command line
  1170.      * arguments, then in the builtin search list.
  1171.      */
  1172.     for (incptr = incdir; incptr < incend; incptr++) {
  1173.         if (strlen(*incptr) + strlen(filename) >= (NWORK - 1))
  1174.         cfatal("Filename work buffer overflow", NULLST);
  1175.         else {
  1176. #if HOST == SYS_UNIX
  1177.         if (filename[0] == '/')
  1178.             strcpy(tmpname, filename);
  1179.         else {
  1180.             sprintf(tmpname, "%s/%s", *incptr, filename);
  1181.         }
  1182. #else
  1183.         if (!hasdirectory(filename, tmpname))
  1184.             sprintf(tmpname, "%s%s", *incptr, filename);
  1185. #endif
  1186.         if (openfile(tmpname))
  1187.             return (TRUE);
  1188.         }
  1189.     }
  1190.     return (FALSE);
  1191. }
  1192.  
  1193. FILE_LOCAL int
  1194. hasdirectory(source, result)
  1195. char        *source;    /* Directory to examine            */
  1196. char        *result;    /* Put directory stuff here        */
  1197. /*
  1198.  * If a device or directory is found in the source filename string, the
  1199.  * node/device/directory part of the string is copied to result and
  1200.  * hasdirectory returns TRUE.  Else, nothing is copied and it returns FALSE.
  1201.  */
  1202. {
  1203. #if HOST == SYS_UNIX
  1204.     register char        *tp;
  1205.  
  1206.     if ((tp = strrchr(source, '/')) == NULL)
  1207.         return (FALSE);
  1208.     else {
  1209.         strncpy(result, source, tp - source + 1);
  1210.         result[tp - source + 1] = EOS;
  1211.         return (TRUE);
  1212.     }
  1213. #else
  1214. #if HOST == SYS_VMS
  1215.     if (vmsparse(source, NULLST, result)
  1216.      && result[0] != EOS)
  1217.         return (TRUE);
  1218.     else {
  1219.         return (FALSE);
  1220.     }
  1221. #else
  1222.     /*
  1223.      * Random DEC operating system (RSX, RT11, RSTS/E)
  1224.      */
  1225.     register char        *tp;
  1226.  
  1227.     if ((tp = strrchr(source, ']')) == NULL
  1228.      && (tp = strrchr(source, ':')) == NULL)
  1229.         return (FALSE);
  1230.     else {
  1231.         strncpy(result, source, tp - source + 1);
  1232.         result[tp - source + 1] = EOS;
  1233.         return (TRUE);
  1234.     }
  1235. #endif
  1236. #endif
  1237. }
  1238.  
  1239. #if HOST == SYS_VMS
  1240.  
  1241. /*
  1242.  * EXP_DEV is set if a device was specified, EXP_DIR if a directory
  1243.  * is specified.  (Both set indicate a file-logical, but EXP_DEV
  1244.  * would be set by itself if you are reading, say, SYS$INPUT:)
  1245.  */
  1246. #define DEVDIR (NAM$M_EXP_DEV | NAM$M_EXP_DIR)
  1247.  
  1248. FILE_LOCAL int
  1249. vmsparse(source, defstring, result)
  1250. char        *source;
  1251. char        *defstring;    /* non-NULL -> default string.        */
  1252. char        *result;    /* Size is at least NAM$C_MAXRSS + 1    */
  1253. /*
  1254.  * Parse the source string, applying the default (properly, using
  1255.  * the system parse routine), storing it in result.
  1256.  * TRUE if it parsed, FALSE on error.
  1257.  *
  1258.  * If defstring is NULL, there are no defaults and result gets
  1259.  * (just) the node::[directory] part of the string (possibly "")
  1260.  */
  1261. {
  1262.     struct FAB    fab = cc$rms_fab;    /* File access block    */
  1263.     struct NAM    nam = cc$rms_nam;    /* File name block    */
  1264.     char        fullname[NAM$C_MAXRSS + 1];
  1265.     register char    *rp;            /* Result pointer    */
  1266.  
  1267.     fab.fab$l_nam = &nam;            /* fab -> nam        */
  1268.     fab.fab$l_fna = source;            /* Source filename    */
  1269.     fab.fab$b_fns = strlen(source);        /* Size of source    */
  1270.     fab.fab$l_dna = defstring;        /* Default string    */
  1271.     if (defstring != NULLST)
  1272.         fab.fab$b_dns = strlen(defstring);    /* Size of default    */
  1273.     nam.nam$l_esa = fullname;        /* Expanded filename    */
  1274.     nam.nam$b_ess = NAM$C_MAXRSS;        /* Expanded name size    */
  1275.     if (sys$parse(&fab) == RMS$_NORMAL) {    /* Parse away        */
  1276.         fullname[nam.nam$b_esl] = EOS;    /* Terminate string    */
  1277.         result[0] = EOS;            /* Just in case        */
  1278.         rp = &result[0];
  1279.         /*
  1280.          * Remove stuff added implicitly, accepting node names and
  1281.          * dev:[directory] strings (but not process-permanent files).
  1282.          */
  1283.         if ((nam.nam$l_fnb & NAM$M_PPF) == 0) {
  1284.         if ((nam.nam$l_fnb & NAM$M_NODE) != 0) {
  1285.             strncpy(result, nam.nam$l_node, nam.nam$b_node);
  1286.             rp += nam.nam$b_node;
  1287.             *rp = EOS;
  1288.         }
  1289.         if ((nam.nam$l_fnb & DEVDIR) == DEVDIR) {
  1290.             strncpy(rp, nam.nam$l_dev, nam.nam$b_dev + nam.nam$b_dir);
  1291.             rp += nam.nam$b_dev + nam.nam$b_dir;
  1292.             *rp = EOS;
  1293.         }
  1294.         }
  1295.         if (defstring != NULLST) {
  1296.         strncpy(rp, nam.nam$l_name, nam.nam$b_name + nam.nam$b_type);
  1297.         rp += nam.nam$b_name + nam.nam$b_type;
  1298.         *rp = EOS;
  1299.         if ((nam.nam$l_fnb & NAM$M_EXP_VER) != 0) {
  1300.             strncpy(rp, nam.nam$l_ver, nam.nam$b_ver);
  1301.             rp[nam.nam$b_ver] = EOS;
  1302.         }
  1303.         }
  1304.         return (TRUE);
  1305.     }
  1306.     return (FALSE);
  1307. }
  1308. #endif
  1309.  
  1310. -h- cpp3.c    Mon Jan  7 23:59:31 1985    cpp3.c
  1311. /*
  1312.  *                C P P 3 . C
  1313.  *
  1314.  *            File open and command line options
  1315.  *
  1316.  * Edit history
  1317.  * 13-Nov-84    MM    Split from cpp1.c
  1318.  */
  1319.  
  1320. #include    <stdio.h>
  1321. #include    <ctype.h>
  1322. #include    "cppdef.h"
  1323. #include    "cpp.h"
  1324. #if DEBUG && (HOST == SYS_VMS || HOST == SYS_UNIX)
  1325. #include    <signal.h>
  1326. extern int    abort();        /* For debugging        */
  1327. #endif
  1328.  
  1329. int
  1330. openfile(filename)
  1331. char        *filename;
  1332. /*
  1333.  * Open a file, add it to the linked list of open files.
  1334.  * This is called only from openfile() above.
  1335.  */
  1336. {
  1337.     register FILE        *fp;
  1338.  
  1339.     if ((fp = fopen(filename, "r")) == NULL) {
  1340. #if DEBUG
  1341.         perror(filename);
  1342. #endif
  1343.         return (FALSE);
  1344.     }
  1345. #if DEBUG
  1346.     if (debug)
  1347.         fprintf(stderr, "Reading from \"%s\"\n", filename);
  1348. #endif
  1349.     addfile(fp, filename);
  1350.     return (TRUE);
  1351. }
  1352.  
  1353. addfile(fp, filename)
  1354. FILE        *fp;            /* Open file pointer        */
  1355. char        *filename;        /* Name of the file        */
  1356. /*
  1357.  * Initialize tables for this open file.  This is called from openfile()
  1358.  * above (for #include files), and from the entry to cpp to open the main
  1359.  * input file.  It calls a common routine, getfile() to build the FILEINFO
  1360.  * structure which is used to read characters.  (getfile() is also called
  1361.  * to setup a macro replacement.)
  1362.  */
  1363. {
  1364.     register FILEINFO    *file;
  1365.     extern FILEINFO        *getfile();
  1366.  
  1367.     file = getfile(NBUFF, filename);
  1368.     file->fp = fp;            /* Better remember FILE *    */
  1369.     file->buffer[0] = EOS;        /* Initialize for first read    */
  1370.     line = 1;            /* Working on line 1 now    */
  1371.     wrongline = TRUE;        /* Force out initial #line    */
  1372. }
  1373.  
  1374. setincdirs()
  1375. /*
  1376.  * Append system-specific directories to the include directory list.
  1377.  * Called only when cpp is started.
  1378.  */
  1379. {
  1380.  
  1381. #ifdef    CPP_INCLUDE
  1382.     *incend++ = CPP_INCLUDE;
  1383. #define    IS_INCLUDE    1
  1384. #else
  1385. #define    IS_INCLUDE    0
  1386. #endif
  1387.  
  1388. #if HOST == SYS_UNIX
  1389.     *incend++ = "/usr/include";
  1390. #define    MAXINCLUDE    (NINCLUDE - 1 - IS_INCLUDE)
  1391. #endif
  1392.  
  1393. #if HOST == SYS_VMS
  1394.     extern char    *getenv();
  1395.  
  1396.     if (getenv("C$LIBRARY") != NULL)
  1397.         *incend++ = "C$LIBRARY:";
  1398.     *incend++ = "SYS$LIBRARY:";
  1399. #define    MAXINCLUDE    (NINCLUDE - 2 - IS_INCLUDE)
  1400. #endif
  1401.  
  1402. #if HOST == SYS_RSX
  1403.     extern int    $$rsts;            /* TRUE on RSTS/E    */
  1404.     extern int    $$pos;            /* TRUE on PRO-350 P/OS    */
  1405.     extern int    $$vms;            /* TRUE on VMS compat.    */
  1406.  
  1407.     if ($$pos) {                /* P/OS?        */
  1408.         *incend++ = "SY:[ZZDECUSC]";    /* C #includes        */
  1409.         *incend++ = "LB:[1,5]";        /* RSX library        */
  1410.     }
  1411.     else if ($$rsts) {            /* RSTS/E?        */
  1412.         *incend++ = "SY:@";            /* User-defined account    */
  1413.         *incend++ = "C:";            /* Decus-C library    */
  1414.         *incend++ = "LB:[1,1]";        /* RSX library        */
  1415.     }
  1416.     else if ($$vms) {            /* VMS compatibility?    */
  1417.         *incend++ = "C:";
  1418.     }
  1419.     else {                    /* Plain old RSX/IAS    */
  1420.         *incend++ = "LB:[1,1]";
  1421.     }
  1422. #define    MAXINCLUDE    (NINCLUDE - 3 - IS_INCLUDE)
  1423. #endif
  1424.  
  1425. #if HOST == SYS_RT11
  1426.     extern int    $$rsts;            /* RSTS/E emulation?    */
  1427.  
  1428.     if ($$rsts)
  1429.         *incend++ = "SY:@";            /* User-defined account    */
  1430.     *incend++ = "C:";            /* Decus-C library disk    */
  1431.     *incend++ = "SY:";            /* System (boot) disk    */
  1432. #define    MAXINCLUDE    (NINCLUDE - 3 - IS_INCLUDE)
  1433. #endif
  1434. }
  1435.  
  1436. int
  1437. dooptions(argc, argv)
  1438. int        argc;
  1439. char        *argv[];
  1440. /*
  1441.  * dooptions is called to process command line arguments (-Detc).
  1442.  * It is called only at cpp startup.
  1443.  */
  1444. {
  1445.     register char        *ap;
  1446.     register DEFBUF        *dp;
  1447.     register int        c;
  1448.     int            i, j;
  1449.     char            *arg;
  1450.     SIZES            *sizp;        /* For -S        */
  1451.     int            size;        /* For -S        */
  1452.     int            isdatum;    /* FALSE for -S*    */
  1453.     int            endtest;    /* For -S        */
  1454.  
  1455.     for (i = j = 1; i < argc; i++) {
  1456.         arg = ap = argv[i];
  1457.         if (*ap++ != '-' || *ap == EOS)
  1458.         argv[j++] = argv[i];
  1459.         else {
  1460.         c = *ap++;            /* Option byte        */
  1461.         if (islower(c))            /* Normalize case    */
  1462.             c = toupper(c);
  1463.         switch (c) {            /* Command character    */
  1464.         case 'C':            /* Keep comments    */
  1465.             cflag = TRUE;
  1466.             keepcomments = TRUE;
  1467.             break;
  1468.  
  1469.         case 'D':            /* Define symbol    */
  1470. #if HOST != SYS_UNIX
  1471.             zap_uc(ap);            /* Force define to U.C.    */
  1472. #endif
  1473.             /*
  1474.              * If the option is just "-Dfoo", make it -Dfoo=1
  1475.              */
  1476.             while (*ap != EOS && *ap != '=')
  1477.             ap++;
  1478.             if (*ap == EOS)
  1479.             ap = "1";
  1480.             else
  1481.             *ap++ = EOS;
  1482.             /*
  1483.              * Now, save the word and its definition.
  1484.              */
  1485.             dp = defendel(argv[i] + 2, FALSE);
  1486.             dp->repl = savestring(ap);
  1487.             dp->nargs = DEF_NOARGS;
  1488.             break;
  1489.  
  1490.         case 'E':            /* Ignore non-fatal    */
  1491.             eflag = TRUE;        /* errors.        */
  1492.             break;
  1493.  
  1494.         case 'I':            /* Include directory    */
  1495.             if (incend >= &incdir[MAXINCLUDE])
  1496.             cfatal("Too many include directories", NULLST);
  1497.             *incend++ = ap;
  1498.             break;
  1499.  
  1500.         case 'N':            /* No predefineds    */
  1501.             nflag++;            /* Repeat to undefine    */
  1502.             break;            /* __LINE__, etc.    */
  1503.  
  1504.         case 'S':
  1505.             sizp = size_table;
  1506.             if (isdatum = (*ap != '*'))    /* If it's just -S,    */
  1507.             endtest = T_FPTR;    /* Stop here        */
  1508.             else {            /* But if it's -S*    */
  1509.             ap++;            /* Step over '*'    */
  1510.             endtest = 0;        /* Stop at end marker    */
  1511.             }
  1512.             while (sizp->bits != endtest && *ap != EOS) {
  1513.             if (!isdigit(*ap)) {    /* Skip to next digit    */
  1514.                 ap++;
  1515.                 continue;
  1516.             }
  1517.             size = 0;        /* Compile the value    */
  1518.             while (isdigit(*ap)) {
  1519.                 size *= 10;
  1520.                 size += (*ap++ - '0');
  1521.             }
  1522.             if (isdatum)
  1523.                 sizp->size = size;    /* Datum size        */
  1524.             else
  1525.                 sizp->psize = size;    /* Pointer size        */
  1526.             sizp++;
  1527.             }
  1528.             if (sizp->bits != endtest)
  1529.             cwarn("-S, too few values specified in %s", argv[i]);
  1530.             else if (*ap != EOS)
  1531.             cwarn("-S, too many values, \"%s\" unused", ap);
  1532.             break;
  1533.  
  1534.         case 'U':            /* Undefine symbol    */
  1535. #if HOST != SYS_UNIX
  1536.             zap_uc(ap);
  1537. #endif
  1538.             if (defendel(ap, TRUE) == NULL)
  1539.             cwarn("\"%s\" wasn't defined", ap);
  1540.             break;
  1541.  
  1542. #if DEBUG
  1543.         case 'X':            /* Debug        */
  1544.             debug = (isdigit(*ap)) ? atoi(ap) : 1;
  1545. #if (HOST == SYS_VMS || HOST == SYS_UNIX)
  1546.             signal(SIGINT, abort);    /* Trap "interrupt"    */
  1547. #endif
  1548.             fprintf(stderr, "Debug set to %d\n", debug);
  1549.             break;
  1550. #endif
  1551.  
  1552.         default:            /* What is this one?    */
  1553.             cwarn("Unknown option \"%s\"", arg);
  1554.             fprintf(stderr, "The following options are valid:\n\
  1555.   -C\t\t\tWrite source file comments to output\n\
  1556.   -Dsymbol=value\tDefine a symbol with the given (optional) value\n\
  1557.   -Idirectory\t\tAdd a directory to the #include search list\n\
  1558.   -N\t\t\tDon't predefine target-specific names\n\
  1559.   -Stext\t\tSpecify sizes for #if sizeof\n\
  1560.   -Usymbol\t\tUndefine symbol\n");
  1561. #if DEBUG
  1562.             fprintf(stderr, "  -Xvalue\t\tSet internal debug flag\n");
  1563. #endif
  1564.             break;
  1565.         }            /* Switch on all options    */
  1566.         }                /* If it's a -option        */
  1567.     }                /* For all arguments        */
  1568.     if (j > 3) {
  1569.         cerror(
  1570.         "Too many file arguments.  Usage: cpp [input [output]]",
  1571.         NULLST);
  1572.     }
  1573.     return (j);            /* Return new argc        */
  1574. }
  1575.  
  1576. #if HOST != SYS_UNIX
  1577. FILE_LOCAL
  1578. zap_uc(ap)
  1579. register char    *ap;
  1580. /*
  1581.  * Dec operating systems mangle upper-lower case in command lines.
  1582.  * This routine forces the -D and -U arguments to uppercase.
  1583.  * It is called only on cpp startup by dooptions().
  1584.  */
  1585. {
  1586.     while (*ap != EOS) {
  1587.         /*
  1588.          * Don't use islower() here so it works with Multinational
  1589.          */
  1590.         if (*ap >= 'a' && *ap <= 'z')
  1591.         *ap = toupper(*ap);
  1592.         ap++;
  1593.     }
  1594. }
  1595. #endif
  1596.  
  1597. initdefines()
  1598. /*
  1599.  * Initialize the built-in #define's.  There are two flavors:
  1600.  *     #define decus    1        (static definitions)
  1601.  *    #define    __FILE__ ??        (dynamic, evaluated by magic)
  1602.  * Called only on cpp startup.
  1603.  *
  1604.  * Note: the built-in static definitions are supressed by the -N option.
  1605.  * __LINE__, __FILE__, and __DATE__ are always present.
  1606.  */
  1607. {
  1608.     register char        **pp;
  1609.     register char        *tp;
  1610.     register DEFBUF        *dp;
  1611.     int            i;
  1612.     long            tvec;
  1613.     extern char        *ctime();
  1614.  
  1615.     /*
  1616.      * Predefine the built-in symbols.  Allow the
  1617.      * implementor to pre-define a symbol as "" to
  1618.      * eliminate it.
  1619.      */
  1620.     if (nflag == 0) {
  1621.         for (pp = preset; *pp != NULL; pp++) {
  1622.         if (*pp[0] != EOS) {
  1623.             dp = defendel(*pp, FALSE);
  1624.             dp->repl = savestring("1");
  1625.             dp->nargs = DEF_NOARGS;
  1626.         }
  1627.         }
  1628.     }
  1629.     /*
  1630.      * The magic pre-defines (__FILE__ and __LINE__ are
  1631.      * initialized with negative argument counts.  expand()
  1632.      * notices this and calls the appropriate routine.
  1633.      * DEF_NOARGS is one greater than the first "magic" definition.
  1634.      */
  1635.     if (nflag < 2) {
  1636.         for (pp = magic, i = DEF_NOARGS; *pp != NULL; pp++) {
  1637.         dp = defendel(*pp, FALSE);
  1638.         dp->nargs = --i;
  1639.         }
  1640. #if OK_DATE
  1641.         /*
  1642.          * Define __DATE__ as today's date.
  1643.          */
  1644.         dp = defendel("__DATE__", FALSE);
  1645.         dp->repl = tp = getmem(27);
  1646.         dp->nargs = DEF_NOARGS;
  1647.         time(&tvec);
  1648.         *tp++ = '"';
  1649.         strcpy(tp, ctime(&tvec));
  1650.         tp[24] = '"';            /* Overwrite newline    */
  1651. #endif
  1652.     }
  1653. }
  1654.  
  1655. #if HOST == SYS_VMS
  1656. /*
  1657.  * getredirection() is intended to aid in porting C programs
  1658.  * to VMS (Vax-11 C) which does not support '>' and '<'
  1659.  * I/O redirection.  With suitable modification, it may
  1660.  * useful for other portability problems as well.
  1661.  */
  1662.  
  1663. int
  1664. getredirection(argc, argv)
  1665. int        argc;
  1666. char        **argv;
  1667. /*
  1668.  * Process vms redirection arg's.  Exit if any error is seen.
  1669.  * If getredirection() processes an argument, it is erased
  1670.  * from the vector.  getredirection() returns a new argc value.
  1671.  *
  1672.  * Warning: do not try to simplify the code for vms.  The code
  1673.  * presupposes that getredirection() is called before any data is
  1674.  * read from stdin or written to stdout.
  1675.  *
  1676.  * Normal usage is as follows:
  1677.  *
  1678.  *    main(argc, argv)
  1679.  *    int        argc;
  1680.  *    char        *argv[];
  1681.  *    {
  1682.  *        argc = getredirection(argc, argv);
  1683.  *    }
  1684.  */
  1685. {
  1686.     register char        *ap;    /* Argument pointer    */
  1687.     int            i;    /* argv[] index        */
  1688.     int            j;    /* Output index        */
  1689.     int            file;    /* File_descriptor     */
  1690.     extern int        errno;    /* Last vms i/o error     */
  1691.  
  1692.     for (j = i = 1; i < argc; i++) {   /* Do all arguments    */
  1693.         switch (*(ap = argv[i])) {
  1694.         case '<':            /* <file        */
  1695.         if (freopen(++ap, "r", stdin) == NULL) {
  1696.             perror(ap);        /* Can't find file    */
  1697.             exit(errno);    /* Is a fatal error    */
  1698.         }
  1699.         break;
  1700.  
  1701.         case '>':            /* >file or >>file    */
  1702.         if (*++ap == '>') {    /* >>file        */
  1703.             /*
  1704.              * If the file exists, and is writable by us,
  1705.              * call freopen to append to the file (using the
  1706.              * file's current attributes).  Otherwise, create
  1707.              * a new file with "vanilla" attributes as if the
  1708.              * argument was given as ">filename".
  1709.              * access(name, 2) returns zero if we can write on
  1710.              * the specified file.
  1711.              */
  1712.             if (access(++ap, 2) == 0) {
  1713.             if (freopen(ap, "a", stdout) != NULL)
  1714.                 break;    /* Exit case statement    */
  1715.             perror(ap);    /* Error, can't append    */
  1716.             exit(errno);    /* After access test    */
  1717.             }            /* If file accessable    */
  1718.         }
  1719.         /*
  1720.          * On vms, we want to create the file using "standard"
  1721.          * record attributes.  creat(...) creates the file
  1722.          * using the caller's default protection mask and
  1723.          * "variable length, implied carriage return"
  1724.          * attributes. dup2() associates the file with stdout.
  1725.          */
  1726.         if ((file = creat(ap, 0, "rat=cr", "rfm=var")) == -1
  1727.          || dup2(file, fileno(stdout)) == -1) {
  1728.             perror(ap);        /* Can't create file    */
  1729.             exit(errno);    /* is a fatal error    */
  1730.         }            /* If '>' creation    */
  1731.         break;            /* Exit case test    */
  1732.  
  1733.         default:
  1734.         argv[j++] = ap;        /* Not a redirector    */
  1735.         break;            /* Exit case test    */
  1736.         }
  1737.     }                /* For all arguments    */
  1738.     argv[j] = NULL;            /* Terminate argv[]    */
  1739.     return (j);            /* Return new argc    */
  1740. }
  1741. #endif
  1742.  
  1743.  
  1744.  
  1745.