blob: 1850258097a38b834c3b9fc954ffdb301fbf2923 [file] [log] [blame]
David Tolnayb79ee962016-09-04 09:39:20 -07001use super::*;
2
David Tolnayb79ee962016-09-04 09:39:20 -07003#[derive(Debug, Clone, Eq, PartialEq)]
4pub enum Ty {
5 /// A variable-length array (`[T]`)
6 Vec(Box<Ty>),
7 /// A fixed length array (`[T; n]`)
8 FixedLengthVec(Box<Ty>, usize),
9 /// A raw pointer (`*const T` or `*mut T`)
10 Ptr(Box<MutTy>),
11 /// A reference (`&'a T` or `&'a mut T`)
12 Rptr(Option<Lifetime>, Box<MutTy>),
13 /// A bare function (e.g. `fn(usize) -> bool`)
14 BareFn(Box<BareFnTy>),
15 /// The never type (`!`)
16 Never,
17 /// A tuple (`(A, B, C, D, ...)`)
18 Tup(Vec<Ty>),
19 /// A path (`module::module::...::Type`), optionally
20 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
21 ///
22 /// Type parameters are stored in the Path itself
23 Path(Option<QSelf>, Path),
24 /// Something like `A+B`. Note that `B` must always be a path.
25 ObjectSum(Box<Ty>, Vec<TyParamBound>),
26 /// A type like `for<'a> Foo<&'a Bar>`
27 PolyTraitRef(Vec<TyParamBound>),
28 /// An `impl TraitA+TraitB` type.
29 ImplTrait(Vec<TyParamBound>),
30 /// No-op; kept solely so that we can pretty-print faithfully
31 Paren(Box<Ty>),
32 /// TyKind::Infer means the type should be inferred instead of it having been
33 /// specified. This can appear anywhere in a type.
34 Infer,
35}
36
37#[derive(Debug, Clone, Eq, PartialEq)]
38pub struct MutTy {
39 pub ty: Ty,
40 pub mutability: Mutability,
41}
42
43#[derive(Debug, Clone, Eq, PartialEq)]
44pub enum Mutability {
45 Mutable,
46 Immutable,
47}
48
49#[derive(Debug, Clone, Eq, PartialEq)]
50pub struct Path {
51 pub global: bool,
52 pub segments: Vec<PathSegment>,
53}
54
55/// A segment of a path: an identifier, an optional lifetime, and a set of types.
56///
57/// E.g. `std`, `String` or `Box<T>`
58#[derive(Debug, Clone, Eq, PartialEq)]
59pub struct PathSegment {
60 pub ident: Ident,
61 pub parameters: PathParameters,
62}
63
64impl PathSegment {
65 pub fn ident(ident: Ident) -> Self {
66 PathSegment {
67 ident: ident,
68 parameters: PathParameters::none(),
69 }
70 }
71}
72
73/// Parameters of a path segment.
74///
75/// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
76#[derive(Debug, Clone, Eq, PartialEq)]
77pub enum PathParameters {
78 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`
79 AngleBracketed(AngleBracketedParameterData),
80 /// The `(A, B)` and `C` in `Foo(A, B) -> C`
81 Parenthesized(ParenthesizedParameterData),
82}
83
84impl PathParameters {
85 pub fn none() -> Self {
86 PathParameters::AngleBracketed(AngleBracketedParameterData::default())
87 }
88}
89
90/// A path like `Foo<'a, T>`
91#[derive(Debug, Clone, Eq, PartialEq, Default)]
92pub struct AngleBracketedParameterData {
93 /// The lifetime parameters for this path segment.
94 pub lifetimes: Vec<Lifetime>,
95 /// The type parameters for this path segment, if present.
96 pub types: Vec<Ty>,
97 /// Bindings (equality constraints) on associated types, if present.
98 ///
99 /// E.g., `Foo<A=Bar>`.
100 pub bindings: Vec<TypeBinding>,
101}
102
103/// Bind a type to an associated type: `A=Foo`.
104#[derive(Debug, Clone, Eq, PartialEq)]
105pub struct TypeBinding {
106 pub ident: Ident,
107 pub ty: Ty,
108}
109
110/// A path like `Foo(A,B) -> C`
111#[derive(Debug, Clone, Eq, PartialEq)]
112pub struct ParenthesizedParameterData {
113 /// `(A, B)`
114 pub inputs: Vec<Ty>,
115 /// `C`
116 pub output: Option<Ty>,
117}
118
119#[derive(Debug, Clone, Eq, PartialEq)]
120pub struct PolyTraitRef {
121 /// The `'a` in `<'a> Foo<&'a T>`
122 pub bound_lifetimes: Vec<LifetimeDef>,
123 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
124 pub trait_ref: Path,
125}
126
127/// The explicit Self type in a "qualified path". The actual
128/// path, including the trait and the associated item, is stored
129/// separately. `position` represents the index of the associated
130/// item qualified with this Self type.
131///
132/// ```rust,ignore
133/// <Vec<T> as a::b::Trait>::AssociatedItem
134/// ^~~~~ ~~~~~~~~~~~~~~^
135/// ty position = 3
136///
137/// <Vec<T>>::AssociatedItem
138/// ^~~~~ ^
139/// ty position = 0
140/// ```
141#[derive(Debug, Clone, Eq, PartialEq)]
142pub struct QSelf {
143 pub ty: Box<Ty>,
144 pub position: usize
145}
146
147#[derive(Debug, Clone, Eq, PartialEq)]
148pub struct BareFnTy {
149 pub lifetimes: Vec<LifetimeDef>,
150 pub decl: FnDecl
151}
152
153/// Header (not the body) of a function declaration.
154///
155/// E.g. `fn foo(bar: baz)`
156#[derive(Debug, Clone, Eq, PartialEq)]
157pub struct FnDecl {
158 pub inputs: Vec<Arg>,
159 pub output: FunctionRetTy,
160}
161
162/// An argument in a function header.
163///
164/// E.g. `bar: usize` as in `fn foo(bar: usize)`
165#[derive(Debug, Clone, Eq, PartialEq)]
166pub struct Arg {
167 pub pat: Option<Ident>,
168 pub ty: Ty,
169}
170
171#[derive(Debug, Clone, Eq, PartialEq)]
172pub enum FunctionRetTy {
173 /// Return type is not specified.
174 ///
175 /// Functions default to `()` and
176 /// closures default to inference. Span points to where return
177 /// type would be inserted.
178 Default,
179 /// Everything else
180 Ty(Ty),
181}
182
David Tolnay86eca752016-09-04 11:26:41 -0700183#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700184pub mod parsing {
185 use super::*;
186 use common::parsing::word;
187 use generics::parsing::{lifetime, lifetime_def, ty_param_bound, bound_lifetimes};
188 use nom::{digit, multispace};
189 use std::str;
David Tolnayda4049b2016-09-04 10:59:23 -0700190
David Tolnayf6ccb832016-09-04 15:00:56 -0700191 named!(pub ty<&str, Ty>, alt_complete!(
David Tolnay9d8f1972016-09-04 11:58:48 -0700192 ty_vec
David Tolnayda4049b2016-09-04 10:59:23 -0700193 |
David Tolnay9d8f1972016-09-04 11:58:48 -0700194 ty_fixed_length_vec
David Tolnayb79ee962016-09-04 09:39:20 -0700195 |
David Tolnay9d8f1972016-09-04 11:58:48 -0700196 ty_ptr
197 |
198 ty_rptr
199 |
200 ty_bare_fn
201 |
202 ty_never
203 |
204 ty_tup
205 |
206 ty_path
207 |
208 ty_qpath
209 |
210 ty_impl_trait
211 |
212 ty_paren
213 ));
David Tolnayb79ee962016-09-04 09:39:20 -0700214
David Tolnay9d8f1972016-09-04 11:58:48 -0700215 named!(ty_vec<&str, Ty>, do_parse!(
216 punct!("[") >>
217 elem: ty >>
218 punct!("]") >>
219 (Ty::Vec(Box::new(elem)))
220 ));
David Tolnayb79ee962016-09-04 09:39:20 -0700221
David Tolnay9d8f1972016-09-04 11:58:48 -0700222 named!(ty_fixed_length_vec<&str, Ty>, do_parse!(
223 punct!("[") >>
224 elem: ty >>
225 punct!(";") >>
David Tolnayf6ccb832016-09-04 15:00:56 -0700226 option!(multispace) >>
David Tolnay9d8f1972016-09-04 11:58:48 -0700227 size: map_res!(digit, str::parse) >>
228 (Ty::FixedLengthVec(Box::new(elem), size))
229 ));
230
231 named!(ty_ptr<&str, Ty>, do_parse!(
232 punct!("*") >>
David Tolnayf6ccb832016-09-04 15:00:56 -0700233 mutability: alt_complete!(
David Tolnay9d8f1972016-09-04 11:58:48 -0700234 punct!("const") => { |_| Mutability::Immutable }
235 |
236 punct!("mut") => { |_| Mutability::Mutable }
237 ) >>
238 target: ty >>
239 (Ty::Ptr(Box::new(MutTy {
240 ty: target,
241 mutability: mutability,
242 })))
243 ));
244
245 named!(ty_rptr<&str, Ty>, do_parse!(
246 punct!("&") >>
David Tolnayf6ccb832016-09-04 15:00:56 -0700247 life: option!(lifetime) >>
David Tolnay9d8f1972016-09-04 11:58:48 -0700248 mutability: mutability >>
249 target: ty >>
250 (Ty::Rptr(life, Box::new(MutTy {
251 ty: target,
252 mutability: mutability,
253 })))
254 ));
255
256 named!(ty_bare_fn<&str, Ty>, do_parse!(
257 punct!("fn") >>
258 multispace >>
259 lifetimes: opt_vec!(delimited!(
260 punct!("<"),
261 separated_list!(punct!(","), lifetime_def),
262 punct!(">")
David Tolnay6b7aaf02016-09-04 10:39:25 -0700263 )) >>
David Tolnay9d8f1972016-09-04 11:58:48 -0700264 punct!("(") >>
265 inputs: separated_list!(punct!(","), fn_arg) >>
266 punct!(")") >>
David Tolnayf6ccb832016-09-04 15:00:56 -0700267 output: option!(preceded!(
David Tolnay9d8f1972016-09-04 11:58:48 -0700268 punct!("->"),
269 ty
270 )) >>
271 (Ty::BareFn(Box::new(BareFnTy {
272 lifetimes: lifetimes,
273 decl: FnDecl {
274 inputs: inputs,
275 output: match output {
276 Some(ty) => FunctionRetTy::Ty(ty),
277 None => FunctionRetTy::Default,
278 },
279 },
280 })))
281 ));
282
283 named!(ty_never<&str, Ty>, map!(punct!("!"), |_| Ty::Never));
284
285 named!(ty_tup<&str, Ty>, do_parse!(
286 punct!("(") >>
287 elems: separated_list!(punct!(","), ty) >>
288 punct!(")") >>
289 (Ty::Tup(elems))
290 ));
291
292 named!(ty_path<&str, Ty>, map!(path, |p| Ty::Path(None, p)));
293
294 named!(ty_qpath<&str, Ty>, do_parse!(
295 punct!("<") >>
296 this: map!(ty, Box::new) >>
David Tolnayf6ccb832016-09-04 15:00:56 -0700297 path: option!(preceded!(
David Tolnay9d8f1972016-09-04 11:58:48 -0700298 tuple!(punct!("as"), multispace),
299 path
David Tolnay6b7aaf02016-09-04 10:39:25 -0700300 )) >>
301 punct!(">") >>
David Tolnay9d8f1972016-09-04 11:58:48 -0700302 punct!("::") >>
303 rest: separated_nonempty_list!(punct!("::"), path_segment) >>
304 ({
305 match path {
306 Some(mut path) => {
307 let pos = path.segments.len();
308 path.segments.extend(rest);
309 Ty::Path(Some(QSelf { ty: this, position: pos }), path)
David Tolnayb79ee962016-09-04 09:39:20 -0700310 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700311 None => {
312 Ty::Path(Some(QSelf { ty: this, position: 0 }), Path {
313 global: false,
314 segments: rest,
315 })
316 }
317 }
David Tolnay6b7aaf02016-09-04 10:39:25 -0700318 })
David Tolnay9d8f1972016-09-04 11:58:48 -0700319 ));
David Tolnayb79ee962016-09-04 09:39:20 -0700320
David Tolnay9d8f1972016-09-04 11:58:48 -0700321 named!(ty_impl_trait<&str, Ty>, do_parse!(
322 punct!("impl") >>
323 multispace >>
324 elem: separated_nonempty_list!(punct!("+"), ty_param_bound) >>
325 (Ty::ImplTrait(elem))
326 ));
David Tolnayb79ee962016-09-04 09:39:20 -0700327
David Tolnay9d8f1972016-09-04 11:58:48 -0700328 named!(ty_paren<&str, Ty>, do_parse!(
329 punct!("(") >>
330 elem: ty >>
331 punct!(")") >>
332 (Ty::Paren(Box::new(elem)))
333 ));
David Tolnayb79ee962016-09-04 09:39:20 -0700334
David Tolnayf6ccb832016-09-04 15:00:56 -0700335 named!(mutability<&str, Mutability>, alt_complete!(
336 do_parse!(
337 punct!("mut") >>
338 multispace >>
339 (Mutability::Mutable)
David Tolnay9d8f1972016-09-04 11:58:48 -0700340 )
David Tolnayf6ccb832016-09-04 15:00:56 -0700341 |
342 epsilon!() => { |_| Mutability::Immutable }
David Tolnay9d8f1972016-09-04 11:58:48 -0700343 ));
344
345 named!(path<&str, Path>, do_parse!(
David Tolnayf6ccb832016-09-04 15:00:56 -0700346 global: option!(punct!("::")) >>
David Tolnay9d8f1972016-09-04 11:58:48 -0700347 segments: separated_nonempty_list!(punct!("::"), path_segment) >>
348 (Path {
349 global: global.is_some(),
350 segments: segments,
351 })
352 ));
353
David Tolnayf6ccb832016-09-04 15:00:56 -0700354 named!(path_segment<&str, PathSegment>, alt_complete!(
David Tolnay9d8f1972016-09-04 11:58:48 -0700355 do_parse!(
356 ident: word >>
357 punct!("<") >>
358 lifetimes: separated_list!(punct!(","), lifetime) >>
359 types: opt_vec!(preceded!(
360 cond!(!lifetimes.is_empty(), punct!(",")),
361 separated_nonempty_list!(
362 punct!(","),
363 terminated!(ty, not!(peek!(punct!("="))))
364 )
365 )) >>
366 bindings: opt_vec!(preceded!(
367 cond!(!lifetimes.is_empty() || !types.is_empty(), punct!(",")),
368 separated_nonempty_list!(punct!(","), type_binding)
369 )) >>
370 punct!(">") >>
371 (PathSegment {
372 ident: ident,
373 parameters: PathParameters::AngleBracketed(
374 AngleBracketedParameterData {
375 lifetimes: lifetimes,
376 types: types,
377 bindings: bindings,
378 }
379 ),
380 })
381 )
382 |
383 map!(word, PathSegment::ident)
384 ));
385
386 named!(type_binding<&str, TypeBinding>, do_parse!(
387 ident: word >>
388 punct!("=") >>
389 ty: ty >>
390 (TypeBinding {
391 ident: ident,
392 ty: ty,
393 })
394 ));
395
396 named!(pub poly_trait_ref<&str, PolyTraitRef>, do_parse!(
397 bound_lifetimes: bound_lifetimes >>
398 trait_ref: path >>
399 (PolyTraitRef {
400 bound_lifetimes: bound_lifetimes,
401 trait_ref: trait_ref,
402 })
403 ));
404
405 named!(fn_arg<&str, Arg>, do_parse!(
David Tolnayf6ccb832016-09-04 15:00:56 -0700406 pat: option!(terminated!(word, punct!(":"))) >>
David Tolnay9d8f1972016-09-04 11:58:48 -0700407 ty: ty >>
408 (Arg {
409 pat: pat,
410 ty: ty,
411 })
412 ));
413}
David Tolnay87d0b442016-09-04 11:52:12 -0700414
415#[cfg(feature = "printing")]
416mod printing {
417 use super::*;
418 use quote::{Tokens, ToTokens};
419
420 impl ToTokens for Ty {
421 fn to_tokens(&self, tokens: &mut Tokens) {
422 match *self {
423 Ty::Vec(ref inner) => {
424 tokens.append("[");
425 inner.to_tokens(tokens);
426 tokens.append("]");
427 }
428 Ty::FixedLengthVec(ref inner, len) => {
429 tokens.append("[");
430 inner.to_tokens(tokens);
431 tokens.append(";");
432 len.to_tokens(tokens);
433 tokens.append("]");
434 }
435 Ty::Ptr(ref target) => {
436 tokens.append("*");
437 match target.mutability {
438 Mutability::Mutable => tokens.append("mut"),
439 Mutability::Immutable => tokens.append("const"),
440 }
441 target.ty.to_tokens(tokens);
442 }
443 Ty::Rptr(ref lifetime, ref target) => {
444 tokens.append("&");
445 lifetime.to_tokens(tokens);
446 if let Mutability::Mutable = target.mutability {
447 tokens.append("mut");
448 }
449 target.ty.to_tokens(tokens);
450 }
451 Ty::BareFn(ref func) => {
452 func.to_tokens(tokens);
453 }
454 Ty::Never => {
455 tokens.append("!");
456 }
457 Ty::Tup(ref elems) => {
458 tokens.append("(");
David Tolnay94ebdf92016-09-04 13:33:16 -0700459 tokens.append_separated(elems, ",");
David Tolnay87d0b442016-09-04 11:52:12 -0700460 if elems.len() == 1 {
461 tokens.append(",");
462 }
463 tokens.append(")");
464 }
David Tolnayf69904a2016-09-04 14:46:07 -0700465 Ty::Path(None, ref path) => {
466 path.to_tokens(tokens);
467 }
468 Ty::Path(Some(ref qself), ref path) => {
469 tokens.append("<");
470 qself.ty.to_tokens(tokens);
471 if qself.position > 0 {
472 tokens.append("as");
473 for (i, segment) in path.segments.iter()
474 .take(qself.position)
475 .enumerate()
476 {
477 if i > 0 || path.global {
478 tokens.append("::");
David Tolnay87d0b442016-09-04 11:52:12 -0700479 }
David Tolnayf69904a2016-09-04 14:46:07 -0700480 segment.to_tokens(tokens);
David Tolnay87d0b442016-09-04 11:52:12 -0700481 }
David Tolnayf69904a2016-09-04 14:46:07 -0700482 }
483 tokens.append(">");
484 for segment in path.segments.iter().skip(qself.position) {
485 tokens.append("::");
486 segment.to_tokens(tokens);
David Tolnay87d0b442016-09-04 11:52:12 -0700487 }
488 }
489 Ty::ObjectSum(_, _) => unimplemented!(),
490 Ty::PolyTraitRef(_) => unimplemented!(),
491 Ty::ImplTrait(ref bounds) => {
492 tokens.append("impl");
David Tolnay94ebdf92016-09-04 13:33:16 -0700493 tokens.append_separated(bounds, "+");
David Tolnay87d0b442016-09-04 11:52:12 -0700494 }
495 Ty::Paren(ref inner) => {
496 tokens.append("(");
497 inner.to_tokens(tokens);
498 tokens.append(")");
499 }
500 Ty::Infer => {
501 tokens.append("_");
502 }
503 }
504 }
505 }
506
507 impl ToTokens for Path {
508 fn to_tokens(&self, tokens: &mut Tokens) {
509 for (i, segment) in self.segments.iter().enumerate() {
510 if i > 0 || self.global {
511 tokens.append("::");
512 }
513 segment.to_tokens(tokens);
514 }
515 }
516 }
517
518 impl ToTokens for PathSegment {
519 fn to_tokens(&self, tokens: &mut Tokens) {
520 self.ident.to_tokens(tokens);
521 self.parameters.to_tokens(tokens);
522 }
523 }
524
525 impl ToTokens for PathParameters {
526 fn to_tokens(&self, tokens: &mut Tokens) {
527 match *self {
528 PathParameters::AngleBracketed(ref parameters) => {
529 parameters.to_tokens(tokens);
530 }
531 PathParameters::Parenthesized(ref parameters) => {
532 parameters.to_tokens(tokens);
533 }
534 }
535 }
536 }
537
538 impl ToTokens for AngleBracketedParameterData {
539 fn to_tokens(&self, tokens: &mut Tokens) {
540 let has_lifetimes = !self.lifetimes.is_empty();
541 let has_types = !self.types.is_empty();
542 let has_bindings = !self.bindings.is_empty();
543 if !has_lifetimes && !has_types && !has_bindings {
544 return;
545 }
546
547 tokens.append("<");
548
549 let mut first = true;
550 for lifetime in &self.lifetimes {
551 if !first {
552 tokens.append(",");
553 }
554 lifetime.to_tokens(tokens);
555 first = false;
556 }
557 for ty in &self.types {
558 if !first {
559 tokens.append(",");
560 }
561 ty.to_tokens(tokens);
562 first = false;
563 }
564 for binding in &self.bindings {
565 if !first {
566 tokens.append(",");
567 }
568 binding.to_tokens(tokens);
569 first = false;
570 }
571
572 tokens.append(">");
573 }
574 }
575
576 impl ToTokens for TypeBinding {
577 fn to_tokens(&self, tokens: &mut Tokens) {
578 self.ident.to_tokens(tokens);
579 tokens.append("=");
580 self.ty.to_tokens(tokens);
581 }
582 }
583
584 impl ToTokens for ParenthesizedParameterData {
585 fn to_tokens(&self, tokens: &mut Tokens) {
586 tokens.append("(");
David Tolnay94ebdf92016-09-04 13:33:16 -0700587 tokens.append_separated(&self.inputs, ",");
David Tolnay87d0b442016-09-04 11:52:12 -0700588 tokens.append(")");
589 if let Some(ref output) = self.output {
590 tokens.append("->");
591 output.to_tokens(tokens);
592 }
593 }
594 }
595
596 impl ToTokens for PolyTraitRef {
597 fn to_tokens(&self, tokens: &mut Tokens) {
598 if !self.bound_lifetimes.is_empty() {
David Tolnaye8796aa2016-09-04 14:48:22 -0700599 tokens.append("for");
David Tolnay87d0b442016-09-04 11:52:12 -0700600 tokens.append("<");
David Tolnay94ebdf92016-09-04 13:33:16 -0700601 tokens.append_separated(&self.bound_lifetimes, ",");
David Tolnay87d0b442016-09-04 11:52:12 -0700602 tokens.append(">");
603 }
604 self.trait_ref.to_tokens(tokens);
605 }
606 }
607
608 impl ToTokens for BareFnTy {
609 fn to_tokens(&self, tokens: &mut Tokens) {
610 tokens.append("fn");
611 if !self.lifetimes.is_empty() {
612 tokens.append("<");
613 for (i, lifetime) in self.lifetimes.iter().enumerate() {
614 if i > 0 {
615 tokens.append(",");
616 }
617 lifetime.to_tokens(tokens);
618 }
619 tokens.append(">");
620 }
621 tokens.append("(");
622 tokens.append(")");
623 }
624 }
625}