[text] q4

Viewer

  1.  
  2. lex
  3. %{
  4. #include "y.tab.h"
  5. %}
  6.  
  7. %%
  8.  
  9. [ \t]          ; // Ignore whitespace
  10. [0-9]+         { yylval.num = atoi(yytext); return NUMBER; }
  11. [-+*/()^]      { return yytext[0]; }
  12. \n             { return EOL; }
  13. .              { yyerror("Invalid character"); }
  14.  
  15. %%
  16.  
  17. int yywrap() {
  18.     return 1;
  19. }
  20.  
  21.  
  22. yacc
  23.  
  24. %{
  25. #include <stdio.h>
  26. %}
  27.  
  28. %token NUMBER
  29. %left '+' '-'
  30. %left '*' '/'
  31. %left '^'
  32.  
  33. %%
  34.  
  35. input: /* empty */
  36.      | input line
  37.      ;
  38.  
  39. line: expr EOL { printf("Result: %d\n", $1); }
  40.     ;
  41.  
  42. expr: NUMBER { $$ = $1; }
  43.     | expr '+' expr { $$ = $1 + $3; }
  44.     | expr '-' expr { $$ = $1 - $3; }
  45.     | expr '*' expr { $$ = $1 * $3; }
  46.     | expr '/' expr { $$ = $1 / $3; }
  47.     | expr '^' expr { $$ = 1; for(int i=0; i<$3; i++) $$ *= $1; }
  48.     | '(' expr ')' { $$ = $2; }
  49.     ;
  50.  
  51. %%
  52.  
  53. int main() {
  54.     yyparse();
  55.     return 0;
  56. }
  57.  
  58. void yyerror(const char *s) {
  59.     printf("Error: %s\n", s);
  60. }
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69. 4y.y:16.12-14: error: symbol ‘EOL’ is used, but is not defined as a token and has no rules
  70.    16 | line: expr EOL { printf("Result: %d\n", $1); }
  71.  
  72.  

Editor

You can edit this paste and save as new:


File Description
  • q4
  • Paste Code
  • 28 Mar-2024
  • 1.08 Kb
You can Share it: