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