parser.rs 82.6 KB
Newer Older
1

2
import std::io;
3
import std::ivec;
4 5
import std::vec;
import std::str;
6 7 8
import std::option;
import std::option::some;
import std::option::none;
9 10 11
import std::either;
import std::either::left;
import std::either::right;
12
import std::map::hashmap;
13
import token::can_begin_expr;
14 15
import ex=ext::base;
import codemap::span;
16
import std::map::new_str_hash;
17
import util::interner;
18

19
tag restriction { UNRESTRICTED; RESTRICT_NO_CALL_EXPRS; }
20

21
tag file_type { CRATE_FILE; SOURCE_FILE; }
22

23 24 25 26 27 28 29 30 31 32
tag ty_or_bang { a_ty(@ast::ty); a_bang; }

type parse_sess = @rec(codemap::codemap cm,
                       mutable ast::node_id next_id);

fn next_node_id(&parse_sess sess) -> ast::node_id {
    auto rv = sess.next_id;
    sess.next_id += 1;
    ret rv;
}
33

34 35 36 37
type parser =
    obj {
        fn peek() -> token::token ;
        fn bump() ;
38
        fn fatal(str) -> !  ;
39
        fn warn(str);
40 41 42
        fn restrict(restriction) ;
        fn get_restriction() -> restriction ;
        fn get_file_type() -> file_type ;
43
        fn get_cfg() -> ast::crate_cfg;
44
        fn get_span() -> span ;
45 46 47 48 49 50 51 52
        fn get_lo_pos() -> uint ;
        fn get_hi_pos() -> uint ;
        fn get_last_lo_pos() -> uint ;
        fn get_prec_table() -> vec[op_spec] ;
        fn get_str(token::str_num) -> str ;
        fn get_reader() -> lexer::reader ;
        fn get_filemap() -> codemap::filemap ;
        fn get_bad_expr_words() -> hashmap[str, ()] ;
53
        fn get_syntax_expanders() -> hashmap[str, ex::syntax_extension] ;
54
        fn get_chpos() -> uint ;
55
        fn get_id() -> ast::node_id ;
56
        fn get_sess() -> parse_sess;
57 58
    };

59 60 61
fn new_parser(parse_sess sess, ast::crate_cfg cfg,
              str path, uint pos) -> parser {
    obj stdio_parser(parse_sess sess,
62
                     ast::crate_cfg cfg,
63 64 65 66 67
                     file_type ftype,
                     mutable token::token tok,
                     mutable uint lo,
                     mutable uint hi,
                     mutable uint last_lo,
68
                     mutable restriction restr,
69 70 71
                     lexer::reader rdr,
                     vec[op_spec] precs,
                     hashmap[str, ()] bad_words,
72
                     hashmap[str, ex::syntax_extension] syntax_expanders) {
73 74 75 76 77 78 79 80 81 82
        fn peek() -> token::token { ret tok; }
        fn bump() {
            // log rdr.get_filename()
            //   + ":" + common::istr(lo.line as int);

            last_lo = lo;
            tok = lexer::next_token(rdr);
            lo = rdr.get_mark_chpos();
            hi = rdr.get_chpos();
        }
83 84 85 86 87 88 89
        fn fatal(str m) -> ! {
            codemap::emit_error(some(self.get_span()), m, sess.cm);
            fail;
        }
        fn warn(str m) {
            codemap::emit_warning(some(self.get_span()), m, sess.cm);
        }
90 91
        fn restrict(restriction r) { restr = r; }
        fn get_restriction() -> restriction { ret restr; }
92
        fn get_span() -> span { ret rec(lo=lo, hi=hi); }
93 94 95 96
        fn get_lo_pos() -> uint { ret lo; }
        fn get_hi_pos() -> uint { ret hi; }
        fn get_last_lo_pos() -> uint { ret last_lo; }
        fn get_file_type() -> file_type { ret ftype; }
97
        fn get_cfg() -> ast::crate_cfg { ret cfg; }
98 99 100 101 102 103 104
        fn get_prec_table() -> vec[op_spec] { ret precs; }
        fn get_str(token::str_num i) -> str {
            ret interner::get(*rdr.get_interner(), i);
        }
        fn get_reader() -> lexer::reader { ret rdr; }
        fn get_filemap() -> codemap::filemap { ret rdr.get_filemap(); }
        fn get_bad_expr_words() -> hashmap[str, ()] { ret bad_words; }
105
        fn get_syntax_expanders() -> hashmap[str, ex::syntax_extension] {
106 107 108
            ret syntax_expanders;
        }
        fn get_chpos() -> uint { ret rdr.get_chpos(); }
109 110
        fn get_id() -> ast::node_id { ret next_node_id(sess); }
        fn get_sess() -> parse_sess { ret sess; }
111
    }
112

113 114
    auto ftype = SOURCE_FILE;
    if (str::ends_with(path, ".rc")) { ftype = CRATE_FILE; }
115 116
    auto srdr = io::file_reader(path);
    auto filemap = codemap::new_filemap(path, pos);
117
    vec::push(sess.cm.files, filemap);
118
    auto itr = @interner::mk(str::hash, str::eq);
119
    auto rdr = lexer::new_reader(sess.cm, srdr, filemap, itr);
120
    // Make sure npos points at first actual token:
121

G
Graydon Hoare 已提交
122
    lexer::consume_whitespace_and_comments(rdr);
123
    auto npos = rdr.get_chpos();
124
    ret stdio_parser(sess, cfg, ftype, lexer::next_token(rdr),
125
                     npos, npos, npos, UNRESTRICTED, rdr,
126 127
                     prec_table(), bad_expr_word_table(),
                     ex::syntax_expander_table());
128 129 130 131 132
}

// These are the words that shouldn't be allowed as value identifiers,
// because, if used at the start of a line, they will cause the line to be
// interpreted as a specific kind of statement, which would be confusing.
133
fn bad_expr_word_table() -> hashmap[str, ()] {
134
    auto words = new_str_hash();
135 136 137 138 139 140 141 142 143 144 145 146 147 148
    words.insert("mod", ());
    words.insert("if", ());
    words.insert("else", ());
    words.insert("while", ());
    words.insert("do", ());
    words.insert("alt", ());
    words.insert("for", ());
    words.insert("break", ());
    words.insert("cont", ());
    words.insert("put", ());
    words.insert("ret", ());
    words.insert("be", ());
    words.insert("fail", ());
    words.insert("type", ());
149
    words.insert("resource", ());
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    words.insert("check", ());
    words.insert("assert", ());
    words.insert("claim", ());
    words.insert("prove", ());
    words.insert("state", ());
    words.insert("gc", ());
    words.insert("native", ());
    words.insert("auto", ());
    words.insert("fn", ());
    words.insert("pred", ());
    words.insert("iter", ());
    words.insert("import", ());
    words.insert("export", ());
    words.insert("let", ());
    words.insert("const", ());
    words.insert("log", ());
    words.insert("log_err", ());
    words.insert("tag", ());
    words.insert("obj", ());
    ret words;
170 171
}

172
fn unexpected(&parser p, token::token t) -> ! {
G
Graydon Hoare 已提交
173
    let str s = "unexpected token: ";
174
    s += token::to_str(p.get_reader(), t);
175
    p.fatal(s);
G
Graydon Hoare 已提交
176 177
}

178
fn expect(&parser p, token::token t) {
179
    if (p.peek() == t) {
180 181 182
        p.bump();
    } else {
        let str s = "expecting ";
183
        s += token::to_str(p.get_reader(), t);
184
        s += ", found ";
185
        s += token::to_str(p.get_reader(), p.peek());
186
        p.fatal(s);
187 188 189
    }
}

190
fn spanned[T](uint lo, uint hi, &T node) -> ast::spanned[T] {
191
    ret rec(node=node, span=rec(lo=lo, hi=hi));
192 193
}

194
fn parse_ident(&parser p) -> ast::ident {
195
    alt (p.peek()) {
196
        case (token::IDENT(?i, _)) { p.bump(); ret p.get_str(i); }
197
        case (_) { p.fatal("expecting ident"); fail; }
198 199
    }
}
200

201
fn parse_value_ident(&parser p) -> ast::ident {
202 203 204
    check_bad_word(p);
    ret parse_ident(p);
}
205

206 207
fn is_word(&parser p, &str word) -> bool {
    ret alt (p.peek()) {
208 209 210
            case (token::IDENT(?sid, false)) { str::eq(word, p.get_str(sid)) }
            case (_) { false }
        };
211
}
212

213 214
fn eat_word(&parser p, &str word) -> bool {
    alt (p.peek()) {
215
        case (token::IDENT(?sid, false)) {
216
            if (str::eq(word, p.get_str(sid))) {
217 218 219 220 221 222 223
                p.bump();
                ret true;
            } else { ret false; }
        }
        case (_) { ret false; }
    }
}
224

225 226
fn expect_word(&parser p, &str word) {
    if (!eat_word(p, word)) {
227
        p.fatal("expecting " + word + ", found " +
228
                  token::to_str(p.get_reader(), p.peek()));
229 230
    }
}
231

232 233
fn check_bad_word(&parser p) {
    alt (p.peek()) {
234
        case (token::IDENT(?sid, false)) {
235 236
            auto w = p.get_str(sid);
            if (p.get_bad_expr_words().contains_key(w)) {
237
                p.fatal("found " + w + " in expression position");
238 239
            }
        }
240
        case (_) { }
241 242
    }
}
243

244
fn parse_ty_fn(ast::proto proto, &parser p, uint lo) -> ast::ty_ {
245 246
    fn parse_fn_input_ty(&parser p) -> ast::ty_arg {
        auto lo = p.get_lo_pos();
247
        auto mode = ast::val;
248
        if (p.peek() == token::BINOP(token::AND)) {
P
Patrick Walton 已提交
249
            p.bump();
250
            mode = ast::alias(eat_word(p, "mutable"));
P
Patrick Walton 已提交
251 252 253
        }
        auto t = parse_ty(p);
        alt (p.peek()) {
254 255
            case (token::IDENT(_, _)) { p.bump();/* ignore param name */ }
            case (_) {/* no param name present */ }
P
Patrick Walton 已提交
256
        }
257
        ret spanned(lo, t.span.hi, rec(mode=mode, ty=t));
P
Patrick Walton 已提交
258
    }
259
    auto lo = p.get_lo_pos();
260 261 262
    auto inputs =
        parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                  parse_fn_input_ty, p);
263
    auto constrs = parse_constrs([], p);
264
    let @ast::ty output;
265
    auto cf = ast::return;
266
    if (p.peek() == token::RARROW) {
P
Patrick Walton 已提交
267
        p.bump();
268 269
        auto tmp = parse_ty_or_bang(p);
        alt (tmp) {
270
            case (a_ty(?t)) { output = t; }
271
            case (a_bang) {
272 273 274 275
                output = @spanned(lo, inputs.span.hi, ast::ty_bot);
                cf = ast::noreturn;
            }
        }
276
    } else { output = @spanned(lo, inputs.span.hi, ast::ty_nil); }
277
    ret ast::ty_fn(proto, inputs.node, output, cf, constrs.node);
278 279
}

280
fn parse_proto(&parser p) -> ast::proto {
281 282 283 284 285 286 287
    if (eat_word(p, "iter")) {
        ret ast::proto_iter;
    } else if (eat_word(p, "fn")) {
        ret ast::proto_fn;
    } else if (eat_word(p, "pred")) {
        ret ast::proto_fn;
    } else { unexpected(p, p.peek()); }
P
Patrick Walton 已提交
288
}
289

290 291
fn parse_ty_obj(&parser p, &mutable uint hi) -> ast::ty_ {
    fn parse_method_sig(&parser p) -> ast::ty_method {
292
        auto flo = p.get_lo_pos();
293
        let ast::proto proto = parse_proto(p);
294
        auto ident = parse_value_ident(p);
G
Graydon Hoare 已提交
295
        auto f = parse_ty_fn(proto, p, flo);
296
        expect(p, token::SEMI);
G
Graydon Hoare 已提交
297
        alt (f) {
298
            case (ast::ty_fn(?proto, ?inputs, ?output, ?cf, ?constrs)) {
299
                ret spanned(flo, output.span.hi,
300 301 302 303 304
                            rec(proto=proto,
                                ident=ident,
                                inputs=inputs,
                                output=output,
                                cf=cf,
305
                                constrs=constrs));
G
Graydon Hoare 已提交
306 307 308 309 310
            }
        }
        fail;
    }
    auto f = parse_method_sig;
311
    auto meths = parse_seq(token::LBRACE, token::RBRACE, none, f, p);
312
    hi = meths.span.hi;
313
    ret ast::ty_obj(meths.node);
G
Graydon Hoare 已提交
314 315
}

316
fn parse_mt(&parser p) -> ast::mt {
317 318 319 320 321
    auto mut = parse_mutability(p);
    auto t = parse_ty(p);
    ret rec(ty=t, mut=mut);
}

322
fn parse_ty_field(&parser p) -> ast::ty_field {
323
    auto lo = p.get_lo_pos();
324
    auto mt = parse_mt(p);
G
Graydon Hoare 已提交
325
    auto id = parse_ident(p);
326
    ret spanned(lo, mt.ty.span.hi, rec(ident=id, mt=mt));
G
Graydon Hoare 已提交
327 328
}

329

330 331 332 333
// if i is the jth ident in args, return j
// otherwise, fail
fn ident_index(&parser p, &vec[ast::arg] args, &ast::ident i) -> uint {
    auto j = 0u;
334
    for (ast::arg a in args) { if (a.ident == i) { ret j; } j += 1u; }
335
    p.fatal("Unbound variable " + i + " in constraint arg");
336 337 338
}

fn parse_constr_arg(vec[ast::arg] args, &parser p) -> @ast::constr_arg {
339
    auto sp = p.get_span();
340 341
    auto carg = ast::carg_base;
    if (p.peek() == token::BINOP(token::STAR)) {
342 343
        p.bump();
    } else {
344 345
        let ast::ident i = parse_value_ident(p);
        carg = ast::carg_ident(ident_index(p, args, i));
346
    }
347
    ret @rec(node=carg, span=sp);
348 349
}

350
fn parse_ty_constr(&vec[ast::arg] fn_args, &parser p) -> @ast::constr {
351
    auto lo = p.get_lo_pos();
352
    auto path = parse_path(p);
353 354
    auto pf = bind parse_constr_arg(fn_args, _);
    let rec(vec[@ast::constr_arg] node, span span) args =
355
        parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA), pf, p);
356
    // FIXME fix the def_id
357

358
    ret @spanned(lo, args.span.hi,
359
                 rec(path=path, args=args.node, id=p.get_id()));
360 361
}

362

363 364 365
// Use the args list to translate each bound variable 
// mentioned in a constraint to an arg index.
// Seems weird to do this in the parser, but I'm not sure how else to.
366
fn parse_constrs(&vec[ast::arg] args, &parser p) ->
367
    ast::spanned[vec[@ast::constr]] {
368 369
    auto lo = p.get_lo_pos();
    auto hi = p.get_hi_pos();
370
    let vec[@ast::constr] constrs = [];
371
    if (p.peek() == token::COLON) {
372
        p.bump();
373
        while (true) {
374
            auto constr = parse_ty_constr(args, p);
375
            hi = constr.span.hi;
376
            vec::push(constrs, constr);
377
            if (p.peek() == token::COMMA) { p.bump(); } else { break; }
378 379
        }
    }
380
    ret spanned(lo, hi, constrs);
381 382
}

383
fn parse_ty_constrs(@ast::ty t, &parser p) -> @ast::ty {
384 385 386 387 388 389
    if (p.peek() == token::COLON) {
        auto constrs = parse_constrs([], p);
        ret @spanned(t.span.lo, constrs.span.hi,
                     ast::ty_constr(t, constrs.node));
    }
    ret t;
390 391
}

392 393 394 395 396 397 398
fn parse_ty_postfix(@ast::ty orig_t, &parser p) -> @ast::ty {
    auto lo = p.get_lo_pos();
    if (p.peek() == token::LBRACKET) {
        p.bump();

        auto mut;
        if (eat_word(p, "mutable")) {
P
Patrick Walton 已提交
399 400 401 402 403 404
            if (p.peek() == token::QUES) {
                p.bump();
                mut = ast::maybe_mut;
            } else {
                mut = ast::mut;
            }
405 406 407 408
        } else {
            mut = ast::imm;
        }

409 410 411 412
        if (mut == ast::imm && p.peek() != token::RBRACKET) {
            // This is explicit type parameter instantiation.
            auto seq = parse_seq_to_end(token::RBRACKET, some(token::COMMA),
                                        parse_ty, p);
413 414 415 416 417

            // FIXME: Remove this vec->ivec conversion.
            auto seq_ivec = ~[];
            for (@ast::ty typ in seq) { seq_ivec += ~[typ]; }

418 419 420 421 422 423
            alt (orig_t.node) {
                case (ast::ty_path(?pth, ?ann)) {
                    auto hi = p.get_hi_pos();
                    ret @spanned(lo, hi,
                                 ast::ty_path(spanned(lo, hi,
                                              rec(idents=pth.node.idents,
424
                                                  types=seq_ivec)),
425 426 427
                                              ann));
                }
                case (_) {
428
                    p.fatal("type parameter instantiation only allowed for " +
429 430 431 432 433
                          "paths");
                }
            }
        }

434 435 436 437 438 439 440 441
        expect(p, token::RBRACKET);
        auto hi = p.get_hi_pos();
        auto t = ast::ty_ivec(rec(ty=orig_t, mut=mut));
        ret parse_ty_postfix(@spanned(lo, hi, t), p);
    }
    ret parse_ty_constrs(orig_t, p);
}

442
fn parse_ty_or_bang(&parser p) -> ty_or_bang {
443
    alt (p.peek()) {
444
        case (token::NOT) { p.bump(); ret a_bang; }
445
        case (_) { ret a_ty(parse_ty(p)); }
446 447 448
    }
}

449
fn parse_ty(&parser p) -> @ast::ty {
450
    auto lo = p.get_lo_pos();
451
    auto hi = lo;
452
    let ast::ty_ t;
453
    // FIXME: do something with this
454

T
Tim Chevalier 已提交
455
    parse_layer(p);
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    if (eat_word(p, "bool")) {
        t = ast::ty_bool;
    } else if (eat_word(p, "int")) {
        t = ast::ty_int;
    } else if (eat_word(p, "uint")) {
        t = ast::ty_uint;
    } else if (eat_word(p, "float")) {
        t = ast::ty_float;
    } else if (eat_word(p, "str")) {
        t = ast::ty_str;
    } else if (eat_word(p, "istr")) {
        t = ast::ty_istr;
    } else if (eat_word(p, "char")) {
        t = ast::ty_char;
    } else if (eat_word(p, "task")) {
        t = ast::ty_task;
    } else if (eat_word(p, "i8")) {
473
        t = ast::ty_machine(ast::ty_i8);
474
    } else if (eat_word(p, "i16")) {
475
        t = ast::ty_machine(ast::ty_i16);
476
    } else if (eat_word(p, "i32")) {
477
        t = ast::ty_machine(ast::ty_i32);
478
    } else if (eat_word(p, "i64")) {
479
        t = ast::ty_machine(ast::ty_i64);
480
    } else if (eat_word(p, "u8")) {
481
        t = ast::ty_machine(ast::ty_u8);
482
    } else if (eat_word(p, "u16")) {
483
        t = ast::ty_machine(ast::ty_u16);
484
    } else if (eat_word(p, "u32")) {
485
        t = ast::ty_machine(ast::ty_u32);
486
    } else if (eat_word(p, "u64")) {
487
        t = ast::ty_machine(ast::ty_u64);
488
    } else if (eat_word(p, "f32")) {
489
        t = ast::ty_machine(ast::ty_f32);
490
    } else if (eat_word(p, "f64")) {
491
        t = ast::ty_machine(ast::ty_f64);
492
    } else if (p.peek() == token::LPAREN) {
493 494 495 496 497 498
        p.bump();
        alt (p.peek()) {
            case (token::RPAREN) {
                hi = p.get_hi_pos();
                p.bump();
                t = ast::ty_nil;
499
            }
500 501 502 503
            case (_) {
                t = parse_ty(p).node;
                hi = p.get_hi_pos();
                expect(p, token::RPAREN);
504 505
            }
        }
506 507 508 509 510
    } else if (p.peek() == token::AT) {
        p.bump();
        auto mt = parse_mt(p);
        hi = mt.ty.span.hi;
        t = ast::ty_box(mt);
511 512 513 514 515
    } else if (p.peek() == token::BINOP(token::STAR)) {
        p.bump();
        auto mt = parse_mt(p);
        hi = mt.ty.span.hi;
        t = ast::ty_ptr(mt);
516 517 518 519 520 521
    } else if (eat_word(p, "vec")) {
        expect(p, token::LBRACKET);
        t = ast::ty_vec(parse_mt(p));
        hi = p.get_hi_pos();
        expect(p, token::RBRACKET);
    } else if (eat_word(p, "tup")) {
522 523 524
        auto elems =
            parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                      parse_mt, p);
525 526 527 528
        hi = elems.span.hi;
        t = ast::ty_tup(elems.node);
    } else if (eat_word(p, "rec")) {
        auto elems =
529 530
            parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                      parse_ty_field, p);
531 532 533 534 535
        hi = elems.span.hi;
        t = ast::ty_rec(elems.node);
    } else if (eat_word(p, "fn")) {
        auto flo = p.get_last_lo_pos();
        t = parse_ty_fn(ast::proto_fn, p, flo);
536
        alt (t) { case (ast::ty_fn(_, _, ?out, _, _)) { hi = out.span.hi; } }
537 538 539
    } else if (eat_word(p, "iter")) {
        auto flo = p.get_last_lo_pos();
        t = parse_ty_fn(ast::proto_iter, p, flo);
540
        alt (t) { case (ast::ty_fn(_, _, ?out, _, _)) { hi = out.span.hi; } }
541 542 543 544 545 546 547 548 549 550 551 552 553
    } else if (eat_word(p, "obj")) {
        t = parse_ty_obj(p, hi);
    } else if (eat_word(p, "port")) {
        expect(p, token::LBRACKET);
        t = ast::ty_port(parse_ty(p));
        hi = p.get_hi_pos();
        expect(p, token::RBRACKET);
    } else if (eat_word(p, "chan")) {
        expect(p, token::LBRACKET);
        t = ast::ty_chan(parse_ty(p));
        hi = p.get_hi_pos();
        expect(p, token::RBRACKET);
    } else if (eat_word(p, "mutable")) {
554
        p.warn("ignoring deprecated 'mutable' type constructor");
555 556 557 558 559
        auto typ = parse_ty(p);
        t = typ.node;
        hi = typ.span.hi;
    } else if (is_ident(p.peek())) {
        auto path = parse_path(p);
560
        t = ast::ty_path(path, p.get_id());
561
        hi = path.span.hi;
562
    } else { p.fatal("expecting type"); t = ast::ty_nil; fail; }
563
    ret parse_ty_postfix(@spanned(lo, hi, t), p);
564 565
}

566
fn parse_arg(&parser p) -> ast::arg {
567 568
    let ast::mode m = ast::val;
    if (p.peek() == token::BINOP(token::AND)) {
569
        p.bump();
570
        m = ast::alias(eat_word(p, "mutable"));
571
    }
572
    let @ast::ty t = parse_ty(p);
573
    let ast::ident i = parse_value_ident(p);
574
    ret rec(mode=m, ty=t, ident=i, id=p.get_id());
575 576
}

577 578
fn parse_seq_to_end[T](token::token ket, option::t[token::token] sep,
                       fn(&parser) -> T  f, &parser p) -> vec[T] {
579
    let bool first = true;
580
    let vec[T] v = [];
581
    while (p.peek() != ket) {
582
        alt (sep) {
583
            case (some(?t)) {
584
                if (first) { first = false; } else { expect(p, t); }
585
            }
586
            case (_) { }
587
        }
588
        v += [f(p)];
589 590
    }
    expect(p, ket);
591 592 593
    ret v;
}

594 595
fn parse_seq[T](token::token bra, token::token ket,
                option::t[token::token] sep, fn(&parser) -> T  f, &parser p)
596
   -> ast::spanned[vec[T]] {
597
    auto lo = p.get_lo_pos();
598
    expect(p, bra);
599 600
    auto result = parse_seq_to_end[T](ket, sep, f, p);
    auto hi = p.get_hi_pos();
601
    ret spanned(lo, hi, result);
602 603
}

604
fn parse_lit(&parser p) -> ast::lit {
605
    auto sp = p.get_span();
606
    let ast::lit_ lit = ast::lit_nil;
607 608 609 610 611 612
    if (eat_word(p, "true")) {
        lit = ast::lit_bool(true);
    } else if (eat_word(p, "false")) {
        lit = ast::lit_bool(false);
    } else {
        alt (p.peek()) {
613 614
            case (token::LIT_INT(?i)) { p.bump(); lit = ast::lit_int(i); }
            case (token::LIT_UINT(?u)) { p.bump(); lit = ast::lit_uint(u); }
615 616 617 618 619 620 621 622 623 624 625 626
            case (token::LIT_FLOAT(?s)) {
                p.bump();
                lit = ast::lit_float(p.get_str(s));
            }
            case (token::LIT_MACH_INT(?tm, ?i)) {
                p.bump();
                lit = ast::lit_mach_int(tm, i);
            }
            case (token::LIT_MACH_FLOAT(?tm, ?s)) {
                p.bump();
                lit = ast::lit_mach_float(tm, p.get_str(s));
            }
627
            case (token::LIT_CHAR(?c)) { p.bump(); lit = ast::lit_char(c); }
628 629
            case (token::LIT_STR(?s)) {
                p.bump();
630
                lit = ast::lit_str(p.get_str(s), ast::sk_rc);
631
            }
632
            case (?t) { unexpected(p, t); }
633
        }
634
    }
635
    ret rec(node=lit, span=sp);
636
}
637

638
fn is_ident(token::token t) -> bool {
639
    alt (t) { case (token::IDENT(_, _)) { ret true; } case (_) { } }
640 641 642
    ret false;
}

643
fn parse_path(&parser p) -> ast::path {
644
    auto lo = p.get_lo_pos();
645
    auto hi = lo;
646
    let ast::ident[] ids = ~[];
647
    while (true) {
648
        alt (p.peek()) {
649
            case (token::IDENT(?i, _)) {
650
                hi = p.get_hi_pos();
651
                ids += ~[p.get_str(i)];
652
                p.bump();
653
                if (p.peek() == token::MOD_SEP) { p.bump(); } else { break; }
654
            }
655
            case (_) { break; }
656 657
        }
    }
658
    hi = p.get_hi_pos();
659
    ret spanned(lo, hi, rec(idents=ids, types=~[]));
660 661 662 663 664 665 666 667
}

fn parse_path_and_ty_param_substs(&parser p) -> ast::path {
    auto lo = p.get_lo_pos();
    auto path = parse_path(p);
    if (p.peek() == token::LBRACKET) {
        auto seq = parse_seq(token::LBRACKET, token::RBRACKET,
                             some(token::COMMA), parse_ty, p);
668 669 670 671 672

        // FIXME: Remove this vec->ivec conversion.
        auto seq_ivec = ~[];
        for (@ast::ty typ in seq.node) { seq_ivec += ~[typ]; }

673
        auto hi = p.get_hi_pos();
674
        path = spanned(lo, hi, rec(idents=path.node.idents, types=seq_ivec));
675 676
    }
    ret path;
677
}
678

679
fn parse_mutability(&parser p) -> ast::mutability {
680
    if (eat_word(p, "mutable")) {
681
        if (p.peek() == token::QUES) { p.bump(); ret ast::maybe_mut; }
682
        ret ast::mut;
683
    }
684
    ret ast::imm;
685 686
}

687
fn parse_field(&parser p) -> ast::field {
688
    auto lo = p.get_lo_pos();
689
    auto m = parse_mutability(p);
G
Graydon Hoare 已提交
690
    auto i = parse_ident(p);
691
    expect(p, token::EQ);
G
Graydon Hoare 已提交
692
    auto e = parse_expr(p);
693
    ret spanned(lo, e.span.hi, rec(mut=m, ident=i, expr=e));
G
Graydon Hoare 已提交
694 695
}

696 697 698 699 700 701
fn mk_expr(&parser p, uint lo, uint hi, &ast::expr_ node) -> @ast::expr {
    ret @rec(id=p.get_id(),
             node=node,
             span=rec(lo=lo, hi=hi));
}

702
fn parse_bottom_expr(&parser p) -> @ast::expr {
703 704
    auto lo = p.get_lo_pos();
    auto hi = p.get_hi_pos();
705 706
    // FIXME: can only remove this sort of thing when both typestate and
    // alt-exhaustive-match checking are co-operating.
707

708
    auto lit = @spanned(lo, hi, ast::lit_nil);
709
    let ast::expr_ ex = ast::expr_lit(lit);
710 711 712 713 714 715 716
    if (p.peek() == token::LPAREN) {
        p.bump();
        alt (p.peek()) {
            case (token::RPAREN) {
                hi = p.get_hi_pos();
                p.bump();
                auto lit = @spanned(lo, hi, ast::lit_nil);
717
                ret mk_expr(p, lo, hi, ast::expr_lit(lit));
718
            }
719
            case (_) {/* fall through */ }
720 721 722 723
        }
        auto e = parse_expr(p);
        hi = p.get_hi_pos();
        expect(p, token::RPAREN);
724
        ret mk_expr(p, lo, hi, e.node);
725
    } else if (p.peek() == token::LBRACE) {
726
        auto blk = parse_block(p);
727
        ret mk_expr(p, blk.span.lo, blk.span.hi, ast::expr_block(blk));
728 729 730 731 732 733 734 735 736 737 738 739
    } else if (eat_word(p, "if")) {
        ret parse_if_expr(p);
    } else if (eat_word(p, "for")) {
        ret parse_for_expr(p);
    } else if (eat_word(p, "while")) {
        ret parse_while_expr(p);
    } else if (eat_word(p, "do")) {
        ret parse_do_while_expr(p);
    } else if (eat_word(p, "alt")) {
        ret parse_alt_expr(p);
    } else if (eat_word(p, "spawn")) {
        ret parse_spawn_expr(p);
740 741
    } else if (eat_word(p, "fn")) {
        ret parse_fn_expr(p);
742
    } else if (eat_word(p, "tup")) {
743
        fn parse_elt(&parser p) -> ast::elt {
744
            auto m = parse_mutability(p);
745
            auto e = parse_expr(p);
746 747
            ret rec(mut=m, expr=e);
        }
748 749 750
        auto es =
            parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                      parse_elt, p);
751
        hi = es.span.hi;
752
        ex = ast::expr_tup(es.node);
G
Graydon Hoare 已提交
753 754
    } else if (p.peek() == token::LBRACKET) {
        p.bump();
755
        auto mut = parse_mutability(p);
756 757 758
        auto es =
            parse_seq_to_end(token::RBRACKET, some(token::COMMA), parse_expr,
                             p);
759
        ex = ast::expr_vec(es, mut, ast::sk_rc);
760 761 762
    } else if (p.peek() == token::TILDE) {
        p.bump();
        alt (p.peek()) {
763 764
            case (token::LBRACKET) { // unique array (temporary)

765 766
                p.bump();
                auto mut = parse_mutability(p);
767 768 769
                auto es =
                    parse_seq_to_end(token::RBRACKET, some(token::COMMA),
                                     parse_expr, p);
770
                ex = ast::expr_vec(es, mut, ast::sk_unique);
771 772 773
            }
            case (token::LIT_STR(?s)) {
                p.bump();
774 775 776
                auto lit =
                    @rec(node=ast::lit_str(p.get_str(s), ast::sk_unique),
                         span=p.get_span());
777
                ex = ast::expr_lit(lit);
778 779
            }
            case (_) {
780
                p.fatal("unimplemented: unique pointer creation");
781 782
            }
        }
L
Lindsey Kuper 已提交
783 784
    } else if (eat_word(p, "obj")) {
        // Anonymous object
785 786

        // FIXME: Can anonymous objects have ty params?
787 788
        auto ty_params = parse_ty_params(p);

789 790
        // Only make people type () if they're actually adding new fields
        let option::t[vec[ast::anon_obj_field]] fields = none;
791
        if (p.peek() == token::LPAREN) {
792
            p.bump();
793 794
            fields =
                some(parse_seq_to_end(token::RPAREN, some(token::COMMA),
795
                                      parse_anon_obj_field, p));
796
        }
797
        let vec[@ast::method] meths = [];
798
        let option::t[@ast::expr] with_obj = none;
799 800
        expect(p, token::LBRACE);
        while (p.peek() != token::RBRACE) {
801
            if (eat_word(p, "with")) {
802
                with_obj = some(parse_expr(p));
803
            } else { vec::push(meths, parse_method(p)); }
804 805
        }
        hi = p.get_hi_pos();
806
        expect(p, token::RBRACE);
L
Lindsey Kuper 已提交
807 808 809
        // fields and methods may be *additional* or *overriding* fields
        // and methods if there's a with_obj, or they may be the *only*
        // fields and methods if there's no with_obj.
810 811 812

        // We don't need to pull ".node" out of fields because it's not a
        // "spanned".
813 814
        let ast::anon_obj ob =
            rec(fields=fields, methods=meths, with_obj=with_obj);
L
Lindsey Kuper 已提交
815
        ex = ast::expr_anon_obj(ob, ty_params);
L
Lindsey Kuper 已提交
816 817
    } else if (eat_word(p, "rec")) {
        expect(p, token::LPAREN);
818
        auto fields = [parse_field(p)];
L
Lindsey Kuper 已提交
819
        auto more = true;
820
        auto base = none;
L
Lindsey Kuper 已提交
821 822 823 824 825 826
        while (more) {
            if (p.peek() == token::RPAREN) {
                hi = p.get_hi_pos();
                p.bump();
                more = false;
            } else if (eat_word(p, "with")) {
827
                base = some(parse_expr(p));
L
Lindsey Kuper 已提交
828 829 830 831 832
                hi = p.get_hi_pos();
                expect(p, token::RPAREN);
                more = false;
            } else if (p.peek() == token::COMMA) {
                p.bump();
833
                fields += [parse_field(p)];
834
            } else { unexpected(p, p.peek()); }
L
Lindsey Kuper 已提交
835
        }
836
        ex = ast::expr_rec(fields, base);
837 838
    } else if (eat_word(p, "bind")) {
        auto e = parse_expr_res(p, RESTRICT_NO_CALL_EXPRS);
839
        fn parse_expr_opt(&parser p) -> option::t[@ast::expr] {
840
            alt (p.peek()) {
841 842
                case (token::UNDERSCORE) { p.bump(); ret none; }
                case (_) { ret some(parse_expr(p)); }
843 844
            }
        }
845 846 847
        auto es =
            parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                      parse_expr_opt, p);
848
        hi = es.span.hi;
849
        ex = ast::expr_bind(e, es.node);
850
    } else if (p.peek() == token::POUND) {
851 852 853
        auto ex_ext = parse_syntax_ext(p);
        lo = ex_ext.span.lo;
        ex = ex_ext.node;
854
    } else if (eat_word(p, "fail")) {
855 856 857 858 859 860 861
        if (can_begin_expr(p.peek())) {
            auto e = parse_expr(p);
            hi = e.span.hi;
            ex = ast::expr_fail(some(e));
        }
        else {
            ex = ast::expr_fail(none);
J
Josh Matthews 已提交
862
        }
863 864
    } else if (eat_word(p, "log")) {
        auto e = parse_expr(p);
865
        ex = ast::expr_log(1, e);
866 867
    } else if (eat_word(p, "log_err")) {
        auto e = parse_expr(p);
868
        ex = ast::expr_log(0, e);
869 870
    } else if (eat_word(p, "assert")) {
        auto e = parse_expr(p);
871
        ex = ast::expr_assert(e);
872 873 874 875
    } else if (eat_word(p, "check")) {
        /* Should be a predicate (pure boolean function) applied to 
           arguments that are all either slot variables or literals.
           but the typechecker enforces that. */
876

877
        auto e = parse_expr(p);
T
Tim Chevalier 已提交
878 879 880 881 882 883 884
        ex = ast::expr_check(ast::checked, e);
    } else if (eat_word(p, "claim")) {
        /* Same rules as check, except that if check-claims
         is enabled (a command-line flag), then the parser turns
        claims into check */
        
        auto e = parse_expr(p);
885
        ex = ast::expr_check(ast::unchecked, e);
886 887
    } else if (eat_word(p, "ret")) {
        alt (p.peek()) {
888
            case (token::SEMI) { ex = ast::expr_ret(none); }
889 890
            // Handle ret as the block result expression
            case (token::RBRACE) { ex = ast::expr_ret(none); }
891 892 893
            case (_) {
                auto e = parse_expr(p);
                hi = e.span.hi;
894
                ex = ast::expr_ret(some(e));
895 896
            }
        }
897
    } else if (eat_word(p, "break")) {
898
        ex = ast::expr_break;
899
    } else if (eat_word(p, "cont")) {
900
        ex = ast::expr_cont;
901 902
    } else if (eat_word(p, "put")) {
        alt (p.peek()) {
903
            case (token::SEMI) { ex = ast::expr_put(none); }
904 905 906
            case (_) {
                auto e = parse_expr(p);
                hi = e.span.hi;
907
                ex = ast::expr_put(some(e));
908 909
            }
        }
910 911
    } else if (eat_word(p, "be")) {
        auto e = parse_expr(p);
912

913
        // FIXME: Is this the right place for this check?
914
        if (/*check*/ast::is_call_expr(e)) {
915
            hi = e.span.hi;
916
            ex = ast::expr_be(e);
917
        } else { p.fatal("Non-call expression in tail call"); }
918
    } else if (eat_word(p, "port")) {
919 920 921 922 923 924
        auto ty = none;
        if(token::LBRACKET == p.peek()) {
            expect(p, token::LBRACKET);
            ty = some(parse_ty(p));
            expect(p, token::RBRACKET);
        }
925 926 927
        expect(p, token::LPAREN);
        expect(p, token::RPAREN);
        hi = p.get_hi_pos();
928
        ex = ast::expr_port(ty);
929 930 931 932 933
    } else if (eat_word(p, "chan")) {
        expect(p, token::LPAREN);
        auto e = parse_expr(p);
        hi = e.span.hi;
        expect(p, token::RPAREN);
934
        ex = ast::expr_chan(e);
935 936 937 938
    } else if (eat_word(p, "self")) {
        log "parsing a self-call...";
        expect(p, token::DOT);
        // The rest is a call expression.
939

940
        let @ast::expr f = parse_self_method(p);
941 942 943
        auto es =
            parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                      parse_expr, p);
944
        hi = es.span.hi;
945
        ex = ast::expr_call(f, es.node);
946
    } else if (is_ident(p.peek()) && !is_word(p, "true") &&
947
               !is_word(p, "false")) {
948
        check_bad_word(p);
949
        auto pth = parse_path_and_ty_param_substs(p);
950
        hi = pth.span.hi;
951
        ex = ast::expr_path(pth);
952 953 954
    } else {
        auto lit = parse_lit(p);
        hi = lit.span.hi;
955
        ex = ast::expr_lit(@lit);
956
    }
957
    ret mk_expr(p, lo, hi, ex);
958 959
}

960 961 962
fn parse_syntax_ext(&parser p) -> @ast::expr {
    auto lo = p.get_lo_pos();
    expect(p, token::POUND);
963
    ret parse_syntax_ext_naked(p, lo);
964 965
}

966
fn parse_syntax_ext_naked(&parser p, uint lo) -> @ast::expr {
967
    auto pth = parse_path(p);
968
    if (ivec::len(pth.node.idents) == 0u) {
969 970
        p.fatal("expected a syntax expander name");
    }
971 972 973 974 975
    auto es = parse_seq(token::LPAREN, token::RPAREN,
                        some(token::COMMA), parse_expr, p);
    auto hi = es.span.hi;
    auto ext_span = rec(lo=lo, hi=hi);
    auto ex = expand_syntax_ext(p, ext_span, pth, es.node, none);
976
    ret mk_expr(p, lo, hi, ex);
977
}
978

B
Brian Anderson 已提交
979
/*
980 981 982
 * FIXME: This is a crude approximation of the syntax-extension system,
 * for purposes of prototyping and/or hard-wiring any extensions we
 * wish to use while bootstrapping. The eventual aim is to permit
983
 * loading rust crates to process extensions.
984
 */
985
fn expand_syntax_ext(&parser p, span sp, &ast::path path,
986 987
                     vec[@ast::expr] args, option::t[str] body) ->
   ast::expr_ {
988
    assert (ivec::len(path.node.idents) > 0u);
989
    auto extname = path.node.idents.(0);
990
    alt (p.get_syntax_expanders().find(extname)) {
991
        case (none) { p.fatal("unknown syntax expander: '" + extname + "'"); }
992 993
        case (some(ex::normal(?ext))) {
            auto ext_cx = ex::mk_ctxt(p.get_sess());
994
            ret ast::expr_ext(path, args, body, ext(ext_cx, sp, args, body));
995
        }
996 997
        // because we have expansion inside parsing, new macros are only
        // visible further down the file
998 999
        case (some(ex::macro_defining(?ext))) {
            auto ext_cx = ex::mk_ctxt(p.get_sess());
1000 1001 1002 1003 1004
            auto name_and_extension = ext(ext_cx, sp, args, body);
            p.get_syntax_expanders().insert(name_and_extension._0,
                                            name_and_extension._1);
            ret ast::expr_tup(vec::empty[ast::elt]());
        }
1005 1006 1007
    }
}

1008
fn parse_self_method(&parser p) -> @ast::expr {
1009
    auto sp = p.get_span();
1010
    let ast::ident f_name = parse_ident(p);
1011
    ret mk_expr(p, sp.lo, sp.hi, ast::expr_self_method(f_name));
1012 1013
}

1014
fn parse_dot_or_call_expr(&parser p) -> @ast::expr {
1015 1016 1017 1018 1019
    ret parse_dot_or_call_expr_with(p, parse_bottom_expr(p));
}

fn parse_dot_or_call_expr_with(&parser p, @ast::expr e) -> @ast::expr {
    auto lo = e.span.lo;
1020
    auto hi = e.span.hi;
G
Graydon Hoare 已提交
1021 1022
    while (true) {
        alt (p.peek()) {
1023
            case (token::LPAREN) {
1024
                if (p.get_restriction() == RESTRICT_NO_CALL_EXPRS) {
1025 1026 1027
                    ret e;
                } else {
                    // Call expr.
1028 1029 1030 1031

                    auto es =
                        parse_seq(token::LPAREN, token::RPAREN,
                                  some(token::COMMA), parse_expr, p);
1032
                    hi = es.span.hi;
1033
                    e = mk_expr(p, lo, hi, ast::expr_call(e, es.node));
1034
                }
1035
            }
1036
            case (token::DOT) {
G
Graydon Hoare 已提交
1037 1038
                p.bump();
                alt (p.peek()) {
1039
                    case (token::IDENT(?i, _)) {
1040
                        hi = p.get_hi_pos();
G
Graydon Hoare 已提交
1041
                        p.bump();
1042 1043
                        e = mk_expr(p, lo, hi,
                                    ast::expr_field(e, p.get_str(i)));
G
Graydon Hoare 已提交
1044
                    }
1045
                    case (token::LPAREN) {
1046
                        p.bump();
1047
                        auto ix = parse_expr(p);
1048
                        hi = ix.span.hi;
1049
                        expect(p, token::RPAREN);
1050
                        e = mk_expr(p, lo, hi, ast::expr_index(e, ix));
G
Graydon Hoare 已提交
1051
                    }
1052
                    case (?t) { unexpected(p, t); }
G
Graydon Hoare 已提交
1053 1054
                }
            }
1055
            case (_) { ret e; }
G
Graydon Hoare 已提交
1056 1057 1058 1059
        }
    }
    ret e;
}
1060

1061
fn parse_prefix_expr(&parser p) -> @ast::expr {
1062
    if (eat_word(p, "mutable")) {
1063
        p.warn("ignoring deprecated 'mutable' prefix operator");
1064
    }
1065 1066
    auto lo = p.get_lo_pos();
    auto hi = p.get_hi_pos();
1067 1068
    // FIXME: can only remove this sort of thing when both typestate and
    // alt-exhaustive-match checking are co-operating.
1069

1070
    auto lit = @spanned(lo, lo, ast::lit_nil);
1071
    let ast::expr_ ex = ast::expr_lit(lit);
1072
    alt (p.peek()) {
1073
        case (token::NOT) {
1074
            p.bump();
G
Graydon Hoare 已提交
1075
            auto e = parse_prefix_expr(p);
1076
            hi = e.span.hi;
1077
            ex = ast::expr_unary(ast::not, e);
1078
        }
1079
        case (token::BINOP(?b)) {
G
Graydon Hoare 已提交
1080
            alt (b) {
1081
                case (token::MINUS) {
1082
                    p.bump();
G
Graydon Hoare 已提交
1083
                    auto e = parse_prefix_expr(p);
1084
                    hi = e.span.hi;
1085
                    ex = ast::expr_unary(ast::neg, e);
G
Graydon Hoare 已提交
1086
                }
1087
                case (token::STAR) {
1088
                    p.bump();
G
Graydon Hoare 已提交
1089
                    auto e = parse_prefix_expr(p);
1090
                    hi = e.span.hi;
1091
                    ex = ast::expr_unary(ast::deref, e);
G
Graydon Hoare 已提交
1092
                }
1093
                case (_) { ret parse_dot_or_call_expr(p); }
G
Graydon Hoare 已提交
1094 1095
            }
        }
1096
        case (token::AT) {
G
Graydon Hoare 已提交
1097
            p.bump();
1098
            auto m = parse_mutability(p);
G
Graydon Hoare 已提交
1099
            auto e = parse_prefix_expr(p);
1100
            hi = e.span.hi;
1101
            ex = ast::expr_unary(ast::box(m), e);
G
Graydon Hoare 已提交
1102
        }
1103
        case (_) { ret parse_dot_or_call_expr(p); }
G
Graydon Hoare 已提交
1104
    }
1105
    ret mk_expr(p, lo, hi, ex);
G
Graydon Hoare 已提交
1106 1107
}

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
fn parse_ternary(&parser p) -> @ast::expr {
    auto cond_expr = parse_binops(p);
    if (p.peek() == token::QUES) {
        p.bump();
        auto then_expr = parse_expr(p);
        expect(p, token::COLON);
        auto else_expr = parse_expr(p);
        ret mk_expr(p, cond_expr.span.lo, else_expr.span.hi,
                    ast::expr_ternary(cond_expr, then_expr, else_expr));
    } else {
        ret cond_expr;
    }
}

1122
type op_spec = rec(token::token tok, ast::binop op, int prec);
1123

1124

M
Marijn Haverbeke 已提交
1125
// FIXME make this a const, don't store it in parser state
1126
fn prec_table() -> vec[op_spec] {
1127
    ret [rec(tok=token::BINOP(token::STAR), op=ast::mul, prec=11),
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
         rec(tok=token::BINOP(token::SLASH), op=ast::div, prec=11),
         rec(tok=token::BINOP(token::PERCENT), op=ast::rem, prec=11),
         rec(tok=token::BINOP(token::PLUS), op=ast::add, prec=10),
         rec(tok=token::BINOP(token::MINUS), op=ast::sub, prec=10),
         rec(tok=token::BINOP(token::LSL), op=ast::lsl, prec=9),
         rec(tok=token::BINOP(token::LSR), op=ast::lsr, prec=9),
         rec(tok=token::BINOP(token::ASR), op=ast::asr, prec=9),
         rec(tok=token::BINOP(token::AND), op=ast::bitand, prec=8),
         rec(tok=token::BINOP(token::CARET), op=ast::bitxor, prec=6),
         rec(tok=token::BINOP(token::OR), op=ast::bitor, prec=6),
         // 'as' sits between here with 5
         rec(tok=token::LT, op=ast::lt, prec=4),
         rec(tok=token::LE, op=ast::le, prec=4),
         rec(tok=token::GE, op=ast::ge, prec=4),
         rec(tok=token::GT, op=ast::gt, prec=4),
         rec(tok=token::EQEQ, op=ast::eq, prec=3),
         rec(tok=token::NE, op=ast::ne, prec=3),
         rec(tok=token::ANDAND, op=ast::and, prec=2),
         rec(tok=token::OROR, op=ast::or, prec=1)];
1147 1148
}

1149
fn parse_binops(&parser p) -> @ast::expr {
1150
    ret parse_more_binops(p, parse_prefix_expr(p), 0);
G
Graydon Hoare 已提交
1151 1152
}

1153
const int unop_prec = 100;
1154

1155
const int as_prec = 5;
1156
const int ternary_prec = 0;
1157

1158
fn parse_more_binops(&parser p, @ast::expr lhs, int min_prec) -> @ast::expr {
1159 1160
    auto peeked = p.peek();
    for (op_spec cur in p.get_prec_table()) {
1161
        if (cur.prec > min_prec && cur.tok == peeked) {
1162
            p.bump();
1163
            auto rhs = parse_more_binops(p, parse_prefix_expr(p), cur.prec);
1164 1165 1166
            auto bin = mk_expr(p, lhs.span.lo, rhs.span.hi,
                               ast::expr_binary(cur.op, lhs, rhs));
            ret parse_more_binops(p, bin, min_prec);
G
Graydon Hoare 已提交
1167 1168
        }
    }
1169 1170
    if (as_prec > min_prec && eat_word(p, "as")) {
        auto rhs = parse_ty(p);
1171 1172 1173
        auto _as = mk_expr(p, lhs.span.lo, rhs.span.hi,
                           ast::expr_cast(lhs, rhs));
        ret parse_more_binops(p, _as, min_prec);
1174
    }
1175
    ret lhs;
1176 1177
}

1178
fn parse_assign_expr(&parser p) -> @ast::expr {
1179
    auto lo = p.get_lo_pos();
1180
    auto lhs = parse_ternary(p);
G
Graydon Hoare 已提交
1181
    alt (p.peek()) {
1182
        case (token::EQ) {
G
Graydon Hoare 已提交
1183 1184
            p.bump();
            auto rhs = parse_expr(p);
1185
            ret mk_expr(p, lo, rhs.span.hi, ast::expr_assign(lhs, rhs));
G
Graydon Hoare 已提交
1186
        }
1187
        case (token::BINOPEQ(?op)) {
1188 1189
            p.bump();
            auto rhs = parse_expr(p);
1190
            auto aop = ast::add;
1191
            alt (op) {
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                case (token::PLUS) { aop = ast::add; }
                case (token::MINUS) { aop = ast::sub; }
                case (token::STAR) { aop = ast::mul; }
                case (token::SLASH) { aop = ast::div; }
                case (token::PERCENT) { aop = ast::rem; }
                case (token::CARET) { aop = ast::bitxor; }
                case (token::AND) { aop = ast::bitand; }
                case (token::OR) { aop = ast::bitor; }
                case (token::LSL) { aop = ast::lsl; }
                case (token::LSR) { aop = ast::lsr; }
                case (token::ASR) { aop = ast::asr; }
1203
            }
1204 1205
            ret mk_expr(p, lo, rhs.span.hi,
                        ast::expr_assign_op(aop, lhs, rhs));
1206
        }
1207 1208 1209
        case (token::LARROW) {
            p.bump();
            auto rhs = parse_expr(p);
1210
            ret mk_expr(p, lo, rhs.span.hi, ast::expr_move(lhs, rhs));
1211
        }
1212
        case (token::SEND) {
1213 1214
            p.bump();
            auto rhs = parse_expr(p);
1215
            ret mk_expr(p, lo, rhs.span.hi, ast::expr_send(lhs, rhs));
1216
        }
1217
        case (token::RECV) {
B
Brian Anderson 已提交
1218 1219
            p.bump();
            auto rhs = parse_expr(p);
1220
            ret mk_expr(p, lo, rhs.span.hi, ast::expr_recv(lhs, rhs));
B
Brian Anderson 已提交
1221
        }
M
Michael Sullivan 已提交
1222 1223 1224
        case (token::DARROW) {
            p.bump();
            auto rhs = parse_expr(p);
1225
            ret mk_expr(p, lo, rhs.span.hi, ast::expr_swap(lhs, rhs));
M
Michael Sullivan 已提交
1226
        }
1227
        case (_) {/* fall through */ }
G
Graydon Hoare 已提交
1228 1229 1230 1231
    }
    ret lhs;
}

T
Tim Chevalier 已提交
1232 1233
fn parse_if_expr_1(&parser p) -> tup(@ast::expr,
                                     ast::block, option::t[@ast::expr],
1234
                                     uint, uint) {
1235
    auto lo = p.get_last_lo_pos();
1236 1237
    auto cond = parse_expr(p);
    auto thn = parse_block(p);
1238
    let option::t[@ast::expr] els = none;
1239
    auto hi = thn.span.hi;
1240 1241 1242 1243
    if (eat_word(p, "else")) {
        auto elexpr = parse_else_expr(p);
        els = some(elexpr);
        hi = elexpr.span.hi;
1244
    }
1245
    ret tup(cond, thn, els, lo, hi);
T
Tim Chevalier 已提交
1246 1247 1248 1249 1250
}

