]> git.proxmox.com Git - rustc.git/blame - src/libsyntax/tokenstream.rs
New upstream version 1.40.0+dfsg1
[rustc.git] / src / libsyntax / tokenstream.rs
CommitLineData
5bcae85e
SL
1//! # Token Streams
2//!
7cac9316 3//! `TokenStream`s represent syntactic objects before they are converted into ASTs.
5bcae85e 4//! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s,
8bb4bdeb 5//! which are themselves a single `Token` or a `Delimited` subsequence of tokens.
5bcae85e
SL
6//!
7//! ## Ownership
9fa01778 8//!
e1599b0c 9//! `TokenStream`s are persistent data structures constructed as ropes with reference
7cac9316
XL
10//! counted-children. In general, this means that calling an operation on a `TokenStream`
11//! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
12//! the original. This essentially coerces `TokenStream`s into 'views' of their subparts,
13//! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
5bcae85e 14//! ownership of the original.
3157f602 15
dc9dc135 16use crate::parse::token::{self, DelimToken, Token, TokenKind};
9fa01778 17
e1599b0c 18use syntax_pos::{BytePos, Span, DUMMY_SP};
9fa01778 19#[cfg(target_arch = "x86_64")]
48663c56 20use rustc_data_structures::static_assert_size;
0731742a 21use rustc_data_structures::sync::Lrc;
532ac7d7 22use smallvec::{SmallVec, smallvec};
5bcae85e 23
e74abb32 24use std::{iter, mem};
3157f602 25
416331ca
XL
26#[cfg(test)]
27mod tests;
28
3157f602
XL
29/// When the main rust parser encounters a syntax-extension invocation, it
30/// parses the arguments to the invocation as a token-tree. This is a very
31/// loose structure, such that all sorts of different AST-fragments can
32/// be passed to syntax extensions using a uniform type.
33///
34/// If the syntax extension is an MBE macro, it will attempt to match its
35/// LHS token tree against the provided token tree, and if it finds a
36/// match, will transcribe the RHS token tree, splicing in any captured
7cac9316 37/// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
3157f602
XL
38///
39/// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
40/// Nothing special happens to misnamed or misplaced `SubstNt`s.
8faf50e0 41#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
3157f602
XL
42pub enum TokenTree {
43 /// A single token
dc9dc135 44 Token(Token),
3157f602 45 /// A delimited sequence of token trees
9fa01778 46 Delimited(DelimSpan, DelimToken, TokenStream),
3157f602
XL
47}
48
dc9dc135
XL
49// Ensure all fields of `TokenTree` is `Send` and `Sync`.
50#[cfg(parallel_compiler)]
51fn _dummy()
52where
53 Token: Send + Sync,
54 DelimSpan: Send + Sync,
55 DelimToken: Send + Sync,
56 TokenStream: Send + Sync,
57{}
58
3157f602 59impl TokenTree {
9fa01778 60 /// Checks if this TokenTree is equal to the other, regardless of span information.
5bcae85e
SL
61 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
62 match (self, other) {
dc9dc135
XL
63 (TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
64 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
9fa01778 65 delim == delim2 && tts.eq_unspanned(&tts2)
83c7162d 66 }
dc9dc135 67 _ => false,
83c7162d
XL
68 }
69 }
70
9fa01778 71 // See comments in `Nonterminal::to_tokenstream` for why we care about
83c7162d
XL
72 // *probably* equal here rather than actual equality
73 //
74 // This is otherwise the same as `eq_unspanned`, only recursing with a
75 // different method.
76 pub fn probably_equal_for_proc_macro(&self, other: &TokenTree) -> bool {
77 match (self, other) {
dc9dc135
XL
78 (TokenTree::Token(token), TokenTree::Token(token2)) => {
79 token.probably_equal_for_proc_macro(token2)
83c7162d 80 }
dc9dc135 81 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
9fa01778 82 delim == delim2 && tts.probably_equal_for_proc_macro(&tts2)
5bcae85e 83 }
dc9dc135 84 _ => false,
5bcae85e
SL
85 }
86 }
87
9fa01778 88 /// Retrieves the TokenTree's span.
5bcae85e 89 pub fn span(&self) -> Span {
dc9dc135
XL
90 match self {
91 TokenTree::Token(token) => token.span,
0731742a 92 TokenTree::Delimited(sp, ..) => sp.entire(),
5bcae85e
SL
93 }
94 }
95
a1dfa0c6 96 /// Modify the `TokenTree`'s span in-place.
3b2f2976 97 pub fn set_span(&mut self, span: Span) {
dc9dc135
XL
98 match self {
99 TokenTree::Token(token) => token.span = span,
100 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
5bcae85e
SL
101 }
102 }
041b39d2
XL
103
104 pub fn joint(self) -> TokenStream {
9fa01778 105 TokenStream::new(vec![(self, Joint)])
0731742a
XL
106 }
107
dc9dc135
XL
108 pub fn token(kind: TokenKind, span: Span) -> TokenTree {
109 TokenTree::Token(Token::new(kind, span))
110 }
111
0731742a
XL
112 /// Returns the opening delimiter as a token tree.
113 pub fn open_tt(span: Span, delim: DelimToken) -> TokenTree {
114 let open_span = if span.is_dummy() {
115 span
116 } else {
117 span.with_hi(span.lo() + BytePos(delim.len() as u32))
118 };
dc9dc135 119 TokenTree::token(token::OpenDelim(delim), open_span)
0731742a
XL
120 }
121
122 /// Returns the closing delimiter as a token tree.
123 pub fn close_tt(span: Span, delim: DelimToken) -> TokenTree {
124 let close_span = if span.is_dummy() {
125 span
126 } else {
127 span.with_lo(span.hi() - BytePos(delim.len() as u32))
128 };
dc9dc135 129 TokenTree::token(token::CloseDelim(delim), close_span)
041b39d2 130 }
3157f602
XL
131}
132
32a655c1 133/// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s.
e1599b0c 134///
32a655c1
SL
135/// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
136/// instead of a representation of the abstract syntax tree.
dc9dc135 137/// Today's `TokenTree`s can still contain AST via `token::Interpolated` for back-compat.
e74abb32
XL
138#[derive(Clone, Debug, Default, RustcEncodable, RustcDecodable)]
139pub struct TokenStream(pub Lrc<Vec<TreeAndJoint>>);
5bcae85e 140
0731742a
XL
141pub type TreeAndJoint = (TokenTree, IsJoint);
142
143// `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
144#[cfg(target_arch = "x86_64")]
48663c56 145static_assert_size!(TokenStream, 8);
0731742a 146
e74abb32 147#[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)]
0731742a
XL
148pub enum IsJoint {
149 Joint,
150 NonJoint
151}
152
9fa01778 153use IsJoint::*;
0731742a 154
b7449926
XL
155impl TokenStream {
156 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
157 /// separating the two arguments with a comma for diagnostic suggestions.
e74abb32 158 pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
b7449926 159 // Used to suggest if a user writes `foo!(a b);`
e74abb32
XL
160 let mut suggestion = None;
161 let mut iter = self.0.iter().enumerate().peekable();
162 while let Some((pos, ts)) = iter.next() {
163 if let Some((_, next)) = iter.peek() {
164 let sp = match (&ts, &next) {
165 (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
166 ((TokenTree::Token(token_left), NonJoint),
167 (TokenTree::Token(token_right), _))
168 if ((token_left.is_ident() && !token_left.is_reserved_ident())
169 || token_left.is_lit()) &&
170 ((token_right.is_ident() && !token_right.is_reserved_ident())
171 || token_right.is_lit()) => token_left.span,
172 ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(),
173 _ => continue,
174 };
175 let sp = sp.shrink_to_hi();
176 let comma = (TokenTree::token(token::Comma, sp), NonJoint);
177 suggestion = Some((pos, comma, sp));
b7449926
XL
178 }
179 }
e74abb32
XL
180 if let Some((pos, comma, sp)) = suggestion {
181 let mut new_stream = vec![];
182 let parts = self.0.split_at(pos + 1);
183 new_stream.extend_from_slice(parts.0);
184 new_stream.push(comma);
185 new_stream.extend_from_slice(parts.1);
186 return Some((TokenStream::new(new_stream), sp));
187 }
b7449926
XL
188 None
189 }
190}
191
0731742a
XL
192impl From<TokenTree> for TokenStream {
193 fn from(tree: TokenTree) -> TokenStream {
9fa01778 194 TokenStream::new(vec![(tree, NonJoint)])
0731742a 195 }
5bcae85e
SL
196}
197
0731742a
XL
198impl From<TokenTree> for TreeAndJoint {
199 fn from(tree: TokenTree) -> TreeAndJoint {
200 (tree, NonJoint)
5bcae85e
SL
201 }
202}
203
e74abb32
XL
204impl iter::FromIterator<TokenTree> for TokenStream {
205 fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
206 TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndJoint>>())
b7449926
XL
207 }
208}
209
32a655c1
SL
210impl Eq for TokenStream {}
211
5bcae85e
SL
212impl PartialEq<TokenStream> for TokenStream {
213 fn eq(&self, other: &TokenStream) -> bool {
32a655c1 214 self.trees().eq(other.trees())
5bcae85e
SL
215 }
216}
217
5bcae85e 218impl TokenStream {
e74abb32
XL
219 pub fn new(streams: Vec<TreeAndJoint>) -> TokenStream {
220 TokenStream(Lrc::new(streams))
3b2f2976
XL
221 }
222
e74abb32
XL
223 pub fn is_empty(&self) -> bool {
224 self.0.is_empty()
9e0c209e
SL
225 }
226
e74abb32
XL
227 pub fn len(&self) -> usize {
228 self.0.len()
5bcae85e
SL
229 }
230
532ac7d7 231 pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
8bb4bdeb 232 match streams.len() {
e74abb32 233 0 => TokenStream::default(),
041b39d2 234 1 => streams.pop().unwrap(),
0731742a 235 _ => {
e74abb32
XL
236 // We are going to extend the first stream in `streams` with
237 // the elements from the subsequent streams. This requires
238 // using `make_mut()` on the first stream, and in practice this
239 // doesn't cause cloning 99.9% of the time.
240 //
241 // One very common use case is when `streams` has two elements,
242 // where the first stream has any number of elements within
243 // (often 1, but sometimes many more) and the second stream has
244 // a single element within.
245
246 // Determine how much the first stream will be extended.
247 // Needed to avoid quadratic blow up from on-the-fly
248 // reallocations (#57735).
249 let num_appends = streams.iter()
250 .skip(1)
251 .map(|ts| ts.len())
9fa01778 252 .sum();
9fa01778 253
e74abb32
XL
254 // Get the first stream. If it's `None`, create an empty
255 // stream.
256 let mut iter = streams.drain();
257 let mut first_stream_lrc = iter.next().unwrap().0;
258
259 // Append the elements to the first stream, after reserving
260 // space for them.
261 let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
262 first_vec_mut.reserve(num_appends);
263 for stream in iter {
264 first_vec_mut.extend(stream.0.iter().cloned());
0731742a 265 }
8bb4bdeb 266
e74abb32
XL
267 // Create the final `TokenStream`.
268 TokenStream(first_stream_lrc)
269 }
0731742a 270 }
8bb4bdeb
XL
271 }
272
273 pub fn trees(&self) -> Cursor {
274 self.clone().into_trees()
5bcae85e
SL
275 }
276
8bb4bdeb 277 pub fn into_trees(self) -> Cursor {
32a655c1 278 Cursor::new(self)
5bcae85e
SL
279 }
280
e1599b0c 281 /// Compares two `TokenStream`s, checking equality without regarding span information.
5bcae85e 282 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
83c7162d
XL
283 let mut t1 = self.trees();
284 let mut t2 = other.trees();
285 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
8bb4bdeb 286 if !t1.eq_unspanned(&t2) {
5bcae85e
SL
287 return false;
288 }
289 }
83c7162d
XL
290 t1.next().is_none() && t2.next().is_none()
291 }
292
9fa01778 293 // See comments in `Nonterminal::to_tokenstream` for why we care about
83c7162d
XL
294 // *probably* equal here rather than actual equality
295 //
296 // This is otherwise the same as `eq_unspanned`, only recursing with a
297 // different method.
298 pub fn probably_equal_for_proc_macro(&self, other: &TokenStream) -> bool {
a1dfa0c6
XL
299 // When checking for `probably_eq`, we ignore certain tokens that aren't
300 // preserved in the AST. Because they are not preserved, the pretty
301 // printer arbitrarily adds or removes them when printing as token
302 // streams, making a comparison between a token stream generated from an
303 // AST and a token stream which was parsed into an AST more reliable.
304 fn semantic_tree(tree: &TokenTree) -> bool {
dc9dc135
XL
305 if let TokenTree::Token(token) = tree {
306 if let
307 // The pretty printer tends to add trailing commas to
308 // everything, and in particular, after struct fields.
309 | token::Comma
310 // The pretty printer emits `NoDelim` as whitespace.
311 | token::OpenDelim(DelimToken::NoDelim)
312 | token::CloseDelim(DelimToken::NoDelim)
313 // The pretty printer collapses many semicolons into one.
314 | token::Semi
315 // The pretty printer collapses whitespace arbitrarily and can
316 // introduce whitespace from `NoDelim`.
317 | token::Whitespace
318 // The pretty printer can turn `$crate` into `::crate_name`
319 | token::ModSep = token.kind {
320 return false;
321 }
a1dfa0c6 322 }
dc9dc135 323 true
a1dfa0c6
XL
324 }
325
326 let mut t1 = self.trees().filter(semantic_tree);
327 let mut t2 = other.trees().filter(semantic_tree);
83c7162d
XL
328 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
329 if !t1.probably_equal_for_proc_macro(&t2) {
330 return false;
331 }
332 }
333 t1.next().is_none() && t2.next().is_none()
5bcae85e 334 }
041b39d2 335
3b2f2976 336 pub fn map_enumerated<F: FnMut(usize, TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
e74abb32
XL
337 TokenStream(Lrc::new(
338 self.0
339 .iter()
340 .enumerate()
341 .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint))
342 .collect()
343 ))
3b2f2976
XL
344 }
345
041b39d2 346 pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
e74abb32
XL
347 TokenStream(Lrc::new(
348 self.0
349 .iter()
350 .map(|(tree, is_joint)| (f(tree.clone()), *is_joint))
351 .collect()
352 ))
041b39d2
XL
353 }
354}
355
532ac7d7 356// 99.5%+ of the time we have 1 or 2 elements in this vector.
8faf50e0 357#[derive(Clone)]
532ac7d7 358pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
041b39d2
XL
359
360impl TokenStreamBuilder {
361 pub fn new() -> TokenStreamBuilder {
532ac7d7 362 TokenStreamBuilder(SmallVec::new())
041b39d2
XL
363 }
364
365 pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
e74abb32
XL
366 let mut stream = stream.into();
367
368 // If `self` is not empty and the last tree within the last stream is a
369 // token tree marked with `Joint`...
370 if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
371 if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() {
372
373 // ...and `stream` is not empty and the first tree within it is
374 // a token tree...
375 let TokenStream(ref mut stream_lrc) = stream;
376 if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() {
377
378 // ...and the two tokens can be glued together...
379 if let Some(glued_tok) = last_token.glue(&token) {
380
381 // ...then do so, by overwriting the last token
382 // tree in `self` and removing the first token tree
383 // from `stream`. This requires using `make_mut()`
384 // on the last stream in `self` and on `stream`,
385 // and in practice this doesn't cause cloning 99.9%
386 // of the time.
387
388 // Overwrite the last token tree with the merged
389 // token.
390 let last_vec_mut = Lrc::make_mut(last_stream_lrc);
391 *last_vec_mut.last_mut().unwrap() =
392 (TokenTree::Token(glued_tok), *is_joint);
393
394 // Remove the first token tree from `stream`. (This
395 // is almost always the only tree in `stream`.)
396 let stream_vec_mut = Lrc::make_mut(stream_lrc);
397 stream_vec_mut.remove(0);
398
399 // Don't push `stream` if it's empty -- that could
400 // block subsequent token gluing, by getting
401 // between two token trees that should be glued
402 // together.
403 if !stream.is_empty() {
404 self.0.push(stream);
405 }
406 return;
407 }
041b39d2
XL
408 }
409 }
410 }
411 self.0.push(stream);
412 }
413
041b39d2 414 pub fn build(self) -> TokenStream {
0731742a 415 TokenStream::from_streams(self.0)
041b39d2 416 }
5bcae85e
SL
417}
418
041b39d2 419#[derive(Clone)]
0731742a
XL
420pub struct Cursor {
421 pub stream: TokenStream,
8bb4bdeb 422 index: usize,
041b39d2
XL
423}
424
425impl Iterator for Cursor {
426 type Item = TokenTree;
427
428 fn next(&mut self) -> Option<TokenTree> {
0731742a 429 self.next_with_joint().map(|(tree, _)| tree)
041b39d2 430 }
32a655c1 431}
5bcae85e 432
8bb4bdeb
XL
433impl Cursor {
434 fn new(stream: TokenStream) -> Self {
0731742a
XL
435 Cursor { stream, index: 0 }
436 }
437
438 pub fn next_with_joint(&mut self) -> Option<TreeAndJoint> {
e74abb32
XL
439 if self.index < self.stream.len() {
440 self.index += 1;
441 Some(self.stream.0[self.index - 1].clone())
442 } else {
443 None
041b39d2
XL
444 }
445 }
446
0731742a
XL
447 pub fn append(&mut self, new_stream: TokenStream) {
448 if new_stream.is_empty() {
449 return;
5bcae85e 450 }
0731742a 451 let index = self.index;
e74abb32 452 let stream = mem::take(&mut self.stream);
532ac7d7 453 *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
0731742a 454 self.index = index;
8bb4bdeb
XL
455 }
456
457 pub fn look_ahead(&self, n: usize) -> Option<TokenTree> {
e74abb32 458 self.stream.0[self.index ..].get(n).map(|(tree, _)| tree.clone())
5bcae85e
SL
459 }
460}
461
b7449926
XL
462#[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
463pub struct DelimSpan {
464 pub open: Span,
465 pub close: Span,
466}
467
468impl DelimSpan {
469 pub fn from_single(sp: Span) -> Self {
470 DelimSpan {
471 open: sp,
472 close: sp,
473 }
474 }
475
476 pub fn from_pair(open: Span, close: Span) -> Self {
477 DelimSpan { open, close }
478 }
479
480 pub fn dummy() -> Self {
481 Self::from_single(DUMMY_SP)
482 }
483
484 pub fn entire(self) -> Span {
485 self.open.with_hi(self.close.hi())
486 }
b7449926 487}