blob: f40a8746177ea678f0060265e287e23b0e553ae9 [file] [log] [blame]
David Tolnay3b1f7d22019-01-28 12:22:11 -08001#[cfg(span_locations)]
Alex Crichton44bffbc2017-05-19 17:51:59 -07002use std::cell::RefCell;
David Tolnay1ebe3972018-01-02 20:14:20 -08003#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -05004use std::cmp;
Alex Crichton44bffbc2017-05-19 17:51:59 -07005use std::fmt;
6use std::iter;
David Tolnay9cd3b4c2018-11-11 16:47:32 -08007#[cfg(procmacro2_semver_exempt)]
8use std::path::Path;
9use std::path::PathBuf;
Alex Crichton44bffbc2017-05-19 17:51:59 -070010use std::str::FromStr;
11use std::vec;
12
David Tolnayb28f38a2018-03-31 22:02:29 +020013use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult};
David Tolnayb1032662017-05-31 15:52:28 -070014use unicode_xid::UnicodeXID;
Alex Crichton44bffbc2017-05-19 17:51:59 -070015
David Tolnayf14813f2018-09-08 17:14:07 -070016use {Delimiter, Punct, Spacing, TokenTree};
Alex Crichton44bffbc2017-05-19 17:51:59 -070017
David Tolnay034205f2018-04-22 16:45:28 -070018#[derive(Clone)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070019pub struct TokenStream {
20 inner: Vec<TokenTree>,
21}
22
23#[derive(Debug)]
24pub struct LexError;
25
26impl TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -070027 pub fn new() -> TokenStream {
Alex Crichton44bffbc2017-05-19 17:51:59 -070028 TokenStream { inner: Vec::new() }
29 }
30
31 pub fn is_empty(&self) -> bool {
32 self.inner.len() == 0
33 }
34}
35
David Tolnay3b1f7d22019-01-28 12:22:11 -080036#[cfg(span_locations)]
Nika Layzella9dbc182017-12-30 14:50:13 -050037fn get_cursor(src: &str) -> Cursor {
David Tolnay6c3b0702019-04-22 16:48:34 -070038 // Create a dummy file & add it to the source map
39 SOURCE_MAP.with(|cm| {
Nika Layzella9dbc182017-12-30 14:50:13 -050040 let mut cm = cm.borrow_mut();
41 let name = format!("<parsed string {}>", cm.files.len());
42 let span = cm.add_file(&name, src);
43 Cursor {
44 rest: src,
45 off: span.lo,
46 }
47 })
48}
49
David Tolnay3b1f7d22019-01-28 12:22:11 -080050#[cfg(not(span_locations))]
Nika Layzella9dbc182017-12-30 14:50:13 -050051fn get_cursor(src: &str) -> Cursor {
David Tolnayb28f38a2018-03-31 22:02:29 +020052 Cursor { rest: src }
Nika Layzella9dbc182017-12-30 14:50:13 -050053}
54
Alex Crichton44bffbc2017-05-19 17:51:59 -070055impl FromStr for TokenStream {
56 type Err = LexError;
57
58 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnay6c3b0702019-04-22 16:48:34 -070059 // Create a dummy file & add it to the source map
Nika Layzella9dbc182017-12-30 14:50:13 -050060 let cursor = get_cursor(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -050061
62 match token_stream(cursor) {
David Tolnay1218e122017-06-01 11:13:45 -070063 Ok((input, output)) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -070064 if skip_whitespace(input).len() != 0 {
65 Err(LexError)
66 } else {
Alex Crichton30a4e9e2018-04-27 17:02:19 -070067 Ok(output)
Alex Crichton44bffbc2017-05-19 17:51:59 -070068 }
69 }
David Tolnay1218e122017-06-01 11:13:45 -070070 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -070071 }
72 }
73}
74
75impl fmt::Display for TokenStream {
76 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 let mut joint = false;
78 for (i, tt) in self.inner.iter().enumerate() {
79 if i != 0 && !joint {
80 write!(f, " ")?;
81 }
82 joint = false;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070083 match *tt {
84 TokenTree::Group(ref tt) => {
85 let (start, end) = match tt.delimiter() {
Alex Crichton44bffbc2017-05-19 17:51:59 -070086 Delimiter::Parenthesis => ("(", ")"),
87 Delimiter::Brace => ("{", "}"),
88 Delimiter::Bracket => ("[", "]"),
89 Delimiter::None => ("", ""),
90 };
Alex Crichton30a4e9e2018-04-27 17:02:19 -070091 if tt.stream().into_iter().next().is_none() {
Alex Crichton852d53d2017-05-19 19:25:08 -070092 write!(f, "{} {}", start, end)?
93 } else {
Alex Crichtonaf5bad42018-03-27 14:45:10 -070094 write!(f, "{} {} {}", start, tt.stream(), end)?
Alex Crichton852d53d2017-05-19 19:25:08 -070095 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070096 }
Alex Crichtonf3888432018-05-16 09:11:05 -070097 TokenTree::Ident(ref tt) => write!(f, "{}", tt)?,
98 TokenTree::Punct(ref tt) => {
99 write!(f, "{}", tt.as_char())?;
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700100 match tt.spacing() {
Alex Crichton1a7f7622017-07-05 17:47:15 -0700101 Spacing::Alone => {}
102 Spacing::Joint => joint = true,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700103 }
104 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700105 TokenTree::Literal(ref tt) => write!(f, "{}", tt)?,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700106 }
107 }
108
109 Ok(())
110 }
111}
112
David Tolnay034205f2018-04-22 16:45:28 -0700113impl fmt::Debug for TokenStream {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 f.write_str("TokenStream ")?;
116 f.debug_list().entries(self.clone()).finish()
117 }
118}
119
Alex Crichton53548482018-08-11 21:54:05 -0700120#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800121impl From<::proc_macro::TokenStream> for TokenStream {
122 fn from(inner: ::proc_macro::TokenStream) -> TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200123 inner
124 .to_string()
125 .parse()
126 .expect("compiler token stream parse failed")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700127 }
128}
129
Alex Crichton53548482018-08-11 21:54:05 -0700130#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800131impl From<TokenStream> for ::proc_macro::TokenStream {
132 fn from(inner: TokenStream) -> ::proc_macro::TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200133 inner
134 .to_string()
135 .parse()
136 .expect("failed to parse to compiler tokens")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700137 }
138}
139
Alex Crichton44bffbc2017-05-19 17:51:59 -0700140impl From<TokenTree> for TokenStream {
141 fn from(tree: TokenTree) -> TokenStream {
142 TokenStream { inner: vec![tree] }
143 }
144}
145
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700146impl iter::FromIterator<TokenTree> for TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200147 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700148 let mut v = Vec::new();
149
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700150 for token in streams.into_iter() {
151 v.push(token);
Alex Crichton44bffbc2017-05-19 17:51:59 -0700152 }
153
154 TokenStream { inner: v }
155 }
156}
157
Alex Crichton53b00672018-09-06 17:16:10 -0700158impl iter::FromIterator<TokenStream> for TokenStream {
159 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
160 let mut v = Vec::new();
161
162 for stream in streams.into_iter() {
163 v.extend(stream.inner);
164 }
165
166 TokenStream { inner: v }
167 }
168}
169
Alex Crichtonf3888432018-05-16 09:11:05 -0700170impl Extend<TokenTree> for TokenStream {
171 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
172 self.inner.extend(streams);
173 }
174}
175
David Tolnay5c58c532018-08-13 11:33:51 -0700176impl Extend<TokenStream> for TokenStream {
177 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
178 self.inner
179 .extend(streams.into_iter().flat_map(|stream| stream));
180 }
181}
182
Alex Crichton1a7f7622017-07-05 17:47:15 -0700183pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700184
185impl IntoIterator for TokenStream {
186 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700187 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700188
Alex Crichton1a7f7622017-07-05 17:47:15 -0700189 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700190 self.inner.into_iter()
191 }
192}
193
Nika Layzellf8d5f212017-12-11 14:07:02 -0500194#[derive(Clone, PartialEq, Eq)]
195pub struct SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800196 path: PathBuf,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500197}
198
199impl SourceFile {
200 /// Get the path to this source file as a string.
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800201 pub fn path(&self) -> PathBuf {
202 self.path.clone()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500203 }
204
205 pub fn is_real(&self) -> bool {
206 // XXX(nika): Support real files in the future?
207 false
208 }
209}
210
Nika Layzellf8d5f212017-12-11 14:07:02 -0500211impl fmt::Debug for SourceFile {
212 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
213 f.debug_struct("SourceFile")
Nika Layzellb35a9a32017-12-30 14:34:35 -0500214 .field("path", &self.path())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500215 .field("is_real", &self.is_real())
216 .finish()
217 }
218}
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub struct LineColumn {
222 pub line: usize,
223 pub column: usize,
224}
225
David Tolnay3b1f7d22019-01-28 12:22:11 -0800226#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227thread_local! {
David Tolnay6c3b0702019-04-22 16:48:34 -0700228 static SOURCE_MAP: RefCell<SourceMap> = RefCell::new(SourceMap {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500229 // NOTE: We start with a single dummy file which all call_site() and
230 // def_site() spans reference.
David Tolnay3b1f7d22019-01-28 12:22:11 -0800231 files: vec![{
232 #[cfg(procmacro2_semver_exempt)]
233 {
234 FileInfo {
235 name: "<unspecified>".to_owned(),
236 span: Span { lo: 0, hi: 0 },
237 lines: vec![0],
238 }
239 }
240
241 #[cfg(not(procmacro2_semver_exempt))]
242 {
243 FileInfo {
244 span: Span { lo: 0, hi: 0 },
245 lines: vec![0],
246 }
247 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500248 }],
249 });
250}
251
David Tolnay3b1f7d22019-01-28 12:22:11 -0800252#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500253struct FileInfo {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800254 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500255 name: String,
256 span: Span,
257 lines: Vec<usize>,
258}
259
David Tolnay3b1f7d22019-01-28 12:22:11 -0800260#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500261impl FileInfo {
262 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200263 assert!(self.span_within(Span {
264 lo: offset as u32,
265 hi: offset as u32
266 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500267 let offset = offset - self.span.lo as usize;
268 match self.lines.binary_search(&offset) {
269 Ok(found) => LineColumn {
270 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200271 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500272 },
273 Err(idx) => LineColumn {
274 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200275 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500276 },
277 }
278 }
279
280 fn span_within(&self, span: Span) -> bool {
281 span.lo >= self.span.lo && span.hi <= self.span.hi
282 }
283}
284
Alex Crichtona914a612018-04-04 07:48:44 -0700285/// Computesthe offsets of each line in the given source string.
David Tolnay3b1f7d22019-01-28 12:22:11 -0800286#[cfg(span_locations)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500287fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500288 let mut lines = vec![0];
289 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500290 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500291 prev += len + 1;
292 lines.push(prev);
293 }
294 lines
295}
296
David Tolnay3b1f7d22019-01-28 12:22:11 -0800297#[cfg(span_locations)]
David Tolnay6c3b0702019-04-22 16:48:34 -0700298struct SourceMap {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500299 files: Vec<FileInfo>,
300}
301
David Tolnay3b1f7d22019-01-28 12:22:11 -0800302#[cfg(span_locations)]
David Tolnay6c3b0702019-04-22 16:48:34 -0700303impl SourceMap {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500304 fn next_start_pos(&self) -> u32 {
305 // Add 1 so there's always space between files.
306 //
307 // We'll always have at least 1 file, as we initialize our files list
308 // with a dummy file.
309 self.files.last().unwrap().span.hi + 1
310 }
311
312 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500313 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500314 let lo = self.next_start_pos();
315 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200316 let span = Span {
317 lo: lo,
318 hi: lo + (src.len() as u32),
319 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500320
David Tolnay3b1f7d22019-01-28 12:22:11 -0800321 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500322 self.files.push(FileInfo {
323 name: name.to_owned(),
324 span: span,
325 lines: lines,
326 });
327
David Tolnay3b1f7d22019-01-28 12:22:11 -0800328 #[cfg(not(procmacro2_semver_exempt))]
329 self.files.push(FileInfo {
330 span: span,
331 lines: lines,
332 });
333 let _ = name;
334
Nika Layzellf8d5f212017-12-11 14:07:02 -0500335 span
336 }
337
338 fn fileinfo(&self, span: Span) -> &FileInfo {
339 for file in &self.files {
340 if file.span_within(span) {
341 return file;
342 }
343 }
344 panic!("Invalid span with no related FileInfo!");
345 }
346}
347
David Tolnay034205f2018-04-22 16:45:28 -0700348#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500349pub struct Span {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800350 #[cfg(span_locations)]
David Tolnayddfca052017-12-31 10:41:24 -0500351 lo: u32,
David Tolnay3b1f7d22019-01-28 12:22:11 -0800352 #[cfg(span_locations)]
David Tolnayddfca052017-12-31 10:41:24 -0500353 hi: u32,
354}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700355
356impl Span {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800357 #[cfg(not(span_locations))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700358 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500359 Span {}
360 }
361
David Tolnay3b1f7d22019-01-28 12:22:11 -0800362 #[cfg(span_locations)]
David Tolnay79105e52017-12-31 11:03:04 -0500363 pub fn call_site() -> Span {
364 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700365 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800366
David Tolnay3b1f7d22019-01-28 12:22:11 -0800367 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800368 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500369 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500370 }
371
David Tolnay3b1f7d22019-01-28 12:22:11 -0800372 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800373 pub fn resolved_at(&self, _other: Span) -> Span {
374 // Stable spans consist only of line/column information, so
375 // `resolved_at` and `located_at` only select which span the
376 // caller wants line/column information from.
377 *self
378 }
379
David Tolnay3b1f7d22019-01-28 12:22:11 -0800380 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800381 pub fn located_at(&self, other: Span) -> Span {
382 other
383 }
384
David Tolnay1ebe3972018-01-02 20:14:20 -0800385 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500386 pub fn source_file(&self) -> SourceFile {
David Tolnay6c3b0702019-04-22 16:48:34 -0700387 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500388 let cm = cm.borrow();
389 let fi = cm.fileinfo(*self);
390 SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800391 path: Path::new(&fi.name).to_owned(),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500392 }
393 })
394 }
395
David Tolnay3b1f7d22019-01-28 12:22:11 -0800396 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500397 pub fn start(&self) -> LineColumn {
David Tolnay6c3b0702019-04-22 16:48:34 -0700398 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500399 let cm = cm.borrow();
400 let fi = cm.fileinfo(*self);
401 fi.offset_line_column(self.lo as usize)
402 })
403 }
404
David Tolnay3b1f7d22019-01-28 12:22:11 -0800405 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500406 pub fn end(&self) -> LineColumn {
David Tolnay6c3b0702019-04-22 16:48:34 -0700407 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500408 let cm = cm.borrow();
409 let fi = cm.fileinfo(*self);
410 fi.offset_line_column(self.hi as usize)
411 })
412 }
413
David Tolnay1ebe3972018-01-02 20:14:20 -0800414 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500415 pub fn join(&self, other: Span) -> Option<Span> {
David Tolnay6c3b0702019-04-22 16:48:34 -0700416 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500417 let cm = cm.borrow();
418 // If `other` is not within the same FileInfo as us, return None.
419 if !cm.fileinfo(*self).span_within(other) {
420 return None;
421 }
422 Some(Span {
423 lo: cmp::min(self.lo, other.lo),
424 hi: cmp::max(self.hi, other.hi),
425 })
426 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800427 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700428}
429
David Tolnay034205f2018-04-22 16:45:28 -0700430impl fmt::Debug for Span {
431 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
432 #[cfg(procmacro2_semver_exempt)]
433 return write!(f, "bytes({}..{})", self.lo, self.hi);
434
435 #[cfg(not(procmacro2_semver_exempt))]
436 write!(f, "Span")
437 }
438}
439
David Tolnayfd8cdc82019-01-19 19:23:59 -0800440pub fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
441 if cfg!(procmacro2_semver_exempt) {
442 debug.field("span", &span);
443 }
444}
445
Alex Crichtonf3888432018-05-16 09:11:05 -0700446#[derive(Clone)]
David Tolnayf14813f2018-09-08 17:14:07 -0700447pub struct Group {
448 delimiter: Delimiter,
449 stream: TokenStream,
450 span: Span,
451}
452
453impl Group {
454 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
455 Group {
456 delimiter: delimiter,
457 stream: stream,
458 span: Span::call_site(),
459 }
460 }
461
462 pub fn delimiter(&self) -> Delimiter {
463 self.delimiter
464 }
465
466 pub fn stream(&self) -> TokenStream {
467 self.stream.clone()
468 }
469
470 pub fn span(&self) -> Span {
471 self.span
472 }
473
David Tolnay3b1f7d22019-01-28 12:22:11 -0800474 #[cfg(procmacro2_semver_exempt)]
David Tolnayf14813f2018-09-08 17:14:07 -0700475 pub fn span_open(&self) -> Span {
476 self.span
477 }
478
David Tolnay3b1f7d22019-01-28 12:22:11 -0800479 #[cfg(procmacro2_semver_exempt)]
David Tolnayf14813f2018-09-08 17:14:07 -0700480 pub fn span_close(&self) -> Span {
481 self.span
482 }
483
484 pub fn set_span(&mut self, span: Span) {
485 self.span = span;
486 }
487}
488
489impl fmt::Display for Group {
490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491 let (left, right) = match self.delimiter {
492 Delimiter::Parenthesis => ("(", ")"),
493 Delimiter::Brace => ("{", "}"),
494 Delimiter::Bracket => ("[", "]"),
495 Delimiter::None => ("", ""),
496 };
497
498 f.write_str(left)?;
499 self.stream.fmt(f)?;
500 f.write_str(right)?;
501
502 Ok(())
503 }
504}
505
506impl fmt::Debug for Group {
507 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
508 let mut debug = fmt.debug_struct("Group");
509 debug.field("delimiter", &self.delimiter);
510 debug.field("stream", &self.stream);
511 #[cfg(procmacro2_semver_exempt)]
512 debug.field("span", &self.span);
513 debug.finish()
514 }
515}
516
517#[derive(Clone)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700518pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700519 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700520 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700521 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700522}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700523
Alex Crichtonf3888432018-05-16 09:11:05 -0700524impl Ident {
525 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay637eef42019-04-20 13:36:18 -0700526 validate_ident(string);
David Tolnay489c6422018-04-07 08:37:28 -0700527
Alex Crichtonf3888432018-05-16 09:11:05 -0700528 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700529 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700530 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700531 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700532 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700533 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700534
Alex Crichtonf3888432018-05-16 09:11:05 -0700535 pub fn new(string: &str, span: Span) -> Ident {
536 Ident::_new(string, false, span)
537 }
538
539 pub fn new_raw(string: &str, span: Span) -> Ident {
540 Ident::_new(string, true, span)
541 }
542
Alex Crichtonb2c94622018-04-04 07:36:41 -0700543 pub fn span(&self) -> Span {
544 self.span
545 }
546
547 pub fn set_span(&mut self, span: Span) {
548 self.span = span;
549 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700550}
551
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000552#[inline]
553fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700554 ('a' <= c && c <= 'z')
555 || ('A' <= c && c <= 'Z')
556 || c == '_'
557 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000558}
559
560#[inline]
561fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700562 ('a' <= c && c <= 'z')
563 || ('A' <= c && c <= 'Z')
564 || c == '_'
565 || ('0' <= c && c <= '9')
566 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000567}
568
David Tolnay637eef42019-04-20 13:36:18 -0700569fn validate_ident(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700570 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700571 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700572 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700573 }
574
575 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700576 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700577 }
578
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000579 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700580 let mut chars = string.chars();
581 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000582 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700583 return false;
584 }
585 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000586 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700587 return false;
588 }
589 }
590 true
591 }
592
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000593 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700594 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700595 }
596}
597
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700598impl PartialEq for Ident {
599 fn eq(&self, other: &Ident) -> bool {
600 self.sym == other.sym && self.raw == other.raw
601 }
602}
603
604impl<T> PartialEq<T> for Ident
605where
606 T: ?Sized + AsRef<str>,
607{
608 fn eq(&self, other: &T) -> bool {
609 let other = other.as_ref();
610 if self.raw {
611 other.starts_with("r#") && self.sym == other[2..]
612 } else {
613 self.sym == other
614 }
615 }
616}
617
Alex Crichtonf3888432018-05-16 09:11:05 -0700618impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700619 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700620 if self.raw {
621 "r#".fmt(f)?;
622 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700623 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700624 }
625}
626
627impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700628 // Ident(proc_macro), Ident(r#union)
629 #[cfg(not(procmacro2_semver_exempt))]
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 let mut debug = f.debug_tuple("Ident");
632 debug.field(&format_args!("{}", self));
633 debug.finish()
634 }
635
636 // Ident {
637 // sym: proc_macro,
638 // span: bytes(128..138)
639 // }
640 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
642 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700643 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700644 debug.field("span", &self.span);
645 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700646 }
647}
648
David Tolnay034205f2018-04-22 16:45:28 -0700649#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700650pub struct Literal {
651 text: String,
652 span: Span,
653}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700654
Alex Crichtona914a612018-04-04 07:48:44 -0700655macro_rules! suffixed_numbers {
656 ($($name:ident => $kind:ident,)*) => ($(
657 pub fn $name(n: $kind) -> Literal {
658 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
659 }
660 )*)
661}
662
663macro_rules! unsuffixed_numbers {
664 ($($name:ident => $kind:ident,)*) => ($(
665 pub fn $name(n: $kind) -> Literal {
666 Literal::_new(n.to_string())
667 }
668 )*)
669}
670
Alex Crichton852d53d2017-05-19 19:25:08 -0700671impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700672 fn _new(text: String) -> Literal {
673 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700674 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700675 span: Span::call_site(),
676 }
677 }
678
Alex Crichtona914a612018-04-04 07:48:44 -0700679 suffixed_numbers! {
680 u8_suffixed => u8,
681 u16_suffixed => u16,
682 u32_suffixed => u32,
683 u64_suffixed => u64,
684 usize_suffixed => usize,
685 i8_suffixed => i8,
686 i16_suffixed => i16,
687 i32_suffixed => i32,
688 i64_suffixed => i64,
689 isize_suffixed => isize,
690
691 f32_suffixed => f32,
692 f64_suffixed => f64,
693 }
694
Alex Crichton69385662018-11-08 06:30:04 -0800695 #[cfg(u128)]
696 suffixed_numbers! {
697 u128_suffixed => u128,
698 i128_suffixed => i128,
699 }
700
Alex Crichtona914a612018-04-04 07:48:44 -0700701 unsuffixed_numbers! {
702 u8_unsuffixed => u8,
703 u16_unsuffixed => u16,
704 u32_unsuffixed => u32,
705 u64_unsuffixed => u64,
706 usize_unsuffixed => usize,
707 i8_unsuffixed => i8,
708 i16_unsuffixed => i16,
709 i32_unsuffixed => i32,
710 i64_unsuffixed => i64,
711 isize_unsuffixed => isize,
712 }
713
Alex Crichton69385662018-11-08 06:30:04 -0800714 #[cfg(u128)]
715 unsuffixed_numbers! {
716 u128_unsuffixed => u128,
717 i128_unsuffixed => i128,
718 }
719
Alex Crichtona914a612018-04-04 07:48:44 -0700720 pub fn f32_unsuffixed(f: f32) -> Literal {
721 let mut s = f.to_string();
722 if !s.contains(".") {
723 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700724 }
Alex Crichtona914a612018-04-04 07:48:44 -0700725 Literal::_new(s)
726 }
727
728 pub fn f64_unsuffixed(f: f64) -> Literal {
729 let mut s = f.to_string();
730 if !s.contains(".") {
731 s.push_str(".0");
732 }
733 Literal::_new(s)
734 }
735
736 pub fn string(t: &str) -> Literal {
David Tolnaye4482f42019-04-22 16:15:14 -0700737 let mut text = String::with_capacity(t.len() + 2);
738 text.push('"');
739 for c in t.chars() {
740 if c == '\'' {
741 // escape_default turns this into "\'" which is unnecessary.
742 text.push(c);
743 } else {
744 text.extend(c.escape_default());
745 }
746 }
747 text.push('"');
748 Literal::_new(text)
Alex Crichtona914a612018-04-04 07:48:44 -0700749 }
750
751 pub fn character(t: char) -> Literal {
David Tolnaye4482f42019-04-22 16:15:14 -0700752 let mut text = String::new();
753 text.push('\'');
754 if t == '"' {
755 // escape_default turns this into '\"' which is unnecessary.
756 text.push(t);
757 } else {
758 text.extend(t.escape_default());
759 }
760 text.push('\'');
761 Literal::_new(text)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700762 }
763
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700764 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700765 let mut escaped = "b\"".to_string();
766 for b in bytes {
767 match *b {
768 b'\0' => escaped.push_str(r"\0"),
769 b'\t' => escaped.push_str(r"\t"),
770 b'\n' => escaped.push_str(r"\n"),
771 b'\r' => escaped.push_str(r"\r"),
772 b'"' => escaped.push_str("\\\""),
773 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200774 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700775 _ => escaped.push_str(&format!("\\x{:02X}", b)),
776 }
777 }
778 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700779 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700780 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700781
Alex Crichtonb2c94622018-04-04 07:36:41 -0700782 pub fn span(&self) -> Span {
783 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700784 }
785
Alex Crichtonb2c94622018-04-04 07:36:41 -0700786 pub fn set_span(&mut self, span: Span) {
787 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700788 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700789}
790
Alex Crichton44bffbc2017-05-19 17:51:59 -0700791impl fmt::Display for Literal {
792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700793 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700794 }
795}
796
David Tolnay034205f2018-04-22 16:45:28 -0700797impl fmt::Debug for Literal {
798 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
799 let mut debug = fmt.debug_struct("Literal");
800 debug.field("lit", &format_args!("{}", self.text));
801 #[cfg(procmacro2_semver_exempt)]
802 debug.field("span", &self.span);
803 debug.finish()
804 }
805}
806
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700807fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700808 let mut trees = Vec::new();
809 loop {
810 let input_no_ws = skip_whitespace(input);
811 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700812 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700813 }
814 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
815 input = a;
816 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700817 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700818 }
819
820 let (a, tt) = match token_tree(input_no_ws) {
821 Ok(p) => p,
822 Err(_) => break,
823 };
824 trees.push(tt);
825 input = a;
826 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700827 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700828}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700829
David Tolnay3b1f7d22019-01-28 12:22:11 -0800830#[cfg(not(span_locations))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700831fn spanned<'a, T>(
832 input: Cursor<'a>,
833 f: fn(Cursor<'a>) -> PResult<'a, T>,
834) -> PResult<'a, (T, ::Span)> {
835 let (a, b) = f(skip_whitespace(input))?;
David Tolnay3b1f7d22019-01-28 12:22:11 -0800836 Ok((a, ((b, ::Span::_new_stable(Span::call_site())))))
David Tolnayddfca052017-12-31 10:41:24 -0500837}
838
David Tolnay3b1f7d22019-01-28 12:22:11 -0800839#[cfg(span_locations)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700840fn spanned<'a, T>(
841 input: Cursor<'a>,
842 f: fn(Cursor<'a>) -> PResult<'a, T>,
843) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500844 let input = skip_whitespace(input);
845 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700846 let (a, b) = f(input)?;
847 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700848 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700849 Ok((a, (b, span)))
850}
851
852fn token_tree(input: Cursor) -> PResult<TokenTree> {
853 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
854 tt.set_span(span);
855 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500856}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700857
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700858named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700859 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700860 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700861 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700862 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700863 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700864 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700865 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700866));
867
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700868named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700869 delimited!(
870 punct!("("),
871 token_stream,
872 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700873 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700874 |
875 delimited!(
876 punct!("["),
877 token_stream,
878 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700879 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700880 |
881 delimited!(
882 punct!("{"),
883 token_stream,
884 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700885 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700886));
887
Alex Crichtonf3888432018-05-16 09:11:05 -0700888fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
889 symbol(skip_whitespace(input))
890}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700891
Alex Crichtonf3888432018-05-16 09:11:05 -0700892fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700893 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700894
Alex Crichtonf3888432018-05-16 09:11:05 -0700895 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200896 if raw {
897 chars.next();
898 chars.next();
899 }
900
Alex Crichton44bffbc2017-05-19 17:51:59 -0700901 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000902 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700903 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700904 }
905
David Tolnay214c94c2017-06-01 12:42:56 -0700906 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700907 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000908 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700909 end = i;
910 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700911 }
912 }
913
David Tolnaya13d1422018-03-31 21:27:48 +0200914 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700915 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700916 Err(LexError)
917 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700918 let ident = if raw {
919 ::Ident::_new_raw(&a[2..], ::Span::call_site())
920 } else {
921 ::Ident::new(a, ::Span::call_site())
922 };
923 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700924 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700925}
926
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700927fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700928 let input_no_ws = skip_whitespace(input);
929
930 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700931 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700932 let start = input.len() - input_no_ws.len();
933 let len = input_no_ws.len() - a.len();
934 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700935 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700936 }
David Tolnay1218e122017-06-01 11:13:45 -0700937 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700938 }
939}
940
941named!(literal_nocapture -> (), alt!(
942 string
943 |
944 byte_string
945 |
946 byte
947 |
948 character
949 |
950 float
951 |
952 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700953));
954
955named!(string -> (), alt!(
956 quoted_string
957 |
958 preceded!(
959 punct!("r"),
960 raw_string
961 ) => { |_| () }
962));
963
964named!(quoted_string -> (), delimited!(
965 punct!("\""),
966 cooked_string,
967 tag!("\"")
968));
969
Nika Layzellf8d5f212017-12-11 14:07:02 -0500970fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700971 let mut chars = input.char_indices().peekable();
972 while let Some((byte_offset, ch)) = chars.next() {
973 match ch {
974 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500975 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700976 }
977 '\r' => {
978 if let Some((_, '\n')) = chars.next() {
979 // ...
980 } else {
981 break;
982 }
983 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200984 '\\' => match chars.next() {
985 Some((_, 'x')) => {
986 if !backslash_x_char(&mut chars) {
987 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700988 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700989 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200990 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
991 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
992 Some((_, 'u')) => {
993 if !backslash_u(&mut chars) {
994 break;
995 }
996 }
997 Some((_, '\n')) | Some((_, '\r')) => {
998 while let Some(&(_, ch)) = chars.peek() {
999 if ch.is_whitespace() {
1000 chars.next();
1001 } else {
1002 break;
1003 }
1004 }
1005 }
1006 _ => break,
1007 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001008 _ch => {}
1009 }
1010 }
David Tolnay1218e122017-06-01 11:13:45 -07001011 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001012}
1013
1014named!(byte_string -> (), alt!(
1015 delimited!(
1016 punct!("b\""),
1017 cooked_byte_string,
1018 tag!("\"")
1019 ) => { |_| () }
1020 |
1021 preceded!(
1022 punct!("br"),
1023 raw_string
1024 ) => { |_| () }
1025));
1026
Nika Layzellf8d5f212017-12-11 14:07:02 -05001027fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001028 let mut bytes = input.bytes().enumerate();
1029 'outer: while let Some((offset, b)) = bytes.next() {
1030 match b {
1031 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001032 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001033 }
1034 b'\r' => {
1035 if let Some((_, b'\n')) = bytes.next() {
1036 // ...
1037 } else {
1038 break;
1039 }
1040 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001041 b'\\' => match bytes.next() {
1042 Some((_, b'x')) => {
1043 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001044 break;
1045 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001046 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001047 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1048 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1049 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1050 let rest = input.advance(newline + 1);
1051 for (offset, ch) in rest.char_indices() {
1052 if !ch.is_whitespace() {
1053 input = rest.advance(offset);
1054 bytes = input.bytes().enumerate();
1055 continue 'outer;
1056 }
1057 }
1058 break;
1059 }
1060 _ => break,
1061 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001062 b if b < 0x80 => {}
1063 _ => break,
1064 }
1065 }
David Tolnay1218e122017-06-01 11:13:45 -07001066 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001067}
1068
Nika Layzellf8d5f212017-12-11 14:07:02 -05001069fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001070 let mut chars = input.char_indices();
1071 let mut n = 0;
1072 while let Some((byte_offset, ch)) = chars.next() {
1073 match ch {
1074 '"' => {
1075 n = byte_offset;
1076 break;
1077 }
1078 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001079 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001080 }
1081 }
1082 for (byte_offset, ch) in chars {
1083 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001084 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1085 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001086 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001087 }
1088 '\r' => {}
1089 _ => {}
1090 }
1091 }
David Tolnay1218e122017-06-01 11:13:45 -07001092 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001093}
1094
1095named!(byte -> (), do_parse!(
1096 punct!("b") >>
1097 tag!("'") >>
1098 cooked_byte >>
1099 tag!("'") >>
1100 (())
1101));
1102
Nika Layzellf8d5f212017-12-11 14:07:02 -05001103fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001104 let mut bytes = input.bytes().enumerate();
1105 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001106 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1107 Some(b'x') => backslash_x_byte(&mut bytes),
1108 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1109 | Some(b'"') => true,
1110 _ => false,
1111 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001112 b => b.is_some(),
1113 };
1114 if ok {
1115 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001116 Some((offset, _)) => {
1117 if input.chars().as_str().is_char_boundary(offset) {
1118 Ok((input.advance(offset), ()))
1119 } else {
1120 Err(LexError)
1121 }
1122 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001123 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001124 }
1125 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001126 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001127 }
1128}
1129
1130named!(character -> (), do_parse!(
1131 punct!("'") >>
1132 cooked_char >>
1133 tag!("'") >>
1134 (())
1135));
1136
Nika Layzellf8d5f212017-12-11 14:07:02 -05001137fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001138 let mut chars = input.char_indices();
1139 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001140 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1141 Some('x') => backslash_x_char(&mut chars),
1142 Some('u') => backslash_u(&mut chars),
1143 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1144 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001145 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001146 _ => false,
1147 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001148 ch => ch.is_some(),
1149 };
1150 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001151 match chars.next() {
1152 Some((idx, _)) => Ok((input.advance(idx), ())),
1153 None => Ok((input.advance(input.len()), ())),
1154 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001155 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001156 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001157 }
1158}
1159
1160macro_rules! next_ch {
1161 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1162 match $chars.next() {
1163 Some((_, ch)) => match ch {
1164 $pat $(| $rest)* => ch,
1165 _ => return false,
1166 },
1167 None => return false
1168 }
1169 };
1170}
1171
1172fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001173where
1174 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001175{
1176 next_ch!(chars @ '0'...'7');
1177 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1178 true
1179}
1180
1181fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001182where
1183 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001184{
1185 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1186 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1187 true
1188}
1189
1190fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001191where
1192 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001193{
1194 next_ch!(chars @ '{');
1195 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001196 loop {
1197 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1198 if c == '}' {
1199 return true;
1200 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001201 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001202}
1203
Nika Layzellf8d5f212017-12-11 14:07:02 -05001204fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001205 let (rest, ()) = float_digits(input)?;
1206 for suffix in &["f32", "f64"] {
1207 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001208 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001209 }
1210 }
1211 word_break(rest)
1212}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001213
Nika Layzellf8d5f212017-12-11 14:07:02 -05001214fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001215 let mut chars = input.chars().peekable();
1216 match chars.next() {
1217 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001218 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001219 }
1220
1221 let mut len = 1;
1222 let mut has_dot = false;
1223 let mut has_exp = false;
1224 while let Some(&ch) = chars.peek() {
1225 match ch {
1226 '0'...'9' | '_' => {
1227 chars.next();
1228 len += 1;
1229 }
1230 '.' => {
1231 if has_dot {
1232 break;
1233 }
1234 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001235 if chars
1236 .peek()
1237 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1238 .unwrap_or(false)
1239 {
David Tolnay1218e122017-06-01 11:13:45 -07001240 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001241 }
1242 len += 1;
1243 has_dot = true;
1244 }
1245 'e' | 'E' => {
1246 chars.next();
1247 len += 1;
1248 has_exp = true;
1249 break;
1250 }
1251 _ => break,
1252 }
1253 }
1254
Nika Layzellf8d5f212017-12-11 14:07:02 -05001255 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001256 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001257 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001258 }
1259
1260 if has_exp {
1261 let mut has_exp_value = false;
1262 while let Some(&ch) = chars.peek() {
1263 match ch {
1264 '+' | '-' => {
1265 if has_exp_value {
1266 break;
1267 }
1268 chars.next();
1269 len += 1;
1270 }
1271 '0'...'9' => {
1272 chars.next();
1273 len += 1;
1274 has_exp_value = true;
1275 }
1276 '_' => {
1277 chars.next();
1278 len += 1;
1279 }
1280 _ => break,
1281 }
1282 }
1283 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001284 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001285 }
1286 }
1287
Nika Layzellf8d5f212017-12-11 14:07:02 -05001288 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001289}
1290
Nika Layzellf8d5f212017-12-11 14:07:02 -05001291fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001292 let (rest, ()) = digits(input)?;
1293 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001294 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001295 ] {
1296 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001297 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001298 }
1299 }
1300 word_break(rest)
1301}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001302
Nika Layzellf8d5f212017-12-11 14:07:02 -05001303fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001304 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001305 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001306 16
1307 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001308 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001309 8
1310 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001311 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001312 2
1313 } else {
1314 10
1315 };
1316
Alex Crichton44bffbc2017-05-19 17:51:59 -07001317 let mut len = 0;
1318 let mut empty = true;
1319 for b in input.bytes() {
1320 let digit = match b {
1321 b'0'...b'9' => (b - b'0') as u64,
1322 b'a'...b'f' => 10 + (b - b'a') as u64,
1323 b'A'...b'F' => 10 + (b - b'A') as u64,
1324 b'_' => {
1325 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001326 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001327 }
1328 len += 1;
1329 continue;
1330 }
1331 _ => break,
1332 };
1333 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001334 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001335 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001336 len += 1;
1337 empty = false;
1338 }
1339 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001340 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001341 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001342 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001343 }
1344}
1345
Alex Crichtonf3888432018-05-16 09:11:05 -07001346fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001347 let input = skip_whitespace(input);
1348 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001349 Ok((rest, '\'')) => {
1350 symbol(rest)?;
1351 Ok((rest, Punct::new('\'', Spacing::Joint)))
1352 }
David Tolnay1218e122017-06-01 11:13:45 -07001353 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001354 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001355 Ok(_) => Spacing::Joint,
1356 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001357 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001358 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001359 }
David Tolnay1218e122017-06-01 11:13:45 -07001360 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001361 }
1362}
1363
Nika Layzellf8d5f212017-12-11 14:07:02 -05001364fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001365 if input.starts_with("//") || input.starts_with("/*") {
1366 // Do not accept `/` of a comment as an op.
1367 return Err(LexError);
1368 }
1369
David Tolnayea75c5f2017-05-31 23:40:33 -07001370 let mut chars = input.chars();
1371 let first = match chars.next() {
1372 Some(ch) => ch,
1373 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001374 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001375 }
1376 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001377 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001378 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001379 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001380 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001381 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001382 }
1383}
1384
Alex Crichton1eb96a02018-04-04 13:07:35 -07001385fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1386 let mut trees = Vec::new();
1387 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001388 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001389 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001390 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001391 }
1392 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001393 TokenTree::Ident(::Ident::new("doc", span)),
1394 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001395 TokenTree::Literal(::Literal::string(comment)),
1396 ];
1397 for tt in stream.iter_mut() {
1398 tt.set_span(span);
1399 }
David Tolnayf14813f2018-09-08 17:14:07 -07001400 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1401 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001402 for tt in trees.iter_mut() {
1403 tt.set_span(span);
1404 }
1405 Ok((rest, trees))
1406}
1407
1408named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001409 do_parse!(
1410 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001411 s: take_until_newline_or_eof!() >>
1412 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001413 )
1414 |
1415 do_parse!(
1416 option!(whitespace) >>
1417 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001418 s: block_comment >>
1419 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001420 )
1421 |
1422 do_parse!(
1423 punct!("///") >>
1424 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001425 s: take_until_newline_or_eof!() >>
1426 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001427 )
1428 |
1429 do_parse!(
1430 option!(whitespace) >>
1431 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001432 s: block_comment >>
1433 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001434 )
1435));