-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.rl
More file actions
139 lines (123 loc) · 2.43 KB
/
lexer.rl
File metadata and controls
139 lines (123 loc) · 2.43 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include<stdio.h>
#include<stddef.h>
#include<stdlib.h>
#include "parser.h"
#include "ast.h"
#include <unistd.h>
#include <string.h>
#define LIST 1000
void *ParseAlloc( void*(*malloc)(size_t) );
void ParseFree(void *pParser, void(*free)(void*) );
void Parse(void *pParser, int tokenCode, void* token);
void ParseTrace(FILE *stream, char *zPrefix);
void* lparser;
%%{
machine calc;
action ident_tok {
Node *n=malloc(sizeof(Node));
n->name=malloc(te-ts+1);
n->type=IDENT;
strncpy(n->name,ts,te-ts);
n->name[te-ts]='\0';
n->a=0;
n->b=0;
Parse(lparser,IDENT,n);
}
action semi_tok {
//Terminate this calculation.
Parse(lparser, SEMI, 0);
}
action plus_tok {
Parse(lparser, PLUS, 0);
}
action minus_tok {
Parse(lparser, MINUS, 0);
}
action times_tok {
Parse(lparser, TIMES, 0);
}
action divide_tok {
Node *n=malloc(sizeof(Node));
n->type=DIVIDE;
Parse(lparser, DIVIDE, n);
}
action openp_tok {
Parse(lparser, OPENP, 0);
}
action closep_tok {
Parse(lparser, CLOSEP, 0);
}
action EOF{
Parse(lparser,0,0);
ParseFree(lparser, free );
}
action number_tok{
Node *n=malloc(sizeof(Node));
n->name=malloc(te-ts+1);
n->type=DOUBLE;
strncpy(n->name,ts,te-ts);
n->name[te-ts]='\0';
Parse(lparser, DOUBLE, n);
}
action equa_tok{
Parse(lparser, EQUA,0);
}
number = [0-9]+('.'[0-9]+)?;
plus = '+';
minus = '-';
openp = '(';
closep = ')';
times = '*';
divide = '/';
equal = '=';
semi = ';';
ident = [A-Za-z_]+;
main := |*
number => number_tok;
plus => plus_tok;
minus => minus_tok;
openp => openp_tok;
closep => closep_tok;
times => times_tok;
divide => divide_tok;
semi => semi_tok;
equal => equa_tok;
ident => ident_tok;
space;
*|;
}%%
%% write data;
static const char *ts;
static char *data=0;
static inline int lpos(void){
return ts-data;
}
void syntax_error(void){
fprintf(stderr,"syntax error...\n%s",data);
int i;
for (i=0;i<lpos();i++) fprintf(stderr," ");
fprintf(stderr,"^~\n");
}
void main(int argc ,char *argv[]){
int cs;
int act;
const char* te,*p;
int len;
lparser=ParseAlloc(malloc);
if (getopt(argc,argv,"d")!=-1)
ParseTrace(stderr,"[dbg]:");
%% write init;
do{
len=getline(&data,&len,stdin);
const char *pe,*eof=0;
if (len >0 ){
p=data;
pe = data + len;
}else{
eof=pe;
}
%% write exec;
}while(len>0);
Parse(lparser,0,0);
ParseFree(lparser, free );
}