Guest User

threeadd.y

a guest
Jun 5th, 2020
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. %{
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. int yylex(void);
  7. int t_count = 1;
  8.  
  9. void yyerror(char *s)
  10. {
  11. fprintf(stderr,"%s\n",s);
  12. return;
  13. }
  14.  
  15. char * generateToken(int i)
  16. {
  17.  
  18. char* ch=(char*)malloc(sizeof(char)*5);
  19.  
  20. sprintf(ch,"t%d",i++);
  21.  
  22. return ch;
  23. }
  24.  
  25. %}
  26.  
  27. %union { double dval; char ivar[50]; }
  28. %token <ivar> DOUBLE
  29. %token <ivar> NAME
  30. %token <ivar> DIGITS
  31. %type <ivar> expr
  32. %type <ivar> term
  33. %left "+" "-"
  34. %left "*" "/"
  35. %left "(" ")"
  36. %%
  37. program:
  38. line program {
  39. }
  40. | line {
  41. }
  42. ;
  43. line:
  44. expr "\n" {
  45. t_count =1;
  46. }
  47. | NAME "=" expr "\n" {
  48.  
  49. printf("%s = %s", $3,$1);
  50. t_count=1;
  51. }
  52. ;
  53. expr:
  54. expr "+" expr {
  55.  
  56.  
  57. char * x=generateToken(t_count);
  58.  
  59. printf("%s = %s + %s",x,$1,$3);
  60. strcpy($$,x);
  61. }
  62. | expr "-" expr {
  63.  
  64.  
  65. strcpy($$,generateToken(t_count));
  66. printf("%s = %s - %s",$$,$1,$3);
  67.  
  68.  
  69. }
  70.  
  71. | expr "*" expr {
  72.  
  73. strcpy($$,generateToken(t_count));
  74. printf("%s = %s * %s",$$,$1,$3);
  75.  
  76. }
  77. | expr "/" expr {
  78.  
  79. strcpy($$,generateToken(t_count));
  80. printf("%s = %s / %s",$$,$1,$3);
  81.  
  82. }
  83. | term {
  84. strcpy($$, $1);
  85. }
  86. | "(" expr ")" {
  87.  
  88. strcpy($$,generateToken(t_count));
  89. printf("%s =( %s )" ,$$,$2);
  90.  
  91. }
  92. ;
  93. term:
  94.  
  95. NAME {
  96.  
  97. strcpy($$, $1);
  98. }
  99. | DIGITS {
  100. strcpy($$, $1);
  101.  
  102. }
  103. ;
  104. %%
  105.  
  106. int main(void)
  107. {
  108.  
  109. yyparse();
  110.  
  111. return 0;
  112. }
Add Comment
Please, Sign In to add comment