-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.y
89 lines (76 loc) · 1.52 KB
/
parse.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
** parse.y for in /home/jamie/myp
**
** Made by James Faure
** Login <james.faure@epitech.eu>
**
** Started on Tue May 9 03:37:36 2017 James Faure
** Last update Thu May 11 04:54:52 2017 James Faure
*/
%{
#include "ops.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int yylex(void);
void yyerror(char const *);
char *get_next_number(const int fd);
char *print_number(char *a);
%}
%define api.value.type union
%token <char *> NUM
%type <char *> exp
%left '-' '+'
%left '*' '/'
%%
input:
%empty
| input line
;
line:
'\n'
| exp '\n' { free(print_number($1)); }
| error '\n' { yyerrok; }
exp:
NUM { $$ = $1; }
| '+' exp { $$ = $2; }
| '-' exp { $$ = negate($2); }
| exp '+' exp { $$ = sum($1, $3); free($1); free($3); } // Is this safe ?
| exp '-' exp { $$ = sub($1, $3); free($1); free($3); }
| exp '*' exp { $$ = mul($1, $3); free($1); free($3); }
| exp '/' exp {
if (!num_strcmp($3, "0") && puts("div by zero"))
YYABORT;
$$ = div($1, $3); free($1); free($3);
}
| '(' exp ')' { $$ = $2; }
;
%%
void yyerror(char const *s)
{
fprintf(stderr, "%s\n", s);
}
#define MYPRINTF
//#define MYPRINTF printf
int yylex()
{
char c;
char *buf;
while ((c = getchar()) == ' ' || c == '\t');
if (c == '.' || isdigit(c))
{
ungetc(c, stdin);
scanf("%m[.0-9]", &buf);
yylval.NUM = buf;
MYPRINTF("got: %s\n", (char *) (yylval.NUM));
return (NUM);
}
if (c == EOF)
return (0);
MYPRINTF("returning: %c\n", c);
return (c);
}
int main()
{
yyparse();
}