Difference between revisions of "The Flex Lexical Analyzer/Exercise 3 - Printing the comments present in a C/C++ program"

From Wiki**3

< The Flex Lexical Analyzer
(The Solution)
 
Line 7: Line 7:
 
[EXPLANATION COMING SOON]
 
[EXPLANATION COMING SOON]
  
<text>
+
<source lang="text">
 
%option 8bit noyywrap yylineno stack
 
%option 8bit noyywrap yylineno stack
 
%{
 
%{
Line 43: Line 43:
 
   return yylex();
 
   return yylex();
 
}
 
}
</text>
+
</source>
  
 
[[category:Compiladores|Flex Lexical Analyzer]]
 
[[category:Compiladores|Flex Lexical Analyzer]]
 
[[category:Ensino]]
 
[[category:Ensino]]

Latest revision as of 13:41, 4 March 2019

The Problem (in Portuguese)

Com o objectivo de gerar documentação, crie um analisador lexical (para a ferramenta Flex) que aceite um programa em C++ e que tenha como saída apenas os comentários existentes no programa, assim como o respectivo número de linha de início. Note que nem todas as ocorrências das sequências "/*" e "//" correspondem a inícios de comentários. Assuma que as sequências iniciadas por "/*" podem ser aninhadas.

The Solution

[EXPLANATION COMING SOON]

%option 8bit noyywrap yylineno stack
%{
#include <iostream>
inline void yyerror(const char *msg) {
  std::cerr << "Error at " << yylineno << ": " << msg << std::endl;
}
%}
%x X_CHAR X_STRING X_COMMENT
%%
 
\'              yy_push_state(X_CHAR);
<X_CHAR>\\\'  ;
<X_CHAR>\'     yy_pop_state();
<X_CHAR>.  ;
<X_CHAR>\n    yyerror("newline in character constant");

\"              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); std::cout << std::endl << yylineno << ": "; ECHO;
<X_COMMENT>"/*" yy_push_state(X_COMMENT);
<X_COMMENT>"*/" yy_pop_state();
<X_COMMENT>.|\n ECHO;

"//".*$         std::cout << yylineno << ": "; ECHO;

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

%%
int main() {
  return yylex();
}