home *** CD-ROM | disk | FTP | other *** search
/ Power Programming / powerprogramming1994.iso / progtool / turbopas / tutorpas.arc / TUTOR2.DOC < prev    next >
Text File  |  1988-07-30  |  33KB  |  900 lines

  1. OPA A
  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.                             LET'S BUILD A COMPILER!
  30.  
  31.                                        By
  32.  
  33.                             Jack W. Crenshaw, Ph.D.
  34.  
  35.                                   24 July 1988
  36.  
  37.  
  38.                           Part II: EXPRESSION PARSING
  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. PA A
  68.  
  69.  
  70.  
  71.  
  72.  
  73.        *****************************************************************
  74.        *                                                               *
  75.        *                        COPYRIGHT NOTICE                       *
  76.        *                                                               *
  77.        *   Copyright 1988 (C) Jack W. Crenshaw. All rights reserved.   *
  78.        *                                                               *
  79.        *****************************************************************
  80.  
  81.  
  82.        GETTING STARTED
  83.  
  84.        If you've read the introduction document to this series, you will
  85.        already know what  we're  about.    You will also have copied the
  86.        cradle software  into your Turbo Pascal system, and have compiled
  87.        it.  So you should be ready to go.
  88.  
  89.  
  90.        The purpose of this article is for us to learn  how  to parse and
  91.        translate mathematical expressions.  What we would like to see as
  92.        output is a series of assembler-language statements  that perform
  93.        the desired actions.    For purposes of definition, an expression
  94.        is the right-hand side of an equation, as in
  95.  
  96.                       x = 2*y + 3/(4*z)
  97.  
  98.        In the early going, I'll be taking things in _VERY_  small steps.
  99.        That's  so  that  the beginners among you won't get totally lost.
  100.        There are also  some  very  good  lessons to be learned early on,
  101.        that will serve us well later.  For the more experienced readers:
  102.        bear with me.  We'll get rolling soon enough.
  103.  
  104.        SINGLE DIGITS
  105.  
  106.        In keeping with the whole theme of this series (KISS, remember?),
  107.        let's start with the absolutely most simple case we can think of.
  108.        That, to me, is an expression consisting of a single digit.
  109.  
  110.        Before starting to code, make sure you have a  baseline  copy  of
  111.        the  "cradle" that I gave last time.  We'll be using it again for
  112.        other experiments.  Then add this code:
  113.  
  114.  
  115.        {---------------------------------------------------------------}
  116.        { Parse and Translate a Math Expression }
  117.  
  118.        procedure Expression;
  119.        begin
  120.           EmitLn('MOVE #' + GetNum + ',D0')
  121.        end;
  122.        {---------------------------------------------------------------}
  123.  
  124.  
  125.        And add the  line  "Expression;"  to  the main program so that it
  126.        reads:A*A*
  127.                                      - 2 -
  128. PA A
  129.  
  130.  
  131.  
  132.  
  133.  
  134.        {---------------------------------------------------------------}
  135.        begin
  136.           Init;
  137.           Expression;
  138.        end.
  139.        {---------------------------------------------------------------}
  140.  
  141.  
  142.        Now  run  the  program. Try any single-digit number as input. You
  143.        should get a single line of assembler-language output.    Now try
  144.        any  other character as input, and you'll  see  that  the  parser
  145.        properly reports an error.
  146.  
  147.  
  148.        CONGRATULATIONS! You have just written a working translator!
  149.  
  150.        OK, I grant you that it's pretty limited. But don't brush  it off
  151.        too  lightly.  This little "compiler" does,  on  a  very  limited
  152.        scale,  exactly  what  any larger compiler does:    it  correctly
  153.        recognizes legal  statements in the input "language" that we have
  154.        defined for it, and  it  produces  correct,  executable assembler
  155.        code,  suitable  for  assembling  into  object  format.  Just  as
  156.        importantly,  it correctly  recognizes  statements  that  are NOT
  157.        legal, and gives a  meaningful  error message.  Who could ask for
  158.        more?  As we expand our  parser,  we'd better make sure those two
  159.        characteristics always hold true.
  160.  
  161.        There  are  some  other  features  of  this  tiny  program  worth
  162.        mentioning.    First,  you  can  see that we don't separate  code
  163.        generation from parsing ...  as  soon as the parser knows what we
  164.        want  done, it generates the object code directly.    In  a  real
  165.        compiler, of course, the reads in GetChar would be  from  a  disk
  166.        file, and the writes to another  disk  file, but this way is much
  167.        easier to deal with while we're experimenting.
  168.  
  169.        Also note that an expression must leave a result somewhere.  I've
  170.        chosen the  68000  register  DO.    I  could have made some other
  171.        choices, but this one makes sense.
  172.  
  173.  
  174.        BINARY EXPRESSIONS
  175.  
  176.        Now that we have that under our belt,  let's  branch  out  a bit.
  177.        Admittedly, an "expression" consisting of only  one  character is
  178.        not going to meet our needs for long, so let's see what we can do
  179.        to extend it. Suppose we want to handle expressions of the form:
  180.  
  181.                                 1+2
  182.             or                  4-3
  183.             or, in general, <term> +/- <term>
  184.  
  185.        (That's a bit of Backus-Naur Form, or BNF.)ABAB
  186.                                      - 3 -A*A*
  187. PA A
  188.  
  189.  
  190.  
  191.  
  192.  
  193.        To do this we need a procedure that recognizes a term  and leaves
  194.        its   result   somewhere,  and  another   that   recognizes   and
  195.        distinguishes  between   a  '+'  and  a  '-'  and  generates  the
  196.        appropriate code.  But if Expression is going to leave its result
  197.        in DO, where should Term leave its result?    Answer:    the same
  198.        place.  We're  going  to  have  to  save the first result of Term
  199.        somewhere before we get the next one.
  200.  
  201.        OK, basically what we want to  do  is have procedure Term do what
  202.        Expression was doing before.  So just RENAME procedure Expression
  203.        as Term, and enter the following new version of Expression:
  204.  
  205.  
  206.        {---------------------------------------------------------------}
  207.        { Parse and Translate an Expression }
  208.  
  209.        procedure Expression;
  210.        begin
  211.           Term;
  212.           EmitLn('MOVE D0,D1');
  213.           case Look of
  214.            '+': Add;
  215.            '-': Subtract;
  216.           else Expected('Addop');
  217.           end;
  218.        end;
  219.        {--------------------------------------------------------------}
  220.  
  221.  
  222.        Next, just above Expression enter these two procedures:
  223.  
  224.  
  225.        {--------------------------------------------------------------}
  226.        { Recognize and Translate an Add }
  227.  
  228.        procedure Add;
  229.        begin
  230.           Match('+');
  231.           Term;
  232.           EmitLn('ADD D1,D0');
  233.        end;
  234.  
  235.  
  236.        {-------------------------------------------------------------}
  237.        { Recognize and Translate a Subtract }
  238.  
  239.        procedure Subtract;
  240.        begin
  241.           Match('-');
  242.           Term;
  243.           EmitLn('SUB D1,D0');
  244.        end;
  245.        {-------------------------------------------------------------}A6A6
  246.                                      - 4 -A*A*
  247. PA A
  248.  
  249.  
  250.  
  251.  
  252.  
  253.        When you're finished with that,  the order of the routines should
  254.        be:
  255.  
  256.         o Term (The OLD Expression)
  257.         o Add
  258.         o Subtract
  259.         o Expression
  260.  
  261.        Now run the program.  Try any combination you can think of of two
  262.        single digits,  separated  by  a  '+' or a '-'.  You should get a
  263.        series of four assembler-language instructions out  of  each run.
  264.        Now  try  some  expressions with deliberate errors in them.  Does
  265.        the parser catch the errors?
  266.  
  267.        Take  a  look  at the object  code  generated.    There  are  two
  268.        observations we can make.  First, the code generated is  NOT what
  269.        we would write ourselves.  The sequence
  270.  
  271.                MOVE #n,D0
  272.                MOVE D0,D1
  273.  
  274.        is inefficient.  If we were  writing  this code by hand, we would
  275.        probably just load the data directly to D1.
  276.  
  277.        There is a  message  here:  code  generated by our parser is less
  278.        efficient  than the code we would write by hand.  Get used to it.
  279.        That's going to be true throughout this series.  It's true of all
  280.        compilers to some extent.  Computer scientists have devoted whole
  281.        lifetimes to the issue of code optimization, and there are indeed
  282.        things that can be done to improve the quality  of  code  output.
  283.        Some compilers do quite well, but  there  is a heavy price to pay
  284.        in complexity, and it's  a  losing  battle  anyway ... there will
  285.        probably never come a time when  a  good  assembler-language pro-
  286.        grammer can't out-program a compiler.    Before  this  session is
  287.        over, I'll briefly mention some ways that we can do a  little op-
  288.        timization,  just  to  show you that we can indeed improve things
  289.        without too much trouble.  But remember, we're here to learn, not
  290.        to see how tight we can make  the  object  code.    For  now, and
  291.        really throughout  this  series  of  articles,  we'll  studiously
  292.        ignore optimization and  concentrate  on  getting  out  code that
  293.        works.
  294.  
  295.        Speaking of which: ours DOESN'T!  The code is _WRONG_!  As things
  296.        are working  now, the subtraction process subtracts D1 (which has
  297.        the FIRST argument in it) from D0 (which has the second).  That's
  298.        the wrong way, so we end up with the wrong  sign  for the result.
  299.        So let's fix up procedure Subtract with a  sign-changer,  so that
  300.        it readsA9A9
  301.  
  302.                                      - 5 -A*A*
  303. PA A
  304.  
  305.  
  306.  
  307.  
  308.  
  309.        {-------------------------------------------------------------}
  310.        { Recognize and Translate a Subtract }
  311.  
  312.        procedure Subtract;
  313.        begin
  314.           Match('-');
  315.           Term;
  316.           EmitLn('SUB D1,D0');
  317.           EmitLn('NEG D0');
  318.        end;
  319.        {-------------------------------------------------------------}
  320.  
  321.  
  322.        Now  our  code  is even less efficient, but at least it gives the
  323.        right answer!  Unfortunately, the  rules that give the meaning of
  324.        math expressions require that the terms in an expression come out
  325.        in an inconvenient  order  for  us.    Again, this is just one of
  326.        those facts of life you learn to live with.   This  one will come
  327.        back to haunt us when we get to division.
  328.  
  329.        OK,  at this point we have a parser that can recognize the sum or
  330.        difference of two digits.    Earlier,  we  could only recognize a
  331.        single digit.  But  real  expressions can have either form (or an
  332.        infinity of others).  For kicks, go back and run the program with
  333.        the single input line '1'.
  334.  
  335.        Didn't work, did it?   And  why  should  it?    We  just finished
  336.        telling  our  parser  that the only kinds of expressions that are
  337.        legal are those  with  two  terms.    We  must  rewrite procedure
  338.        Expression to be a lot more broadminded, and this is where things
  339.        start to take the shape of a real parser.
  340.  
  341.  
  342.        GENERAL EXPRESSIONS
  343.  
  344.        In the  REAL  world,  an  expression  can  consist of one or more
  345.        terms, separated  by  "addops"  ('+'  or  '-').   In BNF, this is
  346.        written
  347.  
  348.                  <expression> ::= <term> [<addop> <term>]*
  349.  
  350.  
  351.        We  can  accomodate  this definition of an  expression  with  the
  352.        addition of a simple loop to procedure Expression:AQAQ
  353.  
  354.                                      - 6 -A*A*
  355. PA A
  356.  
  357.  
  358.  
  359.  
  360.  
  361.        {---------------------------------------------------------------}
  362.        { Parse and Translate an Expression }
  363.  
  364.        procedure Expression;
  365.        begin
  366.           Term;
  367.           while Look in ['+', '-'] do begin
  368.              EmitLn('MOVE D0,D1');
  369.              case Look of
  370.               '+': Add;
  371.               '-': Subtract;
  372.              else Expected('Addop');
  373.              end;
  374.           end;
  375.        end;
  376.        {--------------------------------------------------------------}
  377.  
  378.  
  379.        NOW we're getting somewhere!   This version handles any number of
  380.        terms, and it only cost us two extra lines of code.  As we go on,
  381.        you'll discover that this is characteristic  of  top-down parsers
  382.        ... it only takes a few lines of code to accomodate extensions to
  383.        the  language.    That's  what  makes  our  incremental  approach
  384.        possible.  Notice, too, how well the code of procedure Expression
  385.        matches the BNF definition.   That, too, is characteristic of the
  386.        method.  As you get proficient in the approach, you'll  find that
  387.        you can turn BNF into parser code just about as  fast  as you can
  388.        type!
  389.  
  390.        OK, compile the new version of our parser, and give it a try.  As
  391.        usual,  verify  that  the  "compiler"   can   handle   any  legal
  392.        expression,  and  will  give a meaningful error  message  for  an
  393.        illegal one.  Neat, eh?  You might note that in our test version,
  394.        any error message comes  out  sort of buried in whatever code had
  395.        already been  generated. But remember, that's just because we are
  396.        using  the  CRT  as  our  "output  file"  for   this   series  of
  397.        experiments.  In a production version, the two  outputs  would be
  398.        separated ... one to the output file, and one to the screen.
  399.  
  400.  
  401.        USING THE STACK
  402.  
  403.        At  this  point  I'm going to  violate  my  rule  that  we  don't
  404.        introduce any complexity until  it's  absolutely  necessary, long
  405.        enough to point out a problem with the code we're generating.  As
  406.        things stand now, the parser  uses D0 for the "primary" register,
  407.        and D1 as  a place to store the partial sum.  That works fine for
  408.        now,  because  as  long as we deal with only the "addops" '+' and
  409.        '-', any new term can be added in as soon as it is found.  But in
  410.        general that isn't true.  Consider, for example, the expression
  411.  
  412.                       1+(2-(3+(4-5)))ABAB
  413.                                      - 7 -A*A*
  414. PA A
  415.  
  416.  
  417.  
  418.  
  419.  
  420.        If we put the '1' in D1, where  do  we  put  the  '2'?    Since a
  421.        general expression can have any degree of complexity, we're going
  422.        to run out of registers fast!
  423.  
  424.        Fortunately,  there's  a  simple  solution.    Like  every modern
  425.        microprocessor, the 68000 has a stack, which is the perfect place
  426.        to save a variable number of items. So instead of moving the term
  427.        in D0 to  D1, let's just push it onto the stack.  For the benefit
  428.        of  those unfamiliar with 68000 assembler  language,  a  push  is
  429.        written
  430.  
  431.                       -(SP)
  432.  
  433.        and a pop,     (SP)+ .
  434.  
  435.  
  436.        So let's change the EmitLn in Expression to read:
  437.  
  438.                       EmitLn('MOVE D0,-(SP)');
  439.  
  440.        and the two lines in Add and Subtract to
  441.  
  442.                       EmitLn('ADD (SP)+,D0')
  443.  
  444.        and            EmitLn('SUB (SP)+,D0'),
  445.  
  446.        respectively.  Now try the parser again and make sure  we haven't
  447.        broken it.
  448.  
  449.        Once again, the generated code is less efficient than before, but
  450.        it's a necessary step, as you'll see.
  451.  
  452.  
  453.        MULTIPLICATION AND DIVISION
  454.  
  455.        Now let's get down to some REALLY serious business.  As  you  all
  456.        know,  there  are  other  math   operators   than   "addops"  ...
  457.        expressions can also have  multiply  and  divide operations.  You
  458.        also  know  that  there  is  an implied operator  PRECEDENCE,  or
  459.        hierarchy, associated with expressions, so that in  an expression
  460.        like
  461.  
  462.                            2 + 3 * 4,
  463.  
  464.        we know that we're supposed to multiply FIRST, then  add.    (See
  465.        why we needed the stack?)
  466.  
  467.        In the early days of compiler technology, people used some rather
  468.        complex techniques to insure that the  operator  precedence rules
  469.        were  obeyed.    It turns out,  though,  that  none  of  this  is
  470.        necessary ... the rules can be accommodated quite  nicely  by our
  471.        top-down  parsing technique.  Up till now,  the  only  form  that
  472.        we've considered for a term is that of a  single  decimal  digit.A6A6
  473.                                      - 8 -A*A*
  474. PA A
  475.  
  476.  
  477.  
  478.  
  479.  
  480.        More generally, we  can  define  a  term as a PRODUCT of FACTORS;
  481.        i.e.,
  482.  
  483.                  <term> ::= <factor>  [ <mulop> <factor ]*
  484.  
  485.        What  is  a factor?  For now, it's what a term used to be  ...  a
  486.        single digit.
  487.  
  488.        Notice the symmetry: a  term  has the same form as an expression.
  489.        As a matter of fact, we can  add  to  our  parser  with  a little
  490.        judicious  copying and renaming.  But  to  avoid  confusion,  the
  491.        listing below is the complete set of parsing routines.  (Note the
  492.        way we handle the reversal of operands in Divide.)
  493.  
  494.  
  495.        {---------------------------------------------------------------}
  496.        { Parse and Translate a Math Factor }
  497.  
  498.        procedure Factor;
  499.        begin
  500.           EmitLn('MOVE #' + GetNum + ',D0')
  501.        end;
  502.  
  503.  
  504.        {--------------------------------------------------------------}
  505.        { Recognize and Translate a Multiply }
  506.  
  507.        procedure Multiply;
  508.        begin
  509.           Match('*');
  510.           Factor;
  511.           EmitLn('MULS (SP)+,D0');
  512.        end;
  513.  
  514.  
  515.        {-------------------------------------------------------------}
  516.        { Recognize and Translate a Divide }
  517.  
  518.        procedure Divide;
  519.        begin
  520.           Match('/');
  521.           Factor;
  522.           EmitLn('MOVE (SP)+,D1');
  523.           EmitLn('DIVS D1,D0');
  524.        end;AKAK
  525.  
  526.                                      - 9 -A*A*
  527. PA A
  528.  
  529.  
  530.  
  531.  
  532.  
  533.        {---------------------------------------------------------------}
  534.        { Parse and Translate a Math Term }
  535.  
  536.        procedure Term;
  537.        begin
  538.           Factor;
  539.           while Look in ['*', '/'] do begin
  540.              EmitLn('MOVE D0,-(SP)');
  541.              case Look of
  542.               '*': Multiply;
  543.               '/': Divide;
  544.              else Expected('Mulop');
  545.              end;
  546.           end;
  547.        end;
  548.  
  549.  
  550.        {--------------------------------------------------------------}
  551.        { Recognize and Translate an Add }
  552.  
  553.        procedure Add;
  554.        begin
  555.           Match('+');
  556.           Term;
  557.           EmitLn('ADD (SP)+,D0');
  558.        end;
  559.  
  560.  
  561.        {-------------------------------------------------------------}
  562.        { Recognize and Translate a Subtract }
  563.  
  564.        procedure Subtract;
  565.        begin
  566.           Match('-');
  567.           Term;
  568.           EmitLn('SUB (SP)+,D0');
  569.           EmitLn('NEG D0');
  570.        end;ANAN
  571.  
  572.  
  573.                                     - 10 -A*A*
  574. PA A
  575.  
  576.  
  577.  
  578.  
  579.  
  580.        {---------------------------------------------------------------}
  581.        { Parse and Translate an Expression }
  582.  
  583.        procedure Expression;
  584.        begin
  585.           Term;
  586.           while Look in ['+', '-'] do begin
  587.              EmitLn('MOVE D0,-(SP)');
  588.              case Look of
  589.               '+': Add;
  590.               '-': Subtract;
  591.              else Expected('Addop');
  592.              end;
  593.           end;
  594.        end;
  595.        {--------------------------------------------------------------}
  596.  
  597.  
  598.        Hot dog!  A NEARLY functional parser/translator, in only 55 lines
  599.        of Pascal!  The output is starting to look really useful,  if you
  600.        continue to overlook the inefficiency,  which  I  hope  you will.
  601.        Remember, we're not trying to produce tight code here.
  602.  
  603.  
  604.        PARENTHESES
  605.  
  606.        We  can  wrap  up this part of the parser with  the  addition  of
  607.        parentheses with  math expressions.  As you know, parentheses are
  608.        a  mechanism to force a desired operator  precedence.    So,  for
  609.        example, in the expression
  610.  
  611.                       2*(3+4) ,
  612.  
  613.        the parentheses force the addition  before  the  multiply.   Much
  614.        more importantly, though, parentheses  give  us  a  mechanism for
  615.        defining expressions of any degree of complexity, as in
  616.  
  617.                       (1+2)/((3+4)+(5-6))
  618.  
  619.        The  key  to  incorporating  parentheses  into our parser  is  to
  620.        realize that  no matter how complicated an expression enclosed by
  621.        parentheses may be,  to  the  rest  of  the world it looks like a
  622.        simple factor.  That is, one of the forms for a factor is:
  623.  
  624.                  <factor> ::= (<expression>)
  625.  
  626.        This is where the recursion comes in. An expression can contain a
  627.        factor which contains another expression which contains a factor,
  628.        etc., ad infinitum.
  629.  
  630.        Complicated or not, we can take care of this by adding just a few
  631.        lines of Pascal to procedure Factor:ABAB
  632.                                     - 11 -A*A*
  633. PA A
  634.  
  635.  
  636.  
  637.  
  638.  
  639.        {---------------------------------------------------------------}
  640.        { Parse and Translate a Math Factor }
  641.  
  642.        procedure Expression; Forward;
  643.  
  644.        procedure Factor;
  645.        begin
  646.           if Look = '(' then begin
  647.              Match('(');
  648.              Expression;
  649.              Match(')');
  650.              end
  651.           else
  652.              EmitLn('MOVE #' + GetNum + ',D0');
  653.        end;
  654.        {--------------------------------------------------------------}
  655.  
  656.  
  657.        Note again how easily we can extend the parser, and how  well the
  658.        Pascal code matches the BNF syntax.
  659.  
  660.        As usual, compile the new version and make sure that it correctly
  661.        parses  legal sentences, and flags illegal  ones  with  an  error
  662.        message.
  663.  
  664.  
  665.        UNARY MINUS
  666.  
  667.        At  this  point,  we have a parser that can handle just about any
  668.        expression, right?  OK, try this input sentence:
  669.  
  670.                                 -1
  671.  
  672.        WOOPS!  It doesn't work, does it?   Procedure  Expression expects
  673.        everything to start with an integer, so it coughs up  the leading
  674.        minus  sign.  You'll find that +3 won't  work  either,  nor  will
  675.        something like
  676.  
  677.                            -(3-2) .
  678.  
  679.        There  are  a  couple of ways to fix the problem.    The  easiest
  680.        (although not necessarily the best)  way is to stick an imaginary
  681.        leading zero in  front  of  expressions  of this type, so that -3
  682.        becomes 0-3.  We can easily patch this into our  existing version
  683.        of Expression:AKAK
  684.  
  685.                                     - 12 -A*A*
  686. PA A
  687.  
  688.  
  689.  
  690.  
  691.  
  692.        {---------------------------------------------------------------}
  693.        { Parse and Translate an Expression }
  694.  
  695.        procedure Expression;
  696.        begin
  697.           if IsAddop(Look) then
  698.              EmitLn('CLR D0')
  699.           else
  700.              Term;
  701.           while IsAddop(Look) do begin
  702.              EmitLn('MOVE D0,-(SP)');
  703.              case Look of
  704.               '+': Add;
  705.               '-': Subtract;
  706.              else Expected('Addop');
  707.              end;
  708.           end;
  709.        end;
  710.        {--------------------------------------------------------------}
  711.         
  712.  
  713.        I TOLD you that making changes  was  easy!   This time it cost us
  714.        only  three  new lines of Pascal.   Note  the  new  reference  to
  715.        function IsAddop.  Since the test for an addop appeared  twice, I
  716.        chose  to  embed  it in the new function.  The  form  of  IsAddop
  717.        should be apparent from that for IsAlpha.  Here it is:
  718.  
  719.  
  720.        {--------------------------------------------------------------}
  721.        { Recognize an Addop }
  722.  
  723.        function IsAddop(c: char): boolean;
  724.        begin
  725.           IsAddop := c in ['+', '-'];
  726.        end;
  727.        {--------------------------------------------------------------}
  728.  
  729.  
  730.        OK, make these changes to the program and recompile.   You should
  731.        also include IsAddop in your baseline copy of the cradle.   We'll
  732.        be needing  it  again  later.   Now try the input -1 again.  Wow!
  733.        The efficiency of the code is  pretty  poor ... six lines of code
  734.        just for loading a simple constant ... but at least it's correct.
  735.        Remember, we're not trying to replace Turbo Pascal here.
  736.  
  737.        At this point we're just about finished with the structure of our
  738.        expression parser.   This version of the program should correctly
  739.        parse and compile just about any expression you care to  throw at
  740.        it.    It's still limited in that  we  can  only  handle  factors
  741.        involving single decimal digits.    But I hope that by now you're
  742.        starting  to  get  the  message  that we can  accomodate  further
  743.        extensions  with  just  some  minor  changes to the parser.   You
  744.        probably won't be  surprised  to  hear  that a variable or even a
  745.        function call is just another kind of a factor.A*A*
  746.                                     - 13 -
  747. PA A
  748.  
  749.  
  750.  
  751.  
  752.  
  753.        In  the next session, I'll show you just how easy it is to extend
  754.        our parser to take care of  these  things too, and I'll also show
  755.        you just  how easily we can accomodate multicharacter numbers and
  756.        variable names.  So you see,  we're  not  far at all from a truly
  757.        useful parser.
  758.  
  759.  
  760.        A WORD ABOUT OPTIMIZATION
  761.  
  762.        Earlier in this session, I promised to give you some hints  as to
  763.        how we can improve the quality of the generated code.  As I said,
  764.        the  production of tight code is not the  main  purpose  of  this
  765.        series of articles.  But you need to at least know that we aren't
  766.        just  wasting our time here ... that we  can  indeed  modify  the
  767.        parser further to  make  it produce better code, without throwing
  768.        away everything we've done to date.  As usual, it turns  out that
  769.        SOME optimization is not that difficult to do ... it simply takes
  770.        some extra code in the parser.
  771.  
  772.        There are two basic approaches we can take:
  773.  
  774.          o Try to fix up the code after it's generated
  775.  
  776.            This is  the concept of "peephole" optimization.  The general
  777.            idea it that we  know  what  combinations of instructions the
  778.            compiler  is  going  to generate, and we also know which ones
  779.            are pretty bad (such as the code for -1, above).    So all we
  780.            do  is  to   scan   the  produced  code,  looking  for  those
  781.            combinations, and replacing  them  by better ones.  It's sort
  782.            of   a   macro   expansion,   in   reverse,   and   a  fairly
  783.            straightforward  exercise  in   pattern-matching.   The  only
  784.            complication,  really, is that there may be  a  LOT  of  such
  785.            combinations to look for.  It's called  peephole optimization
  786.            simply because it only looks at a small group of instructions
  787.            at a time.  Peephole  optimization can have a dramatic effect
  788.            on  the  quality  of the code,  with  little  change  to  the
  789.            structure of the compiler  itself.   There is a price to pay,
  790.            though,  in  both  the  speed,   size, and complexity of  the
  791.            compiler.  Looking for all those combinations calls for a lot
  792.            of IF tests, each one of which is a source of error.  And, of
  793.            course, it takes time.
  794.  
  795.             In  the  classical  implementation  of a peephole optimizer,
  796.            it's done as a second pass to the compiler.  The  output code
  797.            is  written  to  disk,  and  then  the  optimizer  reads  and
  798.            processes the disk file again.  As a matter of fact,  you can
  799.            see that the optimizer could  even be a separate PROGRAM from
  800.            the compiler proper.  Since the optimizer only  looks  at the
  801.            code through a  small  "window"  of  instructions  (hence the
  802.            name), a better implementation would be to simply buffer up a
  803.            few lines of output, and scan the buffer after each EmitLn.
  804.  
  805.          o Try to generate better code in the first placeA6A6
  806.                                     - 14 -A*A*
  807. PA A
  808.  
  809.  
  810.  
  811.  
  812.  
  813.            This approach calls for us to look for  special  cases BEFORE
  814.            we Emit them.  As a trivial example,  we  should  be  able to
  815.            identify a constant zero,  and  Emit a CLR instead of a load,
  816.            or even do nothing at all, as in an add of zero, for example.
  817.            Closer to home, if we had chosen to recognize the unary minus
  818.            in Factor  instead of in Expression, we could treat constants
  819.            like -1 as ordinary constants,  rather  then  generating them
  820.            from  positive  ones.   None of these things are difficult to
  821.            deal with ... they only add extra tests in the code, which is
  822.            why  I  haven't  included them in our program.  The way I see
  823.            it, once we get to the point that we have a working compiler,
  824.            generating useful code  that  executes, we can always go back
  825.            and tweak the thing to tighten up the code produced.   That's
  826.            why there are Release 2.0's in the world.
  827.  
  828.        There IS one more type  of  optimization  worth  mentioning, that
  829.        seems to promise pretty tight code without too much hassle.  It's
  830.        my "invention" in the  sense  that I haven't seen it suggested in
  831.        print anywhere, though I have  no  illusions  that  it's original
  832.        with me.
  833.  
  834.        This  is to avoid such a heavy use of the stack, by making better
  835.        use of the CPU registers.  Remember back when we were  doing only
  836.        addition  and  subtraction,  that we used registers  D0  and  D1,
  837.        rather than the stack?  It worked, because with  only  those  two
  838.        operations, the "stack" never needs more than two entries.
  839.  
  840.        Well,  the 68000 has eight data registers.  Why not use them as a
  841.        privately managed stack?  The key is to recognize  that,  at  any
  842.        point in its processing,  the  parser KNOWS how many items are on
  843.        the  stack, so it can indeed manage it properly.  We can define a
  844.        private "stack pointer" that keeps  track  of  which  stack level
  845.        we're at, and addresses the  corresponding  register.   Procedure
  846.        Factor,  for  example,  would  not  cause data to be loaded  into
  847.        register  D0,  but   into  whatever  the  current  "top-of-stack"
  848.        register happened to be.
  849.  
  850.        What we're doing in effect is to replace the CPU's RAM stack with
  851.        a  locally  managed  stack  made  up  of  registers.    For  most
  852.        expressions, the stack level  will  never  exceed eight, so we'll
  853.        get pretty good code out.  Of course, we also  have  to deal with
  854.        those  odd cases where the stack level  DOES  exceed  eight,  but
  855.        that's no problem  either.    We  simply let the stack spill over
  856.        into the CPU  stack.    For  levels  beyond eight, the code is no
  857.        worse  than  what  we're generating now, and for levels less than
  858.        eight, it's considerably better.
  859.  
  860.        For the record, I  have  implemented  this  concept, just to make
  861.        sure  it  works  before  I  mentioned  it to you.  It does.    In
  862.        practice, it turns out that you can't really use all eight levels
  863.        ... you need at least one register free to  reverse  the  operand
  864.        order for division  (sure  wish  the  68000 had an XTHL, like the
  865.        8080!).  For expressions  that  include  function calls, we wouldA6A6
  866.                                     - 15 -A*A*
  867. PA A
  868.  
  869.  
  870.  
  871.  
  872.  
  873.        also need a register reserved for them. Still, there  is  a  nice
  874.        improvement in code size for most expressions.
  875.  
  876.        So, you see, getting  better  code  isn't  that difficult, but it
  877.        does add complexity to the our translator ...  complexity  we can
  878.        do without at this point.  For that reason,  I  STRONGLY  suggest
  879.        that we continue to ignore efficiency issues for the rest of this
  880.        series,  secure  in  the knowledge that we can indeed improve the
  881.        code quality without throwing away what we've done.
  882.  
  883.        Next lesson, I'll show you how to deal with variables factors and
  884.        function calls.  I'll also show you just how easy it is to handle
  885.        multicharacter tokens and embedded white space.
  886.  
  887.        *****************************************************************
  888.        *                                                               *
  889.        *                        COPYRIGHT NOTICE                       *
  890.        *                                                               *
  891.        *   Copyright 1988 (C) Jack W. Crenshaw. All rights reserved.   *
  892.        *                                                               *
  893.        *****************************************************************AIAI
  894.  
  895.  
  896.  
  897.  
  898.  
  899.                                     - 16 -A*A*
  900. @