-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.m
459 lines (457 loc) · 12.6 KB
/
main2.m
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
clc();
clear();
close('all');
grammar = struct();
grammar.('fieldExpr') = {
{'identifier'}
{'(','expression',')'}
};
grammar.('literal') = {
{'chars'}
{'number'}
{'string'}
{'end'}
};
grammar.('field') = {{'.', 'fieldExpr'}};
grammar.('pindex') = {{'(', 'commaSeparatedExprOrEmpty',')'}};
grammar.('bindex') = {{'{', 'commaSeparatedExpr','}'}};
grammar.('subsref') = {
{'field', 'subsref'}
{'pindex', 'subsref'}
{'bindex', 'subsref'}
{}
};
grammar.('operand') = {
{'identifier', 'subsref'}
{'literal'}
{'(','expression',')'}
{'matrix'}
{'cell'}
};
grammar.('powerTrans2') = {
{'.''', 'powerTrans2'}
{'.^', 'operand', 'powerTrans2'}
{'''', 'powerTrans2'}
{'^', 'operand', 'powerTrans2'}
{}
};
grammar.('powerTrans') = {
{'operand', 'powerTrans2'}
};
grammar.('unary') = {
{'+', 'unary'}
{'-', 'unary'}
{'~', 'unary'}
{'powerTrans'}
};
grammar.('mulDiv2') = {
{'.*','unary','mulDiv2'}
{'./','unary','mulDiv2'}
{'.\','unary','mulDiv2'}
{'*','unary','mulDiv2'}
{'/','unary','mulDiv2'}
{'\','unary','mulDiv2'}
{}
};
grammar.('mulDiv') = {{'unary', 'mulDiv2'}};
grammar.('addSub2') = {
{'+', 'mulDiv', 'addSub2'}
{'-', 'mulDiv', 'addSub2'}
{}
};
grammar.('addSub') = {{'mulDiv', 'addSub2'}};
grammar.('colon3') = {
{':','addSub'}
{}
};
grammar.('colon2') = {
{':','addSub','colon3'}
{}
};
grammar.('colon') = {{'addSub', 'colon2'}};
grammar.('compare2') = {
{'<','colon','compare2'}
{'<=','colon','compare2'}
{'>','colon','compare2'}
{'>=','colon','compare2'}
{'==','colon','compare2'}
{'~=','colon','compare2'}
{}
};
grammar.('compare') = {{'colon','compare2'}};
grammar.('elemAnd2') = {
{'&','compare','elemAnd2'}
{}
};
grammar.('elemAnd') = {{'compare','elemAnd2'}};
grammar.('elemOr2') = {
{'|','elemAnd','elemOr2'}
{}
};
grammar.('elemOr') = {{'elemAnd','elemOr2'}};
grammar.('logiAnd2') = {
{'&&','elemOr','logiAnd2'}
{}
};
grammar.('logiAnd') = {{'elemOr','logiAnd2'}};
grammar.('logiOr2') = {
{'||','logiAnd','logiOr2'}
{}
};
grammar.('logiOr') = {{'logiAnd','logiOr2'}};
grammar.('expression') = {
{'logiOr'}
{'lambda'}
};
grammar.('commaSeparatedExpr2') = {
{',','expression','commaSeparatedExpr2'}
{}
};
grammar.('commaSeparatedExpr') = {{'expression','commaSeparatedExpr2'}};
grammar.('commaSeparatedExprOrEmpty') = {
{'commaSeparatedExpr'}
{}
};
grammar.('matrix2') = {
{';','commaSeparatedExprOrEmpty','matrix2'}
{newline,'commaSeparatedExprOrEmpty','matrix2'}
{}
};
grammar.('matrix') = {{'[','commaSeparatedExprOrEmpty','matrix2',']'}};
grammar.('cell') = {{'{','commaSeparatedExprOrEmpty','matrix2','}'}};
grammar.('commaSeparatedIdentifier2') = {
{',','identifier','commaSeparatedIdentifier2'}
{}
};
grammar.('commaSeparatedIdentifier') = {
{'identifier','commaSeparatedIdentifier2'}
{}
};
grammar.('lambdaBody') = {
{'(','commaSeparatedIdentifier',')','expression'}
{'identifier'}
};
grammar.('lambda') = {{'@','lambdaBody'}};
grammar.('expressionOrEmpty') = {
{'expression'}
{}
};
grammar.('line') = {
{newline,'expressionOrEmpty','line'}
{}
};
grammar.('code') = {{'expressionOrEmpty','line','eof'}};
terms = fieldnames(grammar);
first = struct();
follow = struct();
for i = 1:numel(terms)
first = getFirst(first,terms{i},grammar);
follow.(terms{i}) = {};
end
follow = getFollow(follow,'code',grammar,first);
for i = 1:numel(terms)
if ismember('',[first.(terms{i}){:}]) && (any(ismember([first.(terms{i}){:}],follow.(terms{i}))) || any(ismember(follow.(terms{i}),[first.(terms{i}){:}])))
warning(terms{i})
end
print(terms{i},grammar.(terms{i}),first.(terms{i}),follow.(terms{i}));
end
grammar = preprocess(grammar,first,follow);
content = readFile('expr.txt');
tokens = tokenize(content);
tic
parse(tokens,grammar,'code',1);
toc
function content = readFile(filename)
fid = fopen(filename);
content = native2unicode(fread(fid).');
fclose(fid);
while contains(content, sprintf('\r\n'))
content = replace(content, sprintf('\r\n'), newline);
end
end
function i = parse(tokens,grammar,term,i)
stack = {{detectTerm(grammar.(term),tokens{i}),1}};
count = 1;
while count > 0
term = stack{count}{1};
j = stack{count}{2};
while j <= numel(term)
if isfield(grammar,term{j})
stack{count}{2} = j+1;
if numel(stack) == count
tmp = cell(2*numel(stack),1);
tmp(1:count) = stack;
stack = tmp;
end
count = count+1;
stack{count} = {detectTerm(grammar.(term{j}),tokens{i}), 1};
break
else
token = tokens{i};
if strcmp(token.sym,term{j})
i = i+1;
j = j+1;
else
error('unexpected token');
end
end
end
if j > numel(term)
count = count-1;
end
end
end
function term = detectTerm(term,token)
index = find(strcmp(token.sym,term.first));
if isempty(index)
error('unexpected token');
end
term = term.grammar{index};
end
function tokens = tokenize(s)
table = {
'&&'
'||'
'.*'
'./'
'.\'
'.'''
'=='
'~='
'<='
'>='
'('
')'
'['
']'
'{'
'}'
';'
':'
','
'+'
'-'
'*'
'/'
'\'
'<'
'>'
'='
'~'
'.'
'@'
newline
};
j = 1;
tokens = List();
count = 0;
lastToken = '';
while j < numel(s)
count = count + 1;
[j, type, token, sym] = nextToken(s, j, table, lastToken);
tokens.append(Token(type, token, sym));
lastToken = type;
end
tokens.append(Token('eof','eof','eof'));
tokens = tokens.list;
end
function [j, type, token, sym] = nextToken(s, j, table, lastToken)
while j <= numel(s) && s(j) == ' '
j = j + 1;
end
for i = 1 : numel(table)
if j + numel(table{i}) - 1 <= numel(s) && strcmp(s(j : j + numel(table{i}) - 1), table{i})
type = table{i};
token = table{i};
sym = table{i};
j = j + numel(table{i});
return
end
end
if s(j) == ''''
if strcmp(lastToken, 'identifier') || strcmp(lastToken, 'number')
type = 'ctranspose';
token = '''';
sym = '''';
j = j + 1;
return
end
i = j;
j = j + 1;
while j <= numel(s) && ~(s(j) == '''' && (j + 1 > numel(s) || s(j + 1) ~= ''''))
j = j + 1 + (s(j) == '''');
end
j = j + 1;
type = 'chars';
token = s(i : j - 1);
sym = 'chars';
return
end
if s(j) == '"'
i = j;
j = j + 1;
while j <= numel(s) && ~(s(j) == '"' && (j + 1 > numel(s) || s(j + 1) ~= '"'))
j = j + 1 + (s(j) == '"');
end
j = j + 1;
type = 'string';
token = s(i : j - 1);
sym = 'string';
return
end
if ('a' <= s(j) && s(j) <= 'z') || ('A' <= s(j) && s(j) <= 'Z')
i = j;
while j <= numel(s) && (('a' <= s(j) && s(j) <= 'z') || ('A' <= s(j) && s(j) <= 'Z') || ('0' <= s(j) && s(j) <= '9') || s(j) == '_')
j = j + 1;
end
token = s(i : j - 1);
if ismember(token, {'return', 'break', 'continue', 'if', 'elseif', 'for', 'else', 'while', 'end', 'function', 'switch', 'case', 'otherwise', 'classdef', 'properties', 'methods'})
type = 'keyword';
sym = token;
else
type = 'identifier';
sym = 'identifier';
end
return
end
if ('0' <= s(j) && s(j) <= '9') || (s(j) == '.' && j + 1 <= numel(s) && '0' <= s(j + 1) && s(j + 1) <= '9')
% [int].[frac]e[sign][exp]
i = j;
dot = false;
exp = false;
sign = false;
while j <= numel(s) && (('0' <= s(j) && s(j) <= '9') || (~dot && ~exp && s(j) == '.') || (~exp && s(j) == 'e') || (exp && ~sign && (s(j) == '-' || s(j) == '+')))
j = j + 1;
end
type = 'number';
token = s(i : j - 1);
sym = 'number';
return
end
if s(j) == '%'
i = j;
while j <= numel(s) && s(j) ~= newline
j = j + 1;
end
type = 'comment';
token = s(i : j - 1);
sym = 'comment';
return
end
error('unknown token');
end
function follow = getFollow(follow,term,grammar,first)
generatorList = grammar.(term);
for i = 1:numel(generatorList)
last = follow.(term);
generator = generatorList{i};
for j = numel(generator):-1:1
if isfield(grammar,generator{j})
vis = ismember(last,follow.(generator{j}));
if ~all(vis)
follow.(grammar.(term){i}{j}) = [follow.(generator{j}), last(~vis)];
follow = getFollow(follow,generator{j},grammar,first);
end
f = [first.(generator{j}){:}];
eps = strcmp(f,'');
if any(eps)
vis = ismember(f,last);
last = [last, f(~(eps | vis))]; %#ok<AGROW>
else
last = f(~eps);
end
else
last = {generator{j}};
end
end
end
end
function grammar = preprocess(grammar,first,follow)
terms = fieldnames(grammar);
for i = 1:numel(terms)
term = terms{i};
first_ = first.(term);
empty = find(cellfun(@isempty,grammar.(term)));
assert(numel(empty) <= 1);
if ~isempty(empty)
first_{empty} = follow.(term);
end
assert(numel(unique([first_{:}])) == numel([first_{:}]));
index = arrayfun(@(i)repmat(i,size(first_{i})),1:numel(first_),'un',0);
grammar_ = grammar.(term);
grammar.(term) = struct();
grammar.(term).('grammar') = grammar_([index{:}]);
grammar.(term).('first') = [first_{:}];
end
end
function first = getFirst(first,term,grammar)
if isfield(first, term)
if isempty(first.(term))
error('term %s has recursive definition', term);
end
return
end
first.(term) = {};
generatorList = grammar.(term);
set = cell(1, numel(generatorList));
for i = 1:numel(generatorList)
generator = generatorList{i};
if isempty(generator)
if ismember('',[set{:}])
error('term %s has duplicate first token', term);
end
set{i} = {''};
continue
end
set{i} = {};
for j = 1:numel(generator)
if isfield(grammar, generator{j})
first = getFirst(first,generator{j},grammar);
subset = [first.(generator{j}){:}];
eps = strcmp(subset,'');
if any(ismember(subset(~eps),[set{:}]))
error('term %s has duplicate first token', term);
end
set{i} = [set{i}, subset(~eps)];
if ~any(eps)
break
elseif j == numel(generator)
if ismember('',[set{:}])
error('term %s has duplicate first token', term);
end
set{i} = [set{i}, {''}];
end
else
if ismember(generator{j},[set{:}])
error('term %s has duplicate first token', term);
end
set{i} = [set{i}, {generator{j}}];
break
end
end
end
first.(term) = set;
end
function print(term,grammar,first,follow)
assert(numel(grammar) == numel(first));
eps = false;
disp(term+": ");
for i = 1:numel(grammar)
if ~isempty(grammar{i})
str = repmat(' ',1,4)+string(grammar{i}).join(' ');
else
str = repmat(' ',1,4)+"{}";
eps = true;
end
str = str.pad(40);
first_ = first{i};
str = str+string(first_).join(' ');
disp(str.replace(newline,'newline'));
end
if ~eps
str = repmat(' ',1,4)+"`follow`";
str = str.pad(40);
str = str+string(follow).join(' ');
disp(str.replace(newline,'newline'));
end
end