fn parse_if_expr(&parser p) -> @ast::expr {
    if (eat_word(p, "check")) {
            auto q = parse_if_expr_1(p);
1251
            ret mk_expr(p, q._3, q._4, ast::expr_if_check(q._0, q._1, q._2));
T
Tim Chevalier 已提交
1252 1253 1254
    }
    else {
        auto q = parse_if_expr_1(p);
1255
        ret mk_expr(p, q._3, q._4, ast::expr_if(q._0, q._1, q._2));
T
Tim Chevalier 已提交
1256
    }
1257 1258
}

1259 1260 1261 1262 1263
fn parse_fn_expr(&parser p) -> @ast::expr {
    auto lo = p.get_last_lo_pos();
    auto decl = parse_fn_decl(p, ast::impure_fn);
    auto body = parse_block(p);
    auto _fn = rec(decl=decl, proto=ast::proto_fn, body=body);
1264
    ret mk_expr(p, lo, body.span.hi, ast::expr_fn(_fn));
1265 1266
}

1267
fn parse_else_expr(&parser p) -> @ast::expr {
1268 1269 1270 1271
    if (eat_word(p, "if")) {
        ret parse_if_expr(p);
    } else {
        auto blk = parse_block(p);
1272
        ret mk_expr(p, blk.span.lo, blk.span.hi, ast::expr_block(blk));
B
Brian Anderson 已提交
1273
    }
1274 1275
}

1276
fn parse_head_local(&parser p) -> @ast::local {
P
Paul Stansifer 已提交
1277 1278 1279 1280 1281
    if (is_word(p, "auto")) {
        ret parse_auto_local(p);
    } else { 
        ret parse_typed_local(p);
    }
1282 1283
}

1284
fn parse_for_expr(&parser p) -> @ast::expr {
1285 1286
    auto lo = p.get_last_lo_pos();
    auto is_each = eat_word(p, "each");
1287
    expect(p, token::LPAREN);
1288
    auto decl = parse_head_local(p);
1289
    expect_word(p, "in");
1290
    auto seq = parse_expr(p);
1291
    expect(p, token::RPAREN);
1292
    auto body = parse_block(p);
1293
    auto hi = body.span.hi;
1294
    if (is_each) {
1295
        ret mk_expr(p, lo, hi, ast::expr_for_each(decl, seq, body));
1296
    } else {
1297
        ret mk_expr(p, lo, hi, ast::expr_for(decl, seq, body));
1298
    }
1299 1300
}

1301
fn parse_while_expr(&parser p) -> @ast::expr {
1302
    auto lo = p.get_last_lo_pos();
1303 1304
    auto cond = parse_expr(p);
    auto body = parse_block(p);
1305
    auto hi = body.span.hi;
1306
    ret mk_expr(p, lo, hi, ast::expr_while(cond, body));
1307 1308
}

1309
fn parse_do_while_expr(&parser p) -> @ast::expr {
1310
    auto lo = p.get_last_lo_pos();
1311
    auto body = parse_block(p);
1312
    expect_word(p, "while");
1313
    auto cond = parse_expr(p);
1314
    auto hi = cond.span.hi;
1315
    ret mk_expr(p, lo, hi, ast::expr_do_while(body, cond));
1316 1317
}

1318
fn parse_alt_expr(&parser p) -> @ast::expr {
1319
    auto lo = p.get_last_lo_pos();
P
Patrick Walton 已提交
1320
    auto discriminant = parse_expr(p);
1321
    expect(p, token::LBRACE);
1322
    let vec[ast::arm] arms = [];
1323
    while (p.peek() != token::RBRACE) {
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        // Optionally eat the case keyword.
        // FIXME remove this (and the optional parens) once we've updated our
        // code to not use the old syntax
        eat_word(p, "case");
        auto parens = false;
        if (p.peek() == token::LPAREN) { parens = true; p.bump(); }
        auto pat = parse_pat(p);
        if (parens) { expect(p, token::RPAREN); }
        auto block = parse_block(p);
        arms += [rec(pat=pat, block=block)];
P
Patrick Walton 已提交
1334
    }
1335
    auto hi = p.get_hi_pos();
1336
    p.bump();
1337
    ret mk_expr(p, lo, hi, ast::expr_alt(discriminant, arms));
P
Patrick Walton 已提交
1338 1339
}

1340
fn parse_spawn_expr(&parser p) -> @ast::expr {
1341
    auto lo = p.get_last_lo_pos();
1342
    // FIXME: Parse domain and name
1343
    // FIXME: why no full expr?
1344

1345
    auto fn_expr = parse_bottom_expr(p);
1346 1347 1348
    auto es =
        parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                  parse_expr, p);
1349
    auto hi = es.span.hi;
1350 1351
    ret mk_expr(p, lo, hi, ast::expr_spawn
                (ast::dom_implicit, option::none, fn_expr, es.node));
1352 1353
}

1354
fn parse_expr(&parser p) -> @ast::expr {
1355
    ret parse_expr_res(p, UNRESTRICTED);
1356 1357
}

1358
fn parse_expr_res(&parser p, restriction r) -> @ast::expr {
1359 1360
    auto old = p.get_restriction();
    p.restrict(r);
1361
    auto e = parse_assign_expr(p);
1362 1363 1364 1365
    p.restrict(old);
    ret e;
}

1366
fn parse_initializer(&parser p) -> option::t[ast::initializer] {
1367
    alt (p.peek()) {
1368
        case (token::EQ) {
1369
            p.bump();
1370
            ret some(rec(op=ast::init_assign, expr=parse_expr(p)));
1371
        }
1372 1373
        case (token::LARROW) {
            p.bump();
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
            ret some(rec(op=ast::init_move, expr=parse_expr(p)));
        }
        case (
             // Now that the the channel is the first argument to receive,
             // combining it with an initializer doesn't really make sense.
             // case (token::RECV) {
             //     p.bump();
             //     ret some(rec(op = ast::init_recv,
             //                  expr = parse_expr(p)));
             // }
             _) {
1385
            ret none;
1386
        }
P
Patrick Walton 已提交
1387 1388 1389
    }
}

1390
fn parse_pat(&parser p) -> @ast::pat {
1391 1392
    auto lo = p.get_lo_pos();
    auto hi = p.get_hi_pos();
B
Brian Anderson 已提交
1393
    auto pat;
P
Patrick Walton 已提交
1394
    alt (p.peek()) {
1395
        case (token::UNDERSCORE) {
P
Patrick Walton 已提交
1396
            p.bump();
1397
            pat = ast::pat_wild;
P
Patrick Walton 已提交
1398
        }
1399
        case (token::QUES) {
P
Patrick Walton 已提交
1400 1401
            p.bump();
            alt (p.peek()) {
1402
                case (token::IDENT(?id, _)) {
1403
                    hi = p.get_hi_pos();
P
Patrick Walton 已提交
1404
                    p.bump();
1405
                    pat = ast::pat_bind(p.get_str(id));
P
Patrick Walton 已提交
1406
                }
P
Patrick Walton 已提交
1407
                case (?tok) {
1408
                    p.fatal("expected identifier after '?' in pattern but " +
1409
                              "found " + token::to_str(p.get_reader(), tok));
P
Patrick Walton 已提交
1410 1411 1412 1413
                    fail;
                }
            }
        }
1414 1415 1416 1417
        case (?tok) {
            if (!is_ident(tok) || is_word(p, "true") || is_word(p, "false")) {
                auto lit = parse_lit(p);
                hi = lit.span.hi;
1418
                pat = ast::pat_lit(@lit);
1419
            } else {
1420
                auto tag_path = parse_path_and_ty_param_substs(p);
1421 1422 1423 1424 1425
                hi = tag_path.span.hi;
                let vec[@ast::pat] args;
                alt (p.peek()) {
                    case (token::LPAREN) {
                        auto f = parse_pat;
1426 1427 1428
                        auto a =
                            parse_seq(token::LPAREN, token::RPAREN,
                                      some(token::COMMA), f, p);
1429 1430 1431
                        args = a.node;
                        hi = a.span.hi;
                    }
1432
                    case (_) { args = []; }
P
Patrick Walton 已提交
1433
                }
1434
                pat = ast::pat_tag(tag_path, args);
1435
            }
P
Patrick Walton 已提交
1436 1437
        }
    }
1438
    ret @rec(id=p.get_id(), node=pat, span=rec(lo=lo, hi=hi));
P
Patrick Walton 已提交
1439 1440
}

P
Paul Stansifer 已提交
1441 1442 1443
fn parse_local_full(&option::t[@ast::ty] tyopt, &parser p)
    -> @ast::local {
    auto lo = p.get_lo_pos();
1444
    auto ident = parse_value_ident(p);
P
Patrick Walton 已提交
1445
    auto init = parse_initializer(p);
P
Paul Stansifer 已提交
1446 1447 1448 1449 1450
    ret @spanned(lo, p.get_hi_pos(),
                 rec(ty=tyopt,
                     infer=false,
                     ident=ident,
                     init=init,
1451
                     id=p.get_id()));
1452
}
P
Patrick Walton 已提交
1453

P
Paul Stansifer 已提交
1454
fn parse_typed_local(&parser p) -> @ast::local {
1455
    auto ty = parse_ty(p);
1456
    ret parse_local_full(some(ty), p);
1457
}
P
Patrick Walton 已提交
1458

P
Paul Stansifer 已提交
1459
fn parse_auto_local(&parser p) -> @ast::local {
1460
    ret parse_local_full(none, p);
1461
}
1462

1463
fn parse_let(&parser p) -> @ast::decl {
1464
    auto lo = p.get_last_lo_pos();
1465
    auto local = parse_typed_local(p);
1466
    ret @spanned(lo, p.get_hi_pos(), ast::decl_local(local));
1467 1468
}

1469
fn parse_auto(&parser p) -> @ast::decl {
1470
    auto lo = p.get_last_lo_pos();
1471
    auto local = parse_auto_local(p);
1472
    ret @spanned(lo, p.get_hi_pos(), ast::decl_local(local));
P
Patrick Walton 已提交
1473 1474
}

1475
fn parse_stmt(&parser p) -> @ast::stmt {
1476 1477
    if (p.get_file_type() == SOURCE_FILE) {
        ret parse_source_stmt(p);
1478
    } else { ret parse_crate_stmt(p); }
1479 1480
}

1481
fn parse_crate_stmt(&parser p) -> @ast::stmt {
1482
    auto cdir = parse_crate_directive(p, ~[]);
1483
    ret @spanned(cdir.span.lo, cdir.span.hi,
1484
                 ast::stmt_crate_directive(@cdir));
1485 1486
}

1487
fn parse_source_stmt(&parser p) -> @ast::stmt {
1488
    auto lo = p.get_lo_pos();
1489 1490
    if (eat_word(p, "let")) {
        auto decl = parse_let(p);
1491
        ret @spanned(lo, decl.span.hi, ast::stmt_decl(decl, p.get_id()));
1492 1493
    } else if (eat_word(p, "auto")) {
        auto decl = parse_auto(p);
1494
        ret @spanned(lo, decl.span.hi, ast::stmt_decl(decl, p.get_id()));
1495
    } else {
1496 1497

        auto item_attrs;
1498
        alt (parse_outer_attrs_or_ext(p)) {
1499
            case (none) {
1500
                item_attrs = ~[];
1501 1502 1503 1504 1505 1506
            }
            case (some(left(?attrs))) {
                item_attrs = attrs;
            }
            case (some(right(?ext))) {
                ret @spanned(lo, ext.span.hi,
1507
                             ast::stmt_expr(ext, p.get_id()));
1508 1509 1510
            }
        }

1511 1512 1513
        auto maybe_item = parse_item(p, item_attrs);

        // If we have attributes then we should have an item
1514
        if (ivec::len(item_attrs) > 0u) {
1515 1516 1517
            alt (maybe_item) {
                case (got_item(_)) { /* fallthrough */ }
                case (_) {
1518
                    ret p.fatal("expected item");
1519 1520 1521 1522 1523
                }
            }
        }

        alt (maybe_item) {
1524 1525 1526
            case (got_item(?i)) {
                auto hi = i.span.hi;
                auto decl = @spanned(lo, hi, ast::decl_item(i));
1527
                ret @spanned(lo, hi, ast::stmt_decl(decl, p.get_id()));
1528
            }
1529
            case (fn_no_item) { // parse_item will have already skipped "fn"
1530

1531 1532
                auto e = parse_fn_expr(p);
                e = parse_dot_or_call_expr_with(p, e);
1533
                ret @spanned(lo, e.span.hi, ast::stmt_expr(e, p.get_id()));
1534
            }
1535 1536
            case (no_item) {
                // Remainder are line-expr stmts.
1537

1538
                auto e = parse_expr(p);
1539
                ret @spanned(lo, e.span.hi, ast::stmt_expr(e, p.get_id()));
1540
            }
1541
        }
1542
    }
1543
    p.fatal("expected statement");
1544 1545 1546
    fail;
}

1547
fn stmt_to_expr(@ast::stmt stmt) -> option::t[@ast::expr] {
1548
    ret alt (stmt.node) {
1549 1550 1551
            case (ast::stmt_expr(?e, _)) { some(e) }
            case (_) { none }
        };
1552 1553
}

1554
fn stmt_ends_with_semi(&ast::stmt stmt) -> bool {
1555
    alt (stmt.node) {
1556
        case (ast::stmt_decl(?d, _)) {
1557 1558 1559
            ret alt (d.node) {
                case (ast::decl_local(_)) { true }
                case (ast::decl_item(_)) { false }
G
Graydon Hoare 已提交
1560 1561
            }
        }
1562
        case (ast::stmt_expr(?e, _)) {
1563 1564 1565 1566 1567 1568
            ret alt (e.node) {
                case (ast::expr_vec(_, _, _)) { true }
                case (ast::expr_tup(_)) { true }
                case (ast::expr_rec(_, _)) { true }
                case (ast::expr_call(_, _)) { true }
                case (ast::expr_self_method(_)) { false }
T
Tim Chevalier 已提交
1569 1570
                case (ast::expr_bind(_, _)) { true }
                case (ast::expr_spawn(_, _, _, _)) { true }
1571 1572 1573 1574 1575
                case (ast::expr_binary(_, _, _)) { true }
                case (ast::expr_unary(_, _)) { true }
                case (ast::expr_lit(_)) { true }
                case (ast::expr_cast(_, _)) { true }
                case (ast::expr_if(_, _, _)) { false }
1576
                case (ast::expr_ternary(_, _, _)) { true }
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
                case (ast::expr_for(_, _, _)) { false }
                case (ast::expr_for_each(_, _, _)) { false }
                case (ast::expr_while(_, _)) { false }
                case (ast::expr_do_while(_, _)) { false }
                case (ast::expr_alt(_, _)) { false }
                case (ast::expr_fn(_)) { false }
                case (ast::expr_block(_)) { false }
                case (ast::expr_move(_, _)) { true }
                case (ast::expr_assign(_, _)) { true }
                case (ast::expr_swap(_, _)) { true }
                case (ast::expr_assign_op(_, _, _)) { true }
                case (ast::expr_send(_, _)) { true }
                case (ast::expr_recv(_, _)) { true }
                case (ast::expr_field(_, _)) { true }
                case (ast::expr_index(_, _)) { true }
                case (ast::expr_path(_)) { true }
T
Tim Chevalier 已提交
1593
                case (ast::expr_ext(_, _, _, _)) { true }
1594 1595 1596 1597 1598 1599 1600
                case (ast::expr_fail(_)) { true }
                case (ast::expr_break) { true }
                case (ast::expr_cont) { true }
                case (ast::expr_ret(_)) { true }
                case (ast::expr_put(_)) { true }
                case (ast::expr_be(_)) { true }
                case (ast::expr_log(_, _)) { true }
T
Tim Chevalier 已提交
1601
                case (ast::expr_check(_, _)) { true }
T
Tim Chevalier 已提交
1602
                case (ast::expr_if_check(_, _, _)) { false }
1603
                case (ast::expr_port(_)) { true }
T
Tim Chevalier 已提交
1604
                case (ast::expr_chan(_)) { true }
L
Lindsey Kuper 已提交
1605
                case (ast::expr_anon_obj(_,_)) { false }
1606
                case (ast::expr_assert(_)) { true }
1607 1608
            }
        }
1609 1610
        // We should not be calling this on a cdir.
        case (ast::stmt_crate_directive(?cdir)) {
1611
            fail;
1612 1613 1614 1615
        }
    }
}

1616
fn parse_block(&parser p) -> ast::block {
1617
    auto lo = p.get_lo_pos();
1618
    let vec[@ast::stmt] stmts = [];
1619
    let option::t[@ast::expr] expr = none;
1620 1621
    expect(p, token::LBRACE);
    while (p.peek() != token::RBRACE) {
1622
        alt (p.peek()) {
1623
            case (token::SEMI) {
1624
                p.bump(); // empty
1625 1626 1627 1628
            }
            case (_) {
                auto stmt = parse_stmt(p);
                alt (stmt_to_expr(stmt)) {
1629
                    case (some(?e)) {
1630
                        alt (p.peek()) {
1631
                            case (token::SEMI) { p.bump(); stmts += [stmt]; }
1632
                            case (token::RBRACE) { expr = some(e); }
1633
                            case (?t) {
1634
                                if (stmt_ends_with_semi(*stmt)) {
1635
                                    p.fatal("expected ';' or '}' after " +
1636 1637 1638
                                              "expression but found " +
                                              token::to_str(p.get_reader(),
                                                            t));
1639 1640
                                    fail;
                                }
1641
                                stmts += [stmt];
1642 1643 1644
                            }
                        }
                    }
1645
                    case (none) {
1646
                        // Not an expression statement.
1647
                        stmts += [stmt];
1648

1649 1650 1651
                        if (p.get_file_type() == SOURCE_FILE
                            && stmt_ends_with_semi(*stmt)) {
                            expect(p, token::SEMI);
1652 1653 1654 1655 1656 1657
                        }
                    }
                }
            }
        }
    }
1658
    auto hi = p.get_hi_pos();
1659
    p.bump();
1660
    auto bloc = rec(stmts=stmts, expr=expr, id=p.get_id());
1661
    ret spanned(lo, hi, bloc);
1662 1663
}

1664
fn parse_ty_param(&parser p) -> ast::ty_param { ret parse_ident(p); }
1665

1666
fn parse_ty_params(&parser p) -> vec[ast::ty_param] {
1667
    let vec[ast::ty_param] ty_params = [];
1668
    if (p.peek() == token::LBRACKET) {
1669 1670 1671
        ty_params =
            parse_seq(token::LBRACKET, token::RBRACKET, some(token::COMMA),
                      parse_ty_param, p).node;
1672
    }
P
Patrick Walton 已提交
1673 1674 1675
    ret ty_params;
}

1676
fn parse_fn_decl(&parser p, ast::purity purity) -> ast::fn_decl {
1677
    let ast::spanned[vec[ast::arg]] inputs =
1678 1679
        parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA), parse_arg,
                  p);
1680
    let ty_or_bang rslt;
1681
    auto constrs = parse_constrs(inputs.node, p).node;
1682
    if (p.peek() == token::RARROW) {
1683
        p.bump();
1684
        rslt = parse_ty_or_bang(p);
1685
    } else {
1686
        rslt = a_ty(@spanned(inputs.span.lo, inputs.span.hi, ast::ty_nil));
1687
    }
1688
    alt (rslt) {
1689
        case (a_ty(?t)) {
1690 1691 1692 1693 1694
            ret rec(inputs=inputs.node,
                    output=t,
                    purity=purity,
                    cf=ast::return,
                    constraints=constrs);
1695
        }
1696
        case (a_bang) {
1697
            ret rec(inputs=inputs.node,
1698 1699 1700 1701 1702
                    output=@spanned(p.get_lo_pos(), p.get_hi_pos(),
                                    ast::ty_bot),
                    purity=purity,
                    cf=ast::noreturn,
                    constraints=constrs);
1703
        }
1704
    }
1705
}
1706

1707
fn parse_fn(&parser p, ast::proto proto, ast::purity purity) -> ast::_fn {
1708
    auto decl = parse_fn_decl(p, purity);
1709
    auto body = parse_block(p);
1710
    ret rec(decl=decl, proto=proto, body=body);
G
Graydon Hoare 已提交
1711
}
1712

1713
fn parse_fn_header(&parser p) -> tup(ast::ident, vec[ast::ty_param]) {
1714
    auto id = parse_value_ident(p);
G
Graydon Hoare 已提交
1715
    auto ty_params = parse_ty_params(p);
1716
    ret tup(id, ty_params);
1717 1718
}

1719
fn mk_item(&parser p, uint lo, uint hi, &ast::ident ident, &ast::item_ node,
1720
           &ast::attribute[] attrs) -> @ast::item {
1721 1722
    ret @rec(ident=ident,
             attrs=attrs,
1723
             id=p.get_id(),
1724 1725 1726 1727
             node=node,
             span=rec(lo=lo, hi=hi));
}

1728
fn parse_item_fn_or_iter(&parser p, ast::purity purity, ast::proto proto,
1729
                         &ast::attribute[] attrs) -> @ast::item {
1730
    auto lo = p.get_last_lo_pos();
1731
    auto t = parse_fn_header(p);
1732
    auto f = parse_fn(p, proto, purity);
1733
    ret mk_item(p, lo, f.body.span.hi, t._0, ast::item_fn(f, t._1), attrs);
G
Graydon Hoare 已提交
1734 1735
}

1736
fn parse_obj_field(&parser p) -> ast::obj_field {
1737
    auto mut = parse_mutability(p);
G
Graydon Hoare 已提交
1738
    auto ty = parse_ty(p);
1739
    auto ident = parse_value_ident(p);
1740
    ret rec(mut=mut, ty=ty, ident=ident, id=p.get_id());
G
Graydon Hoare 已提交
1741 1742
}

1743 1744 1745 1746 1747 1748
fn parse_anon_obj_field(&parser p) -> ast::anon_obj_field {
    auto mut = parse_mutability(p);
    auto ty = parse_ty(p);
    auto ident = parse_value_ident(p);
    expect(p, token::EQ);
    auto expr = parse_expr(p);
1749
    ret rec(mut=mut, ty=ty, expr=expr, ident=ident, id=p.get_id());
1750 1751
}

1752
fn parse_method(&parser p) -> @ast::method {
1753
    auto lo = p.get_lo_pos();
1754
    auto proto = parse_proto(p);
1755
    auto ident = parse_value_ident(p);
1756
    auto f = parse_fn(p, proto, ast::impure_fn);
1757
    auto meth = rec(ident=ident, meth=f, id=p.get_id());
1758
    ret @spanned(lo, f.body.span.hi, meth);
G
Graydon Hoare 已提交
1759 1760
}

1761
fn parse_dtor(&parser p) -> @ast::method {
1762
    auto lo = p.get_last_lo_pos();
1763
    let ast::block b = parse_block(p);
1764
    let vec[ast::arg] inputs = [];
1765
    let @ast::ty output = @spanned(lo, lo, ast::ty_nil);
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    let ast::fn_decl d =
        rec(inputs=inputs,
            output=output,
            purity=ast::impure_fn,
            cf=ast::return,

            // I guess dtors can't have constraints? 
            constraints=[]);
    let ast::_fn f = rec(decl=d, proto=ast::proto_fn, body=b);
    let ast::method_ m =
1776
        rec(ident="drop", meth=f, id=p.get_id());
1777 1778 1779
    ret @spanned(lo, f.body.span.hi, m);
}

1780
fn parse_item_obj(&parser p, ast::layer lyr, &ast::attribute[] attrs) ->
1781
   @ast::item {
1782
    auto lo = p.get_last_lo_pos();
1783
    auto ident = parse_value_ident(p);
G
Graydon Hoare 已提交
1784
    auto ty_params = parse_ty_params(p);
1785
    let ast::spanned[vec[ast::obj_field]] fields =
1786
        parse_seq[ast::obj_field](token::LPAREN, token::RPAREN,
1787
                                  some(token::COMMA), parse_obj_field, p);
1788
    let vec[@ast::method] meths = [];
1789
    let option::t[@ast::method] dtor = none;
1790 1791
    expect(p, token::LBRACE);
    while (p.peek() != token::RBRACE) {
1792
        if (eat_word(p, "drop")) {
1793
            dtor = some(parse_dtor(p));
1794
        } else { vec::push(meths, parse_method(p)); }
1795
    }
1796
    auto hi = p.get_hi_pos();
1797
    expect(p, token::RBRACE);
1798
    let ast::_obj ob = rec(fields=fields.node, methods=meths, dtor=dtor);
1799
    ret mk_item(p, lo, hi, ident, ast::item_obj(ob, ty_params,
1800
                                                p.get_id()), attrs);
1801 1802
}

1803
fn parse_item_res(&parser p, ast::layer lyr, &ast::attribute[] attrs) ->
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
   @ast::item {
    auto lo = p.get_last_lo_pos();
    auto ident = parse_value_ident(p);
    auto ty_params = parse_ty_params(p);
    expect(p, token::LPAREN);
    auto t = parse_ty(p);
    auto arg_ident = parse_value_ident(p);
    expect(p, token::RPAREN);
    auto dtor = parse_block(p);
    auto decl = rec(inputs=[rec(mode=ast::alias(false), ty=t, ident=arg_ident,
                                id=p.get_id())],
                    output=@spanned(lo, lo, ast::ty_nil),
                    purity=ast::impure_fn,
                    cf=ast::return,
                    constraints=[]);
    auto f = rec(decl=decl, proto=ast::proto_fn, body=dtor);
    ret mk_item(p, lo, dtor.span.hi, ident,
                ast::item_res(f, p.get_id(), ty_params, p.get_id()), attrs);
}

1824
fn parse_mod_items(&parser p, token::token term,
1825 1826
                   &ast::attribute[] first_item_attrs) -> ast::_mod {
    auto view_items = if (ivec::len(first_item_attrs) == 0u) {
1827 1828 1829 1830 1831
        parse_view(p)
    } else {
        // Shouldn't be any view items since we've already parsed an item attr
        []
    };
1832
    let vec[@ast::item] items = [];
1833
    auto initial_attrs = first_item_attrs;
1834
    while (p.peek() != term) {
1835
        auto attrs = initial_attrs + parse_outer_attributes(p);
1836
        initial_attrs = ~[];
B
Brian Anderson 已提交
1837
        alt (parse_item(p, attrs)) {
1838
            case (got_item(?i)) { vec::push(items, i); }
1839
            case (_) {
1840
                p.fatal("expected item but found " +
1841
                          token::to_str(p.get_reader(), p.peek()));
1842 1843
            }
        }
1844
    }
1845
    ret rec(view_items=view_items, items=items);
1846
}
1847

1848
fn parse_item_const(&parser p, &ast::attribute[] attrs) -> @ast::item {
1849
    auto lo = p.get_last_lo_pos();
1850
    auto ty = parse_ty(p);
1851
    auto id = parse_value_ident(p);
1852
    expect(p, token::EQ);
1853
    auto e = parse_expr(p);
1854
    auto hi = p.get_hi_pos();
1855
    expect(p, token::SEMI);
1856
    ret mk_item(p, lo, hi, id, ast::item_const(ty, e), attrs);
1857 1858
}

1859
fn parse_item_mod(&parser p, &ast::attribute[] attrs) -> @ast::item {
1860
    auto lo = p.get_last_lo_pos();
1861
    auto id = parse_ident(p);
1862
    expect(p, token::LBRACE);
1863
    auto inner_attrs = parse_inner_attrs_and_next(p);
1864
    auto first_item_outer_attrs = inner_attrs._1;
1865
    auto m = parse_mod_items(p, token::RBRACE, first_item_outer_attrs);
1866
    auto hi = p.get_hi_pos();
1867
    expect(p, token::RBRACE);
1868
    ret mk_item(p, lo, hi, id, ast::item_mod(m), attrs + inner_attrs._0);
1869 1870
}

1871 1872
fn parse_item_native_type(&parser p, &ast::attribute[] attrs)
        -> @ast::native_item {
1873
    auto t = parse_type_decl(p);
1874
    auto hi = p.get_hi_pos();
1875
    expect(p, token::SEMI);
1876
    ret @rec(ident=t._1,
1877
             attrs=attrs,
1878 1879 1880
             node=ast::native_item_ty,
             id=p.get_id(),
             span=rec(lo=t._0, hi=hi));
1881 1882
}

1883 1884
fn parse_item_native_fn(&parser p, &ast::attribute[] attrs)
        -> @ast::native_item {
1885
    auto lo = p.get_last_lo_pos();
1886
    auto t = parse_fn_header(p);
1887
    auto decl = parse_fn_decl(p, ast::impure_fn);
1888
    auto link_name = none;
1889
    if (p.peek() == token::EQ) {
1890
        p.bump();
1891
        link_name = some(parse_str(p));
1892
    }
1893
    auto hi = p.get_hi_pos();
1894
    expect(p, token::SEMI);
1895
    ret @rec(ident=t._0,
1896
             attrs=attrs,
1897 1898 1899
             node=ast::native_item_fn(link_name, decl, t._1),
             id=p.get_id(),
             span=rec(lo=lo, hi=hi));
1900 1901
}

1902 1903
fn parse_native_item(&parser p, &ast::attribute[] attrs)
        -> @ast::native_item {
T
Tim Chevalier 已提交
1904
    parse_layer(p);
1905
    if (eat_word(p, "type")) {
1906
        ret parse_item_native_type(p, attrs);
1907
    } else if (eat_word(p, "fn")) {
1908
        ret parse_item_native_fn(p, attrs);
1909
    } else { unexpected(p, p.peek()); fail; }
1910 1911
}

1912
fn parse_native_mod_items(&parser p, &str native_name, ast::native_abi abi,
1913 1914 1915
                          &ast::attribute[] first_item_attrs)
        -> ast::native_mod {
    auto view_items = if (ivec::len(first_item_attrs) == 0u) {
1916 1917 1918 1919 1920
        parse_native_view(p)
    } else {
        // Shouldn't be any view items since we've already parsed an item attr
        []
    };
1921
    let vec[@ast::native_item] items = [];
1922 1923 1924
    auto initial_attrs = first_item_attrs;
    while (p.peek() != token::RBRACE) {
        auto attrs = initial_attrs + parse_outer_attributes(p);
1925
        initial_attrs = ~[];
1926 1927
        items += [parse_native_item(p, attrs)];
    }
1928 1929
    ret rec(native_name=native_name,
            abi=abi,
1930
            view_items=view_items,
1931
            items=items);
1932 1933
}

1934
fn parse_item_native_mod(&parser p, &ast::attribute[] attrs) -> @ast::item {
1935
    auto lo = p.get_last_lo_pos();
1936
    auto abi = ast::native_abi_cdecl;
1937
    if (!is_word(p, "mod")) {
1938
        auto t = parse_str(p);
1939 1940
        if (str::eq(t, "cdecl")) {
        } else if (str::eq(t, "rust")) {
1941
            abi = ast::native_abi_rust;
1942
        } else if (str::eq(t, "llvm")) {
1943
            abi = ast::native_abi_llvm;
1944
        } else if (str::eq(t, "rust-intrinsic")) {
1945
            abi = ast::native_abi_rust_intrinsic;
1946
        } else { p.fatal("unsupported abi: " + t); fail; }
R
Rafael Avila de Espindola 已提交
1947
    }
1948
    expect_word(p, "mod");
1949
    auto id = parse_ident(p);
1950
    auto native_name;
1951 1952
    if (p.peek() == token::EQ) {
        expect(p, token::EQ);
1953
        native_name = parse_str(p);
1954
    } else {
1955
        native_name = id;
1956
    }
1957
    expect(p, token::LBRACE);
1958 1959 1960 1961 1962
    auto more_attrs = parse_inner_attrs_and_next(p);
    auto inner_attrs = more_attrs._0;
    auto first_item_outer_attrs = more_attrs._1;
    auto m = parse_native_mod_items(p, native_name, abi,
                                    first_item_outer_attrs);
1963
    auto hi = p.get_hi_pos();
1964
    expect(p, token::RBRACE);
1965
    ret mk_item(p, lo, hi, id, ast::item_native_mod(m), attrs + inner_attrs);
1966 1967
}

1968
fn parse_type_decl(&parser p) -> tup(uint, ast::ident) {
1969
    auto lo = p.get_last_lo_pos();
1970
    auto id = parse_ident(p);
1971 1972 1973
    ret tup(lo, id);
}

1974
fn parse_item_type(&parser p, &ast::attribute[] attrs) -> @ast::item {
1975
    auto t = parse_type_decl(p);
1976
    auto tps = parse_ty_params(p);
1977
    expect(p, token::EQ);
1978
    auto ty = parse_ty(p);
1979
    auto hi = p.get_hi_pos();
1980
    expect(p, token::SEMI);
1981
    ret mk_item(p, t._0, hi, t._1, ast::item_ty(ty, tps), attrs);
1982 1983
}

1984
fn parse_item_tag(&parser p, &ast::attribute[] attrs) -> @ast::item {
1985
    auto lo = p.get_last_lo_pos();
1986
    auto id = parse_ident(p);
P
Patrick Walton 已提交
1987
    auto ty_params = parse_ty_params(p);
1988
    let vec[ast::variant] variants = [];
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
    // Newtype syntax
    if (p.peek() == token::EQ) {
        if (p.get_bad_expr_words().contains_key(id)) {
            p.fatal("found " + id + " in tag constructor position");
        }
        p.bump();
        auto ty = parse_ty(p);
        expect(p, token::SEMI);
        auto variant = spanned(ty.span.lo, ty.span.hi,
                               rec(name=id,
                                   args=[rec(ty=ty, id=p.get_id())],
                                   id=p.get_id()));
        ret mk_item(p, lo, ty.span.hi, id,
                    ast::item_tag([variant], ty_params), attrs);
    }
2004 2005
    expect(p, token::LBRACE);
    while (p.peek() != token::RBRACE) {
2006 2007
        auto tok = p.peek();
        alt (tok) {
2008
            case (token::IDENT(?name, _)) {
2009
                check_bad_word(p);
2010
                auto vlo = p.get_lo_pos();
2011
                p.bump();
2012
                let vec[ast::variant_arg] args = [];
2013
                alt (p.peek()) {
2014
                    case (token::LPAREN) {
2015 2016 2017
                        auto arg_tys =
                            parse_seq(token::LPAREN, token::RPAREN,
                                      some(token::COMMA), parse_ty, p);
2018
                        for (@ast::ty ty in arg_tys.node) {
2019
                            args += [rec(ty=ty, id=p.get_id())];
2020
                        }
2021
                    }
2022
                    case (_) {/* empty */ }
2023
                }
2024
                auto vhi = p.get_hi_pos();
2025
                expect(p, token::SEMI);
T
Tim Chevalier 已提交
2026
                p.get_id();
2027 2028 2029
                auto vr =
                    rec(name=p.get_str(name),
                        args=args,
2030
                        id=p.get_id());
2031
                variants += [spanned(vlo, vhi, vr)];
2032
            }
2033
            case (token::RBRACE) {/* empty */ }
2034
            case (_) {
2035
                p.fatal("expected name of variant or '}' but found " +
2036
                          token::to_str(p.get_reader(), tok));
2037 2038 2039
            }
        }
    }
2040
    auto hi = p.get_hi_pos();
2041
    p.bump();
2042
    ret mk_item(p, lo, hi, id, ast::item_tag(variants, ty_params), attrs);
2043 2044
}

2045
fn parse_layer(&parser p) -> ast::layer {
2046 2047 2048 2049
    if (eat_word(p, "state")) {
        ret ast::layer_state;
    } else if (eat_word(p, "gc")) {
        ret ast::layer_gc;
2050
    } else { ret ast::layer_value; }
2051 2052 2053
    fail;
}

2054
fn parse_auth(&parser p) -> ast::_auth {
2055 2056
    if (eat_word(p, "unsafe")) {
        ret ast::auth_unsafe;
2057
    } else { unexpected(p, p.peek()); }
2058 2059 2060
    fail;
}

2061
tag parsed_item { got_item(@ast::item); no_item; fn_no_item; }
G
Graydon Hoare 已提交
2062

2063
fn parse_item(&parser p, &ast::attribute[] attrs) -> parsed_item {
2064
    if (eat_word(p, "const")) {
2065
        ret got_item(parse_item_const(p, attrs));
2066
    } else if (eat_word(p, "fn")) {
2067
        // This is an anonymous function
2068

2069
        if (p.peek() == token::LPAREN) { ret fn_no_item; }
2070 2071
        ret got_item(parse_item_fn_or_iter(p, ast::impure_fn, ast::proto_fn,
                                           attrs));
2072
    } else if (eat_word(p, "pred")) {
2073 2074
        ret got_item(parse_item_fn_or_iter(p, ast::pure_fn, ast::proto_fn,
                                           attrs));
2075
    } else if (eat_word(p, "iter")) {
2076 2077
        ret got_item(parse_item_fn_or_iter(p, ast::impure_fn, ast::proto_iter,
                                           attrs));
2078
    } else if (eat_word(p, "mod")) {
B
Brian Anderson 已提交
2079
        ret got_item(parse_item_mod(p, attrs));
2080
    } else if (eat_word(p, "native")) {
2081
        ret got_item(parse_item_native_mod(p, attrs));
2082 2083 2084
    }
    auto lyr = parse_layer(p);
    if (eat_word(p, "type")) {
2085
        ret got_item(parse_item_type(p, attrs));
2086
    } else if (eat_word(p, "tag")) {
2087
        ret got_item(parse_item_tag(p, attrs));
2088
    } else if (eat_word(p, "obj")) {
2089
        ret got_item(parse_item_obj(p, lyr, attrs));
2090
    } else if (eat_word(p, "resource")) {
2091
        ret got_item(parse_item_res(p, lyr, attrs));
2092
    } else { ret no_item; }
2093 2094
}

2095 2096
// A type to distingush between the parsing of item attributes or syntax
// extensions, which both begin with token.POUND
2097
type attr_or_ext = option::t[either::t[ast::attribute[], @ast::expr]];
2098

2099
fn parse_outer_attrs_or_ext(&parser p) -> attr_or_ext {
2100 2101 2102 2103
    if (p.peek() == token::POUND) {
        auto lo = p.get_lo_pos();
        p.bump();
        if (p.peek() == token::LBRACKET) {
2104
            auto first_attr = parse_attribute_naked(p, ast::attr_outer, lo);
2105
            ret some(left(~[first_attr] + parse_outer_attributes(p)));
2106
        } else {
2107
            ret some(right(parse_syntax_ext_naked(p, lo)));
2108 2109 2110 2111 2112 2113
        }
    } else {
        ret none;
    }
}

2114
// Parse attributes that appear before an item
2115 2116
fn parse_outer_attributes(&parser p) -> ast::attribute[] {
    let ast::attribute[] attrs = ~[];
2117
    while (p.peek() == token::POUND) {
2118
        attrs += ~[parse_attribute(p, ast::attr_outer)];
2119
    }
B
Brian Anderson 已提交
2120 2121 2122
    ret attrs;
}

2123
fn parse_attribute(&parser p, ast::attr_style style) -> ast::attribute {
2124 2125
    auto lo = p.get_lo_pos();
    expect(p, token::POUND);
2126
    ret parse_attribute_naked(p, style, lo);
2127 2128
}

2129 2130
fn parse_attribute_naked(&parser p, ast::attr_style style,
                         uint lo) -> ast::attribute {
2131 2132 2133 2134
    expect(p, token::LBRACKET);
    auto meta_item = parse_meta_item(p);
    expect(p, token::RBRACKET);
    auto hi = p.get_hi_pos();
2135
    ret spanned(lo, hi, rec(style=style, value=*meta_item));
2136 2137
}

2138 2139 2140 2141 2142 2143
// Parse attributes that appear after the opening of an item, each terminated
// by a semicolon. In addition to a vector of inner attributes, this function
// also returns a vector that may contain the first outer attribute of the
// next item (since we can't know whether the attribute is an inner attribute
// of the containing item or an outer attribute of the first contained item
// until we see the semi).
2144 2145 2146 2147
fn parse_inner_attrs_and_next(&parser p) -> tup(ast::attribute[],
                                                ast::attribute[]) {
    let ast::attribute[] inner_attrs = ~[];
    let ast::attribute[] next_outer_attrs = ~[];
2148
    while (p.peek() == token::POUND) {
2149
        auto attr = parse_attribute(p, ast::attr_inner);
2150 2151
        if (p.peek() == token::SEMI) {
            p.bump();
2152
            inner_attrs += ~[attr];
2153
        } else {
2154 2155 2156 2157 2158
            // It's not really an inner attribute
            auto outer_attr = spanned(attr.span.lo,
                                      attr.span.hi,
                                      rec(style=ast::attr_outer,
                                          value=attr.node.value));
2159
            next_outer_attrs += ~[outer_attr];
2160 2161 2162 2163 2164 2165
            break;
        }
    }
    ret tup(inner_attrs, next_outer_attrs);
}

2166
fn parse_meta_item(&parser p) -> @ast::meta_item {
2167
    auto lo = p.get_lo_pos();
2168 2169
    auto ident = parse_ident(p);
    alt (p.peek()) {
2170
        case (token::EQ) {
2171
            p.bump();
2172 2173 2174
            auto lit = parse_lit(p);
            auto hi = p.get_hi_pos();
            ret @spanned(lo, hi, ast::meta_name_value(ident, lit));
2175 2176 2177 2178 2179 2180 2181 2182 2183
        }
        case (token::LPAREN) {
            auto inner_items = parse_meta_seq(p);
            auto hi = p.get_hi_pos();
            ret @spanned(lo, hi, ast::meta_list(ident, inner_items));
        }
        case (_) {
            auto hi = p.get_hi_pos();
            ret @spanned(lo, hi, ast::meta_word(ident));
2184 2185 2186 2187
        }
    }
}

2188 2189 2190
fn parse_meta_seq(&parser p) -> vec[@ast::meta_item] {
    ret parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
                  parse_meta_item, p).node;
2191 2192
}

2193
fn parse_optional_meta(&parser p) -> vec[@ast::meta_item] {
2194
    alt (p.peek()) {
2195
        case (token::LPAREN) { ret parse_meta_seq(p); }
2196
        case (_) { let vec[@ast::meta_item] v = []; ret v; }
2197 2198 2199
    }
}

2200
fn parse_use(&parser p) -> @ast::view_item {
2201
    auto lo = p.get_last_lo_pos();
2202 2203
    auto ident = parse_ident(p);
    auto metadata = parse_optional_meta(p);
2204
    auto hi = p.get_hi_pos();
2205
    expect(p, token::SEMI);
2206 2207
    auto use_decl =
        ast::view_item_use(ident, metadata, p.get_id());
2208
    ret @spanned(lo, hi, use_decl);
2209 2210
}

2211
fn parse_rest_import_name(&parser p, ast::ident first,
2212 2213
                          option::t[ast::ident] def_ident) ->
   @ast::view_item {
2214
    auto lo = p.get_lo_pos();
2215
    let vec[ast::ident] identifiers = [first];
2216 2217 2218
    let bool glob = false;
    while (true) {
        alt (p.peek()) {
2219
            case (token::SEMI) { p.bump(); break; }
2220
            case (token::MOD_SEP) {
2221
                if (glob) { p.fatal("cannot path into a glob"); }
2222 2223
                p.bump();
            }
2224
            case (_) { p.fatal("expecting '::' or ';'"); }
2225 2226
        }
        alt (p.peek()) {
2227 2228 2229 2230
            case (token::IDENT(_, _)) { identifiers += [parse_ident(p)]; }
            case (
                 //the lexer can't tell the different kinds of stars apart ) :
                 token::BINOP(token::STAR)) {
2231 2232 2233
                glob = true;
                p.bump();
            }
2234
            case (_) { p.fatal("expecting an identifier, or '*'"); }
2235
        }
2236
    }
2237
    auto hi = p.get_hi_pos();
2238
    auto import_decl;
2239
    alt (def_ident) {
2240
        case (some(?i)) {
2241
            if (glob) { p.fatal("globbed imports can't be renamed"); }
2242
            import_decl =
2243
                ast::view_item_import(i, identifiers, p.get_id());
2244 2245
        }
        case (_) {
2246
            if (glob) {
2247
                import_decl =
2248
                    ast::view_item_import_glob(identifiers, p.get_id());
2249
            } else {
2250
                auto len = vec::len(identifiers);
2251 2252
                import_decl =
                    ast::view_item_import(identifiers.(len - 1u), identifiers,
2253
                                          p.get_id());
2254
            }
2255 2256
        }
    }
2257
    ret @spanned(lo, hi, import_decl);
2258 2259
}

2260 2261
fn parse_full_import_name(&parser p, ast::ident def_ident) ->
   @ast::view_item {
2262
    alt (p.peek()) {
2263
        case (token::IDENT(?i, _)) {
2264
            p.bump();
G
Graydon Hoare 已提交
2265
            ret parse_rest_import_name(p, p.get_str(i), some(def_ident));
2266
        }
2267
        case (_) { p.fatal("expecting an identifier"); }
2268
    }
2269
    fail;
2270 2271
}

2272
fn parse_import(&parser p) -> @ast::view_item {
2273
    alt (p.peek()) {
2274
        case (token::IDENT(?i, _)) {
2275 2276
            p.bump();
            alt (p.peek()) {
2277
                case (token::EQ) {
2278
                    p.bump();
G
Graydon Hoare 已提交
2279
                    ret parse_full_import_name(p, p.get_str(i));
2280 2281
                }
                case (_) {
2282
                    ret parse_rest_import_name(p, p.get_str(i), none);
2283 2284 2285
                }
            }
        }
2286
        case (_) { p.fatal("expecting an identifier"); }
2287
    }
2288
    fail;
2289 2290
}

2291
fn parse_export(&parser p) -> @ast::view_item {
2292
    auto lo = p.get_last_lo_pos();
2293
    auto id = parse_ident(p);
2294
    auto hi = p.get_hi_pos();
2295
    expect(p, token::SEMI);
2296
    ret @spanned(lo, hi, ast::view_item_export(id, p.get_id()));
2297 2298
}

2299
fn parse_view_item(&parser p) -> @ast::view_item {
2300 2301 2302 2303
    if (eat_word(p, "use")) {
        ret parse_use(p);
    } else if (eat_word(p, "import")) {
        ret parse_import(p);
2304
    } else if (eat_word(p, "export")) { ret parse_export(p); } else { fail; }
2305 2306
}

2307 2308
fn is_view_item(&parser p) -> bool {
    alt (p.peek()) {
2309
        case (token::IDENT(?sid, false)) {
2310
            auto st = p.get_str(sid);
2311
            ret str::eq(st, "use") || str::eq(st, "import") ||
2312
                    str::eq(st, "export");
2313 2314
        }
        case (_) { ret false; }
2315 2316 2317 2318
    }
    ret false;
}

2319
fn parse_view(&parser p) -> vec[@ast::view_item] {
2320
    let vec[@ast::view_item] items = [];
2321
    while (is_view_item(p)) { items += [parse_view_item(p)]; }
2322
    ret items;
2323 2324
}

2325
fn parse_native_view(&parser p) -> vec[@ast::view_item] {
2326
    let vec[@ast::view_item] items = [];
2327
    while (is_view_item(p)) { items += [parse_view_item(p)]; }
2328 2329 2330
    ret items;
}

2331 2332 2333 2334
fn parse_crate_from_source_file(&str input, &ast::crate_cfg cfg,
                                &codemap::codemap cm) -> @ast::crate {
    auto sess = @rec(cm=cm, mutable next_id=0);
    auto p = new_parser(sess, cfg, input, 0u);
2335
    auto lo = p.get_lo_pos();
2336 2337 2338 2339
    auto crate_attrs = parse_inner_attrs_and_next(p);
    auto first_item_outer_attrs = crate_attrs._1;
    auto m = parse_mod_items(p, token::EOF,
                             first_item_outer_attrs);
2340
    ret @spanned(lo, p.get_lo_pos(), rec(directives=[],
2341
                                         module=m,
2342
                                         attrs=crate_attrs._0,
2343
                                         config=p.get_cfg()));
2344 2345
}

2346 2347 2348 2349 2350 2351 2352 2353 2354
fn parse_str(&parser p) -> ast::ident {
    alt (p.peek()) {
        case (token::LIT_STR(?s)) {
            p.bump();
            ret p.get_str(s);
        }
        case (_) { fail; }
    }
}
2355

2356 2357 2358 2359 2360
// Logic for parsing crate files (.rc)
//
// Each crate file is a sequence of directives.
//
// Each directive imperatively extends its environment with 0 or more items.
2361
fn parse_crate_directive(&parser p, &ast::attribute[] first_outer_attr)
2362 2363 2364
    -> ast::crate_directive {

    // Collect the next attributes
2365
    auto outer_attrs = first_outer_attr + parse_outer_attributes(p);
2366
    // In a crate file outer attributes are only going to apply to mods
2367
    auto expect_mod = ivec::len(outer_attrs) > 0u;
2368

2369
    auto lo = p.get_lo_pos();
2370 2371
    if (expect_mod || is_word(p, "mod")) {
        expect_word(p, "mod");
2372
        auto id = parse_ident(p);
2373 2374 2375 2376
        auto file_opt =
            alt (p.peek()) {
                case (token::EQ) {
                    p.bump();
2377
                    some(parse_str(p))
2378 2379 2380
                }
                case (_) { none }
            };
2381
        alt (p.peek()) {
2382 2383 2384
            case (
                 // mod x = "foo.rs";
                 token::SEMI) {
2385 2386
                auto hi = p.get_hi_pos();
                p.bump();
2387 2388
                ret spanned(lo, hi, ast::cdir_src_mod(id, file_opt,
                                                      outer_attrs));
2389
            }
2390 2391 2392
            case (
                 // mod x = "foo_dir" { ...directives... }
                 token::LBRACE) {
2393
                p.bump();
2394 2395 2396 2397 2398
                auto inner_attrs = parse_inner_attrs_and_next(p);
                auto mod_attrs = outer_attrs + inner_attrs._0;
                auto next_outer_attr = inner_attrs._1;
                auto cdirs = parse_crate_directives(p, token::RBRACE,
                                                    next_outer_attr);
2399 2400
                auto hi = p.get_hi_pos();
                expect(p, token::RBRACE);
2401 2402
                ret spanned(lo, hi, ast::cdir_dir_mod(id, file_opt, cdirs,
                                                      mod_attrs));
2403
            }
2404
            case (?t) { unexpected(p, t); }
2405
        }
2406 2407 2408 2409 2410 2411 2412
    } else if (eat_word(p, "auth")) {
        auto n = parse_path(p);
        expect(p, token::EQ);
        auto a = parse_auth(p);
        auto hi = p.get_hi_pos();
        expect(p, token::SEMI);
        ret spanned(lo, hi, ast::cdir_auth(n, a));
2413
    } else if (is_view_item(p)) {
2414 2415 2416
        auto vi = parse_view_item(p);
        ret spanned(lo, vi.span.hi, ast::cdir_view_item(vi));
    } else {
2417
        ret p.fatal("expected crate directive");
2418 2419 2420
    }
}

2421
fn parse_crate_directives(&parser p, token::token term,
2422
                          &ast::attribute[] first_outer_attr) ->
2423
   vec[@ast::crate_directive] {
2424 2425 2426 2427

    // This is pretty ugly. If we have an outer attribute then we can't accept
    // seeing the terminator next, so if we do see it then fail the same way
    // parse_crate_directive would
2428
    if (ivec::len(first_outer_attr) > 0u && p.peek() == term) {
2429 2430 2431
        expect_word(p, "mod");
    }

2432
    let vec[@ast::crate_directive] cdirs = [];
2433
    while (p.peek() != term) {
2434
        auto cdir = @parse_crate_directive(p, first_outer_attr);
2435
        vec::push(cdirs, cdir);
2436
    }
2437
    ret cdirs;
2438 2439
}

2440 2441 2442 2443
fn parse_crate_from_crate_file(&str input, &ast::crate_cfg cfg,
                               &codemap::codemap cm) -> @ast::crate {
    auto sess = @rec(cm=cm, mutable next_id=0);
    auto p = new_parser(sess, cfg, input, 0u);
2444
    auto lo = p.get_lo_pos();
2445
    auto prefix = std::fs::dirname(p.get_filemap().name);
2446 2447 2448 2449
    auto leading_attrs = parse_inner_attrs_and_next(p);
    auto crate_attrs = leading_attrs._0;
    auto first_cdir_attr = leading_attrs._1;
    auto cdirs = parse_crate_directives(p, token::EOF, first_cdir_attr);
2450
    let vec[str] deps = [];
2451 2452 2453 2454 2455 2456
    auto cx = @rec(p=p,
                   mode=eval::mode_parse,
                   mutable deps=deps,
                   sess=sess,
                   mutable chpos=p.get_chpos(),
                   cfg = p.get_cfg());
2457
    auto m =
2458
        eval::eval_crate_directives_to_mod(cx, cdirs, prefix);
2459
    auto hi = p.get_hi_pos();
2460
    expect(p, token::EOF);
2461 2462
    ret @spanned(lo, hi, rec(directives=cdirs,
                             module=m,
2463
                             attrs=crate_attrs,
2464
                             config=p.get_cfg()));
2465
}
2466 2467 2468 2469 2470 2471 2472
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
2473
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
2474 2475
// End:
//