summaryrefslogtreecommitdiffstats
path: root/src/tools/rust-analyzer/crates/parser/src/grammar/types.rs
blob: 5c6e18fee8bffdde54ce186ac0004d428ed5a697 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use super::*;

pub(super) const TYPE_FIRST: TokenSet = paths::PATH_FIRST.union(TokenSet::new(&[
    T!['('],
    T!['['],
    T![<],
    T![!],
    T![*],
    T![&],
    T![_],
    T![fn],
    T![unsafe],
    T![extern],
    T![for],
    T![impl],
    T![dyn],
    T![Self],
]));

const TYPE_RECOVERY_SET: TokenSet = TokenSet::new(&[
    T![')'],
    T![,],
    // test_err struct_field_recover
    // struct S { f pub g: () }
    T![pub],
]);

pub(crate) fn type_(p: &mut Parser<'_>) {
    type_with_bounds_cond(p, true);
}

pub(super) fn type_no_bounds(p: &mut Parser<'_>) {
    type_with_bounds_cond(p, false);
}

fn type_with_bounds_cond(p: &mut Parser<'_>, allow_bounds: bool) {
    match p.current() {
        T!['('] => paren_or_tuple_type(p),
        T![!] => never_type(p),
        T![*] => ptr_type(p),
        T!['['] => array_or_slice_type(p),
        T![&] => ref_type(p),
        T![_] => infer_type(p),
        T![fn] | T![unsafe] | T![extern] => fn_ptr_type(p),
        T![for] => for_type(p, allow_bounds),
        T![impl] => impl_trait_type(p),
        T![dyn] => dyn_trait_type(p),
        // Some path types are not allowed to have bounds (no plus)
        T![<] => path_type_(p, allow_bounds),
        _ if paths::is_path_start(p) => path_or_macro_type_(p, allow_bounds),
        _ => {
            p.err_recover("expected type", TYPE_RECOVERY_SET);
        }
    }
}

pub(super) fn ascription(p: &mut Parser<'_>) {
    assert!(p.at(T![:]));
    p.bump(T![:]);
    if p.at(T![=]) {
        // recover from `let x: = expr;`, `const X: = expr;` and similars
        // hopefully no type starts with `=`
        p.error("missing type");
        return;
    }
    type_(p);
}

fn paren_or_tuple_type(p: &mut Parser<'_>) {
    assert!(p.at(T!['(']));
    let m = p.start();
    p.bump(T!['(']);
    let mut n_types: u32 = 0;
    let mut trailing_comma: bool = false;
    while !p.at(EOF) && !p.at(T![')']) {
        n_types += 1;
        type_(p);
        if p.eat(T![,]) {
            trailing_comma = true;
        } else {
            trailing_comma = false;
            break;
        }
    }
    p.expect(T![')']);

    let kind = if n_types == 1 && !trailing_comma {
        // test paren_type
        // type T = (i32);
        PAREN_TYPE
    } else {
        // test unit_type
        // type T = ();

        // test singleton_tuple_type
        // type T = (i32,);
        TUPLE_TYPE
    };
    m.complete(p, kind);
}

// test never_type
// type Never = !;
fn never_type(p: &mut Parser<'_>) {
    assert!(p.at(T![!]));
    let m = p.start();
    p.bump(T![!]);
    m.complete(p, NEVER_TYPE);
}

fn ptr_type(p: &mut Parser<'_>) {
    assert!(p.at(T![*]));
    let m = p.start();
    p.bump(T![*]);

    match p.current() {
        // test pointer_type_mut
        // type M = *mut ();
        // type C = *mut ();
        T![mut] | T![const] => p.bump_any(),
        _ => {
            // test_err pointer_type_no_mutability
            // type T = *();
            p.error(
                "expected mut or const in raw pointer type \
                 (use `*mut T` or `*const T` as appropriate)",
            );
        }
    };

    type_no_bounds(p);
    m.complete(p, PTR_TYPE);
}

fn array_or_slice_type(p: &mut Parser<'_>) {
    assert!(p.at(T!['[']));
    let m = p.start();
    p.bump(T!['[']);

    type_(p);
    let kind = match p.current() {
        // test slice_type
        // type T = [()];
        T![']'] => {
            p.bump(T![']']);
            SLICE_TYPE
        }

        // test array_type
        // type T = [(); 92];
        T![;] => {
            p.bump(T![;]);
            expressions::expr(p);
            p.expect(T![']']);
            ARRAY_TYPE
        }
        // test_err array_type_missing_semi
        // type T = [() 92];
        _ => {
            p.error("expected `;` or `]`");
            SLICE_TYPE
        }
    };
    m.complete(p, kind);
}

// test reference_type;
// type A = &();
// type B = &'static ();
// type C = &mut ();
fn ref_type(p: &mut Parser<'_>) {
    assert!(p.at(T![&]));
    let m = p.start();
    p.bump(T![&]);
    if p.at(LIFETIME_IDENT) {
        lifetime(p);
    }
    p.eat(T![mut]);
    type_no_bounds(p);
    m.complete(p, REF_TYPE);
}

// test placeholder_type
// type Placeholder = _;
fn infer_type(p: &mut Parser<'_>) {
    assert!(p.at(T![_]));
    let m = p.start();
    p.bump(T![_]);
    m.complete(p, INFER_TYPE);
}

