home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / cool / cool.lha / ice / pisces / cpp / cpp1.c < prev    next >
Encoding:
Text File  |  1991-09-04  |  25.5 KB  |  780 lines

  1. /*
  2.  * CPP main program.
  3.  *
  4.  * Edit history
  5.  * 21-May-84    MM    "Field test" release
  6.  * 23-May-84    MM    Some minor hacks.
  7.  * 30-May-84    ARF    Didn't get enough memory for __DATE__
  8.  *            Added code to read stdin if no input
  9.  *            files are provided.
  10.  * 29-Jun-84    MM    Added ARF's suggestions, Unixifying cpp.
  11.  * 11-Jul-84    MM    "Official" first release (that's what I thought!)
  12.  * 22-Jul-84    MM/ARF/SCK Fixed line number bugs, added cpp recognition
  13.  *            of #line, fixed problems with #include.
  14.  * 23-Jul-84    MM    More (minor) include hacking, some documentation.
  15.  *            Also, redid cpp's #include files
  16.  * 25-Jul-84    MM    #line filename isn't used for #include searchlist
  17.  *            #line format is <number> <optional name>
  18.  * 25-Jul-84    ARF/MM    Various bugs, mostly serious.  Removed homemade doprint
  19.  * 01-Aug-84    MM    Fixed recursion bug, remove extra newlines and
  20.  *            leading whitespace from cpp output.
  21.  * 02-Aug-84    MM    Hacked (i.e. optimized) out blank lines and unneeded
  22.  *            whitespace in general.  Cleaned up unget()'s.
  23.  * 03-Aug-84    Keie    Several bug fixes from Ed Keizer, Vrije Universitet.
  24.  *            -- corrected arg. count in -D and pre-defined
  25.  *            macros.  Also, allow \n inside macro actual parameter
  26.  *            lists.
  27.  * 06-Aug-84    MM    If debugging, dump the preset vector at startup.
  28.  * 12-Aug-84    MM/SCK    Some small changes from Sam Kendall
  29.  * 15-Aug-84    Keie/MM    cerror, cwarn, etc. take a single string arg.
  30.  *            cierror, etc. take a single int. arg.
  31.  *            changed LINE_PREFIX slightly so it can be
  32.  *            changed in the makefile.
  33.  * 31-Aug-84    MM    USENET net.sources release.
  34.  *  7-Sep-84    SCH/ado Lint complaints
  35.  * 10-Sep-84    Keie    Char's can't be signed in some implementations
  36.  * 11-Sep-84    ado    Added -C flag, pathological line number fix
  37.  * 13-Sep-84    ado    Added -E flag (does nothing) and "-" file for stdin.
  38.  * 14-Sep-84    MM    Allow # 123 as a synonym for #line 123
  39.  * 19-Sep-84    MM    scanid always reads to token, make sure #line is
  40.  *            written to a new line, even if -C switch given.
  41.  *            Also, cpp - - reads stdin, writes stdout.
  42.  * 03-Oct-84    ado/MM    Several changes to line counting and keepcomments
  43.  *            stuff.  Also a rewritten control() hasher -- much
  44.  *            simpler and no less "perfect". Note also changes
  45.  *            in cpp3.c to fix numeric scanning.
  46.  * 04-Oct-84    MM    Added recognition of macro formal parameters if
  47.  *            they are the only thing in a string, per the
  48.  *            draft standard.
  49.  * 08-Oct-84    MM    One more attack on scannumber
  50.  * 15-Oct-84    MM/ado    Added -N to disable predefined symbols.  Fixed
  51.  *            linecount if COMMENT_INVISIBLE enabled.
  52.  * 22-Oct-84    MM    Don't evaluate the #if/#ifdef argument if
  53.  *            compilation is supressed.  This prevents
  54.  *            unnecessary error messages in sequences such as
  55.  *                #ifdef FOO        -- undefined
  56.  *                #if FOO == 10    -- shouldn't print warning
  57.  * 25-Oct-84    MM    Fixed bug in false ifdef supression.  On vms,
  58.  *            #include <foo> should open foo.h -- this duplicates
  59.  *            the behavior of Vax-C
  60.  * 31-Oct-84    ado/MM    Parametized $ in indentifiers.  Added a better
  61.  *            token concatenator and took out the trial
  62.  *            concatenation code.  Also improved #ifdef code
  63.  *            and cleaned up the macro recursion tester.
  64.  *  2-Nov-84    MM/ado    Some bug fixes in token concatenation, also
  65.  *            a variety of minor (uninteresting) hacks.
  66.  *  6-Nov-84    MM    Happy Birthday.  Broke into 4 files and added
  67.  *            #if sizeof (basic_types)
  68.  *  9-Nov-84    MM    Added -S* for pointer type sizes
  69.  * 13-Nov-84    MM    Split cpp1.c, added vms defaulting
  70.  * 23-Nov-84    MM/ado    -E supresses error exit, added CPP_INCLUDE,
  71.  *            fixed strncpy bug.
  72.  *  3-Dec-84    ado/MM    Added OLD_PREPROCESSOR
  73.  *  7-Dec-84    MM    Stuff in Nov 12 Draft Standard
  74.  * 17-Dec-84    george    Fixed problems with recursive macros
  75.  * 17-Dec-84    MM    Yet another attack on #if's (f/t)level removed.
  76.  * 07-Jan-85    ado    Init defines before doing command line options
  77.  *            so -Uunix works.
  78.  * 21-Oct-85    RMS    Rename `token' to `tokenbuf'.
  79.  *            Allocate it dynamically, with size in `tokenbsize'.
  80.  * 23-Oct-85    RMS    Do not print message about number of errors.
  81.  *
  82.  * 19-Jan-90    DKM     Support for MVS.
  83.  * 04-May-90    MJF     Added predefined constant for target_arch.
  84.  * 18-May-90    MBN     Conditional compilation on COOL to get "clean" cpp
  85.  */
  86.  
  87. /*)BUILD
  88.     $(PROGRAM)    = cpp
  89.     $(FILES)    = { cpp1 cpp2 cpp3 cpp4 cpp5 cpp6 }
  90.     $(INCLUDE)    = { cppdef.h cpp.h }
  91.     $(STACK)    = 2000
  92.     $(TKBOPTIONS)    = {
  93.         STACK    = 2000
  94.     }
  95. */
  96.  
  97. /*    DOCUMENTATION
  98.  
  99. title    cpp        C Pre-Processor
  100. index            C pre-processor
  101.  
  102. synopsis
  103.     cpp [-options] [infile [outfile]]
  104.  
  105. description
  106.  
  107.     CPP reads a C source file, expands macros and include
  108.     files, and writes an input file for the C compiler.
  109.     If no file arguments are given, CPP reads from stdin
  110.     and writes to stdout.  If one file argument is given,
  111.     it will define the input file, while two file arguments
  112.     define both input and output files.  The file name "-"
  113.     is a synonym for stdin or stdout as appropriate.
  114.  
  115.     The following options are supported.  Options may
  116.     be given in either case.
  117.  
  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.  
  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.  
  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.  
  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.  
  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.  
  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.  
  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.  
  181.     -Xnumber    Enable debugging code.  If no value is
  182.                     given, a value of 1 will be used.
  183.         -X1             debug print of files #included
  184.         -X2             debug inserts #control as comments in output
  185.         -X3             debug does both -X1 and -X2
  186.  
  187. Pre-Defined Variables
  188.  
  189.     When CPP begins processing, the following variables will
  190.     have been defined (unless the -N option is specified):
  191.  
  192.     Target computer (as appropriate):
  193.  
  194.         pdp11, vax, M68000 m68000 m68k
  195.  
  196.     Target operating system (as appropriate):
  197.  
  198.         rsx, rt11, vms, unix
  199.  
  200.     Target compiler (as appropriate):
  201.  
  202.         decus, vax11c
  203.  
  204.     The implementor may add definitions to this list.
  205.     The default definitions match the definition of the
  206.     host computer, operating system, and C compiler.
  207.  
  208.     The following are always available unless undefined (or
  209.     -N was specified twice):
  210.  
  211.     __FILE__    The input (or #include) file being compiled
  212.     (as a quoted string).
  213.  
  214.     __LINE__    The line number being compiled.
  215.  
  216.     __DATE__    The date of compilation as "Mmm dd yy"
  217.  
  218.     __TIME__    The time of compilation as "hh:mm:ss"
  219.  
  220.     __STDC__    The constant 1.
  221.  
  222.     Thus,
  223.         printf("Bug at line %s,", __LINE__);
  224.         printf(" source file %s", __FILE__);
  225.         printf(" compiled on %s", __DATE__);
  226.  
  227. Draft Proposed Ansi Standard Considerations
  228.  
  229.     When CPP is itself compiled, many features of the Draft
  230.     Proposed Standard that are incompatible with existing
  231.     preprocessors may be disabled.  See the comments in CPP's
  232.     source for details.
  233.  
  234.     Comments are removed from the input text.  The comment
  235.     is replaced by a single space character.  The -C option
  236.     preserves comments, writing them to the output file.
  237.  
  238.     The '$' character is considered to be a letter.  This is
  239.     a permitted extension.
  240.  
  241.     The following new features of C are processed by CPP:
  242.     #elif expression    (_#else _#if)
  243.     '\xNNN'             (Hexadecimal constant)
  244.     '\a'                (Ascii BELL)
  245.     '\v'                (Ascii Vertical Tab)
  246.     #if defined NAME    1 if defined, 0 if not
  247.     #if defined (NAME)  1 if defined, 0 if not  
  248.     #if sizeof (basic type)
  249.     unary +
  250.     U, 123LU            Unsigned ints and longs.
  251.     12.3L               Long double numbers
  252.     token_#token        Token concatenation
  253.     #include token      Expands to filename
  254.         #error tokens       Flags an error
  255.  
  256.     The Draft Proposed Standard has extended C, adding a constant
  257.     string concatenation operator, where
  258.  
  259.         "foo" "bar"
  260.  
  261.     is regarded as the single string "foobar".  (This does not
  262.     affect CPP's processing but does permit a limited form of
  263.     macro argument substitution into strings as will be discussed.)
  264.  
  265.     The Standard Committee plans to add token concatenation
  266.     to #define command lines as follows:
  267.     The sequence "Token1 ## Token2" is treated
  268.     as if the programmer wrote "Token1Token2".  This could
  269.     be used as follows:
  270.  
  271.         #line 123
  272.         #define ATLINE foo ## __LINE__
  273.  
  274.     ATLINE would be defined as foo123.
  275.  
  276.     If the tokens T1 and T2 are concatenated into T3,
  277.     this implementation operates as follows:
  278.  
  279.       1. Expand T1 if it is a macro.
  280.       2. Expand T2 if it is a macro.
  281.       3. Join the tokens, forming T3.
  282.       4. Expand T3 if it is a macro.
  283.  
  284.         If a macro parameter is immediately proceeded by a #, string
  285.         quotes (") are placed around the substituted parameter and
  286.         a \ character is inserted before each " or \ character that
  287.         appears surrounding,or inside a string literal or character
  288.         constant in the argument.
  289.  
  290.         Example:
  291.         #define vprint(name, size) \
  292.           printf(#name "[" "size" "] = {\n")
  293.           ... vprint(vector, 123);
  294.  
  295.     expands (effectively) to
  296.  
  297.           vprint("vector[123] = {\n");
  298.  
  299.     Note that this will be useful if your C compiler supports
  300.     the new string concatenation operation noted above.
  301.  
  302. EXTENSIONS
  303.  
  304.     An extended macro facility is provided which allows and arbitrary unix
  305.     process to act as a macro expander.  To define a macro do one of the
  306.     following:
  307.  
  308.     #pragma defmacro name <file> options
  309.     #pragma defmacro name "file" options
  310.     #pragma defmacro name program options
  311.  
  312.     This provides a mapping between macro names and the file to be
  313.     executed, which is on the include search path. "options" is zero or
  314.         more of the following: 
  315.     recursive    - when present, the macro may be recursively expanded.
  316.     expanding    - when present, input to the macro is macro-expanded.
  317.     delimiter=?  - the default delimiter of ; is replaced with ?
  318.     condition=?  - expand only if this char found after name
  319.     other        - unknown options are passed as arguments to the
  320.                macro expander.
  321.  
  322.     When a "defmacro" style macro's name is found, the name and everything
  323.     until the delimiter (includling all matching {} [] () <> "" '' and
  324.     comments found along the way) is piped into the macro procedure's
  325.     standard-input.  The procedure's standard output is scanned by CPP for
  326.     further processing. The expansion replaces the macro call.
  327.     number.
  328.  
  329. error messages
  330.  
  331.     Many.  CPP prints warning or error messages if you try to
  332.     use multiple-byte character constants (non-transportable)
  333.     if you #undef a symbol that was not defined, or if your
  334.     program has potentially nested comments.
  335.  
  336. authors
  337.  
  338.     Martin Minow (Origional version)
  339.         LaMott Oren  (Macro extensions and ANSI compatability)
  340.  
  341. bugs
  342.  
  343.     The #if expression processor uses signed integers only.
  344.     I.e, #if 0xFFFFu < 0 may be TRUE.
  345.  
  346.         This program differs from tha ANSI specification as follows:
  347.       Trigraph sequences aren't implemented.
  348.  
  349. */
  350.  
  351. #include    <stdio.h>
  352. #include    <ctype.h>
  353. #include    "cppdef.h"
  354. #include    "cpp.h"
  355.  
  356. #if HOST == SYS_MVS
  357. extern char *_stdiamp = "prompt=";  /* no prompting from sysin */
  358. extern char *_stdoamp = "print=no"; /* stdout doesn't need page fmt attr. */
  359. extern char *_stdeamp = "print=no"; /* stderr doesn't need page fmt attr. */
  360. #endif
  361.  
  362. #ifdef COOL
  363. /*
  364.  * Table of internal macros
  365.  *   (Alternating strings and function pointers, termnated with NULL)
  366.  */
  367. extern int parmtype();            /* Make names for parameterized types */
  368. extern int define_symbol();         /* Define a symbol in a package */
  369. extern int define_macro();        /* Define a fancy macro */
  370. extern int member();            /* Symbolic equality test */
  371. extern int class_macro();        /* C++ class processing */
  372. extern int classmac();            /* C++ class processing */
  373. extern int template();            /* Paramertized type definition */
  374. extern int declare();            /* Paramertized type declaration */
  375. extern int implement();            /* Paramertized type code generation */
  376. extern int implement_n();        /* Paramertized type code generation */
  377. extern int exception();            /* Error recovery code generation */
  378. extern int generate();            /* macro looping mechanism */
  379. extern int compress();            /* compress out white space */
  380.  
  381. struct expander_pair internal_macros[] = {
  382.   {"parmtype", parmtype},
  383.   {"define_symbol", define_symbol},
  384.   {"macro", define_macro},
  385.   {"member", member},
  386.   {"class", class_macro},
  387.   {"classmac", classmac},
  388.   {"template", template},
  389.   {"declare", declare},
  390.   {"implement", implement},
  391.   {"implement_n", implement_n},
  392.   {"exception", exception},
  393.   {"generate", generate},
  394.   {"compress", compress},
  395.   {NULL, NULL}};
  396.  
  397. #endif
  398.  
  399. /*
  400.  * Commonly used global variables:
  401.  * line        is the current input line number.
  402.  * wrongline    is set in many places when the actual output
  403.  *        line is out of sync with the numbering, e.g,
  404.  *        when expanding a macro with an embedded newline.
  405.  *
  406.  * tokenbuf    holds the last identifier scanned (which might
  407.  *        be a candidate for macro expansion).
  408.  * errors    is the running cpp error counter.
  409.  * infile    is the head of a linked list of input files (extended by
  410.  *        #include and macros being expanded).  infile always points
  411.  *        to the current file/macro.  infile->parent to the includer,
  412.  *        etc.  infile->fd is NULL if this input stream is a macro.
  413.  */
  414. int        line;            /* Current line number        */
  415. int        wrongline;        /* Force #line to compiler    */
  416. char        *tokenbuf;        /* Buffer for current input token */
  417. int        tokenbsize;        /* Allocated size of tokenbuf, */
  418.                     /* not counting zero at end.  */
  419. int        errors;            /* cpp error counter        */
  420. FILEINFO    *infile = NULL;        /* Current input file        */
  421. int        debug;            /* TRUE if debugging now    */
  422. /*
  423.  * This counter is incremented when a macro expansion is initiated.
  424.  * If it exceeds a built-in value, the expansion stops -- this tests
  425.  * for a runaway condition:
  426.  *    #define X Y
  427.  *    #define Y X
  428.  *    X
  429.  * This can be disabled by falsifying rec_recover.  (Nothing does this
  430.  * currently: it is a hook for an eventual invocation flag.)
  431.  */
  432. int        recursion;        /* Infinite recursion counter    */
  433. int        rec_recover = TRUE;    /* Unwind recursive macros    */
  434. DEFBUF            *macro;                /* Catches start of infinite macro */
  435.  
  436. /*
  437.  * instring is set TRUE when a string is scanned.  It modifies the
  438.  * behavior of the "get next character" routine, causing all characters
  439.  * to be passed to the caller (except <DEF_MAGIC>).  Note especially that
  440.  * comments and \<newline> are not removed from the source.  (This
  441.  * prevents cpp output lines from being arbitrarily long).
  442.  *
  443.  * inmacro is set by #define -- it absorbs comments and converts
  444.  * form-feed and vertical-tab to space, but returns \<newline>
  445.  * to the caller.  Strictly speaking, this is a bug as \<newline>
  446.  * shouldn't delimit tokens, but we'll worry about that some other
  447.  * time -- it is more important to prevent infinitly long output lines.
  448.  *
  449.  * instring and inmarcor are parameters to the get() routine which
  450.  * were made global for speed.
  451.  */
  452. int        instring = FALSE;    /* TRUE if scanning string    */
  453. int        inmacro = FALSE;    /* TRUE if #defining a macro    */
  454.  
  455. /*
  456.  * work[] and workp are used to store one piece of text in a temporay
  457.  * buffer.  To initialize storage, set workp = work.  To store one
  458.  * character, call save(c);  (This will fatally exit if there isn't
  459.  * room.)  To terminate the string, call save(EOS).  Note that
  460.  * the work buffer is used by several subroutines -- be sure your
  461.  * data won't be overwritten.  The extra byte in the allocation is
  462.  * needed for string formal replacement.
  463.  */
  464. char        work[NWORK + 1];    /* Work buffer            */
  465. char        *workp;            /* Work buffer pointer        */
  466.  
  467. /*
  468.  * keepcomments is set TRUE by the -C option.  If TRUE, comments
  469.  * are written directly to the output stream.  This is needed if
  470.  * the output from cpp is to be passed to lint (which uses commands
  471.  * embedded in comments).  cflag contains the permanent state of the
  472.  * -C flag.  keepcomments is always falsified when processing #control
  473.  * commands and when compilation is supressed by a false #if
  474.  *
  475.  * If eflag is set, CPP returns "success" even if non-fatal errors
  476.  * were detected.
  477.  *
  478.  * If nflag is non-zero, no symbols are predefined except __LINE__.
  479.  * __FILE__, and __DATE__.  If nflag > 1, absolutely no symbols
  480.  * are predefined.
  481.  */
  482. int        keepcomments = FALSE;    /* Write out comments flag    */
  483. int        cflag = FALSE;        /* -C option (keep comments)    */
  484. int        eflag = FALSE;        /* -E option (never fail)    */
  485. int        nflag = 0;        /* -N option (no predefines)    */
  486.  
  487. /*
  488.  * ifstack[] holds information about nested #if's.  It is always
  489.  * accessed via *ifptr.  The information is as follows:
  490.  *    WAS_COMPILING    state of compiling flag at outer level.
  491.  *    ELSE_SEEN    set TRUE when #else seen to prevent 2nd #else.
  492.  *    TRUE_SEEN    set TRUE when #if or #elif succeeds
  493.  * ifstack[0] holds the compiling flag.  It is TRUE if compilation
  494.  * is currently enabled.  Note that this must be initialized TRUE.
  495.  */
  496. char        ifstack[BLK_NEST] = { TRUE };    /* #if information    */
  497. char        *ifptr = ifstack;        /* -> current ifstack[] */
  498.  
  499. /*
  500.  * incdir[] stores the -i directories (and the system-specific
  501.  * #include <...> directories.
  502.  */
  503. char    *incdir[NINCLUDE];        /* -i directories        */
  504. char    **incend = incdir;        /* -> free space in incdir[]    */
  505.  
  506. /*
  507.  * This is the table used to predefine target machine and operating
  508.  * system designators.  It may need hacking for specific circumstances.
  509.  * Note: it is not clear that this is part of the Ansi Standard.
  510.  * The -N option supresses preset definitions.
  511.  */
  512. char    *preset[] = {            /* names defined at cpp start    */
  513. #ifdef    MACHINE
  514.     MACHINE,
  515. #endif
  516. #ifdef    SYSTEM
  517.     SYSTEM,
  518. #endif
  519. #ifdef    TARGET_ARCH
  520.     TARGET_ARCH,
  521. #endif
  522. #ifdef    COMPILER
  523.     COMPILER,
  524. #endif
  525. #ifdef  CH_SET
  526.          CH_SET,
  527. #endif
  528. #if    DEBUG
  529.     "decus_cpp",            /* Ourselves!            */
  530. #endif
  531.     NULL                /* Must be last            */
  532. };
  533.  
  534.  
  535. main(argc, argv)
  536. int        argc;
  537. char        *argv[];
  538. {
  539.     register int    i;
  540.  
  541. #if HOST == SYS_VMS
  542.     argc = getredirection(argc, argv);    /* vms >file and <file    */
  543. #endif
  544.     initdefines();                /* O.S. specific def's    */
  545.     i = dooptions(argc, argv);        /* Command line -flags    */
  546.     switch (i) {
  547.     case 3:
  548.         /*
  549.          * Get output file, "-" means use stdout.
  550.          */
  551.         if (!streq(argv[2], "-")) {
  552. #if HOST == SYS_VMS
  553.         /*
  554.          * On vms, reopen stdout with "vanilla rms" attributes.
  555.          */
  556.         if ((i = creat(argv[2], 0, "rat=cr", "rfm=var")) == -1
  557.          || dup2(i, fileno(stdout)) == -1) {
  558. #else
  559.         if (freopen(argv[2], "w", stdout) == NULL) {
  560. #endif
  561.             perror(argv[2]);
  562.             cerror("Can't open output file \"%s\"", argv[2]);
  563.             exit(IO_ERROR);
  564.         }
  565.         }                /* Continue by opening input    */
  566.     case 2:                /* One file -> stdin        */
  567.         /*
  568.          * Open input file, "-" means use stdin.
  569.          */
  570.         if (!streq(argv[1], "-")) {
  571.         if (freopen(argv[1], "r", stdin) == NULL) {
  572.             perror(argv[1]);
  573.             cerror("Can't open input file \"%s\"", argv[1]);
  574.             exit(IO_ERROR);
  575.         }
  576.         strcpy(work, argv[1]);    /* Remember input filename    */
  577.         break;
  578.         }                /* Else, just get stdin        */
  579.     case 0:                /* No args?            */
  580.     case 1:                /* No files, stdin -> stdout    */
  581. #if (HOST == SYS_UNIX  || HOST == SYS_OS2 || HOST == SYS_XENIX || HOST == SYS_MVS)
  582.         work[0] = EOS;        /* Unix can't find stdin name    */
  583. #else
  584.         fgetname(stdin, work);    /* Vax-11C, Decus C know name    */
  585. #endif
  586.         break;
  587.  
  588.     default:
  589.         exit(IO_ERROR);        /* Can't happen            */
  590.     }
  591.     setincdirs();            /* Setup -I include directories    */
  592.     addfile(stdin, work);        /* "open" main input file    */
  593. #if DEBUG
  594.     if (debug > 0)
  595.         dumpdef("preset #define symbols");
  596. #endif
  597.     cppmain();            /* Process main file        */
  598.     if ((i = (ifptr - &ifstack[0])) != 0) {
  599. #if OLD_PREPROCESSOR
  600.         ciwarn("Inside #ifdef block at end of input, depth = %d", i);
  601. #else
  602.         cierror("Inside #ifdef block at end of input, depth = %d", i);
  603. #endif
  604.     }
  605.     fclose(stdout);
  606.     if (errors > 0 && !eflag)
  607.       exit(IO_ERROR);
  608. #ifdef COOL
  609.     finish_symbols();
  610. #endif
  611.     exit(IO_NORMAL);        /* No errors or -E option set    */
  612. }
  613.  
  614. FILE_LOCAL
  615. cppmain()
  616. /*
  617.  * Main process for cpp -- copies tokens from the current input
  618.  * stream (main file, include file, or a macro) to the output
  619.  * file.
  620.  */
  621. {
  622.     register int        c;        /* Current character    */
  623.     register int        counter;    /* newlines and spaces    */
  624.     extern int        output();    /* Output one character    */
  625.  
  626.     /* Initialize for reading tokens */
  627.     tokenbsize = 50;
  628.     tokenbuf = getmem (tokenbsize + 1);
  629.  
  630.     /*
  631.      * Explicitly output a #line at the start of cpp output so
  632.      * that lint (etc.) knows the name of the original source
  633.      * file.  If we don't do this explicitly, we may get
  634.      * the name of the first #include file instead.
  635.      */
  636.     sharp();
  637.     /*
  638.      * This loop is started "from the top" at the beginning of each line
  639.      * wrongline is set TRUE in many places if it is necessary to write
  640.      * a #line record.  (But we don't write them when expanding macros.)
  641.      *
  642.      * The counter variable has two different uses:  at
  643.      * the start of a line, it counts the number of blank lines that
  644.      * have been skipped over.  These are then either output via
  645.      * #line records or by outputting explicit blank lines.
  646.       * When expanding tokens within a line, the counter remembers
  647.      * whether a blank/tab has been output.  These are dropped
  648.      * at the end of the line, and replaced by a single blank
  649.      * within lines.
  650.      */
  651.     for (;;) {
  652.         counter = 0;            /* Count empty lines    */
  653.         for (;;) {                /* For each line, ...    */
  654.           while (type[(c = get())] == SPA) /* Skip leading blanks    */
  655.         if (keepcomments)        /* in this line.    */
  656.           putchar(c);
  657.           if (c == '\n')            /* If line's all blank,    */
  658.         if(keepcomments)
  659.           putchar('\n');
  660.         else
  661.           ++counter;            /* Do nothing now    */
  662.           else if (c == '#') {        /* Is 1st non-space '#'    */
  663.         keepcomments = FALSE;        /* Don't pass comments    */
  664.         counter = control(counter);    /* Yes, do a #command    */
  665.         keepcomments = (cflag && compiling);
  666.           }
  667.           else if (c == EOF_CHAR)        /* At end of file?    */
  668.         break;
  669.           else if (!compiling) {        /* #ifdef false?    */
  670.         skipnl();            /* Skip to newline    */
  671.         if(keepcomments)
  672.           putchar('\n');
  673.         else
  674.           counter++;            /* Count it, too.    */
  675.           }
  676.           else {
  677.         break;                /* Actual token        */
  678.           }
  679.         }
  680.         if (c == EOF_CHAR)            /* Exit process at    */
  681.         break;                /* End of file        */
  682.         /*
  683.          * If the loop didn't terminate because of end of file, we
  684.          * know there is a token to compile.  First, clean up after
  685.          * absorbing newlines.  counter has the number we skipped.
  686.          */
  687.         if (wrongline && infile->fp != NULL)
  688.         sharp();            /* Output # line number    */
  689.         else {                /* If just a few, stuff    */
  690.         while (--counter >= 0)        /* them out ourselves    */
  691.             putchar('\n');
  692.         }
  693.         /*
  694.          * Process each token on this line.
  695.          */
  696.         unget();                /* Reread the char.    */
  697.         for (;;) {                /* For the whole line,    */
  698.           for (counter = 0; (type[(c = get())] == SPA);) {
  699.         if(keepcomments)
  700.           putchar(c);
  701.         else {
  702. #if COMMENT_INVISIBLE
  703.           if (c != COM_SEP)
  704.             counter++;
  705. #else
  706.           counter++;          /* Skip over blanks    */
  707. #endif
  708.         }
  709.           }
  710.           if (c == EOF_CHAR || c == '\n')
  711.         goto end_line;          /* Exit line loop    */
  712.           else if (counter > 0)      /* If we got any spaces    */
  713.         putchar(' ');          /* Output one space    */
  714.           c = macroid(c);          /* Grab the token    */
  715.           if (c == EOF_CHAR || c == '\n') /* From macro exp error    */
  716.         goto end_line;          /* Exit line loop    */
  717.           switch (type[c]) {
  718.           case LET:
  719.         fputs(tokenbuf, stdout);  /* Quite ordinary token    */
  720.         break;
  721.  
  722.  
  723.           case DIG:              /* Output a number    */
  724.           case DOT:              /* Dot may begin floats    */
  725.         scannumber(c, output);
  726.         break;
  727.  
  728.           case QUO:              /* char or string const    */
  729.         scanstring(c, output);      /* Copy it to output    */
  730.         break;
  731.  
  732.           default:              /* Some other character    */
  733.         cput(c);          /* Just output it    */
  734.         break;
  735.           }                  /* Switch ends        */
  736.         }                  /* Line for loop    */
  737. end_line:   if (c == '\n') {            /* Compiling at EOL?    */
  738.         putchar('\n');            /* Output newline, if    */
  739.         if (infile->fp == NULL)        /* Expanding a macro,    */
  740.             wrongline = TRUE;        /* Output # line later    */
  741.         }
  742.     }                    /* Continue until EOF    */
  743. }
  744.  
  745. output(c)
  746. int        c;
  747. /*
  748.  * Output one character to stdout -- output() is passed as an
  749.  * argument to scanstring()
  750.  */
  751. {
  752. #if COMMENT_INVISIBLE
  753.     if (c != TOK_SEP && c != COM_SEP)
  754. #else
  755.     if (c != TOK_SEP)
  756. #endif
  757.         putchar(c);
  758. }
  759.  
  760. FILE_LOCAL
  761. sharp()
  762. /*
  763.  * Output a line number line.
  764.  */
  765. {
  766.     register char        *name;
  767.  
  768.     if (keepcomments)            /* Make sure # comes on    */
  769.         putchar('\n');            /* a fresh, new line.    */
  770.     printf("#%s %d", LINE_PREFIX, line);
  771.     if (infile->fp != NULL) {
  772.         name = (infile->progname != NULL)
  773.         ? infile->progname : infile->filename;
  774.         printf(" \"%s\"", name); 
  775.     }
  776.     putchar('\n');
  777.     wrongline = FALSE;
  778. }
  779.  
  780.