Saturday, 15 October 2016

ECHO


The macro ECHO is a shorthand way of printing out the text of the token. The two rules in the next example have the same effect:
   Jim|James       { ECHO; }
   Jim|James       { printf("%s",yytext); }
The following lex specification draws together several of the points discussed previously.
  1 %{
  2 int subprogcount = 0;
  3 int gstringcount = 0;
  4 %}
  5 %%
  6 -[0-9]+                printf("negative integer\n");
  7 "+"?[0-9]+             printf("positive integer\n");
  8 -0\.[0-9]+             printf("negative real number, no whole number part\n");
  9 rail[ ]+road           printf("railroad is one word\n");
 10 crook                  printf("Here's a crook!\n");
 11 function               subprogcount++;
 12 G[a-zA-Z]*             {
 13                        printf("may have a G word here: %s\n ", yytext);
 14                        gstringcount++;
 15                        }
Explanation:

The first three rules (lines 6-8) recognize negative integers, positive integers, and negative real numbers between 0 and -1.
 The fourth rule (line 9) matches cases where one or more blanks intervene between the two syllables of the word ``railroad''.
 The fifth specification (line 10) matches the word ``crook'' and prints a useful warning. The rule recognizing ``function'' (line 11) increments a counter.
The last rule (lines 12-15) illustrates a multiline action, and the use of yytext.

No comments:

Post a Comment