forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.rs
4270 lines (3898 loc) · 148 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 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use ast::{Sigil, BorrowedSigil, ManagedSigil, OwnedSigil, RustAbi};
use ast::{CallSugar, NoSugar, DoSugar, ForSugar};
use ast::{TyBareFn, TyClosure};
use ast::{RegionTyParamBound, TraitTyParamBound};
use ast::{provided, public, pure_fn, purity, re_static};
use ast::{_mod, add, arg, arm, attribute, bind_by_ref, bind_infer};
use ast::{bind_by_copy, bitand, bitor, bitxor, blk};
use ast::{blk_check_mode, box, by_copy, by_ref, by_val};
use ast::{crate, crate_cfg, decl, decl_item};
use ast::{decl_local, default_blk, deref, div, enum_def, enum_variant_kind};
use ast::{expl, expr, expr_, expr_addr_of, expr_match, expr_again};
use ast::{expr_assert, expr_assign, expr_assign_op, expr_binary, expr_block};
use ast::{expr_break, expr_call, expr_cast, expr_copy, expr_do_body};
use ast::{expr_field, expr_fn_block, expr_if, expr_index};
use ast::{expr_lit, expr_log, expr_loop, expr_loop_body, expr_mac};
use ast::{expr_method_call, expr_paren, expr_path, expr_rec, expr_repeat};
use ast::{expr_ret, expr_swap, expr_struct, expr_tup, expr_unary};
use ast::{expr_vec, expr_vstore, expr_vstore_mut_box};
use ast::{expr_vstore_fixed, expr_vstore_slice, expr_vstore_box};
use ast::{expr_vstore_mut_slice, expr_while, extern_fn, field, fn_decl};
use ast::{expr_vstore_uniq, TyClosure, TyBareFn, Onceness, Once, Many};
use ast::{foreign_item, foreign_item_const, foreign_item_fn, foreign_mod};
use ast::{ident, impure_fn, infer, inherited, item, item_, item_const};
use ast::{item_const, item_enum, item_fn, item_foreign_mod, item_impl};
use ast::{item_mac, item_mod, item_struct, item_trait, item_ty, lit, lit_};
use ast::{lit_bool, lit_float, lit_float_unsuffixed, lit_int};
use ast::{lit_int_unsuffixed, lit_nil, lit_str, lit_uint, local, m_const};
use ast::{m_imm, m_mutbl, mac_, mac_invoc_tt, matcher, match_nonterminal};
use ast::{match_seq, match_tok, method, mode, module_ns, mt, mul, mutability};
use ast::{named_field, neg, node_id, noreturn, not, pat, pat_box, pat_enum};
use ast::{pat_ident, pat_lit, pat_range, pat_rec, pat_region, pat_struct};
use ast::{pat_tup, pat_uniq, pat_wild, path, private};
use ast::{re_self, re_anon, re_named, region, rem, required};
use ast::{ret_style, return_val, self_ty, shl, shr, stmt, stmt_decl};
use ast::{stmt_expr, stmt_semi, stmt_mac, struct_def, struct_field};
use ast::{struct_immutable, struct_mutable, struct_variant_kind, subtract};
use ast::{sty_box, sty_by_ref, sty_region, sty_static, sty_uniq, sty_value};
use ast::{token_tree, trait_method, trait_ref, tt_delim, tt_seq, tt_tok};
use ast::{tt_nonterminal, tuple_variant_kind, Ty, ty_, ty_bot, ty_box};
use ast::{ty_field, ty_fixed_length_vec, ty_closure, ty_bare_fn};
use ast::{ty_infer, ty_mac, ty_method};
use ast::{ty_nil, TyParam, TyParamBound, ty_path, ty_ptr, ty_rec, ty_rptr};
use ast::{ty_tup, ty_u32, ty_uniq, ty_vec, type_value_ns, uniq};
use ast::{unnamed_field, unsafe_blk, unsafe_fn, variant, view_item};
use ast::{view_item_, view_item_extern_mod, view_item_use};
use ast::{view_path, view_path_glob, view_path_list, view_path_simple};
use ast::{visibility, vstore, vstore_box, vstore_fixed, vstore_slice};
use ast;
use ast_util::{ident_to_path, operator_prec};
use ast_util;
use codemap::{span,FssNone, BytePos, spanned, respan, mk_sp};
use codemap;
use parse::attr::parser_attr;
use parse::classify;
use parse::common::{seq_sep_none, token_to_str};
use parse::common::{seq_sep_trailing_disallowed, seq_sep_trailing_allowed};
use parse::lexer::reader;
use parse::lexer::TokenAndSpan;
use parse::obsolete::{ObsoleteClassTraits, ObsoleteModeInFnType};
use parse::obsolete::{ObsoleteLet, ObsoleteFieldTerminator};
use parse::obsolete::{ObsoleteMoveInit, ObsoleteBinaryMove};
use parse::obsolete::{ObsoleteSyntax, ObsoleteLowerCaseKindBounds};
use parse::obsolete::{ObsoleteUnsafeBlock, ObsoleteImplSyntax};
use parse::obsolete::{ObsoleteTraitBoundSeparator, ObsoleteMutOwnedPointer};
use parse::obsolete::{ObsoleteMutVector, ObsoleteTraitImplVisibility};
use parse::prec::{as_prec, token_to_binop};
use parse::token::{can_begin_expr, is_ident, is_ident_or_path};
use parse::token::{is_plain_ident, INTERPOLATED, special_idents};
use parse::token;
use parse::{new_sub_parser_from_file, next_node_id, ParseSess};
use opt_vec;
use opt_vec::OptVec;
use core::either::{Either, Left, Right};
use core::either;
use core::vec;
use std::oldmap::HashMap;
#[deriving_eq]
enum restriction {
UNRESTRICTED,
RESTRICT_STMT_EXPR,
RESTRICT_NO_CALL_EXPRS,
RESTRICT_NO_BAR_OP,
RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
}
// So that we can distinguish a class dtor from other class members
enum class_contents { dtor_decl(blk, ~[attribute], codemap::span),
members(~[@struct_field]) }
type arg_or_capture_item = Either<arg, ()>;
type item_info = (ident, item_, Option<~[attribute]>);
pub enum item_or_view_item {
// indicates a failure to parse any kind of item:
iovi_none,
iovi_item(@item),
iovi_foreign_item(@foreign_item),
iovi_view_item(@view_item)
}
enum view_item_parse_mode {
VIEW_ITEMS_AND_ITEMS_ALLOWED,
VIEW_ITEMS_AND_FOREIGN_ITEMS_ALLOWED,
IMPORTS_AND_ITEMS_ALLOWED
}
/* The expr situation is not as complex as I thought it would be.
The important thing is to make sure that lookahead doesn't balk
at INTERPOLATED tokens */
macro_rules! maybe_whole_expr (
($p:expr) => (
match *($p).token {
INTERPOLATED(token::nt_expr(copy e)) => {
$p.bump();
return e;
}
INTERPOLATED(token::nt_path(copy pt)) => {
$p.bump();
return $p.mk_expr(
($p).span.lo,
($p).span.hi,
expr_path(pt)
);
}
_ => ()
}
)
)
macro_rules! maybe_whole (
($p:expr, $constructor:ident) => (
match *($p).token {
INTERPOLATED(token::$constructor(copy x)) => {
$p.bump();
return x;
}
_ => ()
}
);
(deref $p:expr, $constructor:ident) => (
match *($p).token {
INTERPOLATED(token::$constructor(copy x)) => {
$p.bump();
return copy *x;
}
_ => ()
}
);
(Some $p:expr, $constructor:ident) => (
match *($p).token {
INTERPOLATED(token::$constructor(copy x)) => {
$p.bump();
return Some(x);
}
_ => ()
}
);
(iovi $p:expr, $constructor:ident) => (
match *($p).token {
INTERPOLATED(token::$constructor(copy x)) => {
$p.bump();
return iovi_item(x);
}
_ => ()
}
);
(pair_empty $p:expr, $constructor:ident) => (
match *($p).token {
INTERPOLATED(token::$constructor(copy x)) => {
$p.bump();
return (~[], x);
}
_ => ()
}
)
)
pure fn maybe_append(+lhs: ~[attribute], rhs: Option<~[attribute]>)
-> ~[attribute] {
match rhs {
None => lhs,
Some(ref attrs) => vec::append(lhs, (*attrs))
}
}
struct ParsedItemsAndViewItems {
attrs_remaining: ~[attribute],
view_items: ~[@view_item],
items: ~[@item],
foreign_items: ~[@foreign_item]
}
/* ident is handled by common.rs */
pub fn Parser(sess: @mut ParseSess,
+cfg: ast::crate_cfg,
+rdr: reader) -> Parser {
let tok0 = copy rdr.next_token();
let interner = rdr.interner();
Parser {
reader: rdr,
interner: interner,
sess: sess,
cfg: cfg,
token: @mut copy tok0.tok,
span: @mut copy tok0.sp,
last_span: @mut copy tok0.sp,
buffer: @mut [copy tok0, .. 4],
buffer_start: @mut 0,
buffer_end: @mut 0,
tokens_consumed: @mut 0,
restriction: @mut UNRESTRICTED,
quote_depth: @mut 0,
keywords: token::keyword_table(),
strict_keywords: token::strict_keyword_table(),
reserved_keywords: token::reserved_keyword_table(),
obsolete_set: HashMap(),
mod_path_stack: @mut ~[],
}
}
pub struct Parser {
sess: @mut ParseSess,
cfg: crate_cfg,
token: @mut token::Token,
span: @mut span,
last_span: @mut span,
buffer: @mut [TokenAndSpan * 4],
buffer_start: @mut int,
buffer_end: @mut int,
tokens_consumed: @mut uint,
restriction: @mut restriction,
quote_depth: @mut uint, // not (yet) related to the quasiquoter
reader: reader,
interner: @token::ident_interner,
keywords: HashMap<~str, ()>,
strict_keywords: HashMap<~str, ()>,
reserved_keywords: HashMap<~str, ()>,
/// The set of seen errors about obsolete syntax. Used to suppress
/// extra detail when the same error is seen twice
obsolete_set: HashMap<ObsoleteSyntax, ()>,
/// Used to determine the path to externally loaded source files
mod_path_stack: @mut ~[~str],
}
impl Drop for Parser {
/* do not copy the parser; its state is tied to outside state */
fn finalize(&self) {}
}
pub impl Parser {
// advance the parser by one token
fn bump(&self) {
*self.last_span = copy *self.span;
let next = if *self.buffer_start == *self.buffer_end {
self.reader.next_token()
} else {
let next = copy self.buffer[*self.buffer_start];
*self.buffer_start = (*self.buffer_start + 1) & 3;
next
};
*self.token = copy next.tok;
*self.span = copy next.sp;
*self.tokens_consumed += 1u;
}
// EFFECT: replace the current token and span with the given one
fn replace_token(&self, +next: token::Token, +lo: BytePos, +hi: BytePos) {
*self.token = next;
*self.span = mk_sp(lo, hi);
}
fn buffer_length(&self) -> int {
if *self.buffer_start <= *self.buffer_end {
return *self.buffer_end - *self.buffer_start;
}
return (4 - *self.buffer_start) + *self.buffer_end;
}
fn look_ahead(&self, distance: uint) -> token::Token {
let dist = distance as int;
while self.buffer_length() < dist {
self.buffer[*self.buffer_end] = self.reader.next_token();
*self.buffer_end = (*self.buffer_end + 1) & 3;
}
return copy self.buffer[(*self.buffer_start + dist - 1) & 3].tok;
}
fn fatal(&self, m: ~str) -> ! {
self.sess.span_diagnostic.span_fatal(*copy self.span, m)
}
fn span_fatal(&self, sp: span, m: ~str) -> ! {
self.sess.span_diagnostic.span_fatal(sp, m)
}
fn span_note(&self, sp: span, m: ~str) {
self.sess.span_diagnostic.span_note(sp, m)
}
fn bug(&self, m: ~str) -> ! {
self.sess.span_diagnostic.span_bug(*copy self.span, m)
}
fn warn(&self, m: ~str) {
self.sess.span_diagnostic.span_warn(*copy self.span, m)
}
fn span_err(&self, sp: span, m: ~str) {
self.sess.span_diagnostic.span_err(sp, m)
}
fn abort_if_errors(&self) {
self.sess.span_diagnostic.handler().abort_if_errors();
}
fn get_id(&self) -> node_id { next_node_id(self.sess) }
pure fn id_to_str(&self, id: ident) -> @~str {
self.sess.interner.get(id)
}
fn token_is_closure_keyword(&self, tok: &token::Token) -> bool {
self.token_is_keyword(&~"pure", tok) ||
self.token_is_keyword(&~"unsafe", tok) ||
self.token_is_keyword(&~"once", tok) ||
self.token_is_keyword(&~"fn", tok)
}
fn parse_ty_bare_fn(&self) -> ty_
{
/*
extern "ABI" [pure|unsafe] fn <'lt> (S) -> T
^~~~^ ^~~~~~~~~~~~^ ^~~~^ ^~^ ^
| | | | |
| | | | Return type
| | | Argument types
| | Lifetimes
| |
| Purity
ABI
*/
let purity = self.parse_purity();
self.expect_keyword(&~"fn");
return ty_bare_fn(@TyBareFn {
abi: RustAbi,
purity: purity,
decl: self.parse_ty_fn_decl()
});
}
fn parse_ty_closure(&self, pre_sigil: Option<ast::Sigil>,
pre_region_name: Option<ident>) -> ty_
{
/*
(&|~|@) [r/] [pure|unsafe] [once] fn <'lt> (S) -> T
^~~~~~^ ^~~^ ^~~~~~~~~~~~^ ^~~~~^ ^~~~^ ^~^ ^
| | | | | | |
| | | | | | Return type
| | | | | Argument types
| | | | Lifetimes
| | | Once-ness (a.k.a., affine)
| | Purity
| Lifetime bound
Allocation type
*/
// At this point, the allocation type and lifetime bound have been
// parsed.
let purity = self.parse_purity();
let onceness = parse_onceness(self);
self.expect_keyword(&~"fn");
let sigil = match pre_sigil { None => BorrowedSigil, Some(p) => p };
let region = if pre_region_name.is_some() {
Some(self.region_from_name(pre_region_name))
} else {
None
};
return ty_closure(@TyClosure {
sigil: sigil,
region: region,
purity: purity,
onceness: onceness,
decl: self.parse_ty_fn_decl()
});
fn parse_onceness(self: &Parser) -> Onceness {
if self.eat_keyword(&~"once") { Once } else { Many }
}
}
fn parse_purity(&self) -> purity {
if self.eat_keyword(&~"pure") {
return pure_fn;
} else if self.eat_keyword(&~"unsafe") {
return unsafe_fn;
} else {
return impure_fn;
}
}
fn parse_ty_fn_decl(&self) -> fn_decl {
/*
(fn) <'lt> (S) -> T
^~~~^ ^~^ ^
| | |
| | Return type
| Argument types
Lifetimes
*/
if self.eat(&token::LT) {
let _lifetimes = self.parse_lifetimes();
self.expect(&token::GT);
}
let inputs = self.parse_unspanned_seq(
&token::LPAREN,
&token::RPAREN,
seq_sep_trailing_disallowed(token::COMMA),
|p| p.parse_arg_general(false)
);
let (ret_style, ret_ty) = self.parse_ret_ty();
ast::fn_decl { inputs: inputs, output: ret_ty, cf: ret_style }
}
fn parse_trait_methods(&self) -> ~[trait_method] {
do self.parse_unspanned_seq(
&token::LBRACE,
&token::RBRACE,
seq_sep_none()
) |p| {
let attrs = p.parse_outer_attributes();
let lo = p.span.lo;
let is_static = p.parse_staticness();
let static_sty = spanned(lo, p.span.hi, sty_static);
let vis = p.parse_visibility();
let pur = p.parse_fn_purity();
// NB: at the moment, trait methods are public by default; this
// could change.
let ident = p.parse_ident();
let generics = p.parse_generics();
let (self_ty, d) = do self.parse_fn_decl_with_self() |p| {
// This is somewhat dubious; We don't want to allow argument
// names to be left off if there is a definition...
either::Left(p.parse_arg_general(false))
};
// XXX: Wrong. Shouldn't allow both static and self_ty
let self_ty = if is_static { static_sty } else { self_ty };
let hi = p.last_span.hi;
debug!("parse_trait_methods(): trait method signature ends in \
`%s`",
token_to_str(p.reader, © *p.token));
match *p.token {
token::SEMI => {
p.bump();
debug!("parse_trait_methods(): parsing required method");
// NB: at the moment, visibility annotations on required
// methods are ignored; this could change.
required(ty_method {
ident: ident,
attrs: attrs,
purity: pur,
decl: d,
generics: generics,
self_ty: self_ty,
id: p.get_id(),
span: mk_sp(lo, hi)
})
}
token::LBRACE => {
debug!("parse_trait_methods(): parsing provided method");
let (inner_attrs, body) =
p.parse_inner_attrs_and_block(true);
let attrs = vec::append(attrs, inner_attrs);
provided(@ast::method {
ident: ident,
attrs: attrs,
generics: generics,
self_ty: self_ty,
purity: pur,
decl: d,
body: body,
id: p.get_id(),
span: mk_sp(lo, hi),
self_id: p.get_id(),
vis: vis,
})
}
_ => {
p.fatal(
fmt!(
"expected `;` or `}` but found `%s`",
token_to_str(p.reader, © *p.token)
)
);
}
}
}
}
fn parse_mt(&self) -> mt {
let mutbl = self.parse_mutability();
let t = self.parse_ty(false);
mt { ty: t, mutbl: mutbl }
}
fn parse_ty_field(&self) -> ty_field {
let lo = self.span.lo;
let mutbl = self.parse_mutability();
let id = self.parse_ident();
self.expect(&token::COLON);
let ty = self.parse_ty(false);
spanned(
lo,
ty.span.hi,
ast::ty_field_ {
ident: id,
mt: ast::mt { ty: ty, mutbl: mutbl },
}
)
}
fn parse_ret_ty(&self) -> (ret_style, @Ty) {
return if self.eat(&token::RARROW) {
let lo = self.span.lo;
if self.eat(&token::NOT) {
(
noreturn,
@Ty {
id: self.get_id(),
node: ty_bot,
span: mk_sp(lo, self.last_span.hi)
}
)
} else {
(return_val, self.parse_ty(false))
}
} else {
let pos = self.span.lo;
(
return_val,
@Ty {
id: self.get_id(),
node: ty_nil,
span: mk_sp(pos, pos),
}
)
}
}
fn region_from_name(&self, s: Option<ident>) -> @region {
let r = match s {
Some(id) if id == special_idents::static => ast::re_static,
Some(id) if id == special_idents::self_ => re_self,
Some(id) => re_named(id),
None => re_anon
};
@ast::region { id: self.get_id(), node: r }
}
// Parses something like "&x"
fn parse_region(&self) -> @region {
self.expect(&token::BINOP(token::AND));
match *self.token {
token::IDENT(sid, _) => {
self.bump();
self.region_from_name(Some(sid))
}
_ => {
self.region_from_name(None)
}
}
}
fn parse_ty(&self, colons_before_params: bool) -> @Ty {
maybe_whole!(self, nt_ty);
let lo = self.span.lo;
let t = if *self.token == token::LPAREN {
self.bump();
if *self.token == token::RPAREN {
self.bump();
ty_nil
} else {
// (t) is a parenthesized ty
// (t,) is the type of a tuple with only one field,
// of type t
let mut ts = ~[self.parse_ty(false)];
let mut one_tuple = false;
while *self.token == token::COMMA {
self.bump();
if *self.token != token::RPAREN {
ts.push(self.parse_ty(false));
}
else {
one_tuple = true;
}
}
let t = if ts.len() == 1 && !one_tuple {
copy ts[0].node
} else {
ty_tup(ts)
};
self.expect(&token::RPAREN);
t
}
} else if *self.token == token::AT {
self.bump();
self.parse_box_or_uniq_pointee(ManagedSigil, ty_box)
} else if *self.token == token::TILDE {
self.bump();
self.parse_box_or_uniq_pointee(OwnedSigil, ty_uniq)
} else if *self.token == token::BINOP(token::STAR) {
self.bump();
ty_ptr(self.parse_mt())
} else if *self.token == token::LBRACE {
let elems = self.parse_unspanned_seq(
&token::LBRACE,
&token::RBRACE,
seq_sep_trailing_allowed(token::COMMA),
|p| p.parse_ty_field()
);
if elems.len() == 0 {
self.unexpected_last(&token::RBRACE);
}
ty_rec(elems)
} else if *self.token == token::LBRACKET {
self.expect(&token::LBRACKET);
let mt = self.parse_mt();
if mt.mutbl == m_mutbl { // `m_const` too after snapshot
self.obsolete(*self.last_span, ObsoleteMutVector);
}
// Parse the `* 3` in `[ int * 3 ]`
let t = match self.maybe_parse_fixed_vstore_with_star() {
None => ty_vec(mt),
Some(suffix) => ty_fixed_length_vec(mt, suffix)
};
self.expect(&token::RBRACKET);
t
} else if *self.token == token::BINOP(token::AND) {
self.bump();
self.parse_borrowed_pointee()
} else if self.eat_keyword(&~"extern") {
self.parse_ty_bare_fn()
} else if self.token_is_closure_keyword(© *self.token) {
self.parse_ty_closure(None, None)
} else if *self.token == token::MOD_SEP
|| is_ident_or_path(&*self.token) {
let path = self.parse_path_with_tps(colons_before_params);
ty_path(path, self.get_id())
} else {
self.fatal(~"expected type");
};
let sp = mk_sp(lo, self.last_span.hi);
@Ty {id: self.get_id(), node: t, span: sp}
}
fn parse_box_or_uniq_pointee(
&self,
sigil: ast::Sigil,
ctor: &fn(+v: mt) -> ty_) -> ty_
{
// @'foo fn() or @foo/fn() or @fn() are parsed directly as fn types:
match *self.token {
token::LIFETIME(rname) => {
self.bump();
return self.parse_ty_closure(Some(sigil), Some(rname));
}
token::IDENT(rname, _) => {
if self.look_ahead(1u) == token::BINOP(token::SLASH) &&
self.token_is_closure_keyword(&self.look_ahead(2u))
{
self.bump();
self.bump();
return self.parse_ty_closure(Some(sigil), Some(rname));
} else if self.token_is_closure_keyword(© *self.token) {
return self.parse_ty_closure(Some(sigil), None);
}
}
_ => {}
}
// other things are parsed as @ + a type. Note that constructs like
// @[] and @str will be resolved during typeck to slices and so forth,
// rather than boxed ptrs. But the special casing of str/vec is not
// reflected in the AST type.
let mt = self.parse_mt();
if mt.mutbl != m_imm && sigil == OwnedSigil {
self.obsolete(*self.last_span, ObsoleteMutOwnedPointer);
}
ctor(mt)
}
fn parse_borrowed_pointee(&self) -> ty_ {
// look for `&'lt` or `&foo/` and interpret `foo` as the region name:
let rname = match *self.token {
token::LIFETIME(sid) => {
self.bump();
Some(sid)
}
token::IDENT(sid, _) => {
if self.look_ahead(1u) == token::BINOP(token::SLASH) {
self.bump(); self.bump();
Some(sid)
} else {
None
}
}
_ => { None }
};
if self.token_is_closure_keyword(© *self.token) {
return self.parse_ty_closure(Some(BorrowedSigil), rname);
}
let r = self.region_from_name(rname);
let mt = self.parse_mt();
return ty_rptr(r, mt);
}
fn parse_arg_mode(&self) -> mode {
if self.eat(&token::BINOP(token::MINUS)) {
expl(by_copy) // NDM outdated syntax
} else if self.eat(&token::ANDAND) {
expl(by_ref)
} else if self.eat(&token::BINOP(token::PLUS)) {
if self.eat(&token::BINOP(token::PLUS)) {
expl(by_val)
} else {
expl(by_copy)
}
} else {
infer(self.get_id())
}
}
fn is_named_argument(&self) -> bool {
let offset = if *self.token == token::BINOP(token::AND) {
1
} else if *self.token == token::BINOP(token::MINUS) {
1
} else if *self.token == token::ANDAND {
1
} else if *self.token == token::BINOP(token::PLUS) {
if self.look_ahead(1) == token::BINOP(token::PLUS) {
2
} else {
1
}
} else { 0 };
if offset == 0 {
is_plain_ident(&*self.token)
&& self.look_ahead(1) == token::COLON
} else {
is_plain_ident(&self.look_ahead(offset))
&& self.look_ahead(offset + 1) == token::COLON
}
}
// This version of parse arg doesn't necessarily require
// identifier names.
fn parse_arg_general(&self, require_name: bool) -> arg {
let mut m;
let mut is_mutbl = false;
let pat = if require_name || self.is_named_argument() {
m = self.parse_arg_mode();
is_mutbl = self.eat_keyword(&~"mut");
let pat = self.parse_pat(false);
self.expect(&token::COLON);
pat
} else {
m = infer(self.get_id());
ast_util::ident_to_pat(self.get_id(),
*self.last_span,
special_idents::invalid)
};
let t = self.parse_ty(false);
ast::arg { mode: m, is_mutbl: is_mutbl,
ty: t, pat: pat, id: self.get_id() }
}
fn parse_arg(&self) -> arg_or_capture_item {
either::Left(self.parse_arg_general(true))
}
fn parse_fn_block_arg(&self) -> arg_or_capture_item {
let m = self.parse_arg_mode();
let is_mutbl = self.eat_keyword(&~"mut");
let pat = self.parse_pat(false);
let t = if self.eat(&token::COLON) {
self.parse_ty(false)
} else {
@Ty {
id: self.get_id(),
node: ty_infer,
span: mk_sp(self.span.lo, self.span.hi),
}
};
either::Left(ast::arg {
mode: m,
is_mutbl: is_mutbl,
ty: t,
pat: pat,
id: self.get_id()
})
}
fn maybe_parse_fixed_vstore_with_star(&self) -> Option<uint> {
if self.eat(&token::BINOP(token::STAR)) {
match *self.token {
token::LIT_INT_UNSUFFIXED(i) if i >= 0i64 => {
self.bump();
Some(i as uint)
}
_ => {
self.fatal(
fmt!(
"expected integral vector length \
but found `%s`",
token_to_str(self.reader, © *self.token)
)
);
}
}
} else {
None
}
}
fn lit_from_token(&self, tok: &token::Token) -> lit_ {
match *tok {
token::LIT_INT(i, it) => lit_int(i, it),
token::LIT_UINT(u, ut) => lit_uint(u, ut),
token::LIT_INT_UNSUFFIXED(i) => lit_int_unsuffixed(i),
token::LIT_FLOAT(s, ft) => lit_float(self.id_to_str(s), ft),
token::LIT_FLOAT_UNSUFFIXED(s) =>
lit_float_unsuffixed(self.id_to_str(s)),
token::LIT_STR(s) => lit_str(self.id_to_str(s)),
token::LPAREN => { self.expect(&token::RPAREN); lit_nil },
_ => { self.unexpected_last(tok); }
}
}
fn parse_lit(&self) -> lit {
let lo = self.span.lo;
let lit = if self.eat_keyword(&~"true") {
lit_bool(true)
} else if self.eat_keyword(&~"false") {
lit_bool(false)
} else {
// XXX: This is a really bad copy!
let tok = copy *self.token;
self.bump();
self.lit_from_token(&tok)
};
codemap::spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
}
// parse a path that doesn't have type parameters attached
fn parse_path_without_tps(&self)
-> @ast::path {
maybe_whole!(self, nt_path);
let lo = self.span.lo;
let global = self.eat(&token::MOD_SEP);
let mut ids = ~[];
loop {
let is_not_last =
self.look_ahead(2u) != token::LT
&& self.look_ahead(1u) == token::MOD_SEP;
if is_not_last {
ids.push(self.parse_ident());
self.expect(&token::MOD_SEP);
} else {
ids.push(self.parse_ident());
break;
}
}
@ast::path { span: mk_sp(lo, self.last_span.hi),
global: global,
idents: ids,
rp: None,
types: ~[] }
}
fn parse_path_with_tps(&self, colons: bool) -> @ast::path {
debug!("parse_path_with_tps(colons=%b)", colons);
maybe_whole!(self, nt_path);
let lo = self.span.lo;
let path = self.parse_path_without_tps();
if colons && !self.eat(&token::MOD_SEP) {
return path;
}
// Parse the region parameter, if any, which will
// be written "foo/&x"
let rp = {
// Hack: avoid parsing vstores like /@ and /~. This is painful
// because the notation for region bounds and the notation for
// vstores is... um... the same. I guess that's my fault. This
// is still not ideal as for &str we end up parsing more than we
// ought to and have to sort it out later.
if *self.token == token::BINOP(token::SLASH)
&& self.look_ahead(1u) == token::BINOP(token::AND) {
self.expect(&token::BINOP(token::SLASH));
Some(self.parse_region())
} else {
None
}
};
// Parse any lifetime or type parameters which may appear:
let tps = self.parse_generic_values();
let hi = self.span.lo;
@ast::path { span: mk_sp(lo, hi),
rp: rp,
types: tps,
.. copy *path }
}
fn parse_opt_lifetime(&self) -> Option<ast::Lifetime> {
/*!
*
* Parses 0 or 1 lifetime.
*/
match *self.token {
token::LIFETIME(_) => {
Some(self.parse_lifetime())
}
_ => {
None
}
}
}
fn parse_lifetime(&self) -> ast::Lifetime {
/*!
*
* Parses a single lifetime.
*/
match *self.token {
token::LIFETIME(i) => {
self.bump();
return ast::Lifetime {
id: self.get_id(),
span: *self.span,
ident: i
};
}
_ => {
self.fatal(fmt!("Expected a lifetime name"));
}
}
}
fn parse_lifetimes(&self) -> OptVec<ast::Lifetime> {
/*!
*