-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathparser.rs
2836 lines (2587 loc) · 93 KB
/
parser.rs
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 The Goscript Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
//
// This code is adapted from the offical Go code written in Go
// with license as follows:
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use super::ast::*;
use super::errors::{ErrorList, FilePosErrors};
use super::objects::*;
use super::position;
use super::scanner;
use super::scope::*;
use super::token::{Token, LOWEST_PREC};
use std::rc::Rc;
macro_rules! new_scope {
($owner:ident, $outer:expr) => {
$owner.objects.scopes.insert(Scope::new($outer))
};
}
macro_rules! new_ident {
($owner:ident, $pos:expr, $name:expr, $entity:expr) => {
$owner.objects.idents.insert(Ident {
pos: $pos,
name: $name,
entity: $entity,
})
};
}
macro_rules! new_field {
($owner:ident, $names:expr, $typ:expr, $tag:expr) => {
$owner.objects.fields.insert(Field {
names: $names,
typ: $typ,
tag: $tag,
})
};
}
// Parsing modes for parseSimpleStmt.
#[derive(PartialEq, Eq)]
enum ParseSimpleMode {
Basic,
LabelOk,
RangeOk,
}
pub struct Parser<'a> {
objects: &'a mut AstObjects,
scanner: scanner::Scanner<'a>,
errors: &'a ErrorList,
trace: bool,
indent: isize,
pos: position::Pos,
token: Token,
sync_pos: position::Pos,
sync_count: isize,
expr_level: isize,
in_rhs: bool,
pkg_scope: Option<ScopeKey>,
top_scope: Option<ScopeKey>,
unresolved: Vec<IdentKey>,
imports: Vec<SpecKey>, //ImportSpec
label_scope: Option<ScopeKey>,
target_stack: Vec<Vec<IdentKey>>,
}
impl<'a> Parser<'a> {
pub fn new(
objs: &'a mut AstObjects,
file: &'a mut position::File,
el: &'a ErrorList,
src: &'a str,
trace: bool,
) -> Parser<'a> {
let s = scanner::Scanner::new(file, src, el);
let mut p = Parser {
objects: objs,
scanner: s,
errors: el,
trace: trace,
indent: 0,
pos: 0,
token: Token::NONE,
sync_pos: 0,
sync_count: 0,
expr_level: 0,
in_rhs: false,
pkg_scope: None,
top_scope: None,
unresolved: vec![],
imports: vec![],
label_scope: None,
target_stack: vec![],
};
p.next(); // get the first token ready
p
}
// ----------------------------------------------------------------------------
// Getters
pub fn get_errors(&self) -> &ErrorList {
self.errors
}
// ----------------------------------------------------------------------------
// Scoping support
fn open_scope(&mut self) {
self.top_scope = Some(new_scope!(self, self.top_scope));
}
fn close_scope(&mut self) {
self.top_scope = self.objects.scopes[self.top_scope.unwrap()].outer;
}
fn open_label_scope(&mut self) {
self.label_scope = Some(new_scope!(self, self.label_scope));
self.target_stack.push(vec![]);
}
fn close_label_scope(&mut self) {
let scope = &self.objects.scopes[*self.label_scope.as_ref().unwrap()];
match self.target_stack.pop() {
Some(v) => {
for i in v {
let ident = &mut self.objects.idents[i];
match scope.look_up(&ident.name) {
Some(e) => {
ident.entity = IdentEntity::Entity(*e);
}
None => {
let s = format!("label {} undefined", ident.name);
self.error(self.pos, s);
}
}
}
}
_ => panic!("invalid target stack."),
}
self.label_scope = self.objects.scopes[self.label_scope.unwrap()].outer;
}
fn declare(&mut self, decl: DeclObj, data: EntityData, kind: EntityKind, scope_ind: &ScopeKey) {
let mut names: Vec<IdentKey> = vec![];
let idents = match decl {
DeclObj::Field(id) => &(self.objects.fields[id].names),
DeclObj::Spec(id) => match &self.objects.specs[id] {
Spec::Value(vs) => &vs.names,
Spec::Type(ts) => {
names.push(ts.name);
&names
}
Spec::Import(_) => &names,
},
DeclObj::FuncDecl(i) => {
let func_decl = &self.objects.fdecls[i];
names.push(func_decl.name);
&names
}
DeclObj::LabeledStmt(i) => {
names.push(self.objects.l_stmts[i].label);
&names
}
DeclObj::AssignStmt(_) => {
unreachable!();
}
DeclObj::NoDecl => &names,
};
for id in idents.iter() {
let mut_ident = &mut self.objects.idents[*id];
let entity_obj = Entity::new(
kind.clone(),
mut_ident.name.clone(),
decl.clone(),
data.clone(),
);
let entity = self.objects.entities.insert(entity_obj);
mut_ident.entity = IdentEntity::Entity(entity);
let ident = &self.objects.idents[*id];
if ident.name != "_" {
let scope = &mut self.objects.scopes[*scope_ind];
match scope.insert(ident.name.clone(), entity) {
Some(prev_decl) => {
let p = self.objects.entities[prev_decl].pos(&self.objects);
self.error(
ident.pos,
format!(
"{} redeclared in this block\n\tprevious declaration at {}",
ident.name,
self.file().position(p)
),
);
}
_ => {}
}
}
}
}
fn short_var_decl(&mut self, stmt: &Stmt) {
// Go spec: A short variable declaration may redeclare variables
// provided they were originally declared in the same block with
// the same type, and at least one of the non-blank variables is new.
let assign = if let Stmt::Assign(idx) = stmt {
*idx
} else {
unreachable!();
};
let list = &self.objects.a_stmts[assign].lhs;
let mut n = 0; // number of new variables
for expr in list {
match expr {
Expr::Ident(id) => {
let ident = &mut self.objects.idents[*id];
if ident.name != "_" {
let top_scope = &mut self.objects.scopes[self.top_scope.unwrap()];
match top_scope.look_up(&ident.name) {
Some(e) => {
ident.entity = IdentEntity::Entity(*e);
}
None => {
let entity_obj = Entity::new(
EntityKind::Var,
ident.name.clone(),
DeclObj::AssignStmt(assign),
EntityData::NoData,
);
let entity = self.objects.entities.insert(entity_obj);
top_scope.insert(ident.name.clone(), entity);
ident.entity = IdentEntity::Entity(entity);
n += 1;
}
}
}
}
_ => {
self.error_expected(expr.pos(&self.objects), "identifier on left side of :=");
}
}
}
if n == 0 {
self.error_str(
list[0].pos(&self.objects),
"no new variables on left side of :=",
)
}
}
// If x is an identifier, tryResolve attempts to resolve x by looking up
// the object it denotes. If no object is found and collectUnresolved is
// set, x is marked as unresolved and collected in the list of unresolved
// identifiers.
fn try_resolve(&mut self, x: &Expr, collect_unresolved: bool) {
if let Expr::Ident(i) = x {
let ident = &mut self.objects.idents[*i];
assert!(
ident.entity.is_none(),
"identifier already declared or resolved"
);
if ident.name == "_" {
return;
}
// try to resolve the identifier
let mut s = self.top_scope;
loop {
match s {
Some(sidx) => {
let scope = &self.objects.scopes[sidx];
if let Some(entity) = scope.look_up(&ident.name) {
ident.entity = IdentEntity::Entity(*entity);
return;
}
s = scope.outer;
}
None => {
break;
}
}
}
// all local scopes are known, so any unresolved identifier
// must be found either in the file scope, package scope
// (perhaps in another file), or universe scope --- collect
// them so that they can be resolved later
if collect_unresolved {
ident.entity = IdentEntity::Sentinel;
self.unresolved.push(*i);
}
}
}
fn resolve(&mut self, x: &Expr) {
self.try_resolve(x, true)
}
// ----------------------------------------------------------------------------
// Parsing support
fn file(&self) -> &position::File {
self.scanner.file()
}
fn print_trace(&self, pos: position::Pos, msg: &str) {
if !self.trace {
return;
}
let f = self.file();
let p = f.position(pos);
let mut buf = format!("{:5}:{:3}:", p.line, p.column);
for _ in 0..self.indent {
buf.push_str("..");
}
print!("{}{}\n", buf, msg);
}
fn trace_begin(&mut self, msg: &str) {
let mut trace_str = msg.to_string();
trace_str.push('(');
self.print_trace(self.pos, &trace_str);
self.indent += 1;
}
fn trace_end(&mut self) {
self.indent -= 1;
self.print_trace(self.pos, ")");
}
fn next(&mut self) {
// Get next token and skip comments
loop {
let (token, pos) = self.scanner.scan();
match token {
Token::COMMENT(_) => {
// Skip comment
self.print_trace(pos, &format!("{}", token));
}
_ => {
self.print_trace(pos, &format!("next: {}", token));
self.token = token;
self.pos = pos;
break;
}
}
}
}
fn error_str(&self, pos: position::Pos, s: &str) {
FilePosErrors::new(self.file(), self.errors).parser_add_str(pos, s);
}
fn error(&self, pos: position::Pos, msg: String) {
FilePosErrors::new(self.file(), self.errors).parser_add(pos, msg);
}
fn error_expected(&self, pos: position::Pos, msg: &str) {
let mut mstr = "expected ".to_owned();
mstr.push_str(msg);
if pos == self.pos {
match &self.token {
Token::SEMICOLON(real) => {
if !*real.as_bool() {
mstr.push_str(", found newline");
}
}
_ => {
mstr.push_str(", found ");
mstr.push_str(self.token.text());
}
}
}
self.error(pos, mstr);
}
fn expect(&mut self, token: &Token) -> position::Pos {
let pos = self.pos;
if self.token != *token {
self.error_expected(pos, &format!("'{}'", token));
}
self.next();
pos
}
// https://github.com/golang/go/issues/3008
// Same as expect but with better error message for certain cases
fn expect_closing(&mut self, token: &Token, context: &str) -> position::Pos {
if let Token::SEMICOLON(real) = token {
if !*real.as_bool() {
let msg = format!("missing ',' before newline in {}", context);
self.error(self.pos, msg);
self.next();
}
}
self.expect(token)
}
fn expect_semi(&mut self) {
// semicolon is optional before a closing ')' or '}'
match self.token {
Token::RPAREN | Token::RBRACE => {}
Token::SEMICOLON(_) => {
self.next();
}
_ => {
if let Token::COMMA = self.token {
// permit a ',' instead of a ';' but complain
self.error_expected(self.pos, "';'");
self.next();
}
self.error_expected(self.pos, "';'");
self.advance(Token::is_stmt_start);
}
}
}
fn at_comma(&self, context: &str, follow: &Token) -> bool {
if self.token == Token::COMMA {
true
} else if self.token != *follow {
let mut msg = "missing ','".to_owned();
if let Token::SEMICOLON(real) = &self.token {
if !*real.as_bool() {
msg.push_str(" before newline");
}
}
msg = format!("{} in {}", msg, context);
self.error(self.pos, msg);
true
} else {
false
}
}
// advance consumes tokens until the current token p.tok
// is in the 'to' set, or token.EOF. For error recovery.
fn advance(&mut self, to: fn(&Token) -> bool) {
while self.token != Token::EOF {
self.next();
if to(&self.token) {
// Return only if parser made some progress since last
// sync or if it has not reached 10 advance calls without
// progress. Otherwise consume at least one token to
// avoid an endless parser loop (it is possible that
// both parseOperand and parseStmt call advance and
// correctly do not advance, thus the need for the
// invocation limit p.syncCnt).
if self.pos == self.sync_pos && self.sync_count < 10 {
self.sync_count += 1;
break;
}
if self.pos > self.sync_pos {
self.sync_pos = self.pos;
self.sync_count = 0;
break;
}
// Reaching here indicates a parser bug, likely an
// incorrect token list in this function, but it only
// leads to skipping of possibly correct code if a
// previous error is present, and thus is preferred
// over a non-terminating parse.
}
}
}
// safe_pos returns a valid file position for a given position: If pos
// is valid to begin with, safe_pos returns pos. If pos is out-of-range,
// safe_pos returns the EOF position.
//
// This is hack to work around "artificial" end positions in the AST which
// are computed by adding 1 to (presumably valid) token positions. If the
// token positions are invalid due to parse errors, the resulting end position
// may be past the file's EOF position, which would lead to panics if used
// later on.
fn safe_pos(&self, pos: position::Pos) -> position::Pos {
let max = self.file().base() + self.file().size();
if pos > max {
max
} else {
pos
}
}
// ----------------------------------------------------------------------------
// Identifiers
fn parse_ident(&mut self) -> IdentKey {
let pos = self.pos;
let mut name = "_".to_owned();
if let Token::IDENT(lit) = &self.token {
name = lit.as_str().clone();
self.next();
} else {
self.expect(&Token::IDENT("".to_owned().into()));
}
self.objects.idents.insert(Ident {
pos: pos,
name: name,
entity: IdentEntity::NoEntity,
})
}
fn parse_ident_list(&mut self) -> Vec<IdentKey> {
self.trace_begin("IdentList");
let mut list = vec![self.parse_ident()];
while self.token == Token::COMMA {
self.next();
list.push(self.parse_ident());
}
self.trace_end();
list
}
// ----------------------------------------------------------------------------
// Common productions
fn parse_expr_list(&mut self, lhs: bool) -> Vec<Expr> {
self.trace_begin("ExpressionList");
let expr = self.parse_expr(lhs);
let mut list = vec![self.check_expr(expr)];
while self.token == Token::COMMA {
self.next();
let expr = self.parse_expr(lhs);
list.push(self.check_expr(expr));
}
self.trace_end();
list
}
fn parse_lhs_list(&mut self) -> Vec<Expr> {
let bak = self.in_rhs;
self.in_rhs = false;
let list = self.parse_expr_list(true);
match self.token {
// lhs of a short variable declaration
// but doesn't enter scope until later:
// caller must call self.short_var_decl(list)
// at appropriate time.
Token::DEFINE => {}
// lhs of a label declaration or a communication clause of a select
// statement (parse_lhs_list is not called when parsing the case clause
// of a switch statement):
// - labels are declared by the caller of parse_lhs_list
// - for communication clauses, if there is a stand-alone identifier
// followed by a colon, we have a syntax error; there is no need
// to resolve the identifier in that case
Token::COLON => {}
_ => {
// identifiers must be declared elsewhere
for x in list.iter() {
self.resolve(x);
}
}
}
self.in_rhs = bak;
list
}
fn parse_rhs_list(&mut self) -> Vec<Expr> {
let bak = self.in_rhs;
self.in_rhs = true;
let list = self.parse_expr_list(false);
self.in_rhs = bak;
list
}
// ----------------------------------------------------------------------------
// Types
fn parse_type(&mut self) -> Expr {
self.trace_begin("Type");
let typ = self.try_type();
let ret = if typ.is_none() {
let pos = self.pos;
self.error_expected(pos, "type");
self.next();
Expr::new_bad(pos, self.pos)
} else {
typ.unwrap()
};
self.trace_end();
ret
}
// If the result is an identifier, it is not resolved.
fn parse_type_name(&mut self) -> Expr {
self.trace_begin("TypeName");
let ident = self.parse_ident();
let x_ident = Expr::Ident(ident);
// don't resolve ident yet - it may be a parameter or field name
let ret = if let Token::PERIOD = self.token {
// ident is a package name
self.next();
self.resolve(&x_ident);
let sel = self.parse_ident();
Expr::new_selector(x_ident, sel)
} else {
x_ident
};
self.trace_end();
ret
}
fn parse_array_type(&mut self) -> Expr {
self.trace_begin("ArrayType");
let lpos = self.expect(&Token::LBRACK);
self.expr_level += 1;
let len = match self.token {
// always permit ellipsis for more fault-tolerant parsing
Token::ELLIPSIS => {
let ell = Expr::new_ellipsis(self.pos, None);
self.next();
Some(ell)
}
_ if self.token != Token::RBRACK => Some(self.parse_rhs()),
_ => None,
};
self.expr_level -= 1;
self.expect(&Token::RBRACK);
let elt = self.parse_type();
self.trace_end();
Expr::Array(Rc::new(ArrayType {
l_brack: lpos,
len: len,
elt: elt,
}))
}
fn make_ident_list(&mut self, exprs: &mut Vec<Expr>) -> Vec<IdentKey> {
exprs
.iter()
.map(|x| {
match x {
Expr::Ident(ident) => *ident,
_ => {
let pos = x.pos(&self.objects);
if let Expr::Bad(_) = x {
// only report error if it's a new one
self.error_expected(pos, "identifier")
}
new_ident!(self, pos, "_".to_owned(), IdentEntity::NoEntity)
}
}
})
.collect()
}
fn parse_field_decl(&mut self, scope: ScopeKey) -> FieldKey {
self.trace_begin("FieldDecl");
// 1st FieldDecl
// A type name used as an anonymous field looks like a field identifier.
let mut list = vec![];
loop {
list.push(self.parse_var_type(false));
if self.token != Token::COMMA {
break;
}
self.next();
}
let mut idents = vec![];
let typ = match self.try_var_type(false) {
Some(t) => {
idents = self.make_ident_list(&mut list);
t
}
// ["*"] TypeName (AnonymousField)
None => {
let first = &list[0]; // we always have at least one element
if list.len() > 1 {
self.error_expected(self.pos, "type");
Expr::new_bad(self.pos, self.pos)
} else if !Parser::is_type_name(Parser::deref(first)) {
self.error_expected(self.pos, "anonymous field");
Expr::new_bad(
first.pos(&self.objects),
self.safe_pos(first.end(&self.objects)),
)
} else {
list.into_iter().nth(0).unwrap()
}
}
};
// Tag
let token = self.token.clone();
let tag = if let Token::STRING(_) = token {
let t = Some(Expr::new_basic_lit(self.pos, self.token.clone()));
self.next();
t
} else {
None
};
self.expect_semi();
let to_resolve = typ.clone_ident();
let field = new_field!(self, idents, typ, tag);
self.declare(
DeclObj::Field(field),
EntityData::NoData,
EntityKind::Var,
&scope,
);
if let Some(ident) = to_resolve {
self.resolve(&ident);
}
self.trace_end();
field
}
fn parse_struct_type(&mut self) -> Expr {
self.trace_begin("FieldDecl");
let stru = self.expect(&Token::STRUCT);
let lbrace = self.expect(&Token::LBRACE);
let scope = new_scope!(self, None);
let mut list = vec![];
loop {
match &self.token {
Token::IDENT(_) | Token::MUL | Token::LPAREN => {
list.push(self.parse_field_decl(scope));
}
_ => {
break;
}
}
}
let rbrace = self.expect(&Token::RBRACE);
self.trace_end();
Expr::Struct(Rc::new(StructType {
struct_pos: stru,
fields: FieldList::new(Some(lbrace), list, Some(rbrace)),
incomplete: false,
}))
}
fn parse_pointer_type(&mut self) -> Expr {
self.trace_begin("PointerType");
let star = self.expect(&Token::MUL);
let base = self.parse_type();
self.trace_end();
Expr::Star(Rc::new(StarExpr {
star: star,
expr: base,
}))
}
// If the result is an identifier, it is not resolved.
fn try_var_type(&mut self, is_param: bool) -> Option<Expr> {
if is_param {
if let Token::ELLIPSIS = self.token {
let pos = self.pos;
self.next();
let typ = if let Some(t) = self.try_ident_or_type() {
self.resolve(&t);
t
} else {
self.error_str(pos, "'...' parameter is missing type");
Expr::new_bad(pos, self.pos)
};
return Some(Expr::new_ellipsis(pos, Some(typ)));
}
}
self.try_ident_or_type()
}
fn parse_var_type(&mut self, is_param: bool) -> Expr {
match self.try_var_type(is_param) {
Some(typ) => typ,
None => {
let pos = self.pos;
self.error_expected(pos, "type");
self.next();
Expr::new_bad(pos, self.pos)
}
}
}
fn parse_parameter_list(&mut self, scope: ScopeKey, ellipsis_ok: bool) -> Vec<FieldKey> {
self.trace_begin("ParameterList");
// 1st ParameterDecl
// A list of identifiers looks like a list of type names.
let mut list = vec![];
loop {
list.push(self.parse_var_type(ellipsis_ok));
if self.token != Token::COMMA {
break;
}
self.next();
if self.token == Token::RPAREN {
break;
}
}
let mut params = vec![];
let typ = self.try_var_type(ellipsis_ok);
if let Some(t) = typ {
// IdentifierList Type
let idents = self.make_ident_list(&mut list);
let to_resolve = t.clone_ident();
let field = new_field!(self, idents, t, None);
params.push(field);
// Go spec: The scope of an identifier denoting a function
// parameter or result variable is the function body.
self.declare(
DeclObj::Field(field),
EntityData::NoData,
EntityKind::Var,
&scope,
);
if let Some(ident) = to_resolve {
self.resolve(&ident);
}
if !self.at_comma("parameter list", &Token::RPAREN) {
self.trace_end();
return params;
}
self.next();
while self.token != Token::RPAREN && self.token != Token::EOF {
let idents = self.parse_ident_list();
let t = self.parse_var_type(ellipsis_ok);
let to_resolve = t.clone_ident();
let field = new_field!(self, idents, t, None);
// warning: copy paste
params.push(field);
// Go spec: The scope of an identifier denoting a function
// parameter or result variable is the function body.
self.declare(
DeclObj::Field(field),
EntityData::NoData,
EntityKind::Var,
&scope,
);
if let Some(ident) = to_resolve {
self.resolve(&ident);
}
if !self.at_comma("parameter list", &Token::RPAREN) {
break;
}
self.next();
}
} else {
// Type { "," Type } (anonymous parameters)
for typ in list {
self.resolve(&typ);
params.push(new_field!(self, vec![], typ, None));
}
}
self.trace_end();
params
}
fn parse_parameters(&mut self, scope: ScopeKey, ellipsis_ok: bool) -> FieldList {
self.trace_begin("Parameters");
let mut params = vec![];
let lparen = Some(self.expect(&Token::LPAREN));
if self.token != Token::RPAREN {
params = self.parse_parameter_list(scope, ellipsis_ok);
}
let rparen = Some(self.expect(&Token::RPAREN));
self.trace_end();
FieldList::new(lparen, params, rparen)
}
fn parse_result(&mut self, scope: ScopeKey) -> Option<FieldList> {
self.trace_begin("Result");
let ret = if self.token == Token::LPAREN {
Some(self.parse_parameters(scope, false))
} else {
self.try_type().map(|t| {
let field = new_field!(self, vec![], t, None);
FieldList::new(None, vec![field], None)
})
};
self.trace_end();
ret
}
fn parse_signature(&mut self, scope: ScopeKey) -> (FieldList, Option<FieldList>) {
self.trace_begin("Signature");
let params = self.parse_parameters(scope, true);
let results = self.parse_result(scope);
self.trace_end();
(params, results)
}
fn parse_func_type(&mut self) -> (FuncType, ScopeKey) {
self.trace_begin("FuncType");
let pos = self.expect(&Token::FUNC);
let scope = new_scope!(self, self.top_scope);
let (params, results) = self.parse_signature(scope);
self.trace_end();
(FuncType::new(Some(pos), params, results), scope)
}
// method spec in interface
fn parse_method_spec(&mut self, scope: ScopeKey) -> FieldKey {
self.trace_begin("MethodSpec");
let mut idents = vec![];
let mut typ = self.parse_type_name();
let ident = typ.try_as_ident();
if ident.is_some() && self.token == Token::LPAREN {
idents = vec![*ident.unwrap()];
let scope = new_scope!(self, self.top_scope);
let (params, results) = self.parse_signature(scope);
typ = Expr::box_func_type(FuncType::new(None, params, results), &mut self.objects);
} else {
// embedded interface
self.resolve(&typ);
}
self.expect_semi();
let field = new_field!(self, idents, typ, None);
self.declare(
DeclObj::Field(field),
EntityData::NoData,
EntityKind::Fun,
&scope,
);
self.trace_end();
field
}
fn parse_interface_type(&mut self) -> InterfaceType {
self.trace_begin("InterfaceType");
let pos = self.expect(&Token::INTERFACE);
let lbrace = self.expect(&Token::LBRACE);
let scope = new_scope!(self, None);
let mut list = vec![];
loop {
if let Token::IDENT(_) = self.token {
} else {
break;
}
list.push(self.parse_method_spec(scope));
}
let rbrace = self.expect(&Token::RBRACE);
self.trace_end();
InterfaceType {
interface: pos,
methods: FieldList {
openning: Some(lbrace),
list: list,
closing: Some(rbrace),
},
incomplete: false,
}
}
fn parse_map_type(&mut self) -> MapType {
self.trace_begin("MapType");
let pos = self.expect(&Token::MAP);
self.expect(&Token::LBRACK);
let key = self.parse_type();
self.expect(&Token::RBRACK);
let val = self.parse_type();
self.trace_end();
MapType {
map: pos,
key: key,
val: val,