Menu

qtFlexC++_4

Laurent ROUDIER

Go to the first, previous, next, last section, table of contents.

First some simple examples to get the flavor of how one uses qtFlexC++. The following qtFlexC++ input specifies a scanner which whenever it encounters the string "username" will replace it with the user's login name:

%2{ QString getLogin();%}

%%
username    yyout<<getLogin();
%%
QString test1::getLogin()
{
    return "login";
}

By default, any text not matched by a qtFlexC++ scanner is copied to the output, so the net effect of this scanner is to copy its input file to its output with each occurrence of "username" expanded. In this input, there is just one rule. "username" is the <VAR>pattern</VAR> and the "yyout<<" is the <VAR>action</VAR>. The "%%" marks the beginning of the rules.

Here's another simple example:

%1{ int num_lines;%}
%1{ int num_chars;%}
%6{ num_lines= 0;%}
%6{ num_chars= 0;%}
%%
\n      ++num_lines; ++num_chars;
.       ++num_chars;

This scanner counts the number of characters and the number of lines in its input (it produces no output other than the final report on the counts). The first line declares two variables in the lexer class, "num_lines" and "num_chars" in the header file (public part), which are accessible both inside yylex()' and in themain()'. the two next lines intialize the variable in the constructor.

There are two rules, one which matches a newline ("\n") and increments both the line count and the character count, and one which matches any character other than a newline (indicated by the "." regular expression).

A somewhat more complicated example:

/* scanner for a toy Pascal-like language */

DIGIT    [0-9]
ID       [a-z][a-z0-9]*

%%

{DIGIT}+    {
            yyout<<"An integer: "<< yytext <<"\n";
            }

{DIGIT}+"."{DIGIT}*        {
            yyout<<"A float: "<< yytext <<"\n";
            }

if|then|begin|end|procedure|function        {
            yyout<<"A keyword: "<< yytext <<"\n";
            }

{ID}        yyout<<"An identifier: "<< yytext <<"\n";

"+"|"-"|"*"|"/"   yyout<<"An operator: "<< yytext <<"\n";

"{"[^}\n]*"}"     /* eat up one-line comments */

[ \t\n]+          /* eat up whitespace */

.           yyout<<"Unrecognized character: "<< yytext <<"\n";

This is the beginnings of a simple scanner for a language like Pascal. It identifies different types of <VAR>tokens</VAR> and reports on what it has seen.

The details of this example will be explained in the following sections.

Go to the first, previous, next, last section, table of contents.


Related

Wiki: Home
Wiki: qtFlexC++_1
Wiki: qtFlexC++_3
Wiki: qtFlexC++_5

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.