home *** CD-ROM | disk | FTP | other *** search
/ Boston 2 / boston-2.iso / DOS / PROGRAM / C / LEX / LEX.MEM < prev    next >
Text File  |  1993-12-01  |  73KB  |  2,260 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.          
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.                             DECUS C LANGUAGE SYSTEM
  95.  
  96.  
  97.                                       LEX
  98.                           A lexical Analyser Generator
  99.  
  100.  
  101.                                        by
  102.  
  103.                                Charles H. Forsyth
  104.  
  105.                             University of Waterloo
  106.                             Waterloo, Ontario, N2L 3G1
  107.                             Canada
  108.  
  109.  
  110.                                    Revised by
  111.  
  112.                          Robert B. Denny & Martin Minow
  113.  
  114.  
  115.         LEX  transforms  a  regular-expression  grammar  and  associated
  116.         action  routines into a C function and set of tables, yielding a
  117.         table-driven lexical analyser which manages to  be  compact  and
  118.         rapid.
  119.  
  120.  
  121.                          DECUS Structured Languages SIG
  122.  
  123.                               Version of 30-Oct-82
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.            
  134.  
  135.  
  136.  
  137.  
  138.  
  139.  
  140.  
  141.  
  142.                      Copyright (C) 1978, Charles H. Forsyth
  143.  
  144.  
  145.  
  146.  
  147.  
  148.                  Modifications Copyright (C) 1980, 1982, DECUS
  149.  
  150.             General permission  to  copy  or  modify,  but  not  for
  151.             profit,  is  hereby  granted,  provided  that  the above
  152.             copyright notice is included and reference made  to  the
  153.             fact that reproduction privileges were granted by DECUS.
  154.  
  155.             The information in this document is  subject  to  change
  156.             without   notice  and  should  not  be  construed  as  a
  157.             commitment by Digital Equipment Corporation or by DECUS.
  158.  
  159.             Neither Digital Equipment Corporation,  DECUS,  nor  the
  160.             authors   assume  any  responsibility  for  the  use  or
  161.             reliability of this document or the described software.
  162.  
  163.             This software is  made  available  without  any  support
  164.             whatsoever.     The    person    responsible    for   an
  165.             implementation of this system should expect to  have  to
  166.             understand  and  modify  the source code if any problems
  167.             are  encountered  in  implementing  or  maintaining  the
  168.             compiler or its run-time library.  The DECUS 'Structured
  169.             Languages Special Interest Group' is the  primary  focus
  170.             for communication among users of this software.
  171.  
  172.  
  173.  
  174.  
  175.  
  176.  
  177.  
  178.  
  179.  
  180.         UNIX is  a  trademark  of  Bell  Telephone  Laboratories.   RSX,
  181.         RSTS/E,  RT-11  and  VMS  are  trademarks  of  Digital Equipment
  182.         Corporation.
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.         A Lexical Analyser Generator                                      Page 3
  200.  
  201.  
  202.         1.0  Introduction
  203.              ____________
  204.  
  205.  
  206.         A computer program often has an input stream which  is  composed
  207.         of  small elements, such as a stream of characters, and which it
  208.         would like to convert to larger elements in order to process the
  209.         data  conveniently.   A  compiler  is a common example of such a
  210.         program:  it reads a stream of characters forming a program, and
  211.         would  like  to turn this sequence of characters into a sequence
  212.         of larger items, namely identifiers, numbers, and operators, for
  213.         parsing.   In  a  compiler,  the  procedures  which  do this are
  214.         collectively called the  lexical  analyser,  or  scanner;   this
  215.                                  _______  ________       _______
  216.         terminology will be used more generally here.
  217.  
  218.         It may happen that the speed with which this  transformation  is
  219.         done  will  noticeably affect the speed at which the rest of the
  220.         program operates.  It is certainly true that although such  code
  221.         is  rarely  difficult to write, writing and debugging it is both
  222.         tedious, and time-consuming,  and  one  typically  would  rather
  223.         spend  the  time  on  the hard parts of the program.  It is also
  224.         true that while certain transformations are easily  thought  of,
  225.         they   are  often  hard  to  express  succinctly  in  the  usual
  226.         general-purpose programming languages (eg, the description of  a
  227.         floating-point number).
  228.  
  229.         LEX is a program which tries to give a programmer a good deal of
  230.         help  in  this,  by  writing large parts of the lexical analyser
  231.         automatically, based on a description supplied by the programmer
  232.         of  the  items  to be recognised (which are known as tokens), as
  233.                                                              ______
  234.         patterns of the more basic elements of the  input  stream.   The
  235.         LEX  description  is  very  much  a special-purpose language for
  236.         writing lexical analysers, and LEX is then simply  a  translator
  237.         for  this  language.  The LEX language is easy to write, and the
  238.         resulting processor is compact and fast running.
  239.  
  240.         The purpose of a LEX program is to read  an  input  stream,  and
  241.         recognise tokens.  As the lexical analyser will usually exist as
  242.                   ______
  243.         a subroutine in a larger set  of  programs,  it  will  return  a
  244.         "token  number",  which  indicates  which  token  was found, and
  245.         possibly  a  "token  value",  which   provides   more   detailed
  246.         information  about the token (eg, a copy of the token itself, or
  247.         an index into a symbol  table).   This  need  not  be  the  only
  248.         possibility;   a  LEX program is often a good description of the
  249.         structure of the whole computation, and  in  such  a  case,  the
  250.         lexical  analyser might choose to call other routines to perform
  251.         the necessary actions whenever a particular token is recognised,
  252.         without reference to its own caller.
  253.  
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.         A Lexical Analyser Generator                                      Page 4
  266.  
  267.  
  268.         2.0  The Lex Language
  269.              ___ ___ ________
  270.  
  271.         LEX transforms a regular-expression grammar into a deterministic
  272.         finite-state  automaton that recognizes that grammar.  Each rule
  273.         of the grammar is associated with  an  action  which  is  to  be
  274.         performed  when  that rule successfully matches some part of the
  275.         input data.
  276.  
  277.         Because of the nature of regular  expression  grammars,  certain
  278.         language  constructions  cannot  be  recognized by LEX programs.
  279.         Specifically, expressions with balanced  parentheses  cannot  be
  280.         recognized.  This means that LEX cannot be used to recognize all
  281.         Fortran keywords as some  (DO,  IF,  and  FORMAT,  for  example)
  282.         require  elaborate  recognition to distinguish between ambiguous
  283.         constructions.
  284.  
  285.  
  286.  
  287.         2.1  Elementary Things
  288.              __________ ______
  289.  
  290.  
  291.         Strings,  characters,  sets  of  characters   called   character
  292.         classes,  and  operators  to  form  these into patterns, are the
  293.         fundamental elements of the LEX language.
  294.  
  295.         A string is a sequence of  characters,  not  including  newline,
  296.           ______
  297.         enclosed  in  quotes,  or  apostrophes.   Within  a  string, the
  298.         following escape sequences
  299.         (which are those of the C language) allow any 8-bit character to
  300.         be  represented,  including  the  escape  character, quotes, and
  301.         newlines:
  302.  
  303.                 \n      NL      (012)
  304.                 \r      CR      (015)
  305.                 \b      BS      (010)
  306.                 \t      TAB     (011)
  307.                 \"      "
  308.                 \'      '
  309.                 \c      c
  310.                 \\      \
  311.                 \NNN    (NNN)
  312.  
  313.         where NNN  is  a  number  in  octal,  and  c  is  any  printable
  314.                                                    _
  315.         character.   A  string may be continued across a line by writing
  316.         the escape character before the newline.
  317.  
  318.         Outside a string, a sequence of upper-case letters stands for  a
  319.         sequence  of the equivalent lower-case letters, while a sequence
  320.                                     __________
  321.         of lower-case letters is taken as the name of a LEX  expression,
  322.         and  handled  specially,  as described below.  These conventions
  323.         make the  use  of  named  expressions  and  the  description  of
  324.         lower-case  keywords (the usual case on Unix) fairly convenient.
  325.         Keywords in case-independent languages, such as Fortran, require
  326.         additional effort to match, as will be noted.
  327.  
  328.  
  329.  
  330.  
  331.         A Lexical Analyser Generator                                      Page 5
  332.  
  333.  
  334.         An Ascii character other than one of
  335.  
  336.                 () {} [ * | = ; % / \ ' " -
  337.  
  338.         may be used in LEX to stand for itself.
  339.  
  340.         A sequence of characters enclosed  by  brackets  ('['  and  ']')
  341.         forms  a  character class, which stands for all those characters
  342.         within the brackets.  If a circumflex ('^') follows the  opening
  343.         bracket,  then  the  class  will  instead  stand  for  all those
  344.         characters but those inside the brackets.  The escapes  used  in
  345.                    ___
  346.         strings may be used in character classes as well.
  347.  
  348.         Within a character class, the construction "A-B" (where "A"  and
  349.         "B" are arbitrary characters) stands for the range of characters
  350.         between "A" and "B" inclusive.
  351.  
  352.         For example,
  353.  
  354.                 "ABC"           matches "abc"
  355.  
  356.                 "[ABC]"         matches "A" or "B" or "C"
  357.  
  358.                 "[A-Za-z0-9]"   matches all letters and digits
  359.  
  360.         Case-independent keyword recognition may be described  by  using
  361.         auxiliary  definitions  to  define expressions that match either
  362.         case.  For example,
  363.  
  364.                 a = [Aa];
  365.                 b = [Bb];
  366.                 ...
  367.                 z = [Zz];
  368.                 %%
  369.                 d o             Matches "DO", "do", "Do", or "dO"
  370.  
  371.  
  372.  
  373.  
  374.         2.2  Putting Things Together
  375.              _______ ______ ________
  376.  
  377.  
  378.         Several operators are provided to allow construction of  a  type
  379.         of pattern called a regular expression.  Such expressions can be
  380.                             _______ __________
  381.         implemented as finite-state automata (without memory or stacks).
  382.         A  reference  to  an  "occurrence"  of  a  regular expression is
  383.         generally taken to mean an occurrence of any string  matched  by
  384.         that  regular  expression.  The operators are presented in order
  385.         of decreasing priority.  In all cases, operators work on  either
  386.         strings or character classes, or on other regular expressions.
  387.  
  388.         Any string or character class forms a regular  expression  which
  389.         matches  whatever  the  string or character class stands for (as
  390.         described above).
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.         A Lexical Analyser Generator                                      Page 6
  398.  
  399.  
  400.         The operator '*' applied following a regular expression forms  a
  401.         new  regular  expression  which matches an arbitrary number (ie,
  402.         zero or more) of  adjacent  occurrences  of  the  first  regular
  403.         expression.   The  operation  is  often  referred to as (Kleene)
  404.         closure.
  405.  
  406.         The operation of concatenation of  two  regular  expressions  is
  407.                          _____________
  408.         expressed  simply by writing the regular expressions adjacent to
  409.         each  other.   The  resulting  regular  expression  matches  any
  410.         occurrence  of the first regular expression followed directly by
  411.         an occurrence of the second regular expression.
  412.  
  413.         The operator  '|',  alternation,  written  between  two  regular
  414.                             ___________
  415.         expressions   forms   a  regular  expression  which  matches  an
  416.         occurrence of the first regular expression or an  occurrence  of
  417.         the second regular expression.
  418.  
  419.         Any regular expression may be enclosed in parentheses  to  cause
  420.         the priority of operators to be overridden in the usual manner.
  421.  
  422.         A few examples should help to make all of this clear:
  423.  
  424.                 "[0-9]*"        matches a (possibly empty)  sequence  of
  425.                                 digits.
  426.  
  427.                 "[A-Za-z_$][A-Za-z0-9_$]*"
  428.                                 matches a C identifier.
  429.  
  430.                 "([A-Za-z_$]|[0-9])*"
  431.                                 matches a C identifier, or a sequence of
  432.                                 digits,  or  a  sequence  of letters and
  433.                                 digits intermixed, or nothing.
  434.  
  435.  
  436.  
  437.  
  438.         2.3  The General Form of Lex Programs
  439.              ___ _______ ____ __ ___ ________
  440.  
  441.  
  442.         A LEX source input file consists of three sections:   a  section
  443.         containing   auxiliary   definitions,   a   section   containing
  444.                      _________   ___________
  445.         translations, and a section containing programs.
  446.         ____________                           ________
  447.  
  448.         Throughout a LEX program, spaces, tabs, and newlines may be used
  449.         freely, and PL/1-style comments:
  450.  
  451.                 /* ... anything but '*/' ... */
  452.  
  453.         may be used, and are treated as a space.
  454.  
  455.         The auxiliary definition section must be present, separated from
  456.             _________ __________
  457.         following  sections  by the two-character sequence '%%', but may
  458.         be empty.  This  section  allows  definition  of  named  regular
  459.  
  460.  
  461.  
  462.  
  463.         expressions,  which  provide  the useful ability to use names of
  464.         regular expressions in the  translation  section,  in  place  of
  465.  
  466.  
  467.  
  468.  
  469.  
  470.  
  471.  
  472.  
  473.  
  474.  
  475.  
  476.  
  477.  
  478.  
  479.  
  480.  
  481.  
  482.  
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.         A Lexical Analyser Generator                                      Page 7
  530.  
  531.  
  532.         common sub-expressions, or to make that section more readable.
  533.  
  534.         The translation section follows the '%%' sequence, and  contains
  535.             ___________
  536.         regular  expressions paired with actions which describe what the
  537.                                          _______
  538.         lexical analyser should do when it discovers an occurrence of  a
  539.         given regular expression in its input stream.
  540.  
  541.         The program section may be omitted;  if it is present it must be
  542.             _______
  543.         separated from the translation section by the '%%' sequence.  If
  544.         present, it may contain anything in general,  as  it  is  simply
  545.         tacked on to the end of the LEX output file.
  546.  
  547.         The style of this layout will be familiar to users of Yacc.   As
  548.         LEX  is  often used with that processor, it seemed reasonable to
  549.         keep to a similar format.
  550.  
  551.  
  552.  
  553.         2.4  Auxiliary Definitions
  554.              _________ ___________
  555.  
  556.  
  557.         Given the set of regular expressions forming a complete  syntax,
  558.         there  are often common sub-expressions.  LEX allows these to be
  559.         named, defined  but  once,  and  referred  to  by  name  in  any
  560.         subsequent   regular  expression.   Note  that  definition  must
  561.         precede use.  A definition has the form:
  562.  
  563.                 expression_name = regular_expression ;
  564.  
  565.         where a name is composed of a lower-case letter  followed  by  a
  566.         sequence  string  of letters and digits, and where an underscore
  567.         is considered a letter.  For example,
  568.  
  569.                 digit   = [0-9];
  570.                 letter  = [a-zA-Z];
  571.                 name    = letter(letter|digit)*;
  572.  
  573.         The semicolon is needed to resolve some ambiguities in  the  LEX
  574.         syntax.
  575.  
  576.         Three  auxiliary  definitions  have  special  meaning  to   LEX:
  577.         "break",  "illegal",  and  "ignore."  They  are  all  defined as
  578.         character classes ("break = [,.?]", for example) and are used as
  579.         follows:
  580.  
  581.                 break   An input token will always terminate if a member
  582.                         of the "break" class is scanned.
  583.  
  584.                 illegal The "illegal"  class  allows  simplification  of
  585.                         error detection, as will be described in a later
  586.                         section.  If this  class  is  defined,  and  the
  587.                         lexical  analyser  stops  at  a  character  that
  588.                         "cannot"  occur  in  its  present  context,  the
  589.                         analyser  will  output  a suitable error message
  590.                         and ignore the offender.
  591.  
  592.  
  593.  
  594.  
  595.         A Lexical Analyser Generator                                      Page 8
  596.  
  597.  
  598.                 ignore  This class defines a set of characters that  are
  599.                         ignored by the analyser's input routine.
  600.  
  601.  
  602.  
  603.  
  604.         2.5  Translations
  605.              ____________
  606.  
  607.  
  608.         One would like to provide a description  of  the  action  to  be
  609.         taken  when  a  particular sequence of input characters has been
  610.         matched by a given regular expression.  The kind of action taken
  611.         might  vary  considerably, depending upon the application.  In a
  612.         compiler, typical actions are:  enter an identifer into a symbol
  613.         table,  read and store a string, or return a particular token to
  614.         the parser.  In text processing, one  might  wish  to  reproduce
  615.         most  of  the input stream on an output stream unchanged, making
  616.         substitutions when a particular sequence of characters is found.
  617.         In  general,  it  is  hard to predict what form the action might
  618.         take, and so, in LEX the nature of the action  is  left  to  the
  619.         user,  by allowing specification, for each regular expression of
  620.         interest, C-language code to be executed when a string  matching
  621.         that  expression  is  discovered  by  the driving program of the
  622.         lexical  analyser.   An  action,  together  with   its   regular
  623.         expression, is called a translation, and has the format:
  624.                                 ___________
  625.  
  626.                 regular_expression { action }
  627.  
  628.         All of this may be spread across several lines.  The action  may
  629.         be empty, but the braces must appear.
  630.  
  631.         Earlier, it was argued that most general-purpose  languages  are
  632.         inappropriate for writing lexical analysers, and it is important
  633.         to see that the subsequent use of such a language  to  form  the
  634.         actions  is not a contradiction.  Most languages are fairly good
  635.         at  expressing  the  actions  described  above   (symbol   table
  636.         manipulation,  writing  character  strings,  and such).  Leaving
  637.         this part of the lexical analyser to those  languages  therefore
  638.         not  only  makes  sense,  but also ensures that decisions by the
  639.         writer of the lexical analyser generator will not  unduly  cramp
  640.         the  user's style.  However, general-purpose languages do not as
  641.         a rule provide inexpensive pattern matching facilities, or input
  642.         description formats, appropriate for describing or structuring a
  643.         lexical analyser.
  644.  
  645.         Allowing a user to provide his own code is not really enough, as
  646.         he  will  need  some  help  from  LEX  to obtain a copy of, or a
  647.         pointer to, the current token, if nothing else.  LEX provides  a
  648.         library  of C functions which may be called to obtain controlled
  649.         access to some of  the  data  structures  used  by  the  driving
  650.         programs  of  the  lexical  analyser.   These are described in a
  651.         later section.
  652.  
  653.  
  654.  
  655.  
  656.  
  657.  
  658.  
  659.  
  660.  
  661.         A Lexical Analyser Generator                                      Page 9
  662.  
  663.  
  664.         2.5.1  Numbers and Values -
  665.                _______ ___ ______
  666.  
  667.         Typically, a lexical analyser will return a value to its  caller
  668.         indicating  which  token has been found.  Within an action, this
  669.         is done by writing a  C  return  statement,  which  returns  the
  670.                                  ______
  671.         appropriate value:
  672.  
  673.                 BEGIN   {
  674.                                 return(T_BEGIN);
  675.                         }
  676.                 name    {
  677.                                 lookup(token(NULL));
  678.                                 return(T_NAME);
  679.                         }
  680.                 "/"     {
  681.                                 return('/');
  682.                         }
  683.  
  684.         Note that function lookup() is provided by the user program.
  685.  
  686.         In many cases, other information must be supplied to its  caller
  687.         by  the scanner.  When an identifier is recognised, for example,
  688.         both a pointer to a symbol-table entry,  and  the  token  number
  689.         T_NAME  must  be returned, yet the C return statement can return
  690.                                              ______
  691.         but a single value.  Yacc has a  similar  problem,  and  so  its
  692.         lexical  analyser  sets  an  external word 'yylval' to the token
  693.         value, while the token number is returned by the  scanner.   LEX
  694.         uses  the external 'yylval' (to be compatible), but, to make LEX
  695.         programs more readable when used alone, the name 'lexval' is set
  696.         by a #define statement to 'yylval'.  For example,
  697.  
  698.                 name    {
  699.                                 lexval = lookup(token(NULL));
  700.                                 return(T_NAME);
  701.                         }
  702.  
  703.  
  704.         Certain  token  numbers  are  treated  specially;    these   are
  705.         automatically defined as manifests (see section 3.2) by LEX, and
  706.         all begin with the sequence 'LEX...' so as not to clash with the
  707.         user's own names.  There are two such tokens defined at present:
  708.  
  709.                 LEXSKIP When  returned  by  a  user's  action   routine,
  710.                         LEXSKIP  causes  the  lexical analyser to ignore
  711.                         the current token (ie, it does  not  inform  the
  712.                         parser of its presence), and to look instead for
  713.                         a new token.  This may be used  when  a  comment
  714.                         sequence has been discovered, and discarded.  It
  715.                         is also useful when the action routine completes
  716.                         processing  of the token.  See the discussion of
  717.                         the comment() library function for an example of
  718.                         its usage.
  719.  
  720.                 LEXERR  This  is  returned  by  the   lexical   analyser
  721.                         (function  yylex()) when an unrecognizable input
  722.  
  723.  
  724.  
  725.  
  726.  
  727.         A Lexical Analyser Generator                                     Page 10
  728.  
  729.  
  730.                         sequence has been detected.  By default,  LEXERR
  731.                         is 256.  This the same as the yacc error value.
  732.  
  733.  
  734.         To summarise, the token number is  set  by  the  action  with  a
  735.         return   statement,   and   the   token   value  (ie,  auxiliary
  736.         ______
  737.         information) is set by assigning  this  value  to  the  external
  738.         integer 'lexval'.
  739.  
  740.  
  741.  
  742.         2.6  Declaration Sections
  743.              ___________ ________
  744.  
  745.  
  746.         Declarations in the language of the actions may be  included  in
  747.         both  the  auxiliary  definition  section and in the translation
  748.         section.   In  the  former  case,  these  declarations  will  be
  749.         external  to  the lexical analyser, and in the latter case, they
  750.         will be local to the lexical analyser (ie, static, or  automatic
  751.         storage).    Declaration  sections  consist  of  a  sequence  of
  752.         declarations surrounded by the special bracketing sequences '%{'
  753.         and '%}' (as in Yacc).  The characters within these brackets are
  754.         copied unchanged into  the  appropriate  spots  in  the  lexical
  755.         analyser  program  that  LEX writes.  The examples in appendix A
  756.         suggest how these might be used.
  757.  
  758.  
  759.  
  760.         3.0  Using Lex from C
  761.              _____ ___ ____ _
  762.  
  763.  
  764.         The present version of LEX is intended for use with C;   and  it
  765.         is this usage which will be described here.
  766.  
  767.  
  768.  
  769.         3.1  The Function yylex()
  770.              ___ ________ _______
  771.  
  772.  
  773.         The structure  of  LEX  programs  is  influenced  by  what  Yacc
  774.         requires of its lexical analyser.
  775.  
  776.         To begin with, the lexical analyser must be named  'yylex',  has
  777.         no  parameters,  and is expected to return a token number, where
  778.         that number is determined by Yacc.   The  token  number  for  an
  779.         Ascii  character  is  its  Ascii  value  (ie,  its  value as a C
  780.         character constant).  Named tokens,  defined  in  yacc  '%token'
  781.         statements,  have a number above 256, with the particular number
  782.         accessible through a Yacc-produced #define of  the  given  token
  783.         name as its number.  Yacc also allows 'yylex' to pass a value to
  784.         the Yacc  action  routines,  by  assigning  that  value  to  the
  785.         external 'yylval'.
  786.  
  787.         LEX thus provides a lexical  analyser  function  named  'yylex',
  788.         which interprets tables constructed by the LEX program returning
  789.  
  790.  
  791.  
  792.  
  793.         A Lexical Analyser Generator                                     Page 11
  794.  
  795.  
  796.         the token number returned by the actions  it  performs.   Values
  797.         assigned  to  lexval are available in 'yylval', so that use with
  798.         Yacc is straightforward.
  799.  
  800.         A value of zero is returned by 'yylex' at  end-of-file,  and  in
  801.         the absence of a return statement in an action, a non-zero value
  802.                          ______
  803.         is returned.   If  computation  is  performed  entirely  by  the
  804.         lexical analyser, then a suitable main program would be
  805.  
  806.                 main()
  807.                    {
  808.                    while (yylex()) ;
  809.                    }
  810.  
  811.  
  812.  
  813.  
  814.         3.2  Serial Re-Use of yylex()
  815.              ______ ______ __ _______
  816.  
  817.  
  818.         The  yylex()  function  contains  several  variables  which  are
  819.         statically  initialized  at  compile time.  Once yylex() sees an
  820.         EOF (-1) input character, it will continue to return  NULL.   If
  821.         yylex()  is  to  be  used inside a loop which processes multiple
  822.         files, it must be re-initialized at the beginning  of  each  new
  823.         file  with  a  call  to  the  LEX library routine llinit().  For
  824.         example (slightly extending the previous example):
  825.  
  826.                 main()
  827.                    {
  828.                    getfilelist();
  829.                    for(file = first; file != last; file = next)
  830.                       {
  831.                       llinit();
  832.                       while (yylex());
  833.                       }
  834.                    printf("All files done\n");
  835.                    }
  836.  
  837.         The call to llinit() is unnecessary if  yylex()  is  to  process
  838.         only one file, or is kept from seeing an EOF input character.
  839.  
  840.  
  841.  
  842.         3.3  The Lex Table File
  843.              ___ ___ _____ ____
  844.  
  845.  
  846.         In the absence of instructions to the contrary (see below),  LEX
  847.         reads a given LEX language file, (from the standard input, if an
  848.         input file has not been specified) and produces a C program file
  849.         'lextab.c'  which  largely  consists  of  tables  which are then
  850.         interpreted by 'yylex()' (which is in  the  LEX  library).   The
  851.         actions  supplied  by  the user in each translation are combined
  852.         with a switch statement into a single function, which is  called
  853.                ______
  854.         by  the table interpreter when a particular token is found.  The
  855.  
  856.  
  857.  
  858.  
  859.         A Lexical Analyser Generator                                     Page 12
  860.  
  861.  
  862.         contents of the program section of the LEX file are added at the
  863.         end  of  the  output  file (lextab.c by default).  Normally, LEX
  864.         also inserts the lines
  865.  
  866.                 #include <stdio.h>
  867.                 #include <lex.h>
  868.  
  869.         at the top of the file;  this causes  declarations  required  by
  870.         the  standard  I/O  library and by LEX to be included when the C
  871.         program is compiled.
  872.  
  873.  
  874.  
  875.         3.4  Analyzers Which Don't Use "Standard I/O"
  876.              _________ _____ _____ ___ _________ ____
  877.  
  878.  
  879.         With  the  current  release,  LEX  supports  the  generation  of
  880.         analyzers  which  may be incorporated into programs which do not
  881.         use the "standard I/O" library.  By setting the "-s" switch,  as
  882.         shown  below, the generation of the "#include <stdio.h>" line is
  883.         supressed.  All references to standard I/O  specific  files  and
  884.         stdio.h  have  been removed from the LEX library (described in a
  885.         later section), with the  exception  of  lexgetc(),  lexerror(),
  886.         mapch() and lexecho(), which are standard I/O dependent.
  887.  
  888.         The declaration of yylex()'s input file iov pointer "lexin"  now
  889.         resides  in LEXGET.C (lexgetc()).  The code which defaults lexin
  890.         to stdin has been moved from yylex() to the table file.  yylex()
  891.         now  calls  the  routine  llstin(),  which is generated into the
  892.         table file.  There are no longer any hardwired references to the
  893.         variable   "lextab",  the  default  table  name.   Instead,  LEX
  894.         generates a call to lexswitch() in llstin(),  which  initializes
  895.         yylex()  to use the table whose name was given in a "-t" or "-e"
  896.         option in LEX's command line.  If neither was given, the default
  897.         name  "lextab" is used.  Once the initial table has been set up,
  898.         further automatic calls to lexswitch() are  supressed,  allowing
  899.         the user to manually switch tables as before.
  900.  
  901.         In addition, If the "-s" switch is not given (i.e.,  normal  use
  902.         with  standard  I/O), llstin() defaults lexin to stdin.  If "-s"
  903.         is given, llstin() is generated to do the lexswitch()  mentioned
  904.         above  only.  In any case, yylex() contains no references to the
  905.         standard I/O system.
  906.  
  907.         What all of this means is that under normal operation, you won't
  908.         notice  any  change  in LEX's characteristics.  In addition, you
  909.         may use the "-e" ("easy") switch, which will generate a C output
  910.         file  and  LEX tables which (conveniently) have the same name as
  911.         the input file, and everything will get  set  up  automagically.
  912.         If  you  specify the "-s" switch, the table file will contain no
  913.         references to the standard I/O package, and you may use  any  of
  914.         the  lexlib  routines  except  lexgetc(), lexerror(), mapch() or
  915.         lexecho().
  916.  
  917.         Don't forget that you  must  supply  your  own  startup  routine
  918.  
  919.  
  920.  
  921.  
  922.  
  923.  
  924.  
  925.         A Lexical Analyser Generator                                     Page 13
  926.  
  927.  
  928.         "$$main"  if  you  do not want the standard I/O library.  With a
  929.         bit of care in this regard, it will be  possible  to  link  your
  930.         program  with the C library without dragging in any I/O modules.
  931.         This prevents your having to build another library in  order  to
  932.         access  non-I/O  library  functions.  Just make the reference to
  933.         the C library the last one given to the linker or taskbuilder so
  934.         that  only  those routines which have not already been found are
  935.         pulled from CLIB.
  936.  
  937.  
  938.                                       NOTE
  939.  
  940.             Programs that use LEX-generated analyzers and do not use
  941.             the standard I/O package must supply their own lexgetc()
  942.             and lexerror() routines.  Failure to do so  will  result
  943.             in undefined globals.
  944.  
  945.  
  946.  
  947.  
  948.  
  949.         3.5  Operating LEX
  950.              _________ ___
  951.  
  952.  
  953.         LEX normally reads the grammar from the standard input,  writing
  954.         the  C  program  to  the  file  'lextab.c'.   It  may be further
  955.         controlled by using the following flags upon invocation:
  956.  
  957.                 -i filename     The grammar is read from 'filename'.
  958.  
  959.                 -o filename     The analyser is written to 'filename'.
  960.  
  961.                 -t tablename    The default  finite-state  automaton  is
  962.                                 named  lextab  (and  it  is, by default,
  963.                                 written to  file  'lextab.c').   The  -t
  964.                                 switch  causes the internal tables to be
  965.                                 named 'tablename' and, if the -o  switch
  966.                                 is    not   given,   written   to   file
  967.                                 'tablename.c'.  This is necessary if the
  968.                                 processor-switching         capabilities
  969.                                 described in a later section are  to  be
  970.                                 used.
  971.  
  972.                 -e name         "Easy"  command  line.    "-e name"   is
  973.                                 equivalent to typing
  974.  
  975.                                    -i name.LXI -o name.C -t name
  976.  
  977.                                 Do not  include  device  names  or  file
  978.                                 extensions on the "easy" command line.
  979.  
  980.                 -v [filename]   Internal state information is written to
  981.                                 'filename.'   If   not   present,  state
  982.                                 information   is   written    to    file
  983.                                 'lex.out.'
  984.  
  985.  
  986.  
  987.  
  988.  
  989.  
  990.  
  991.         A Lexical Analyser Generator                                     Page 14
  992.  
  993.  
  994.                 -d              Enable various debugging printouts.
  995.  
  996.                 -s              Generate analyzer without references  to
  997.                                 standard I/O
  998.  
  999.  
  1000.         The command line  for  compilation  of  the  table  file  should
  1001.         contain no surprises:
  1002.  
  1003.                 cc -c -O lextab.c       (on Unix)
  1004.  
  1005.                 xcc lextab -a           (on Dec operating systems)
  1006.  
  1007.         but when one is producing  the  running  program,  one  must  be
  1008.         careful to include the necessary libraries.  On Unix, the proper
  1009.         sequence is:
  1010.  
  1011.                 cc userprog.o lextab.o -ll -lS
  1012.  
  1013.         The '-ll'  causes  the  LEX  library  (described  below)  to  be
  1014.         searched,  and  the  '-lS' causes the Standard I/O library to be
  1015.         used;  both libraries are required.  If Yacc is  used  as  well,
  1016.         the  library  '-ly'  should  be  included before the '-ll'.  The
  1017.                                                   ______
  1018.         actual order and content of the rest  of  the  command  line  is
  1019.         determined by the user's own requirements.
  1020.  
  1021.         If using the Decus C compiler, the lexical analyser built by LEX
  1022.         is linked with c:lexlib.
  1023.  
  1024.         The complete process (assuming the  Decus  compiler  running  on
  1025.         RSTS/E in RT11 mode) is thus:
  1026.  
  1027.                 mcr lex -i grammar.lxi -o grammar.c     ! Build analyser
  1028.                 cc grammar                              ! Compile the
  1029.                 as grammar                              ! grammar table
  1030.                 link out=in,grammar,c:lexlib,c:suport,c:clib/b:2000
  1031.  
  1032.  
  1033.  
  1034.  
  1035.         4.0  The Lex Library
  1036.              ___ ___ _______
  1037.  
  1038.  
  1039.         All programs using grammars generated  by  LEX  must  be  linked
  1040.         together  with  the LEX library.  On Unix, this is '/lib/libl.a'
  1041.         (or '-ll' on the cc command line) and on DEC operating  systems,
  1042.         C:LEXLIB  (LB:[1,1]LEX.OLB for RSX).  It contains routines which
  1043.         are either essential or merely useful  to  users  of  LEX.   The
  1044.         essential  routines  include  a  routine to obtain a copy of the
  1045.         current token, and a routine to switch to  a  different  set  of
  1046.         scanning  tables.  Routines of the second, useful, class perform
  1047.         functions which might well be written by the user  himself,  but
  1048.         are  there  to  save  him  the  bother;   including a routine to
  1049.         process various forms of comments and  a  routine  to  transform
  1050.         numbers  written  in arbitrary bases.  Both sets of routines are
  1051.  
  1052.  
  1053.  
  1054.  
  1055.  
  1056.  
  1057.         A Lexical Analyser Generator                                     Page 15
  1058.  
  1059.  
  1060.         expected to grow as LEX sees use.
  1061.  
  1062.         Those functions which  produce  diagnostics  do  so  by  calling
  1063.         lexerror(), which is called as
  1064.  
  1065.                 lexerror(string, arg1, ..., argN)
  1066.  
  1067.         and is expected to write its arguments (likely using the "remote
  1068.         format"  facility  of  the  fprintf()  function),  followed by a
  1069.         newline, on  some  output  stream.   A  Lexerror()  function  is
  1070.         included  in  the LEX library, but a user is free to include his
  1071.         own.  The routine in the LEX library is standard I/O specific.
  1072.  
  1073.  
  1074.                                       NOTE
  1075.  
  1076.             The VAX/VMS native C library  does  not  support  remote
  1077.             formats.   The  Lexerror  function  in  the  LEX library
  1078.             conditionally compiles to support a call  to  lexerror()
  1079.             with  only  an error message string.  Remote formats are
  1080.             supported under Decus C.  Learn to use  them,  they  are
  1081.             very nice!
  1082.  
  1083.  
  1084.  
  1085.  
  1086.  
  1087.         4.0.1  Comment -- skip over a comment -
  1088.                _______ __ ____ ____ _ _______
  1089.  
  1090.                 comment(delim)
  1091.                 char delim[];
  1092.  
  1093.         Comment() may be called by a translation when  the  sequence  of
  1094.         characters which mark the start of a comment in the given syntax
  1095.         has been recognised by LEX.  It takes a string which  gives  the
  1096.         sequence  of  characters  which  mark  the end of a comment, and
  1097.         skips over characters in the input stream until this sequence is
  1098.         found.   Newlines  found  while  skipping  characters  cause the
  1099.         external 'yyline' to be incremented;  an unexpected  end-of-file
  1100.         produces  a  suitable diagnostic.  Thus, 'comment("*/")' matches
  1101.         C-style comments, and 'comment("\n")' matches as-style comments.
  1102.         There  are  other  methods  of  handling  comments  in LEX;  the
  1103.         comment() function is usually the best with regard to both space
  1104.         and time.
  1105.  
  1106.  
  1107.  
  1108.         4.0.2  Gettoken -- obtain a copy of token -
  1109.                ________ __ ______ _ ____ __ _____
  1110.  
  1111.                 gettoken(buf, sizeof(buf))
  1112.                 char buf[];
  1113.  
  1114.         Gettoken() takes the address of a character buffer, and its size
  1115.         in bytes, and copies the token most recently matched by LEX into
  1116.         the buffer.  A null byte is added to mark the end of  the  token
  1117.  
  1118.  
  1119.  
  1120.  
  1121.  
  1122.  
  1123.         A Lexical Analyser Generator                                     Page 16
  1124.  
  1125.  
  1126.         in  the  buffer, but, as null bytes are legitimate characters to
  1127.         LEX, the true length of the token is returned by gettoken().
  1128.  
  1129.         For example, the following function calls lexlength() to  obtain
  1130.         the  length  of a token.  It then calls the storage allocator to
  1131.         allocate sufficient storage for the token and copies  the  token
  1132.         into the allocated area.
  1133.  
  1134.                 char *
  1135.                 save()
  1136.                 /*
  1137.                  * Save current token, return a pointer to it
  1138.                  */
  1139.                 {
  1140.                         register char   *tbuffer;
  1141.                         register int    len;
  1142.                         register char   *tend;
  1143.                         extern char     *token();
  1144.                         extern char     *copy();
  1145.  
  1146.                         len = lexlength() + 1;
  1147.                         if (tbuffer = malloc(len)) == NULL)
  1148.                                 error("No room for token");
  1149.                         gettoken(tbuffer, len);
  1150.                         return(tbuffer);
  1151.                 }
  1152.  
  1153.  
  1154.  
  1155.  
  1156.         4.0.3  Integ -- long integer, any base -
  1157.                _____ __ ____ ________ ___ ____
  1158.  
  1159.                 long
  1160.                 integ(nptr, base)
  1161.                 char *nptr;
  1162.  
  1163.         Integ() converts the Ascii string at 'nptr' into a long integer,
  1164.         which  it  returns.   Conversion  stops  at the first non-digit,
  1165.         where the digits are  taken  from  the  class  "[0-9a-zA-Z]"  as
  1166.         limited by the given 'base'.  Integ() does not understand signs,
  1167.         nor are blanks or tabs allowed in the string.
  1168.  
  1169.  
  1170.  
  1171.         4.0.4  Lexchar -- steal character -
  1172.                _______ __ _____ _________
  1173.  
  1174.                 lexchar()
  1175.  
  1176.         Lexchar() returns the next character from the LEX input  stream.
  1177.         (This  means  that  LEX  will  no  longer  see  it.)  LEX uses a
  1178.         look-ahead buffer to handle complex languages, and this function
  1179.         takes this into account.
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.  
  1186.  
  1187.  
  1188.  
  1189.         A Lexical Analyser Generator                                     Page 17
  1190.  
  1191.  
  1192.         4.0.5  Lexecho -- write token to a file (STDIO ONLY) -
  1193.                _______ __ _____ _____ __ _ ____ ______ _____
  1194.  
  1195.                 lexecho(fp);
  1196.                 FILE *fp;
  1197.  
  1198.         Lexecho() may be called by a LEX action  routine  to  write  the
  1199.         current token to a specified file.
  1200.  
  1201.  
  1202.                                       NOTE
  1203.  
  1204.             Programs using analyzers built with  LEX's  "-s"  switch
  1205.             must supply their own lexecho() function if needed.
  1206.  
  1207.  
  1208.  
  1209.  
  1210.  
  1211.         4.0.6  Lexgetc -- supply characters to yylex (STDIO ONLY) -
  1212.                _______ __ ______ __________ __ _____ ______ _____
  1213.  
  1214.                 lexgetc()
  1215.  
  1216.         Lexgetc() is called by the lexical analyser to obtain characters
  1217.         from  its input stream.  The version in the library is dependent
  1218.         on the standard I/O package, and is:
  1219.  
  1220.                 FILE *lexin;    /* Declare iov address locally */
  1221.                 lexgetc()
  1222.                 {
  1223.                         return(getc(lexin));
  1224.                 }
  1225.  
  1226.         If lexin is NULL when yylex() is entered, it will be assigned to
  1227.         stdin.   This  is done by yylex() calling the function llstin(),
  1228.         which is generated in the table file.  Unless the "-s" switch is
  1229.         given  to  LEX,  the llstin() function assigns lexin to stdin if
  1230.         lexin is NULL.  If the  "-s"  switch  was  given,  the  llstin()
  1231.         routine  is  a  no-op.   The user may provide his own version of
  1232.         lexgetc() to pre-process the data to the lexical  analyser.   An
  1233.         example of this is shown in the appendix.
  1234.  
  1235.  
  1236.                                       NOTE
  1237.  
  1238.             Programs using analyzers built with  LEX's  "-s"  switch
  1239.             must  supply  their  own lexgetc() function, and "lexin"
  1240.             has no meaning in this context.
  1241.  
  1242.  
  1243.  
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.  
  1252.  
  1253.  
  1254.  
  1255.         A Lexical Analyser Generator                                     Page 18
  1256.  
  1257.  
  1258.         4.0.7  Lexlength -- return length of a token. -
  1259.                _________ __ ______ ______ __ _ ______
  1260.  
  1261.                 lexlength();
  1262.  
  1263.         Lexlength() may be called by a LEX action routine to obtain  the
  1264.         length  of  the  current  token in bytes.  An example of this is
  1265.         shown in the description of gettoken().
  1266.  
  1267.  
  1268.  
  1269.         4.0.8  Lexpeek -- examine character -
  1270.                _______ __ _______ _________
  1271.  
  1272.                 lexpeek()
  1273.  
  1274.         Lexpeek() performs a function similar to that of Lexchar(),  but
  1275.         does  not  have  the  side-effect of removing the character from
  1276.         LEX's view.
  1277.  
  1278.  
  1279.  
  1280.         4.0.9  Lexswitch -- switch scanning tables -
  1281.                _________ __ ______ ________ ______
  1282.  
  1283.                 struct lextab *
  1284.                 lexswitch(newtb)
  1285.                 struct lextab *newtb;
  1286.  
  1287.         Lexswitch() is called to cause LEX to use a  different  scanning
  1288.         table;  it returns a pointer to the one previously in use.  This
  1289.         facility is useful if  certain  objects  of  the  language  (eg,
  1290.         strings  in  C) have a fairly complicated structure of their own
  1291.         which cannot be handled within the translation  section  of  the
  1292.         LEX description of the larger language.
  1293.  
  1294.  
  1295.  
  1296.         4.0.10  Llinit -- Reinitialize yylex() -
  1297.                 ______ __ ____________ _______
  1298.  
  1299.                 llinit()
  1300.  
  1301.         Llinit() is a function which resets the state of yylex() to it's
  1302.         cold-start   condition.   Several  of  yylex()'s  variables  are
  1303.         initialized at compile time, and must be reinitialized if it  is
  1304.         to  be serially re-used.  An example of this is where yylex() is
  1305.         repeatedly called inside a loop which processes  multiple  input
  1306.         files.  Each time a new file is started, llinit() must be called
  1307.         before the first call to yylex() for the new file.
  1308.  
  1309.  
  1310.  
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.  
  1318.  
  1319.  
  1320.  
  1321.         A Lexical Analyser Generator                                     Page 19
  1322.  
  1323.  
  1324.         4.0.11  Mapch -- Handle C escapes within strings (STDIO ONLY) -
  1325.                 _____ __ ______ _ _______ ______ _______ ______ _____
  1326.  
  1327.                 int mapch(delim, esc)
  1328.                 char delim;
  1329.                 char esc;
  1330.  
  1331.         Mapch() is a function which handles C "escape"  characters  such
  1332.         as "\n" and "\nnn".  It will scan off the entire escape sequence
  1333.         and return the equivalent ASCII code as an integer.  It is meant
  1334.         for  use  with  YACC while scanning quoted strings and character
  1335.         constants.
  1336.  
  1337.         If it encounters EOF while  scanning,  it  calls  lexerror()  to
  1338.         print  an  error message warning of "Unterminated string".  If a
  1339.         normal character is  read,  it  returns  the  ASCII  value.   If
  1340.         "delim"  (usually " or ') is read, it returns EOF.  If a newline
  1341.         (ASCII linefeed) is read, it increments the global "yyline"  and
  1342.         calls itself recursively for the next line of input.  It may use
  1343.         _____ ______ ___________
  1344.         the ungetc() function to back up in the input stream.
  1345.  
  1346.  
  1347.                                       NOTE
  1348.  
  1349.             This routine is very application-specific for use by LEX
  1350.             and  YACC  when  they  are working together.  You should
  1351.             read the code in MAPCH.C before using this function.
  1352.  
  1353.  
  1354.  
  1355.  
  1356.  
  1357.         4.0.12  Token -- get pointer to token -
  1358.                 _____ __ ___ _______ __ _____
  1359.  
  1360.                 char *
  1361.                 token(end_pointer)
  1362.                 char **end_pointer;
  1363.  
  1364.         Token() locates the first byte of the current token and  returns
  1365.         its  address.   It  takes  an argument which is either NULL or a
  1366.         pointer to a character pointer;  if the latter, that pointer  is
  1367.         set  to  point  to  the  byte after the last byte of the current
  1368.                                       _____
  1369.         token.  Token() is slightly faster,  and  more  convenient  than
  1370.         gettoken()  for  those  cases where the token is only one or two
  1371.         bytes long.
  1372.  
  1373.  
  1374.  
  1375.  
  1376.         5.0  Error Detection and Recovery
  1377.              _____ _________ ___ ________
  1378.  
  1379.  
  1380.         If a character is detected in the input stream which  cannot  be
  1381.         added  to  the  last-matched  string,  and  which cannot start a
  1382.         string, then that character is considered illegal by  LEX.   LEX
  1383.  
  1384.  
  1385.  
  1386.  
  1387.         may be instructed to return a special 'error' token, or to write
  1388.  
  1389.  
  1390.  
  1391.  
  1392.  
  1393.  
  1394.  
  1395.  
  1396.  
  1397.  
  1398.  
  1399.  
  1400.  
  1401.  
  1402.  
  1403.  
  1404.  
  1405.  
  1406.  
  1407.  
  1408.  
  1409.  
  1410.  
  1411.  
  1412.  
  1413.  
  1414.  
  1415.  
  1416.  
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425.  
  1426.  
  1427.  
  1428.  
  1429.  
  1430.  
  1431.  
  1432.  
  1433.  
  1434.  
  1435.  
  1436.  
  1437.  
  1438.  
  1439.  
  1440.  
  1441.  
  1442.  
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.  
  1450.  
  1451.  
  1452.  
  1453.         A Lexical Analyser Generator                                     Page 20
  1454.  
  1455.  
  1456.         a diagnostic with lexerror().  At present,  the  former  is  the
  1457.         default action.
  1458.  
  1459.         The token LEXERR is a special value which is recognised by Yacc,
  1460.         and causes it to start its own error recovery.  It is defined by
  1461.         the header file lex.h for use by other programs.
  1462.  
  1463.         Often, it makes more sense to simply type a suitable diagnostic,
  1464.         and  continue by ignoring the offending character.  It is fairly
  1465.         easy to cause  LEX  to  do  this,  by  including  the  auxiliary
  1466.         definition:
  1467.  
  1468.                 illegal = [\0-\377];
  1469.  
  1470.         which defines a  character  class  "illegal"  which  is  handled
  1471.         specially  by LEX.  If the character that is causing the trouble
  1472.         is a member of that character class (and  in  the  example,  all
  1473.         characters  are),  then  LEX will write a diagnostic, and ignore
  1474.         it;  otherwise, it will return the special token LEXERR
  1475.  
  1476.         More comprehensive  techniques  may  be  added  as  they  become
  1477.         apparent.
  1478.  
  1479.  
  1480.  
  1481.         6.0  Ambiguity and Look-ahead
  1482.              _________ ___ __________
  1483.  
  1484.         Many computer languages have ambiguous grammars in that an input
  1485.         token  may represent more than one logical entity.  This section
  1486.         discusses the  way  in  which  grammars  built  by  LEX  resolve
  1487.         ambiguous  input,  as  well  as  a way for the grammar to assign
  1488.         unique meaning to a token by looking ahead in the input stream.
  1489.  
  1490.  
  1491.  
  1492.         6.1  Resolving Ambiguities
  1493.              _________ ___________
  1494.  
  1495.  
  1496.         A LEX program may be ambiguous, in the sense that  a  particular
  1497.         input  string  or  strings  might  be  matched  by  the  regular
  1498.         expression of more than one translation.  Consider,
  1499.  
  1500.                 [a-z] { putchar(*token(NULL)); }
  1501.                 aaa*  { printf("abc"); }
  1502.  
  1503.         in which the string 'aa' is matched by both regular  expressions
  1504.         (twice  by the first, and once by the second).  Also, the string
  1505.         'aaaaaa' may be matched in many  different  ways.   LEX  has  to
  1506.         decide    somehow    which    actions   should   be   performed.
  1507.         (Alternatively, it could produce a diagnostic, and give up.   As
  1508.         it happens, LEX never does this.)
  1509.  
  1510.         Consider a second example,
  1511.  
  1512.                 letter = [a-z];
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.         A Lexical Analyser Generator                                     Page 21
  1520.  
  1521.  
  1522.                 %%
  1523.                 A(letter)*      { return(1); }
  1524.                 AB(letter)*     { return(2); }
  1525.  
  1526.         which attempts to distinguish sequences of  letters  that  begin
  1527.         with 'a' from similar sequences that begin with 'ab'.  These two
  1528.         examples illustrate two different kinds of  ambiguity,  and  the
  1529.         following indicates how LEX resolves these.
  1530.  
  1531.         In the first example, it seems likely that  the  intent  was  to
  1532.         have both 'aa' and 'aaaaaa' perform the second action, while all
  1533.         single letters 'a' cause the first action to be performed.   LEX
  1534.         does  this  by  ensuring  that  the longest possible part of the
  1535.         input stream will be used to determine the match.  Thus,
  1536.  
  1537.                 <       { return(LESS); }
  1538.                 <=      { return(LESSEQ); }
  1539.  
  1540.         or
  1541.  
  1542.                 digit(digit)*           { return(NUMBER); }
  1543.                 letter(letter|digit)*   { return(NAME); }
  1544.  
  1545.         would work as one might expect.
  1546.  
  1547.         In the second example, the longest-string need not work.  On the
  1548.         string  "abb9",  either  action could apply, and so another rule
  1549.         must be followed.  This states that if, after the longest-string
  1550.         rule  has  been  applied,  there  remains an ambiguity, then the
  1551.         action which appears first in the LEX  program  file  is  to  be
  1552.         performed.   As the second example is written, the second action
  1553.         will never be performed.  It would have been written as:
  1554.  
  1555.                 letter = [a-z];
  1556.                 %%
  1557.                 AB(letter)*     { return(1); }
  1558.                 A(letter)*      { return(2); }
  1559.  
  1560.         The two rules together completely determine a string.
  1561.  
  1562.         At present, LEX produces  no  diagnostic  in  either  case;   it
  1563.         merely  applies  the  rules  and  proceeds.   In  the case where
  1564.         priority is given to the first-appearing rule,  it  might  be  a
  1565.         good idea to produce a diagnostic.
  1566.  
  1567.  
  1568.  
  1569.         6.2  Look-ahead
  1570.              __________
  1571.  
  1572.  
  1573.         Some facility for looking ahead in the input stream is sometimes
  1574.         required.   (This  facility  might also be regarded as a way for
  1575.         the  programmer  to  more  closely   control   LEX's   ambiguity
  1576.         resolution  process.)  For example, in C, a name followed by "("
  1577.         is to be contextually declared as an external function if it  is
  1578.  
  1579.  
  1580.  
  1581.  
  1582.  
  1583.  
  1584.  
  1585.         A Lexical Analyser Generator                                     Page 22
  1586.  
  1587.  
  1588.         otherwise undefined.
  1589.  
  1590.         In Pascal, look-ahead is required to determine that
  1591.  
  1592.                 123..1234
  1593.  
  1594.         is an  integer  123,  followed  by  the  subrange  symbol  "..",
  1595.         followed  by  the  integer 1234, and not simply two real numbers
  1596.         run together.
  1597.  
  1598.         In both of these cases, the desire is to look ahead in the input
  1599.         stream  far  enough  to  be able to make a decision, but without
  1600.         losing tokens in the process.
  1601.  
  1602.         A special  form  of  regular  expression  is  used  to  indicate
  1603.         look-ahead:
  1604.  
  1605.                 re1 '/' re2     '{' action '}'
  1606.  
  1607.         where 're1' and 're2' are regular  expressions.   The  slash  is
  1608.         treated  as  concatenation for the purposes of matching incoming
  1609.         characters;  thus both 're1' and 're2' must match adjacently for
  1610.         the  action  to  be performed.  'Re1' indicates that part of the
  1611.         input string which is the token  to  be  returned,  while  're2'
  1612.         indicates  the context.  The characters matched by 're2' will be
  1613.         re-read at the next call to yylex(), and broken into tokens.
  1614.  
  1615.         Note that you cannot write:
  1616.  
  1617.                 name = re1 / re2;
  1618.  
  1619.         The look-ahead operator must be part of the  rule.   It  is  not
  1620.         valid in definitions.
  1621.  
  1622.         In the first example, the look-ahead operator would be used as:
  1623.  
  1624.                 name / "(" {
  1625.                                 if (name undefined)
  1626.                                         declare name a global function;
  1627.                         }
  1628.                 name    {       /* usual processing for identifiers */
  1629.                         }
  1630.  
  1631.         In the second example, the range construction would be parsed as
  1632.         follows:
  1633.  
  1634.                 digit   = [0-9];
  1635.                 int     = digit(digit)*;
  1636.                 %%
  1637.                 int / ".." int  { /* Start of a range */
  1638.                 ".." int        { /* End of a range   */
  1639.  
  1640.  
  1641.         Note that right-context is  not  sufficient  to  handle  certain
  1642.         types of ambiguity, as is found in several places in the Fortran
  1643.  
  1644.  
  1645.  
  1646.  
  1647.  
  1648.  
  1649.  
  1650.  
  1651.         A Lexical Analyser Generator                                     Page 23
  1652.  
  1653.  
  1654.         language.  For example,
  1655.  
  1656.                 do i = 1        Is an assignment statement
  1657.                 do i = 1, 4     Is a DO statement
  1658.  
  1659.         It is not sufficient to use right-context scanning to  look  for
  1660.         the   comma,   as   it   may   occur   within   a  parenthesized
  1661.         sub-expression:
  1662.  
  1663.                 do i = j(k,l)   Is an assignment statement
  1664.  
  1665.         In Fortran, similar problems exist for IF and FORMAT statements,
  1666.         as  well  as counted (Hollerith) string constants.  All of these
  1667.         require a more  powerful  grammar  than  is  possible  with  LEX
  1668.         regular-expressions.
  1669.  
  1670.  
  1671.  
  1672.         7.0  Multiple Scanning Tables; Processor Switching
  1673.              ________ ________ _______ _________ _________
  1674.  
  1675.  
  1676.         Even a fairly simple syntax may be difficult, or impossible,  to
  1677.         describe  and  process  with  a  single set of translations.  An
  1678.         example of this may be found in C, where strings, which are part
  1679.         of  the language, have quite a different structure, and in order
  1680.         to process them, either a function must be  called  which  reads
  1681.         and parses the input stream for itself, or some mechanism within
  1682.         LEX must be invoked to  cause  a  (usually  massive)  change  of
  1683.         state.
  1684.  
  1685.         LEX does provide such a facility, which is known, after AED,  as
  1686.         'processor  switching'.   Yylex()  locates  its tables through a
  1687.         pointer;  if one simply changes the pointer to point  at  a  new
  1688.         set  of  tables,  one  will have effected the required change of
  1689.         state.  The LEX library function lexswitch(), which is described
  1690.         elsewhere  in  this guide, arranges to do this;  it also returns
  1691.         the old value of the pointer so that it may  be  restored  by  a
  1692.         later  call  to  Lexswitch.   Thus, scanning environments may be
  1693.         stacked, or not, as the user requires.
  1694.  
  1695.  
  1696.  
  1697.         7.1  Creation of a Processor
  1698.              ________ __ _ _________
  1699.  
  1700.  
  1701.         It should be clear that if all the tables produced by LEX from a
  1702.         user's translation file have the same name, someone (the loader)
  1703.         is bound to object.  Some method must be provided to change  the
  1704.         name of the table.
  1705.  
  1706.         This is done by an option flag to the LEX command:
  1707.  
  1708.                 -t name
  1709.  
  1710.         will cause the scanning table to be declared as
  1711.  
  1712.  
  1713.  
  1714.  
  1715.  
  1716.  
  1717.         A Lexical Analyser Generator                                     Page 24
  1718.  
  1719.  
  1720.                 struct lextab name;
  1721.  
  1722.         so that it may be passed to LEXswitch:
  1723.  
  1724.                 lexswitch(&name);
  1725.  
  1726.         LEX also writes the program file to  the  file  "name.c"  rather
  1727.         than to "lextab.c."
  1728.  
  1729.  
  1730.                                       NOTE
  1731.  
  1732.             If you use the "easy"  command  line  ("-e  name")  when
  1733.             running  LEX,  the  output  file  and  table  names will
  1734.             correspond nicely.  Re-read the section on operating LEX
  1735.             for more details.
  1736.  
  1737.  
  1738.  
  1739.  
  1740.  
  1741.         8.0  Conclusion
  1742.              __________
  1743.  
  1744.  
  1745.         LEX seems to handle most lexical analysis tasks easily.  Indeed,
  1746.         LEX   may  be  more  generally  used  to  write  commands  of  a
  1747.         text-processing nature;  an example of such usage may  be  found
  1748.         in  an  appendix.  LEX programs are far easier to write than the
  1749.         equivalent  C  programs,  and  generally  consume   less   space
  1750.         (although  there  is  an  initial  overhead for the more general
  1751.         table-interpreter  program).   The  encoding  suggested  in  [4]
  1752.         achieves   a  reasonable  compromise  between  table  size,  and
  1753.         scanning speed.  Certainly lexical analysers  are  less  tedious
  1754.         and time-consuming to write.
  1755.  
  1756.         It is expected that most change in the future  will  be  through
  1757.         additions  to  the  LEX  library.   The  LEX language may change
  1758.         slightly to accomodate common kinds  of  processing  (eg,  break
  1759.         characters),  or  to  extend  its range of application.  Neither
  1760.         kind of change should affect existing LEX programs.
  1761.  
  1762.         LEX produces tables and programs for the C language.  The tables
  1763.         are  in a very simple (and stylised) format, and when LEX copies
  1764.         the action routines or the program section, the  code  might  as
  1765.         well  be Fortran for all it cares.  One could write Unix filters
  1766.         to  translate  the  very  simple  C  format  tables  into  other
  1767.         languages,  allowing  LEX  to  be  used  with a larger number of
  1768.         languages, with little extra development  cost.   This  seems  a
  1769.         likely future addition.
  1770.  
  1771.         Because of the look-ahead necessary to  implement  the  "longest
  1772.         string  match"  rule, LEX is unsuitable for interactive programs
  1773.         whose overall structure is:
  1774.  
  1775.                 for (;;) {
  1776.  
  1777.  
  1778.  
  1779.  
  1780.  
  1781.  
  1782.  
  1783.         A Lexical Analyser Generator                                     Page 25
  1784.  
  1785.  
  1786.                         prompt_user();
  1787.                         get_input();
  1788.                         process();
  1789.                         print_output();
  1790.                 }
  1791.  
  1792.         If these are rewritten as LEX-generated grammars, the user  will
  1793.         be  confused  by the fact the second input datum must be entered
  1794.         before the first is processed.  It is  possible  to  solve  this
  1795.         dilemna   by   rewriting   function   lexgetc()   to  return  an
  1796.         "end-of-line" character until processing is  complete  for  that
  1797.         line.  An example is shown in the Appendix.
  1798.  
  1799.  
  1800.  
  1801.         9.0  Acknowledgements
  1802.              ________________
  1803.  
  1804.  
  1805.         LEX  is  based  on  a  processor  of  the  same  name  at   Bell
  1806.         Laboratories,   which  also  runs  under  Unix  [3],  and,  more
  1807.         distantly, on AED-0 [1].  This version of LEX was based  on  the
  1808.         description  and suggestions of [4], although the implementation
  1809.         differs significantly in a number of ways.
  1810.  
  1811.  
  1812.  
  1813.         10.0  References
  1814.               __________
  1815.  
  1816.  
  1817.              1. Johnson,  W.L.,  et.   al.,  "Automatic  generation   of
  1818.                 efficient   lexical   analysers   using   finite   state
  1819.                 techniques", CACM Vol.  11, No.  12, pp.  805-813, 1968.
  1820.  
  1821.              2. Johnson, S.C., "Yacc -- Yet Another  Compiler-Compiler",
  1822.                 CSTR-32,  Bell  Telephone Laboratories, Murray Hill, New
  1823.                 Jersey, 1974.
  1824.  
  1825.              3. Lesk,  M.E.,  "Lex  -  a  lexical  analyser  generator",
  1826.                 CSTR-39,  Bell  Telephone Laboratories, Murray Hill, New
  1827.                 Jersey, 1975.
  1828.  
  1829.              4. Aho, A.V., Ullman, J.D., Principles of Compiler  Design,
  1830.                                          __________ __ ________  _______
  1831.                 Addison-Wesley, Don Mills, Ontario, 1977.
  1832.  
  1833.  
  1834.  
  1835.  
  1836.  
  1837.  
  1838.  
  1839.  
  1840.  
  1841.  
  1842.  
  1843.  
  1844.  
  1845.  
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.  
  1853.  
  1854.  
  1855.  
  1856.  
  1857.  
  1858.  
  1859.  
  1860.  
  1861.                                    APPENDIX A
  1862.  
  1863.                                LEX SOURCE GRAMMAR
  1864.  
  1865.  
  1866.  
  1867.         The following is a  grammar  of  LEX  programs  which  generally
  1868.         follows  Bacus-Naur  conventions.  In the rules, "||" stands for
  1869.         alternation (choose one  or  the  other).   Other  graphic  text
  1870.         stands  for  itself.   Several  grammar  elements  have  special
  1871.         meaning:
  1872.  
  1873.                 <anything>      Any text  not  including  the  following
  1874.                                 grammar  element  (either  a  literal or
  1875.                                 end-of-file).
  1876.  
  1877.                 <nothing>       Nothing  --  used  for   optional   rule
  1878.                                 elements.
  1879.  
  1880.                 <name>          A variable name.
  1881.  
  1882.                 <char_class>    A character class specifier.
  1883.  
  1884.                 <string>        A string (text inclosed in '"').
  1885.  
  1886.                 <EOF>           The end of the input file.
  1887.  
  1888.         This grammar was  abstracted  from  the  Yacc  grammar  used  to
  1889.         describe LEX.
  1890.  
  1891.                 program :==             aux_section trans_section
  1892.  
  1893.                 aux_section ::=         auxiliaries %%
  1894.                                 ||      %%
  1895.  
  1896.                 auxiliaries ::=         auxiliaries aux_def
  1897.                                 ||      aux_def
  1898.  
  1899.                 aux_def ::=             name_def = reg_exp ;
  1900.                                 ||      %{ <anything> %}
  1901.  
  1902.                 name_def ::=            <name>
  1903.  
  1904.                 reg_exp ::=             <char_class>
  1905.                                 ||      <string>
  1906.                                 ||      <name>
  1907.  
  1908.  
  1909.  
  1910.  
  1911.  
  1912.  
  1913.  
  1914.  
  1915.         A Lexical Analyser Generator                                    Page A-2
  1916.         LEX Source Grammar
  1917.  
  1918.  
  1919.                                 ||      reg_exp *
  1920.                                 ||      reg_exp | reg_exp
  1921.                                 ||      reg_exp  reg_exp
  1922.                                 ||      ( reg_exp )
  1923.  
  1924.                 trans_section ::=       translations
  1925.                                 ||      <nothing>
  1926.  
  1927.                 translations ::=        translations translation
  1928.                                 ||      translation
  1929.  
  1930.                 translation ::=         pattern action
  1931.                                 ||      %{ <anything> %}
  1932.                                 ||      %% <anything> <EOF>
  1933.  
  1934.                 pattern ::=             reg_exp / reg_exp
  1935.                                 ||      reg_exp
  1936.  
  1937.  
  1938.  
  1939.  
  1940.  
  1941.  
  1942.  
  1943.  
  1944.  
  1945.  
  1946.  
  1947.  
  1948.  
  1949.  
  1950.  
  1951.  
  1952.  
  1953.  
  1954.  
  1955.  
  1956.  
  1957.  
  1958.  
  1959.  
  1960.  
  1961.  
  1962.  
  1963.  
  1964.  
  1965.  
  1966.  
  1967.  
  1968.  
  1969.  
  1970.  
  1971.  
  1972.  
  1973.  
  1974.  
  1975.  
  1976.  
  1977.  
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984.  
  1985.  
  1986.  
  1987.  
  1988.  
  1989.  
  1990.  
  1991.  
  1992.  
  1993.                                    APPENDIX B
  1994.  
  1995.                               SOME SMALL EXAMPLES
  1996.  
  1997.  
  1998.  
  1999.  
  2000.  
  2001.         The following example illustrates  the  use  of  the  look-ahead
  2002.         operator, and various other of the nuances of using LEX.
  2003.  
  2004.  
  2005.  
  2006.         B.1  A Complete Command
  2007.              _ ________ _______
  2008.  
  2009.  
  2010.         The C programming language has had two different ways of writing
  2011.         its  assignment  operators.   The original method was to write a
  2012.         binary operator immediately following  the  ordinary  assignment
  2013.         operator, forming a compound operator.  Thus 'a =+ b' caused the
  2014.         value of 'a+b' to be assigned to 'a'.  Similarly,
  2015.  
  2016.                 =- =/ =% =* =<< =>> =| =& =^
  2017.  
  2018.         were written  for  the  assignment  operators  corresponding  to
  2019.         subtraction,  division,  modulus,  multiplication,  left  shift,
  2020.         right shift, logical OR, logical AND, and exclusive OR.  In  the
  2021.         current  version of the language, the binary operator is written
  2022.         to the left of the  assignment  operator,  to  remove  potential
  2023.         ambiguity.
  2024.  
  2025.         The LEX program "ctoc"  is  a  filter  which  converts  programs
  2026.         written  in  the  older style into programs written in the newer
  2027.         style.   It  uses  the  look-ahead  operator,  and  the  various
  2028.         dis-ambiguating rules to ensure that sequences like
  2029.  
  2030.                 a==-1           a=++b
  2031.  
  2032.         remain unchanged.
  2033.  
  2034.  
  2035.  
  2036.  
  2037.  
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043.  
  2044.  
  2045.  
  2046.  
  2047.         A Lexical Analyser Generator                                    Page B-2
  2048.         Some Small Examples
  2049.  
  2050.  
  2051.         /*
  2052.          * ctoc.lxi  --  Convert old C operators to new C form
  2053.          *
  2054.          * Adapted from example in C. Forsythe's LEX manual.
  2055.          *
  2056.          * NOTE:
  2057.          *      Forsythe's program put an entire comment into the token
  2058.          *      buffer. Either define a huge token buffer for my typical
  2059.          *      monster comments, or filter text within comments as if
  2060.          *      it were real C code. This is what I did. So =+ inside
  2061.          *      a comment will get changed to +=, etc.  Note tnat you
  2062.          *      may use the commen() function in LEXLIB if you want the
  2063.          *      comments eaten. I wanted 'em in the output.
  2064.          * by
  2065.          *      Bob Denny
  2066.          *      31-Feb-81
  2067.          */
  2068.         %{
  2069.         char tbuf[80];          /* Token buffer */
  2070.         main()
  2071.           {
  2072.           while (yylex())
  2073.             ;
  2074.           }
  2075.         %}
  2076.         any             = [\0-\177];
  2077.         nesc            = [^\\];
  2078.         nescquote       = [^\\"];
  2079.         nescapost       = [^\\'];
  2080.         schar           = "\\" any | nescquote;
  2081.         cchar           = "\\" any | nescapost;
  2082.         string          = '"' schar* '"';
  2083.         charcon         = "'" cchar* "'";
  2084.         %%
  2085.         "=" ( << | >> | "*" | + | - | "/" | "%" | "&" | "|" | "^" )
  2086.                         {
  2087.                         gettoken(tbuf, sizeof tbuf);
  2088.                         printf("%s=",tbuf+1);
  2089.                         }
  2090.         /*
  2091.          * The following will overflow the token buffer on any but a
  2092.          * small comment:
  2093.          */
  2094.         /*********
  2095.         "/*" ([^*] | "*"[^/])* "*/"
  2096.                 {
  2097.                         lexecho(stdout);
  2098.                 }
  2099.         **********/
  2100.         [<=>!]"=" | "="[<>]
  2101.                         {
  2102.                         lexecho(stdout);
  2103.                         }
  2104.         "=" / ( ++ | -- )
  2105.  
  2106.  
  2107.  
  2108.  
  2109.  
  2110.  
  2111.  
  2112.  
  2113.         A Lexical Analyser Generator                                    Page B-3
  2114.         Some Small Examples
  2115.  
  2116.  
  2117.                         {
  2118.                         lexecho(stdout);
  2119.                         }
  2120.         charcon
  2121.                         {
  2122.                         lexecho(stdout);
  2123.                         }
  2124.         string
  2125.                         {
  2126.                         lexecho(stdout);
  2127.                         }
  2128.         [\0-\377]
  2129.                         {
  2130.                         lexecho(stdout);
  2131.                         }
  2132.  
  2133.  
  2134.         Assuming the Decus compiler running on RSTS/E in RT11 mode,  the
  2135.         above program would be built and executed as follows:
  2136.  
  2137.                 mcr     lex -i ctoc.lxi -o ctoc.c
  2138.                 cc      ctoc/v
  2139.                 as      ctoc/d
  2140.                 link    ctoc=ctoc,c:lexlib,c:suport,c:clib/b:2000
  2141.  
  2142.                 mcr ctoc <old.c >new.c
  2143.  
  2144.  
  2145.  
  2146.  
  2147.         B.2  Interactive Lexical Analysis
  2148.              ___________ _______ ________
  2149.  
  2150.         The following program reads words from  the  terminal,  counting
  2151.         each  as they are entered.  The interaction with the operator is
  2152.         "natural" in the sense that processing for one line is  complete
  2153.         before  the  next  line is input.  To implement this program, it
  2154.         was necessary to include a special version  of  lexgetc()  which
  2155.         returns   <NULL>   if  the  current  line  has  been  completely
  2156.         transmitted to the parser.  Because the parser must  still  have
  2157.         some  look-ahead context, it will return the "end-of-line" token
  2158.         twice at  the  beginning  of  processing.   This  required  some
  2159.         _____
  2160.         additional tests in the main program.
  2161.  
  2162.         /*
  2163.          * Count words -- interactively
  2164.          */
  2165.         white   = [\n\t ];      /* End of a word        */
  2166.         eol     = [\0];         /* End of input line    */
  2167.         any     = [!-~];        /* All printing char's  */
  2168.         illegal = [\0-\377];    /* Skip over junk       */
  2169.         %{
  2170.         char            line[133];
  2171.         char            *linep          = &line;
  2172.         int             iseof           = 0;
  2173.  
  2174.  
  2175.  
  2176.  
  2177.  
  2178.  
  2179.         A Lexical Analyser Generator                                    Page B-4
  2180.         Some Small Examples
  2181.  
  2182.  
  2183.         int             wordct          = 0;
  2184.         #define T_EOL   1
  2185.         main()
  2186.         {
  2187.                 register int    i;
  2188.                 while ((i = yylex()) != 0) {
  2189.                         /*
  2190.                          * If the "end-of-line"  token  is
  2191.                          * returned  AND  we're  really at
  2192.                          * the end of  a  line,  read  the
  2193.                          * next line.  Note that T_EOL is
  2194.                          * returned twice when the program
  2195.                          * starts because of the nature of
  2196.                          * the look-ahead algorithms.
  2197.                          */
  2198.                         if (i == T_EOL && !is_eof
  2199.                                         && *linep == 0) {
  2200.                                 printf("* ");
  2201.                                 fflush(stdout);
  2202.                                 getline();
  2203.                         }
  2204.                 }
  2205.                 printf("%d words\n", wordct);
  2206.         }
  2207.         %}
  2208.         %%
  2209.         any(any)*       {
  2210.                                 /*
  2211.                                  * Write each  word  on  a
  2212.                                  * seperate output line.
  2213.                                  */
  2214.                                 lexecho(stdout);
  2215.                                 printf("\n");
  2216.                                 wordct++;
  2217.                                 return(LEXSKIP);
  2218.                         }
  2219.         eol             {
  2220.                                 return(T_EOL);
  2221.                         }
  2222.         white(white)*   {
  2223.                                 return(LEXSKIP);
  2224.                         }
  2225.         %%
  2226.         getline()
  2227.         /*
  2228.          * Read a line for lexgetc()
  2229.          */
  2230.         {
  2231.                 is_eof = (fgets(line, sizeof line, stdin)
  2232.                                 == NULL);
  2233.                 linep = &line;
  2234.         }
  2235.         lexgetc()
  2236.         /*
  2237.  
  2238.  
  2239.  
  2240.  
  2241.  
  2242.  
  2243.  
  2244.  
  2245.         A Lexical Analyser Generator                                    Page B-5
  2246.         Some Small Examples
  2247.  
  2248.  
  2249.          * Homemade  lexgetc  --  return zero while at the
  2250.          * end of an input line or EOF at end of file.  If
  2251.          * more on this line, return the next byte.
  2252.          */
  2253.         {
  2254.                 return(   (is_eof) ?            EOF
  2255.                         : (*linep == 0) ?       0
  2256.                         :                       *linep++);
  2257.         }
  2258. EOF
  2259.                         : (*linep == 0) ?       0
  2260.                         :                       *linep++);