fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int COMMENT = 0; // Flag for multi-line comments
  6. %}
  7.  
  8. identifier [a-zA-Z_][a-zA-Z0-9_]*
  9. number [0-9]+
  10.  
  11. %%
  12.  
  13. #.* { printf("\n%s is a PREPROCESSOR DIRECTIVE", yytext); }
  14.  
  15. (int|float|char|double|while|for|struct|typedef|do|if|break|continue|void|switch|return|else|goto)
  16. { printf("\n%s is a KEYWORD", yytext); }
  17.  
  18. "/*" { COMMENT = 1; printf("\n%s is a COMMENT", yytext); }
  19. "*/" { COMMENT = 0; printf("\n%s ends COMMENT", yytext); }
  20.  
  21. {identifier}\( { if(!COMMENT) printf("\n%s FUNCTION", yytext); }
  22.  
  23. {identifier}(\[[0-9]*\])? { if(!COMMENT) printf("\n%s IDENTIFIER", yytext); }
  24.  
  25. \{ { if(!COMMENT) printf("\nBLOCK BEGINS"); }
  26. \} { if(!COMMENT) printf("\nBLOCK ENDS"); }
  27.  
  28. \; { if(!COMMENT) printf("\n%s PUNCTUATOR", yytext); }
  29.  
  30. \".*\" { if(!COMMENT) printf("\n%s STRING", yytext); }
  31.  
  32. {number} { if(!COMMENT) printf("\n%s NUMBER", yytext); }
  33.  
  34. = { if(!COMMENT) printf("\n%s ASSIGNMENT OPERATOR", yytext); }
  35.  
  36. "=="|"<="|">="|"<"|">" { if(!COMMENT) printf("\n%s RELATIONAL OPERATOR", yytext); }
  37.  
  38. "+"|"-"|"*"|"/" { if(!COMMENT) printf("\n%s ARITHMETIC OPERATOR", yytext); }
  39.  
  40. [ \t\n]+ { /* ignore whitespace */ }
  41.  
  42. . { /* ignore other characters */ }
  43.  
  44. %%
  45.  
  46. int main(int argc, char **argv) {
  47. FILE *file = fopen("var.c", "r"); // File to analyze
  48. if (!file) {
  49. printf("Could not open the file\n");
  50. exit(0);
  51. }
  52.  
  53. yyin = file; // Set input for lexer
  54. yylex(); // Start lexical analysis
  55. printf("\nLexical Analysis Complete.\n");
  56. return 0;
  57. }
  58.  
  59. int yywrap() {
  60. return 1;
  61. }
  62.  
Success #stdin #stdout #stderr 0.03s 6808KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/VTwlbK/prog:2:1: Syntax error: Operator expected
ERROR: /home/VTwlbK/prog:61:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit