-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodules.go
More file actions
610 lines (549 loc) · 12.1 KB
/
modules.go
File metadata and controls
610 lines (549 loc) · 12.1 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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package main
import (
"bufio"
"fmt"
"os"
"strings"
"unicode"
"unicode/utf8"
)
type Tag int
type Lexem struct {
Tag
Image string
}
const (
ERROR Tag = 1 << iota // Неправильная лексема
COMMA // Запятая
NUMBER // Целое число
IDENT // Имя переменной
PLUS // Знак +
MINUS // Знак -
MUL // Знак *
DIV // Знак /
EQUAL // Знак =
LT // <
GT // >
LE // <=
GE // >=
NE // <>
LPAREN // Левая круглая скобка
RPAREN // Правая круглая скобка
SEMICOLON // Точка с запятой
QUESTION // Вопросительный знак
COLON // Двоеточие
WALRUS // Моржовый оператор
EOF
)
var Lexems = map[Tag]string {
ERROR : "ERROR",
COMMA : "COMMA",
NUMBER : "NUMBER",
IDENT : "IDENT",
PLUS : "PLUS",
MINUS : "MINUS",
MUL : "MUL",
DIV : "DIV",
EQUAL : "EQUAL",
LT : "LT",
GT : "GT",
GE : "GE",
NE : "NE",
LPAREN : "LPAREN",
RPAREN : "RPAREN",
SEMICOLON : "SEMICOLON",
QUESTION : "QUESTION",
COLON : "COLON",
WALRUS : "WALRUS",
EOF: "EOF",
}
func (l Lexem) String() string {
return fmt.Sprintf("{%s %s}", Lexems[l.Tag], l.Image)
}
type Lexer struct {
start,
pos,
width int
lexems chan Lexem
state StateFn
input string
}
type StateFn func(l *Lexer) StateFn
func (l *Lexer) run() {
for state := lexText; state != nil; {
state = state(l)
}
close(l.lexems)
}
func lex(input string) *Lexer {
l := &Lexer{
input: input,
state: lexText,
lexems: make(chan Lexem),
}
go l.run()
return l
}
func (l *Lexer) NextLexem() (Lexem, bool) {
lexem, ok := <-l.lexems
return lexem, ok
}
func (l *Lexer) Emit(t Tag) {
l.lexems <- Lexem{t, l.input[l.start:l.pos]}
l.start = l.pos
}
func (l *Lexer) Next() (r rune) {
if l.pos >= len(l.input) {
l.width = 0
return -1
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return r
}
func (l *Lexer) Ignore() { l.start = l.pos }
func (l *Lexer) Backup() { l.pos -= l.width }
func (l *Lexer) Peek() rune {
r := l.Next()
l.Backup()
return r
}
func (l *Lexer) Errorf(format string, args ...interface{}) StateFn {
l.lexems <- Lexem{
ERROR,
fmt.Sprintf(format, args...),
}
return nil
}
func lexNumber(l *Lexer) StateFn {
for isNumeric(l.Next()) {
}
l.Backup()
if isAlpha(l.Peek()) {
l.Next()
return l.Errorf("Bad number syntax: %q", l.input[l.start:l.pos])
}
l.Emit(NUMBER)
return lexText
}
func lexIdentifier(l *Lexer) StateFn {
for isAlphaNumeric(l.Next()) {
}
l.Backup()
l.Emit(IDENT)
return lexText
}
func lexText(l *Lexer) StateFn {
for {
switch r := l.Next(); {
case r == -1:
l.Emit(EOF)
return nil
case unicode.IsSpace(r):
l.Ignore()
case r == '(':
l.Emit(LPAREN)
case r == ',':
l.Emit(COMMA)
case r == ')':
l.Emit(RPAREN)
case r == '=':
l.Emit(EQUAL)
case r == '<':
if l.Peek() == '>' {
l.Next()
l.Emit(NE)
} else if l.Peek() == '=' {
l.Next()
l.Emit(LE)
} else {
l.Emit(LT)
}
case r == '>':
if l.Peek() == '=' {
l.Next()
l.Emit(GE)
} else {
l.Emit(GT)
}
case isOperation(r):
if r == '+' {
l.Emit(PLUS)
} else if r == '-' {
l.Emit(MINUS)
} else if r == '*' {
l.Emit(MUL)
} else if r == '/' {
l.Emit(DIV)
}
case r == ':':
if l.Peek() == '=' {
l.Next()
l.Emit(WALRUS)
} else {
l.Emit(COLON)
}
case r == '?':
l.Emit(QUESTION)
case r == ';':
l.Emit(SEMICOLON)
case unicode.IsDigit(r):
l.Backup()
return lexNumber
case isAlphaNumeric(r):
l.Backup()
return lexIdentifier
default:
return l.Errorf("Unexpexced character: %q", l.input[l.start:l.pos])
}
}
}
func isOperation(r rune) bool {
return r == '+' ||
r == '-' ||
r == '*' ||
r == '/'
}
func isAlpha(r rune) bool {
return r >= 'a' && r <= 'z' ||
r >= 'A' && r <= 'Z'
}
func isNumeric(r rune) bool {
return r >= '0' && r <= '9'
}
func isAlphaNumeric(r rune) bool {
return isAlpha(r) || isNumeric(r)
}
type Function struct {
ident string
dependencies []string
formalArgs map[string]bool
actualArgsCount []*int
vars map[string]bool
}
type Parser struct {
Lexem
l *Lexer
ident string
defined map[string]*Function
definition *Function
functions []*Function
}
func parser(l *Lexer) *Parser {
p := &Parser{
l: l,
defined: make(map[string]*Function),
functions: make([]*Function, 0),
}
return p
}
func (p *Parser) run() ([]*Function, map[string]*Function, bool) {
defer func() {
x := recover(); if x != nil {
p.functions, p.defined = nil, nil
}
}()
p.Next()
p.Program()
return p.functions, p.defined, p.Lexem.Tag & EOF != 0
}
func (p *Parser) Next() {
lexem, ok := p.l.NextLexem()
if ok {
p.Lexem = lexem
} else {
p.Lexem = Lexem{EOF, ""}
}
}
// <program> ::= <function> <program> | <empty>
func (p *Parser) Program() {
if p.Lexem.Tag & IDENT != 0 {
p.definition = &Function{p.Lexem.Image, make([]string, 0),
make(map[string]bool),
make([]*int, 0), make(map[string]bool)}
p.defined[p.Lexem.Image] = p.definition
p.functions = append(p.functions, p.definition)
p.Function()
p.Program()
}
}
// <function> ::= <ident> LPAREN <formal-args-list> RPAREN := <expr> SEMICOLON
func (p *Parser) Function() {
p.Ident()
p.Lparen()
p.FormalArgsList()
p.Rparen()
p.Walrus()
p.Expr()
p.Semicolon()
}
func (p *Parser) Ident() {
if p.Lexem.Tag & IDENT != 0 {
p.ident = p.Lexem.Image
p.definition.vars[p.Lexem.Image] = true
p.Next()
} else {
panic(fmt.Sprintf("Expected IDENT but got %v", p.Lexem))
}
}
func (p *Parser) Lparen() {
if p.Lexem.Tag & LPAREN != 0 {
p.Next()
} else {
panic(fmt.Sprintf("Expected LPAREN but got %v", p.Lexem))
}
}
func (p *Parser) Rparen() {
if p.Lexem.Tag & RPAREN != 0 {
p.Next()
} else {
panic(fmt.Sprintf("Expected RPAREN but got %v", p.Lexem))
}
}
func (p *Parser) Walrus() {
if p.Lexem.Tag & WALRUS != 0 {
p.Next()
} else {
panic(fmt.Sprintf("Expected WALRUS but got %v", p.Lexem))
}
}
// <expr> ::= <comparison-expr> <expr-tail>
func (p *Parser) Expr() {
if p.Lexem.Tag & (NUMBER | IDENT | LPAREN | MINUS) != 0 {
p.ComparisonExpr()
p.ExprTail()
} else {
panic(fmt.Sprintf("Expected NUMBER, IDENT, LPAREN or MINUS but got %v", p.Lexem))
}
}
// <expr-tail> ::= QUESTION <comparison-expr> COLON <expr> | <empty>
func (p *Parser) ExprTail() {
if p.Lexem.Tag & QUESTION != 0 {
p.Next()
p.ComparisonExpr()
p.Colon()
p.Expr()
}
}
// <comparison-expr> ::= <arith-expr> <comparison-expr-tail>
func (p *Parser) ComparisonExpr() {
if p.Lexem.Tag & (NUMBER | IDENT | LPAREN | MINUS) != 0 {
p.ArithExpr()
p.ComparisonExprTail()
} else {
panic(fmt.Sprintf("Expected NUMBER, IDENT, LPAREN or MINUS but got %v", p.Lexem))
}
}
// <comparison-expr-tail> ::= <comparison-op> <arith-expr> | <empty>
func (p *Parser) ComparisonExprTail() {
if p.Lexem.Tag & (EQUAL | NE | LT | GT | LE | GE) != 0 {
p.Next()
p.ArithExpr()
}
}
// <arith-expr> ::= <term> <arith-expr-tail>
func (p *Parser) ArithExpr() {
if p.Lexem.Tag & (NUMBER | IDENT | LPAREN | MINUS) != 0 {
p.Term()
p.ArithExprTail()
} else {
panic(fmt.Sprintf("Expected NUMBER, IDENT, LPAREN or MINUS but got %v", p.Lexem))
}
}
// <arith-expr-tail> ::= PLUS <term> <arith-expr-tail> | MINUS <term> <arith-expr-tail> | <empty>
func (p *Parser) ArithExprTail() {
if p.Lexem.Tag & (PLUS | MINUS) != 0 {
p.Next()
p.Term()
p.ArithExprTail()
}
}
// <term> ::= <factor> <term-tail>
func (p *Parser) Term() {
if p.Lexem.Tag & (NUMBER | IDENT | LPAREN | MINUS) != 0 {
p.Factor()
p.TermTail()
} else {
panic(fmt.Sprintf("Expected NUMBER, IDENT, LPAREN or MINUS but got %v", p.Lexem))
}
}
// <term-tail> ::= MUL <factor> <term-tail> | DIV <factor> <term-tail> | <empty>
func (p *Parser) TermTail() {
if p.Lexem.Tag & (MUL | DIV) != 0 {
p.Next()
p.Factor()
p.TermTail()
}
}
// <factor> ::= <number> | <ident> <factor-tail> | LPAREN <expr> RPAREN | MINUS <factor>
func (p *Parser) Factor() {
if p.Lexem.Tag & NUMBER != 0 {
p.Next()
} else if p.Lexem.Tag & IDENT != 0 {
p.Ident()
p.FactorTail()
} else if p.Lexem.Tag & LPAREN != 0 {
p.Lparen()
p.Expr()
p.Rparen()
} else if p.Lexem.Tag & MINUS != 0 {
p.Next()
p.Factor()
} else {
panic(fmt.Sprintf("Expected NUMBER, IDENT, LPAREN or MINUS but got %v", p.Lexem))
}
}
// <factor-tail> ::= LPAREN <actual-args-list> RPAREN | <empty>
func (p *Parser) FactorTail() {
if p.Lexem.Tag & LPAREN != 0 {
dependency := p.ident
p.definition.dependencies = append(p.definition.dependencies, dependency)
p.Lparen()
i := 0
count := &i
p.definition.actualArgsCount = append(p.definition.actualArgsCount, count)
p.ActualArgsList(count)
p.Rparen()
}
}
// <actual-args-tail> ::= <expr-list> | <empty>
func (p *Parser) ActualArgsList(count *int) {
if p.Lexem.Tag & (NUMBER | IDENT | LPAREN | MINUS) != 0 {
p.ExprList(count)
}
}
// <expr-list> ::= <expr> <expr-list-tail>
func (p *Parser) ExprList(count *int) {
if p.Lexem.Tag & (NUMBER | IDENT | LPAREN | MINUS) != 0 {
p.Expr()
*count++
p.ExprListTail(count)
}
}
// <expr-list-tail> ::= COMMA <expr> <expr-list-tail> | <empty>
func (p *Parser) ExprListTail(count *int) {
if p.Lexem.Tag & COMMA != 0 {
p.Next()
p.Expr()
*count++
p.ExprListTail(count)
}
}
func (p *Parser) Semicolon() {
if p.Lexem.Tag & SEMICOLON != 0 {
p.Next()
} else {
panic(fmt.Sprintf("Expected SEMICOLON but got %v", p.Lexem))
}
}
// <formal-args-list> ::= <ident-list> | <empty>
func (p *Parser) FormalArgsList() {
if p.Lexem.Tag & IDENT != 0 {
p.IdentList()
}
}
// <ident-list> ::= <ident> <ident-list-tail>
func (p *Parser) IdentList() {
p.definition.formalArgs[p.Lexem.Image] = true
p.Ident()
p.IdentListTail()
}
// <ident-list-tail> ::= COMMA <ident> <ident-list-tail> | <empty>
func (p *Parser) IdentListTail() {
if p.Lexem.Tag & COMMA != 0 {
p.Next()
p.definition.formalArgs[p.Lexem.Image] = true
p.Ident()
p.IdentListTail()
}
}
func (p *Parser) Colon() {
if p.Lexem.Tag & COLON != 0 {
p.Next()
} else {
panic(fmt.Sprintf("Expected COLON but got %v", p.Lexem))
}
}
type Stack []*Function
func (s *Stack) Push(f *Function) {
*s = append(*s, f)
}
func (s *Stack) Pop() *Function {
l := len(*s)
f := (*s)[l-1]
*s = (*s)[:l-1]
return f
}
func tarjan(functions []*Function, defined map[string]*Function) int {
in := make(map[string]int)
low := make(map[string]int)
comp := make(map[string]int)
for _, f := range functions {
in[f.ident], low[f.ident], comp[f.ident] = 0, 0, 0
}
stack := Stack(make([]*Function, 0))
time, count := 1, 1
var visit func(f *Function)
visit = func(f *Function) {
in[f.ident], low[f.ident] = time, time
time++
stack.Push(f)
for _, dependency := range f.dependencies {
if in[dependency] == 0 {
visit(defined[dependency])
}
if comp[dependency] == 0 && low[f.ident] > low[dependency] {
low[f.ident] = low[dependency]
}
}
if in[f.ident] == low[f.ident] {
for {
u := stack.Pop()
comp[u.ident] = count
if u.ident == f.ident {
break
}
}
count++
}
}
for _, f := range functions {
if in[f.ident] == 0 {
visit(f)
}
}
return count - 1
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
var sb strings.Builder
for scanner.Scan() {
sb.WriteString(scanner.Text())
}
l := lex(sb.String())
p := parser(l)
functions, defined, ok := p.run()
if !ok {
fmt.Println("error")
return
}
for _, f := range functions {
for i, dependency := range f.dependencies {
if _, isDefined := defined[dependency]; !isDefined {
fmt.Println("error")
return
}
if len(defined[dependency].formalArgs) != *f.actualArgsCount[i] {
fmt.Println("error")
return
}
}
for v, _ := range f.vars {
if _, isGlobal := defined[v]; !(isGlobal || f.formalArgs[v]) {
fmt.Println("error")
return
}
}
}
fmt.Println(tarjan(functions, defined))
}