Difference between revisions of "The Flex Lexical Analyzer/Exercise 2 - Printing the number of times access operators are used"

From Wiki**3

< The Flex Lexical Analyzer
(The Solution)
 
(5 intermediate revisions by the same user not shown)
Line 5: Line 5:
 
== The Solution ==
 
== The Solution ==
  
<text>
+
[EXPLANATION COMING SOON]
 +
 
 +
<source lang="text">
 
%option 8bit noyywrap yylineno stack
 
%option 8bit noyywrap yylineno stack
 
%{
 
%{
Line 30: Line 32:
  
 
"/*"            yy_push_state(X_COMMENT);
 
"/*"            yy_push_state(X_COMMENT);
<X_COMMENT>"/*" yy_push_state(X_COMMENT);
 
 
<X_COMMENT>"*/" yy_pop_state();
 
<X_COMMENT>"*/" yy_pop_state();
 
<X_COMMENT>.|\n ;
 
<X_COMMENT>.|\n ;
Line 36: Line 37:
 
"//".*$        ;
 
"//".*$        ;
  
[[:digit:]]"."|"."[[:digit:]]  ;
+
[[:digit:]]"."[[:digit:]]|"."[[:digit:]]  ;
  
 
"."|"->"        count++;
 
"."|"->"        count++;
Line 48: Line 49:
 
   return 0;
 
   return 0;
 
}
 
}
</text>
+
</source>
  
[[category:Compilers]]
+
[[category:Compiladores|Flex Lexical Analyzer]]
[[category:Teaching]]
+
[[category:Ensino]]

Latest revision as of 16:39, 24 March 2021

The Problem (in Portuguese)

Em C++, os operadores . e -> são utilizados para aceder a métodos e variáveis de instância. Com o objectivo de analisar o estilo de programação, crie um analisador lexical (para a ferramenta Flex) que aceite um programa em C++ e que tenha como única saída o número de ocorrências de cada um destes operadores. Note que nem todas as ocorrências das sequências . e -> correspondem a operadores.

The Solution

[EXPLANATION COMING SOON]

%option 8bit noyywrap yylineno stack
%{
#include <iostream>
int count = 0;
inline void yyerror(const char *msg) {
  std::cerr << "Error at " << yylineno << ": " << msg << std::endl;
}
%}
%x X_STRING X_COMMENT X_CHAR
%%

\'              yy_push_state(X_CHAR);
<X_CHAR>\\\'    ;
<X_CHAR>\'      yy_pop_state();
<X_CHAR>.       ;
<X_CHAR>\n      yyerror("newline in char");

\"              yy_push_state(X_STRING);
<X_STRING>\\\"  ;
<X_STRING>\"    yy_pop_state();
<X_STRING>.     ;
<X_STRING>\n    yyerror("newline in string");

"/*"            yy_push_state(X_COMMENT);
<X_COMMENT>"*/" yy_pop_state();
<X_COMMENT>.|\n ;

"//".*$         ;

[[:digit:]]"."[[:digit:]]|"."[[:digit:]]   ;

"."|"->"        count++;

.|\n            ; /* ignore the rest */

%%
int main() {
  yylex();
  std::cout << count << std::endl;
  return 0;
}