fork download
  1. %{
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. // Define token types for printing
  6. void print_token(const char* type, const char* lexeme) {
  7. printf("Token: %-12s Lexeme: %s\n", type, lexeme);
  8. }
  9. %}
  10.  
  11. // Define keywords
  12. KEYWORD (if|else|while|for|return|int|float|char|double|void)
  13.  
  14. // Define identifier: starts with letter or _, followed by letters, digits, or _
  15. ID [a-zA-Z_][a-zA-Z0-9_]*
  16.  
  17. // Define number (integer only here)
  18. NUMBER [0-9]+
  19.  
  20. // Operators (including multi-char)
  21. OPERATOR (\+\+|--|==|!=|<=|>=|&&|\|\||[+\-*/%=<>!&|])
  22.  
  23. // Separators
  24. SEPARATOR [\(\)\{\}\[\];,\.]
  25.  
  26. // Ignore whitespace (spaces, tabs, newlines)
  27. WHITESPACE [ \t\n\r]+
  28.  
  29. %%
  30.  
  31. {WHITESPACE} ; // Ignore whitespace characters
  32.  
  33. {KEYWORD} { print_token("Keyword", yytext); }
  34. {ID} { print_token("Identifier", yytext); }
  35. {NUMBER} { print_token("Number", yytext); }
  36. {OPERATOR} { print_token("Operator", yytext); }
  37. {SEPARATOR} { print_token("Separator", yytext); }
  38.  
  39. . { printf("Unknown character: %s\n", yytext); }
  40.  
  41. %%
  42.  
  43. int main(int argc, char **argv)
  44. {
  45. if (argc > 1) {
  46. FILE *file = fopen(argv[1], "r");
  47. if (!file) {
  48. perror("Cannot open file");
  49. return 1;
  50. }
  51. yyin = file;
  52. }
  53. yylex();
  54. return 0;
  55. }
  56.  
Success #stdin #stdout #stderr 0.03s 6776KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/MrZWHm/prog:55:1: Syntax error: end_of_file_in_quasi_quotation
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit