home *** CD-ROM | disk | FTP | other *** search
/ Amiga Elysian Archive / AmigaElysianArchive.iso / prog / c / cpp.lha / cpp1.c < prev    next >
Text File  |  1991-10-19  |  37KB  |  907 lines

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