aboutsummaryrefslogtreecommitdiff
path: root/store/works/life/compile-principle-experiment/1/hoc.y
blob: c4452ad71d0009a568729453f6bc73f10c0866ba (plain)
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
%{
#define  YYSTYPE  double   /* data type of yacc stack */
#include <stdio.h>
#include <ctype.h>
#include <math.h>

int yylex();
int yyerror(const char * s);
%}
%token  NUMBER
%left  '+' '-'    /* left associative, same precedence */
%left  '*' '/' '%'   /* left assoc., higher precedence */
%left	UNARYMINUS
%%
list:    /* nothing */
  | list '\n'
  | list expr '\n'    { printf("%lf\n", $2); }
  ;
expr:    NUMBER  { $$ = $1; }
  | expr '+' expr  { $$ = $1 + $3; }
  | expr '-' expr  { $$ = $1 - $3; }
  | expr '*' expr  { $$ = $1 * $3; }
  | expr '/' expr  { $$ = $1 / $3; }
  | expr '%' expr  { $$ = fmod($1, $3); }
	| '-' expr  %prec UNARYMINUS { $$ = -$2; }
  | '(' expr ')'  { $$ = $2; }
  ;
%%
  
int lineno = 1;

int main(int argc, char** argv)
{
  yyparse();
  return 0;
}

int yylex()
{
  int c;

  do {
    c = getchar();
  } while (c == ' ' || c == '\t');

  if (c == EOF)
    return 0;

  if (c == '.' || isdigit(c)) {
    ungetc(c, stdin);
    scanf("%lf", &yylval);
    return NUMBER;
  }

  if (c == '\n')
    lineno++;

  return c;
}

int yyerror(const char* s)
{
  fprintf(stderr, "Error occured near line %d\n", lineno);
  return 0;
}