The following example illustrates the use of
input() and
unput(). The subroutine
skipcmnts() is used to ignore comments in a language like C, where comments occur between `/
' and `
/' :
There are three other things to note in this example. First, the
unput() function (which puts back the last character read) is necessary to avoid missing the final ``
//'' if the comment ends with a
/. In this case, having read an ``
'', the analyzer finds that the next character is not the terminal `
/' and must read some more. Second, the expression
yytext[
yyleng-1] refers to the last character read. Third, this routine assumes that the comments are not nested, as is indeed the case with the C language. If, unlike in C, they are nested in the source text, after reading the first
/ ending the inner group of comments, the lexical analyzer reads the rest of the comments as if they were part of the input to be searched for patterns.
To handle special I/O needs, such as writing to several files, standard I/O routines in C can be used to rewrite the functions input(), unput(), and output(). These and other programmer-defined functions should be placed in the subroutine section. The new routines will then replace the standard ones. lex's input() is equivalent to getchar(), and output() is equivalent to putchar().
No comments:
Post a Comment