Saturday, 15 October 2016

Actions

An action is a block of C code that is executed whenever the corresponding pattern in the lex specification is matched. Once the lex-generated lexical analyzer matches a regular expression specified in a rule in the specification, it looks to the right of the rule for the action to be performed. Actions typically involve operations such as a transformation of the matched string, returning a token to a parser, or compiling statistics on the input.

The simplest action contains no statements at all. Input text that matches the pattern associated with a null action is ignored. A sequence of characters that does not match any pattern in the rules section is written to the standard output without being modified in any way. To cause lex to generate a lexical analyzer that prints everything in the input text with the exception of the word ``orange'', which is ignored, the following rules section is used:
   %%
   orange  ;
Note that there must be some white space (spaces or tabs) between the pattern and the semicolon.
You may want to print out a message noting that a string of text was found, or a message transforming the text in some way. To recognize the expression ``Amelia Earhart'', the following rule can be used:
   "Amelia Earhart"   printf("found Amelia's bookcase!\n");
To replace a lengthy medical term with its acronym, a rule such as this is called for:
   Electroencephalogram    printf("EEG");
In order to count the lines in a text file, the analyzer must recognize end-of-lines and increment a counter. The following rule is used for this purpose:
   %{
   int lineno=0;
   %}
   %%
   \n   lineno++;


NOTE: If an action consists of two or more C statements spread over two or more lines, the code must be enclosed in curly braces, '{' and '}'.

No comments:

Post a Comment