Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209207
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: 系统运维

2011-05-04 09:15:10

This section describes the implementation of hoc1, a program that provides about the same capabilities as a minimal pocket  calculator, and is substantially less portable.

Grammars
Even since Backus-Naur Form was developed for Algol, languages have been described by formal grammars. The grammar for hoc1 is small and simple in its abstract representation:
  1. list: expr \n
  2.       list expr \n
  3. expr: NUMBER
  4.       expr + expr
  5.       expr - expr
  6.       expr * expr
  7.       expr / expr
  8.       ( expr )
 In other words, a list is a sequence of expressions, each followed by a newline. An expression is a number, or a pair of expressions joined by an operator, or a parenthesized expression.

Overview of yacc
yacc is a parser generator, that is, a program for converting a grammatical specification of a language like the one above into a parser that will parse statement in the language. yacc provides a way to associate meanings with the components of the grammar in such a way that as the parsing takes place, the meaning can be "evaluated" as well. The stages in using yacc are the following.
  • First, a grammar is written, like the one above, but more precise. This specifies the syntax of the language. yacc can be used at this stage to warn of errors and ambiguities in the grammar.
  • Second, each rule or production of the grammar can be augmented with an action---a statement of what to do when an instance of that grammatical form is found in a program being parsed. The "What to do" part is written in C, with conventions for connecting the grammar to the C code. This defines the semantics of the language.
  • Third, a lexical analyzer is needed, which will read the input being parsed and break it up into meaningful chunks for the parser. A NUMBER is an example of a lexical chunk that is several characters long; sigle-character operators like + and * are also chunks. A luxical chunk is traditionally called a token.
  • Finally, a controlling routine is needed, to call the parser that yacc built.
yacc processes the grammar and the semantic actions into a parsing function, named yyparse, and writes it out as a file of C code. If yacc finds no errors, the parser, the lexical analyzer, and the control routine can be compiled, perhaps linked with other C routines, and executed. The operation of this program is to call repeatedly upon the lexical analyzer for tokens, recognize the grammatical (syntactic) structure in the input, and perform the semantic actions as each grammatical rule is recognized. The entry to the lexical analyzer must be named yylex, since that is the function that yyparse calls each time it wants another token. (All names used by yacc start with y.)
To be somewhat more precise, the input to yacc takes this form:
  1. %{
  2. C statements like #include, declarations, etc. This section is optional.
  3. %}
  4. yacc declarations: lexical tokens, grammar variables, precedence and associativity information
  5. %%
  6. grammar rules and actions
  7. %%
  8. more C statements (optional):
  9. main() {...; yyparse(); ...}
  10. yylex() {...}
  11. ...
This is processed by yacc and the result written into a file called y.tab.c, whose layout is like this:
  1. C statements from between %{ and %}, if any C statements from after second %%, if any:
  2. main() {...; yyparse(); ...}
  3. yylex() {...}
  4. ...
  5. yyparse() {parser, which calls yylex() }
It is typical of the UNIX approach that yacc produces C instead of a compiled object (.o) file. This is the most flexible arrangement---the generated code is portable and amenable to other processing whenever someone has a good idea.
yacc itself is a powerful tool. yacc-generated parsers are small, efficient, and correct; many nasty parsing problems are taken care of automatically. Language-recognizing programs are easy to build, and can be modified repeatedly as the language definition evolves.

Stage 1 program
The source code for hoc1 consists of a grammar with actions, a lexical routine yylex, and a main, all in one file hoc.y.
  1. %{
  2. #define YYSTYPE double /* data type of yacc stack */
  3.     %}
  4.     %token NUMBER
  5.     %left '+' '-' /* left associative, same precedence */
  6.     %left '*' '/' /* left assoc., higher precedence */
  7.     %%
  8.     list: /* nothing */
  9.         | list '\n'
  10.         | list expr '\n' {printf("\t%.8g\n", $2);}
  11.         ;
  12.     expr: NUMBER {$$ = $1; }
  13.         | expr '+' expr {$$ = $1 + $3;}
  14.         | expr '-' expr {$$ = $1 - $3;}
  15.         | expr '*' expr {$$ = $1 * $3;}
  16.         | expr '/' expr {$$ = $1 / $3;}
  17.         | '(' expr ')' { $$ = $2;}
  18.         ;
  19.     %%
  20.     /* end of grammar */

  21. #include <stdio.h>
  22. #include <ctype.h>
  23. char *progname; /* for error messages */
  24. int lineno = 1;

  25. main(int argc, char* argv[])
  26. {
  27.     progname = argv[0];
  28.     yyparse();
  29. }

  30. yylex()
  31. {
  32.     int c;
  33.     while ((c=getchar()) == ' ' || c == '\t')
  34.      ;
  35.     if (c == EOF)
  36.      return 0;
  37.     if (c == '.' || isdigit(c))
  38.     {
  39.         ungetc(c, stdin);
  40.         scanf("%lf", &yylval);
  41.         return NUMBER;
  42.     }
  43.     if (c == '\n')
  44.      lineno++;
  45.     return c;
  46. }

  47. yyerror(char *s)
  48. {
  49.     warning (s, (char *)0);
  50. }

  51. warning (char *s, char *t)
  52. {
  53.     fprintf(stderr, "%s: %s", progname, s);
  54.     if (t)
  55.      fprintf(stderr, "%s", t);
  56.     fprintf(stderr, " near line %d\n", lineno);
  57. }
Compilation of a yacc program is a two-step process:
  1. $ yacc hoc.y
  2. $ cc y.tab.c -o hoc1
  3. $./hoc1
  4. 2/3
  5.           0.6666667
  6. -3-4
  7. hoc1: syntax error near line 1
  8. $
A digression on make
The program make reads a specification of how the components of a program depend on each other, and how to process them to create an up-to-date version of the program. It checks the times at which the various components were last modified, figures out the minimum amount of recompilation that has to be done to make a consistent new version ,then runs the processes. make also understands the intricacies of multi-step processes like yacc, so these tasks can be put into a make specification without spelling out the individual steps.
make is most useful when the program being created is large enough to be spread over several source files, but it's handy even for something as small as hoc1.
  1. $ cat makefile
  2. hoc1: hoc.o
  3.        cc hoc.o -o hoc1
  4. $
阅读(480) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~