// test fn_pointer_type
// type A = fn();
// type B = unsafe fn();
// type C = unsafe extern "C" fn();
// type D = extern "C" fn ( u8 , ... ) -> u8;
fn fn_ptr_type(p: &mut Parser<'_>) {
    let m = p.start();
    p.eat(T![unsafe]);
    if p.at(T![extern]) {
        abi(p);
    }
    // test_err fn_pointer_type_missing_fn
    // type F = unsafe ();
    if !p.eat(T![fn]) {
        m.abandon(p);
        p.error("expected `fn`");
        return;
    }
    if p.at(T!['(']) {
        params::param_list_fn_ptr(p);
    } else {
        p.error("expected parameters");
    }
    // test fn_pointer_type_with_ret
    // type F = fn() -> ();
    opt_ret_type(p);
    m.complete(p, FN_PTR_TYPE);
}

pub(super) fn for_binder(p: &mut Parser<'_>) {
    assert!(p.at(T![for]));
    p.bump(T![for]);
    if p.at(T![<]) {
        generic_params::opt_generic_param_list(p);
    } else {
        p.error("expected `<`");
    }
}

// test for_type
// type A = for<'a> fn() -> ();
// type B = for<'a> unsafe extern "C" fn(&'a ()) -> ();
// type Obj = for<'a> PartialEq<&'a i32>;
pub(super) fn for_type(p: &mut Parser<'_>, allow_bounds: bool) {
    assert!(p.at(T![for]));
    let m = p.start();
    for_binder(p);
    match p.current() {
        T![fn] | T![unsafe] | T![extern] => {}
        // OK: legacy trait object format
        _ if paths::is_use_path_start(p) => {}
        _ => {
            p.error("expected a function pointer or path");
        }
    }
    type_no_bounds(p);
    let completed = m.complete(p, FOR_TYPE);

    // test no_dyn_trait_leading_for
    // type A = for<'a> Test<'a> + Send;
    if allow_bounds {
        opt_type_bounds_as_dyn_trait_type(p, completed);
    }
}

// test impl_trait_type
// type A = impl Iterator<Item=Foo<'a>> + 'a;
fn impl_trait_type(p: &mut Parser<'_>) {
    assert!(p.at(T![impl]));
    let m = p.start();
    p.bump(T![impl]);
    generic_params::bounds_without_colon(p);
    m.complete(p, IMPL_TRAIT_TYPE);
}

// test dyn_trait_type
// type A = dyn Iterator<Item=Foo<'a>> + 'a;
fn dyn_trait_type(p: &mut Parser<'_>) {
    assert!(p.at(T![dyn]));
    let m = p.start();
    p.bump(T![dyn]);
    generic_params::bounds_without_colon(p);
    m.complete(p, DYN_TRAIT_TYPE);
}

// test path_type
// type A = Foo;
// type B = ::Foo;
// type C = self::Foo;
// type D = super::Foo;
pub(super) fn path_type(p: &mut Parser<'_>) {
    path_type_(p, true);
}

// test macro_call_type
// type A = foo!();
// type B = crate::foo!();
fn path_or_macro_type_(p: &mut Parser<'_>, allow_bounds: bool) {
    assert!(paths::is_path_start(p));
    let r = p.start();
    let m = p.start();

    paths::type_path(p);

    let kind = if p.at(T![!]) && !p.at(T![!=]) {
        items::macro_call_after_excl(p);
        m.complete(p, MACRO_CALL);
        MACRO_TYPE
    } else {
        m.abandon(p);
        PATH_TYPE
    };

    let path = r.complete(p, kind);

    if allow_bounds {
        opt_type_bounds_as_dyn_trait_type(p, path);
    }
}

pub(super) fn path_type_(p: &mut Parser<'_>, allow_bounds: bool) {
    assert!(paths::is_path_start(p));
    let m = p.start();
    paths::type_path(p);

    // test path_type_with_bounds
    // fn foo() -> Box<T + 'f> {}
    // fn foo() -> Box<dyn T + 'f> {}
    let path = m.complete(p, PATH_TYPE);
    if allow_bounds {
        opt_type_bounds_as_dyn_trait_type(p, path);
    }
}

/// This turns a parsed PATH_TYPE or FOR_TYPE optionally into a DYN_TRAIT_TYPE
/// with a TYPE_BOUND_LIST
fn opt_type_bounds_as_dyn_trait_type(p: &mut Parser<'_>, type_marker: CompletedMarker) {
    assert!(matches!(
        type_marker.kind(),
        SyntaxKind::PATH_TYPE | SyntaxKind::FOR_TYPE | SyntaxKind::MACRO_TYPE
    ));
    if !p.at(T![+]) {
        return;
    }

    // First create a TYPE_BOUND from the completed PATH_TYPE
    let m = type_marker.precede(p).complete(p, TYPE_BOUND);

    // Next setup a marker for the TYPE_BOUND_LIST
    let m = m.precede(p);

    // This gets consumed here so it gets properly set
    // in the TYPE_BOUND_LIST
    p.eat(T![+]);

    // Parse rest of the bounds into the TYPE_BOUND_LIST
    let m = generic_params::bounds_without_colon_m(p, m);

    // Finally precede everything with DYN_TRAIT_TYPE
    m.precede(p).complete(p, DYN_TRAIT_TYPE);
}