Advertisement
LeeeeT

Untitled

Oct 3rd, 2024
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. %{
  2. #include <stdio.h>
  3. #include <ctype.h>
  4.  
  5. // Declare tokens
  6. #define IDENTIFIER 1
  7. #define INTEGER 2
  8. #define FLOAT 3
  9. #define KEYWORD 4
  10. #define OPERATOR 5
  11. #define PARENTHESIS 6
  12.  
  13. void yyerror(const char *msg);
  14. %}
  15.  
  16. %%
  17.  
  18. /* Keywords */
  19. "var"        { printf("KEYWORD: var\n"); return KEYWORD; }
  20. "if"         { printf("KEYWORD: if\n"); return KEYWORD; }
  21. "then"       { printf("KEYWORD: then\n"); return KEYWORD; }
  22. "else"       { printf("KEYWORD: else\n"); return KEYWORD; }
  23. "begin"      { printf("KEYWORD: begin\n"); return KEYWORD; }
  24. "end"        { printf("KEYWORD: end\n"); return KEYWORD; }
  25. "or"         { printf("KEYWORD: or\n"); return KEYWORD; }
  26. "and"        { printf("KEYWORD: and\n"); return KEYWORD; }
  27.  
  28. /* Identifiers */
  29. [a-zA-Z_][a-zA-Z0-9_]* { printf("IDENTIFIER: %s\n", yytext); return IDENTIFIER; }
  30.  
  31. /* Numbers */
  32. [0-9]+ { printf("INTEGER: %s\n", yytext); return INTEGER; }
  33. [0-9]+"."[0-9]+ { printf("FLOAT: %s\n", yytext); return FLOAT; }
  34.  
  35. /* Arithmetic operators */
  36. "+"|"-"|"*"|"/" { printf("OPERATOR: %s\n", yytext); return OPERATOR; }
  37.  
  38. /* Parentheses */
  39. "(" { printf("PARENTHESIS: %s\n", yytext); return PARENTHESIS; }
  40. ")" { printf("PARENTHESIS: %s\n", yytext); return PARENTHESIS; }
  41.  
  42. /* Ignore whitespace */
  43. [ \t\n]+      { /* ignore whitespace */ }
  44.  
  45. /* Error handling */
  46. .             { printf("Unknown character: %s\n", yytext); }
  47.  
  48. %%
  49.  
  50. int yywrap() {
  51.     return 1;
  52. }
  53.  
  54. void yyerror(const char *msg) {
  55.     fprintf(stderr, "%s\n", msg);
  56. }
  57.  
  58. int main() {
  59.     yylex();
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement