cad97 | 89bb945 | 2019-01-20 18:33:48 -0500 | [diff] [blame] | 1 | //! Extensions to the parsing API with niche applicability. |
| 2 | |
| 3 | use super::*; |
| 4 | |
| 5 | /// Extensions to the `ParseStream` API to support speculative parsing. |
| 6 | pub trait Speculative { |
| 7 | /// Advance this parse stream to the position of a forked parse stream. |
| 8 | /// |
| 9 | /// This is the opposite operation to [`ParseStream::fork`]. |
| 10 | /// You can fork a parse stream, perform some speculative parsing, then join |
| 11 | /// the original stream to the fork to "commit" the parsing from the fork to |
| 12 | /// the main stream. |
| 13 | /// |
| 14 | /// If you can avoid doing this, you should, as it limits the ability to |
| 15 | /// generate useful errors. That said, it is often the only way to parse |
| 16 | /// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem |
| 17 | /// is that when the fork fails to parse an `A`, it's impossible to tell |
| 18 | /// whether that was because of a syntax error and the user meant to provide |
| 19 | /// an `A`, or that the `A`s are finished and its time to start parsing `B`s. |
| 20 | /// Use with care. |
| 21 | /// |
| 22 | /// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by parsing |
| 23 | /// `B*` and removing the leading members of `A` from the repetition, bypassing |
| 24 | /// the need to involve the downsides associated with speculative parsing. |
| 25 | /// |
| 26 | /// [`ParseStream::fork`]: ../struct.ParseBuffer.html#method.fork |
| 27 | /// |
| 28 | /// # Example |
| 29 | /// |
| 30 | /// There has been chatter about the possibility of making the colons in the |
| 31 | /// turbofish syntax like `path::to::<T>` no longer required by accepting |
| 32 | /// `path::to<T>` in expression position. Specifically, according to [RFC#2544], |
| 33 | /// [`PathSegment`] parsing should always try to consume a following `<` token |
| 34 | /// as the start of generic arguments, and reset to the `<` if that fails |
| 35 | /// (e.g. the token is acting as a less-than operator). |
| 36 | /// |
| 37 | /// This is the exact kind of parsing behavior which requires the "fork, try, |
| 38 | /// commit" behavior that [`ParseStream::fork`] discourages. With `advance_to`, |
| 39 | /// we can avoid having to parse the speculatively parsed content a second time. |
| 40 | /// |
| 41 | /// This change in behavior can be implemented in syn by replacing just the |
| 42 | /// `Parse` implementation for `PathSegment`: |
| 43 | /// |
| 44 | /// ```edition2018 |
| 45 | /// # use syn::ext::IdentExt; |
| 46 | /// use syn::parse::discouraged::Speculative; |
| 47 | /// # use syn::parse::{Parse, ParseStream}; |
| 48 | /// # use syn::{Ident, PathArguments, Result, Token}; |
| 49 | /// |
| 50 | /// pub struct PathSegment { |
| 51 | /// pub ident: Ident, |
| 52 | /// pub arguments: PathArguments, |
| 53 | /// } |
| 54 | /// |
| 55 | /// # impl<T> From<T> for PathSegment |
| 56 | /// # where |
| 57 | /// # T: Into<Ident>, |
| 58 | /// # { |
| 59 | /// # fn from(ident: T) -> Self { |
| 60 | /// # PathSegment { |
| 61 | /// # ident: ident.into(), |
| 62 | /// # arguments: PathArguments::None, |
| 63 | /// # } |
| 64 | /// # } |
| 65 | /// # } |
| 66 | /// |
| 67 | /// |
| 68 | /// impl Parse for PathSegment { |
| 69 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 70 | /// if input.peek(Token![super]) |
| 71 | /// || input.peek(Token![self]) |
| 72 | /// || input.peek(Token![Self]) |
| 73 | /// || input.peek(Token![crate]) |
| 74 | /// || input.peek(Token![extern]) |
| 75 | /// { |
| 76 | /// let ident = input.call(Ident::parse_any)?; |
| 77 | /// return Ok(PathSegment::from(ident)); |
| 78 | /// } |
| 79 | /// |
| 80 | /// let ident = input.parse()?; |
| 81 | /// if input.peek(Token![::]) && input.peek3(Token![<]) { |
| 82 | /// return Ok(PathSegment { |
| 83 | /// ident: ident, |
| 84 | /// arguments: PathArguments::AngleBracketed(input.parse()?), |
| 85 | /// }); |
| 86 | /// } |
| 87 | /// if input.peek(Token![<]) && !input.peek(Token![<=]) { |
| 88 | /// let fork = input.fork(); |
| 89 | /// if let Ok(arguments) = fork.parse() { |
| 90 | /// input.advance_to(&fork); |
| 91 | /// return Ok(PathSegment { |
| 92 | /// ident: ident, |
| 93 | /// arguments: PathArguments::AngleBracketed(arguments), |
| 94 | /// }); |
| 95 | /// } |
| 96 | /// } |
| 97 | /// Ok(PathSegment::from(ident)) |
| 98 | /// } |
| 99 | /// } |
| 100 | /// |
| 101 | /// # syn::parse_str::<PathSegment>("a<b,c>").unwrap(); |
| 102 | /// ``` |
| 103 | /// |
cad97 | 810c890 | 2019-06-18 17:39:32 -0400 | [diff] [blame] | 104 | /// # Drawbacks |
| 105 | /// |
| 106 | /// The main drawback of this style of speculative parsing is in error |
| 107 | /// presentation. Even if the lookahead is the "correct" parse, the error |
| 108 | /// that is shown is that of the "fallback" parse. To use the same example |
| 109 | /// as the turbofish above, take the following unfinished "turbofish": |
| 110 | /// |
| 111 | /// ```text |
| 112 | /// let _ = f<&'a fn(), for<'a> serde::>(); |
| 113 | /// ``` |
| 114 | /// |
| 115 | /// If this is parsed as generic arguments, we can provide the error message |
| 116 | /// |
| 117 | /// ```text |
| 118 | /// error: expected identifier |
| 119 | /// --> src.rs:L:C |
| 120 | /// | |
| 121 | /// L | let _ = f<&'a fn(), for<'a> serde::>(); |
| 122 | /// | ^ |
| 123 | /// ``` |
| 124 | /// |
| 125 | /// but if parsed using the above speculative parsing, it falls back to |
| 126 | /// assuming that the `<` is a less-than when it fails to parse the |
| 127 | /// generic arguments, and tries to interpret the `&'a` as the start of a |
| 128 | /// labelled loop, resulting in the much less helpful error |
| 129 | /// |
| 130 | /// ```text |
| 131 | /// error: expected `:` |
| 132 | /// --> src.rs:L:C |
| 133 | /// | |
| 134 | /// L | let _ = f<&'a fn(), for<'a> serde::>(); |
| 135 | /// | ^^ |
| 136 | /// ``` |
| 137 | /// |
| 138 | /// This can be mitigated with various heuristics (two examples: show both |
| 139 | /// forks' parse errors, or show the one that consumed more tokens), but |
| 140 | /// when you can control the grammar, sticking to something that can be |
| 141 | /// parsed LL(3) and without the LL(*) speculative parsing this makes |
| 142 | /// possible, displaying reasonable errors becomes much more simple. |
| 143 | /// |
cad97 | 89bb945 | 2019-01-20 18:33:48 -0500 | [diff] [blame] | 144 | /// [RFC#2544]: https://github.com/rust-lang/rfcs/pull/2544 |
| 145 | /// [`PathSegment`]: ../../struct.PathSegment.html |
| 146 | /// |
| 147 | /// # Panics |
| 148 | /// |
| 149 | /// The forked stream that this joins with must be derived by forking this parse stream. |
| 150 | fn advance_to(&self, fork: &Self); |
| 151 | } |
| 152 | |
| 153 | impl<'a> Speculative for ParseBuffer<'a> { |
| 154 | fn advance_to(&self, fork: &Self) { |
David Tolnay | 6db0f2a | 2019-06-23 13:37:39 -0700 | [diff] [blame^] | 155 | if !private::same_scope(self.cursor(), fork.cursor()) { |
| 156 | panic!("Fork was not derived from the advancing parse stream"); |
| 157 | } |
| 158 | |
cad97 | 89bb945 | 2019-01-20 18:33:48 -0500 | [diff] [blame] | 159 | // See comment on `cell` in the struct definition. |
David Tolnay | 5368954 | 2019-06-23 13:02:47 -0700 | [diff] [blame] | 160 | self.cell |
| 161 | .set(unsafe { mem::transmute::<Cursor, Cursor<'static>>(fork.cursor()) }) |
cad97 | 89bb945 | 2019-01-20 18:33:48 -0500 | [diff] [blame] | 162 | } |
| 163 | } |