-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo2-parse.y
79 lines (67 loc) · 984 Bytes
/
demo2-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
/* vim: set filetype=yacc: */
%define api.pure full
%locations
%name-prefix "demo2"
%param {yyscan_t yyscanner}
%code requires {
// break the cyclic dependency between scanner and parser headers
typedef void *yyscan_t;
}
%{
#include <stdio.h>
#include <string.h>
#include "demo2-lex.h"
%}
%code {
void yyerror(YYLTYPE *, yyscan_t, const char *msg);
}
%token NEWLINE
%token <c> CHAR
%type <s> chars
%type <s> line
%union
{
char c;
char *s;
}
%%
lines
: line
{
printf("line: %s\n", $1);
}
| lines line
{
printf("line: %s\n", $2);
}
;
line
: NEWLINE
{
$$ = strdup("");
}
| chars NEWLINE
;
chars
: CHAR
{
$$ = (char *)malloc(2);
$$[0] = $1;
$$[1] = '\0';
}
| chars CHAR
{
size_t len = strlen($1);
$$ = (char *)realloc($1, len + 2);
$$[len] = $2;
$$[len + 1] = '\0';
}
;
%%
void yyerror(YYLTYPE *unused1, yyscan_t unused2, const char *msg)
{
(void)unused1;
(void)unused2;
fprintf(stderr, "%s\n", msg);
abort();
}