home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / nethack-3.1 / sys / unix / cpp2.shr / cpp1.c next >
Encoding:
C/C++ Source or Header  |  1993-01-26  |  23.2 KB  |  721 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.  */
  79.  
  80. /*)BUILD
  81.     $(PROGRAM)    = cpp
  82.     $(FILES)    = { cpp1 cpp2 cpp3 cpp4 cpp5 cpp6 }
  83.     $(INCLUDE)    = { cppdef.h cpp.h }
  84.     $(STACK)    = 2000
  85.     $(TKBOPTIONS)    = {
  86.         STACK    = 2000
  87.     }
  88. */
  89.  
  90. #ifdef    DOCUMENTATION
  91.  
  92. title    cpp        C Pre-Processor
  93. index            C pre-processor
  94.  
  95. synopsis
  96.     .s.nf
  97.     cpp [-options] [infile [outfile]]
  98.     .s.f
  99. description
  100.  
  101.     CPP reads a C source file, expands macros and include
  102.     files, and writes an input file for the C compiler.
  103.     If no file arguments are given, CPP reads from stdin
  104.     and writes to stdout.  If one file argument is given,
  105.     it will define the input file, while two file arguments
  106.     define both input and output files.  The file name "-"
  107.     is a synonym for stdin or stdout as appropriate.
  108.  
  109.     The following options are supported.  Options may
  110.     be given in either case.
  111.     .lm +16
  112.     .p -16
  113.     -C        If set, source-file comments are written
  114.     to the output file.  This allows the output of CPP to be
  115.     used as the input to a program, such as lint, that expects
  116.     commands embedded in specially-formatted comments.
  117.     .p -16
  118.     -Dname=value    Define the name as if the programmer wrote
  119.  
  120.         #define name value
  121.  
  122.     at the start of the first file.  If "=value" is not
  123.     given, a value of "1" will be used.
  124.  
  125.     On non-unix systems, all alphabetic text will be forced
  126.     to upper-case.
  127.     .p -16
  128.     -E        Always return "success" to the operating
  129.     system, even if errors were detected.  Note that some fatal
  130.     errors, such as a missing #include file, will terminate
  131.     CPP, returning "failure" even if the -E option is given.
  132.     .p -16
  133.     -Idirectory    Add this directory to the list of
  134.     directories searched for #include "..." and #include <...>
  135.     commands.  Note that there is no space between the
  136.     "-I" and the directory string.  More than one -I command
  137.     is permitted.  On non-Unix systems "directory" is forced
  138.     to upper-case.
  139.     .p -16
  140.     -N        CPP normally predefines some symbols defining
  141.     the target computer and operating system.  If -N is specified,
  142.     no symbols will be predefined.  If -N -N is specified, the
  143.     "always present" symbols, __LINE__, __FILE__, and __DATE__
  144.     are not defined.
  145.     .p -16
  146.     -Stext        CPP normally assumes that the size of
  147.     the target computer's basic variable types is the same as the size
  148.     of these types of the host computer.  (This can be overridden
  149.     when CPP is compiled, however.)  The -S option allows dynamic
  150.     respecification of these values.  "text" is a string of
  151.     numbers, separated by commas, that specifies correct sizes.
  152.     The sizes must be specified in the exact order:
  153.  
  154.         char short int long float double
  155.  
  156.     If you specify the option as "-S*text", pointers to these
  157.     types will be specified.  -S* takes one additional argument
  158.     for pointer to function (e.g. int (*)())
  159.  
  160.     For example, to specify sizes appropriate for a PDP-11,
  161.     you would write:
  162.  
  163.            c s i l f d func
  164.          -S1,2,2,2,4,8,
  165.         -S*2,2,2,2,2,2,2
  166.  
  167.     Note that all values must be specified.
  168.     .p -16
  169.     -Uname        Undefine the name as if
  170.  
  171.         #undef name
  172.  
  173.     were given.  On non-Unix systems, "name" will be forced to
  174.     upper-case.
  175.     .p -16
  176.     -Xnumber    Enable debugging code.  If no value is
  177.     given, a value of 1 will be used.  (For maintenence of
  178.     CPP only.)
  179.     .s.lm -16
  180.  
  181. Pre-Defined Variables
  182.  
  183.     When CPP begins processing, the following variables will
  184.     have been defined (unless the -N option is specified):
  185.     .s
  186.     Target computer (as appropriate):
  187.     .s
  188.         pdp11, vax, M68000 m68000 m68k
  189.     .s
  190.     Target operating system (as appropriate):
  191.     .s
  192.         rsx, rt11, vms, unix
  193.     .s
  194.     Target compiler (as appropriate):
  195.     .s
  196.         decus, vax11c
  197.     .s
  198.     The implementor may add definitions to this list.
  199.     The default definitions match the definition of the
  200.     host computer, operating system, and C compiler.
  201.     .s
  202.     The following are always available unless undefined (or
  203.     -N was specified twice):
  204.     .lm +16
  205.     .p -12
  206.     __FILE__    The input (or #include) file being compiled
  207.     (as a quoted string).
  208.     .p -12
  209.     __LINE__    The line number being compiled.
  210.     .p -12
  211.     __DATE__    The date and time of compilation as
  212.     a Unix ctime quoted string (the trailing newline is removed).
  213.     Thus,
  214.     .s
  215.         printf("Bug at line %s,", __LINE__);
  216.         printf(" source file %s", __FILE__);
  217.         printf(" compiled on %s", __DATE__);
  218.     .s.lm -16
  219.  
  220. Draft Proposed Ansi Standard Considerations
  221.  
  222.     The current version of the Draft Proposed Standard
  223.     explicitly states that "readers are requested not to specify
  224.     or claim conformance to this draft."  Readers and users
  225.     of Decus CPP should not assume that Decus CPP conforms
  226.     to the standard, or that it will conform to the actual
  227.     C Language Standard.
  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.     The latest version of the Draft Proposed Standard (as reflected
  235.     in Decus CPP) is dated November 12, 1984.
  236.  
  237.     Comments are removed from the input text.  The comment
  238.     is replaced by a single space character.  The -C option
  239.     preserves comments, writing them to the output file.
  240.  
  241.     The '$' character is considered to be a letter.  This is
  242.     a permitted extension.
  243.  
  244.     The following new features of C are processed by CPP:
  245.     .s.comment Note: significant spaces, not tabs, .br quotes #if, #elif
  246.     .br;####_#elif expression    (_#else _#if)
  247.     .br;####'_\xNNN'             (Hexadecimal constant)
  248.     .br;####'_\a'                (Ascii BELL)
  249.     .br;####'_\v'                (Ascii Vertical Tab)
  250.     .br;####_#if defined NAME    1 if defined, 0 if not
  251.     .br;####_#if defined (NAME)  1 if defined, 0 if not  
  252.     .br;####_#if sizeof (basic type)
  253.     .br;####unary +
  254.     .br;####123U, 123LU          Unsigned ints and longs.
  255.     .br;####12.3L                Long double numbers
  256.     .br;####token_#token         Token concatenation
  257.     .br;####_#include token      Expands to filename
  258.  
  259.     The Draft Proposed Standard has extended C, adding a constant
  260.     string concatenation operator, where
  261.  
  262.         "foo" "bar"
  263.  
  264.     is regarded as the single string "foobar".  (This does not
  265.     affect CPP's processing but does permit a limited form of
  266.     macro argument substitution into strings as will be discussed.)
  267.  
  268.     The Standard Committee plans to add token concatenation
  269.     to #define command lines.  One suggested implementation
  270.     is as follows:  the sequence "Token1#Token2" is treated
  271.     as if the programmer wrote "Token1Token2".  This could
  272.     be used as follows:
  273.  
  274.         #line 123
  275.         #define ATLINE foo#__LINE__
  276.  
  277.     ATLINE would be defined as foo123.
  278.  
  279.     Note that "Token2" must either have the format of an
  280.     identifier or be a string of digits.  Thus, the string
  281.  
  282.         #define ATLINE foo#1x3
  283.  
  284.     generates two tokens: "foo1" and "x3".
  285.  
  286.     If the tokens T1 and T2 are concatenated into T3,
  287.     this implementation operates as follows:
  288.  
  289.       1. Expand T1 if it is a macro.
  290.       2. Expand T2 if it is a macro.
  291.       3. Join the tokens, forming T3.
  292.       4. Expand T3 if it is a macro.
  293.  
  294.     A macro formal parameter will be substituted into a string
  295.     or character constant if it is the only component of that
  296.     constant:
  297.  
  298.         #define VECSIZE 123
  299.         #define vprint(name, size) \
  300.           printf("name" "[" "size" "] = {\n")
  301.           ... vprint(vector, VECSIZE);
  302.  
  303.     expands (effectively) to
  304.  
  305.           vprint("vector[123] = {\n");
  306.  
  307.     Note that this will be useful if your C compiler supports
  308.     the new string concatenation operation noted above.
  309.     As implemented here, if you write
  310.  
  311.         #define string(arg) "arg"
  312.           ... string("foo") ...
  313.  
  314.     This implementation generates "foo", rather than the strictly
  315.     correct ""foo"" (which will probably generate an error message).
  316.     This is, strictly speaking, an error in CPP and may be removed
  317.     from future releases.
  318.  
  319. error messages
  320.  
  321.     Many.  CPP prints warning or error messages if you try to
  322.     use multiple-byte character constants (non-transportable)
  323.     if you #undef a symbol that was not defined, or if your
  324.     program has potentially nested comments.
  325.  
  326. author
  327.  
  328.     Martin Minow
  329.  
  330. bugs
  331.  
  332.     The #if expression processor uses signed integers only.
  333.     I.e, #if 0xFFFFu < 0 may be TRUE.
  334.  
  335. #endif
  336.  
  337. #include    <stdio.h>
  338. #include    <ctype.h>
  339. #include    "cppdef.h"
  340. #include    "cpp.h"
  341.  
  342. /*
  343.  * Commonly used global variables:
  344.  * line        is the current input line number.
  345.  * wrongline    is set in many places when the actual output
  346.  *        line is out of sync with the numbering, e.g,
  347.  *        when expanding a macro with an embedded newline.
  348.  *
  349.  * token    holds the last identifier scanned (which might
  350.  *        be a candidate for macro expansion).
  351.  * errors    is the running cpp error counter.
  352.  * infile    is the head of a linked list of input files (extended by
  353.  *        #include and macros being expanded).  infile always points
  354.  *        to the current file/macro.  infile->parent to the includer,
  355.  *        etc.  infile->fd is NULL if this input stream is a macro.
  356.  */
  357. int        line;            /* Current line number        */
  358. int        wrongline;        /* Force #line to compiler    */
  359. char        token[IDMAX + 1];    /* Current input token        */
  360. int        errors;            /* cpp error counter        */
  361. FILEINFO    *infile = NULL;        /* Current input file        */
  362. #if DEBUG
  363. int        debug;            /* TRUE if debugging now    */
  364. #endif
  365. /*
  366.  * This counter is incremented when a macro expansion is initiated.
  367.  * If it exceeds a built-in value, the expansion stops -- this tests
  368.  * for a runaway condition:
  369.  *    #define X Y
  370.  *    #define Y X
  371.  *    X
  372.  * This can be disabled by falsifying rec_recover.  (Nothing does this
  373.  * currently: it is a hook for an eventual invocation flag.)
  374.  */
  375. int        recursion;        /* Infinite recursion counter    */
  376. int        rec_recover = TRUE;    /* Unwind recursive macros    */
  377.  
  378. /*
  379.  * instring is set TRUE when a string is scanned.  It modifies the
  380.  * behavior of the "get next character" routine, causing all characters
  381.  * to be passed to the caller (except <DEF_MAGIC>).  Note especially that
  382.  * comments and \<newline> are not removed from the source.  (This
  383.  * prevents cpp output lines from being arbitrarily long).
  384.  *
  385.  * inmacro is set by #define -- it absorbs comments and converts
  386.  * form-feed and vertical-tab to space, but returns \<newline>
  387.  * to the caller.  Strictly speaking, this is a bug as \<newline>
  388.  * shouldn't delimit tokens, but we'll worry about that some other
  389.  * time -- it is more important to prevent infinitly long output lines.
  390.  *
  391.  * instring and inmarcor are parameters to the get() routine which
  392.  * were made global for speed.
  393.  */
  394. int        instring = FALSE;    /* TRUE if scanning string    */
  395. int        inmacro = FALSE;    /* TRUE if #defining a macro    */
  396.  
  397. /*
  398.  * work[] and workp are used to store one piece of text in a temporay
  399.  * buffer.  To initialize storage, set workp = work.  To store one
  400.  * character, call save(c);  (This will fatally exit if there isn't
  401.  * room.)  To terminate the string, call save(EOS).  Note that
  402.  * the work buffer is used by several subroutines -- be sure your
  403.  * data won't be overwritten.  The extra byte in the allocation is
  404.  * needed for string formal replacement.
  405.  */
  406. char        work[NWORK + 1];    /* Work buffer            */
  407. char        *workp;            /* Work buffer pointer        */
  408.  
  409. /*
  410.  * keepcomments is set TRUE by the -C option.  If TRUE, comments
  411.  * are written directly to the output stream.  This is needed if
  412.  * the output from cpp is to be passed to lint (which uses commands
  413.  * embedded in comments).  cflag contains the permanent state of the
  414.  * -C flag.  keepcomments is always falsified when processing #control
  415.  * commands and when compilation is supressed by a false #if
  416.  *
  417.  * If eflag is set, CPP returns "success" even if non-fatal errors
  418.  * were detected.
  419.  *
  420.  * If nflag is non-zero, no symbols are predefined except __LINE__.
  421.  * __FILE__, and __DATE__.  If nflag > 1, absolutely no symbols
  422.  * are predefined.
  423.  */
  424. int        keepcomments = FALSE;    /* Write out comments flag    */
  425. int        cflag = FALSE;        /* -C option (keep comments)    */
  426. int        eflag = FALSE;        /* -E option (never fail)    */
  427. int        nflag = 0;        /* -N option (no predefines)    */
  428.  
  429. /*
  430.  * ifstack[] holds information about nested #if's.  It is always
  431.  * accessed via *ifptr.  The information is as follows:
  432.  *    WAS_COMPILING    state of compiling flag at outer level.
  433.  *    ELSE_SEEN    set TRUE when #else seen to prevent 2nd #else.
  434.  *    TRUE_SEEN    set TRUE when #if or #elif succeeds
  435.  * ifstack[0] holds the compiling flag.  It is TRUE if compilation
  436.  * is currently enabled.  Note that this must be initialized TRUE.
  437.  */
  438. char        ifstack[BLK_NEST] = { TRUE };    /* #if information    */
  439. char        *ifptr = ifstack;        /* -> current ifstack[] */
  440.  
  441. /*
  442.  * incdir[] stores the -i directories (and the system-specific
  443.  * #include <...> directories.
  444.  */
  445. char    *incdir[NINCLUDE];        /* -i directories        */
  446. char    **incend = incdir;        /* -> free space in incdir[]    */
  447.  
  448. /*
  449.  * This is the table used to predefine target machine and operating
  450.  * system designators.  It may need hacking for specific circumstances.
  451.  * Note: it is not clear that this is part of the Ansi Standard.
  452.  * The -N option supresses preset definitions.
  453.  */
  454. char    *preset[] = {            /* names defined at cpp start    */
  455. #ifdef    MACHINE
  456.     MACHINE,
  457. #endif
  458. #ifdef    SYSTEM
  459.     SYSTEM,
  460. #endif
  461. #ifdef    COMPILER
  462.     COMPILER,
  463. #endif
  464. #if    DEBUG
  465.     "decus_cpp",            /* Ourselves!            */
  466. #endif
  467.     NULL                /* Must be last            */
  468. };
  469.  
  470. /*
  471.  * The value of these predefined symbols must be recomputed whenever
  472.  * they are evaluated.  The order must not be changed.
  473.  */
  474. char    *magic[] = {            /* Note: order is important    */
  475.     "__LINE__",
  476.     "__FILE__",
  477.     NULL                /* Must be last            */
  478. };
  479.  
  480. main(argc, argv)
  481. int        argc;
  482. char        *argv[];
  483. {
  484.     register int    i;
  485.  
  486. #if HOST == SYS_VMS
  487.     argc = getredirection(argc, argv);    /* vms >file and <file    */
  488. #endif
  489.     initdefines();                /* O.S. specific def's    */
  490.     i = dooptions(argc, argv);        /* Command line -flags    */
  491.     switch (i) {
  492.     case 3:
  493.         /*
  494.          * Get output file, "-" means use stdout.
  495.          */
  496.         if (!streq(argv[2], "-")) {
  497. #if HOST == SYS_VMS
  498.         /*
  499.          * On vms, reopen stdout with "vanilla rms" attributes.
  500.          */
  501.         if ((i = creat(argv[2], 0, "rat=cr", "rfm=var")) == -1
  502.          || dup2(i, fileno(stdout)) == -1) {
  503. #else
  504.         if (freopen(argv[2], "w", stdout) == NULL) {
  505. #endif
  506.             perror(argv[2]);
  507.             cerror("Can't open output file \"%s\"", argv[2]);
  508.             exit(IO_ERROR);
  509.         }
  510.         }                /* Continue by opening input    */
  511.     case 2:                /* One file -> stdin        */
  512.         /*
  513.          * Open input file, "-" means use stdin.
  514.          */
  515.         if (!streq(argv[1], "-")) {
  516.         if (freopen(argv[1], "r", stdin) == NULL) {
  517.             perror(argv[1]);
  518.             cerror("Can't open input file \"%s\"", argv[1]);
  519.             exit(IO_ERROR);
  520.         }
  521.         strcpy(work, argv[1]);    /* Remember input filename    */
  522.         break;
  523.         }                /* Else, just get stdin        */
  524.     case 0:                /* No args?            */
  525.     case 1:                /* No files, stdin -> stdout    */
  526. #if HOST == SYS_UNIX
  527.         work[0] = EOS;        /* Unix can't find stdin name    */
  528. #else
  529.         fgetname(stdin, work);    /* Vax-11C, Decus C know name    */
  530. #endif
  531.         break;
  532.  
  533.     default:
  534.         exit(IO_ERROR);        /* Can't happen            */
  535.     }
  536.     setincdirs();            /* Setup -I include directories    */
  537.     addfile(stdin, work);        /* "open" main input file    */
  538. #if DEBUG
  539.     if (debug > 0)
  540.         dumpdef("preset #define symbols");
  541. #endif
  542.     cppmain();            /* Process main file        */
  543.     if ((i = (ifptr - &ifstack[0])) != 0) {
  544. #if OLD_PREPROCESSOR
  545.         ciwarn("Inside #ifdef block at end of input, depth = %d", i);
  546. #else
  547.         cierror("Inside #ifdef block at end of input, depth = %d", i);
  548. #endif
  549.     }
  550.     fclose(stdout);
  551.     if (errors > 0) {
  552.         fprintf(stderr, (errors == 1)
  553.         ? "%d error in preprocessor\n"
  554.         : "%d errors in preprocessor\n", errors);
  555.         if (!eflag)
  556.         exit(IO_ERROR);
  557.     }
  558.     exit(IO_NORMAL);        /* No errors or -E option set    */
  559. }
  560.  
  561. FILE_LOCAL
  562. cppmain()
  563. /*
  564.  * Main process for cpp -- copies tokens from the current input
  565.  * stream (main file, include file, or a macro) to the output
  566.  * file.
  567.  */
  568. {
  569.     register int        c;        /* Current character    */
  570.     register int        counter;    /* newlines and spaces    */
  571.     extern int        output();    /* Output one character    */
  572.  
  573.     /*
  574.      * Explicitly output a #line at the start of cpp output so
  575.      * that lint (etc.) knows the name of the original source
  576.      * file.  If we don't do this explicitly, we may get
  577.      * the name of the first #include file instead.
  578.      */
  579.     sharp();
  580.     /*
  581.      * This loop is started "from the top" at the beginning of each line
  582.      * wrongline is set TRUE in many places if it is necessary to write
  583.      * a #line record.  (But we don't write them when expanding macros.)
  584.      *
  585.      * The counter variable has two different uses:  at
  586.      * the start of a line, it counts the number of blank lines that
  587.      * have been skipped over.  These are then either output via
  588.      * #line records or by outputting explicit blank lines.
  589.       * When expanding tokens within a line, the counter remembers
  590.      * whether a blank/tab has been output.  These are dropped
  591.      * at the end of the line, and replaced by a single blank
  592.      * within lines.
  593.      */
  594.     for (;;) {
  595.         counter = 0;            /* Count empty lines    */
  596.         for (;;) {                /* For each line, ...    */
  597.         while (type[(c = get())] == SPA) /* Skip leading blanks    */
  598.             ;                /* in this line.    */
  599.         if (c == '\n')            /* If line's all blank,    */
  600.             ++counter;            /* Do nothing now    */
  601.         else if (c == '#') {        /* Is 1st non-space '#'    */
  602.             keepcomments = FALSE;    /* Don't pass comments    */
  603.             counter = control(counter);    /* Yes, do a #command    */
  604.             keepcomments = (cflag && compiling);
  605.         }
  606.         else if (c == EOF_CHAR)        /* At end of file?    */
  607.             break;
  608.         else if (!compiling) {        /* #ifdef false?    */
  609.             skipnl();            /* Skip to newline    */
  610.             counter++;            /* Count it, too.    */
  611.         }
  612.         else {
  613.             break;            /* Actual token        */
  614.         }
  615.         }
  616.         if (c == EOF_CHAR)            /* Exit process at    */
  617.         break;                /* End of file        */
  618.         /*
  619.          * If the loop didn't terminate because of end of file, we
  620.          * know there is a token to compile.  First, clean up after
  621.          * absorbing newlines.  counter has the number we skipped.
  622.          */
  623.         if ((wrongline && infile->fp != NULL) || counter > 4)
  624.         sharp();            /* Output # line number    */
  625.         else {                /* If just a few, stuff    */
  626.         while (--counter >= 0)        /* them out ourselves    */
  627.             putchar('\n');
  628.         }
  629.         /*
  630.          * Process each token on this line.
  631.          */
  632.         unget();                /* Reread the char.    */
  633.         for (;;) {                /* For the whole line,    */
  634.         do {                /* Token concat. loop    */
  635.             for (counter = 0; (type[(c = get())] == SPA);) {
  636. #if COMMENT_INVISIBLE
  637.             if (c != COM_SEP)
  638.                 counter++;
  639. #else
  640.             counter++;        /* Skip over blanks    */
  641. #endif
  642.             }
  643.             if (c == EOF_CHAR || c == '\n')
  644.             goto end_line;        /* Exit line loop    */
  645.             else if (counter > 0)    /* If we got any spaces    */
  646.             putchar(' ');        /* Output one space    */
  647.             c = macroid(c);        /* Grab the token    */
  648.         } while (type[c] == LET && catenate());
  649.         if (c == EOF_CHAR || c == '\n')    /* From macro exp error    */
  650.             goto end_line;        /* Exit line loop    */
  651.         switch (type[c]) {
  652.         case LET:
  653.             fputs(token, stdout);    /* Quite ordinary token    */
  654.             break;
  655.  
  656.  
  657.         case DIG:            /* Output a number    */
  658.         case DOT:            /* Dot may begin floats    */
  659.             scannumber(c, output);
  660.             break;
  661.  
  662.         case QUO:            /* char or string const    */
  663.             scanstring(c, output);    /* Copy it to output    */
  664.             break;
  665.  
  666.         default:            /* Some other character    */
  667.             cput(c);            /* Just output it    */
  668.             break;
  669.         }                /* Switch ends        */
  670.         }                    /* Line for loop    */
  671. end_line:   if (c == '\n') {            /* Compiling at EOL?    */
  672.         putchar('\n');            /* Output newline, if    */
  673.         if (infile->fp == NULL)        /* Expanding a macro,    */
  674.             wrongline = TRUE;        /* Output # line later    */
  675.         }
  676.     }                    /* Continue until EOF    */
  677. }
  678.  
  679. output(c)
  680. int        c;
  681. /*
  682.  * Output one character to stdout -- output() is passed as an
  683.  * argument to scanstring()
  684.  */
  685. {
  686. #if COMMENT_INVISIBLE
  687.     if (c != TOK_SEP && c != COM_SEP)
  688. #else
  689.     if (c != TOK_SEP)
  690. #endif
  691.         putchar(c);
  692. }
  693.  
  694. static char    *sharpfilename = NULL;
  695.  
  696. FILE_LOCAL
  697. sharp()
  698. /*
  699.  * Output a line number line.
  700.  */
  701. {
  702.     register char        *name;
  703.  
  704.     if (keepcomments)            /* Make sure # comes on    */
  705.         putchar('\n');            /* a fresh, new line.    */
  706.     printf("#%s %d", LINE_PREFIX, line);
  707.     if (infile->fp != NULL) {
  708.         name = (infile->progname != NULL)
  709.         ? infile->progname : infile->filename;
  710.         if (sharpfilename == NULL
  711.          || sharpfilename != NULL && !streq(name, sharpfilename)) {
  712.         if (sharpfilename != NULL)
  713.             free(sharpfilename);
  714.         sharpfilename = savestring(name);
  715.         printf(" \"%s\"", name);
  716.          }
  717.     }
  718.     putchar('\n');
  719.     wrongline = FALSE;
  720. }
  721.