fork download
  1. %option noyywrap
  2.  
  3. %{
  4. #include <stdio.h>
  5. void yyerror(char *s);
  6. %}
  7.  
  8. letter [a-zA-Z]
  9. digit [0-9]
  10. op [-+*/]
  11. punct [,.;"]
  12. %%
  13.  
  14. else|if|void|int {printf("%s is a keyword\n", yytext);}
  15. {digit}+ {printf("%s is a number\n", yytext);}
  16. {letter}({letter}|{digit})* {printf("%s is an identifier\n", yytext);}
  17. {op} {printf("%s is an operator\n", yytext);}
  18. [ ] ;
  19. \) {printf("%s is a close parenthesis\n", yytext);}
  20. {punct} {printf("%s is a punctuation\n", yytext);}
  21. . {yyerror("Invalid token");}
  22.  
  23. %%
  24.  
  25. void yyerror(char *s)
  26. {
  27. fprintf(stderr, "Error: %s at token '%s'\n", s, yytext);
  28. }
  29.  
  30. int main(int argc, char *argv[])
  31. {
  32. FILE *fp;
  33.  
  34. if (argc < 2) {
  35. fprintf(stderr, "Usage: %s <input file>\n", argv[0]);
  36. return 1;
  37. }
  38.  
  39. if ((fp = fopen(argv[1], "r")) == NULL) {
  40. perror("Error opening file");
  41. return 1;
  42. }
  43.  
  44. yyin = fp;
  45. yylex();
  46. fclose(fp);
  47. return 0;
  48. }
  49.  
Success #stdin #stdout #stderr 0.03s 6932KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/YePIBc/prog:4:5: Syntax error: Operator expected
ERROR: /home/YePIBc/prog:48:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit