blob: 73912f58843088b491162e525b7ef28b391e4ed5 [file] [log] [blame]
Alex Crichtona914a612018-04-04 07:48:44 -07001#![cfg_attr(not(procmacro2_semver_exempt), allow(dead_code))]
Alex Crichtonaf5bad42018-03-27 14:45:10 -07002
David Tolnayc2309ca2018-06-02 15:47:57 -07003#[cfg(procmacro2_semver_exempt)]
Alex Crichton44bffbc2017-05-19 17:51:59 -07004use std::cell::RefCell;
David Tolnay1ebe3972018-01-02 20:14:20 -08005#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -05006use std::cmp;
Alex Crichton44bffbc2017-05-19 17:51:59 -07007use std::fmt;
8use std::iter;
Alex Crichton44bffbc2017-05-19 17:51:59 -07009use std::str::FromStr;
10use std::vec;
11
David Tolnayb28f38a2018-03-31 22:02:29 +020012use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult};
David Tolnayb1032662017-05-31 15:52:28 -070013use unicode_xid::UnicodeXID;
Alex Crichton44bffbc2017-05-19 17:51:59 -070014
Alex Crichtonf3888432018-05-16 09:11:05 -070015use {Delimiter, Group, Punct, Spacing, TokenTree};
Alex Crichton44bffbc2017-05-19 17:51:59 -070016
David Tolnay034205f2018-04-22 16:45:28 -070017#[derive(Clone)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070018pub struct TokenStream {
19 inner: Vec<TokenTree>,
20}
21
22#[derive(Debug)]
23pub struct LexError;
24
25impl TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -070026 pub fn new() -> TokenStream {
Alex Crichton44bffbc2017-05-19 17:51:59 -070027 TokenStream { inner: Vec::new() }
28 }
29
30 pub fn is_empty(&self) -> bool {
31 self.inner.len() == 0
32 }
33}
34
David Tolnay1ebe3972018-01-02 20:14:20 -080035#[cfg(procmacro2_semver_exempt)]
Nika Layzella9dbc182017-12-30 14:50:13 -050036fn get_cursor(src: &str) -> Cursor {
37 // Create a dummy file & add it to the codemap
38 CODEMAP.with(|cm| {
39 let mut cm = cm.borrow_mut();
40 let name = format!("<parsed string {}>", cm.files.len());
41 let span = cm.add_file(&name, src);
42 Cursor {
43 rest: src,
44 off: span.lo,
45 }
46 })
47}
48
David Tolnay1ebe3972018-01-02 20:14:20 -080049#[cfg(not(procmacro2_semver_exempt))]
Nika Layzella9dbc182017-12-30 14:50:13 -050050fn get_cursor(src: &str) -> Cursor {
David Tolnayb28f38a2018-03-31 22:02:29 +020051 Cursor { rest: src }
Nika Layzella9dbc182017-12-30 14:50:13 -050052}
53
Alex Crichton44bffbc2017-05-19 17:51:59 -070054impl FromStr for TokenStream {
55 type Err = LexError;
56
57 fn from_str(src: &str) -> Result<TokenStream, LexError> {
Nika Layzellf8d5f212017-12-11 14:07:02 -050058 // Create a dummy file & add it to the codemap
Nika Layzella9dbc182017-12-30 14:50:13 -050059 let cursor = get_cursor(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -050060
61 match token_stream(cursor) {
David Tolnay1218e122017-06-01 11:13:45 -070062 Ok((input, output)) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -070063 if skip_whitespace(input).len() != 0 {
64 Err(LexError)
65 } else {
Alex Crichton30a4e9e2018-04-27 17:02:19 -070066 Ok(output)
Alex Crichton44bffbc2017-05-19 17:51:59 -070067 }
68 }
David Tolnay1218e122017-06-01 11:13:45 -070069 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -070070 }
71 }
72}
73
74impl fmt::Display for TokenStream {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 let mut joint = false;
77 for (i, tt) in self.inner.iter().enumerate() {
78 if i != 0 && !joint {
79 write!(f, " ")?;
80 }
81 joint = false;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070082 match *tt {
83 TokenTree::Group(ref tt) => {
84 let (start, end) = match tt.delimiter() {
Alex Crichton44bffbc2017-05-19 17:51:59 -070085 Delimiter::Parenthesis => ("(", ")"),
86 Delimiter::Brace => ("{", "}"),
87 Delimiter::Bracket => ("[", "]"),
88 Delimiter::None => ("", ""),
89 };
Alex Crichton30a4e9e2018-04-27 17:02:19 -070090 if tt.stream().into_iter().next().is_none() {
Alex Crichton852d53d2017-05-19 19:25:08 -070091 write!(f, "{} {}", start, end)?
92 } else {
Alex Crichtonaf5bad42018-03-27 14:45:10 -070093 write!(f, "{} {} {}", start, tt.stream(), end)?
Alex Crichton852d53d2017-05-19 19:25:08 -070094 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070095 }
Alex Crichtonf3888432018-05-16 09:11:05 -070096 TokenTree::Ident(ref tt) => write!(f, "{}", tt)?,
97 TokenTree::Punct(ref tt) => {
98 write!(f, "{}", tt.as_char())?;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070099 match tt.spacing() {
Alex Crichton1a7f7622017-07-05 17:47:15 -0700100 Spacing::Alone => {}
101 Spacing::Joint => joint = true,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700102 }
103 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700104 TokenTree::Literal(ref tt) => write!(f, "{}", tt)?,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700105 }
106 }
107
108 Ok(())
109 }
110}
111
David Tolnay034205f2018-04-22 16:45:28 -0700112impl fmt::Debug for TokenStream {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 f.write_str("TokenStream ")?;
115 f.debug_list().entries(self.clone()).finish()
116 }
117}
118
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800119#[cfg(feature = "proc-macro")]
120impl From<::proc_macro::TokenStream> for TokenStream {
121 fn from(inner: ::proc_macro::TokenStream) -> TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200122 inner
123 .to_string()
124 .parse()
125 .expect("compiler token stream parse failed")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700126 }
127}
128
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800129#[cfg(feature = "proc-macro")]
130impl From<TokenStream> for ::proc_macro::TokenStream {
131 fn from(inner: TokenStream) -> ::proc_macro::TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200132 inner
133 .to_string()
134 .parse()
135 .expect("failed to parse to compiler tokens")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700136 }
137}
138
Alex Crichton44bffbc2017-05-19 17:51:59 -0700139impl From<TokenTree> for TokenStream {
140 fn from(tree: TokenTree) -> TokenStream {
141 TokenStream { inner: vec![tree] }
142 }
143}
144
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700145impl iter::FromIterator<TokenTree> for TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200146 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700147 let mut v = Vec::new();
148
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700149 for token in streams.into_iter() {
150 v.push(token);
Alex Crichton44bffbc2017-05-19 17:51:59 -0700151 }
152
153 TokenStream { inner: v }
154 }
155}
156
Alex Crichtonf3888432018-05-16 09:11:05 -0700157impl Extend<TokenTree> for TokenStream {
158 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
159 self.inner.extend(streams);
160 }
161}
162
Alex Crichton1a7f7622017-07-05 17:47:15 -0700163pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700164
165impl IntoIterator for TokenStream {
166 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700167 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700168
Alex Crichton1a7f7622017-07-05 17:47:15 -0700169 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700170 self.inner.into_iter()
171 }
172}
173
Nika Layzellb35a9a32017-12-30 14:34:35 -0500174#[derive(Clone, PartialEq, Eq, Debug)]
175pub struct FileName(String);
176
Alex Crichtonf3888432018-05-16 09:11:05 -0700177#[allow(dead_code)]
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700178pub fn file_name(s: String) -> FileName {
179 FileName(s)
180}
181
Nika Layzellb35a9a32017-12-30 14:34:35 -0500182impl fmt::Display for FileName {
183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184 self.0.fmt(f)
185 }
186}
187
Nika Layzellf8d5f212017-12-11 14:07:02 -0500188#[derive(Clone, PartialEq, Eq)]
189pub struct SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500190 name: FileName,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500191}
192
193impl SourceFile {
194 /// Get the path to this source file as a string.
Nika Layzellb35a9a32017-12-30 14:34:35 -0500195 pub fn path(&self) -> &FileName {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500196 &self.name
197 }
198
199 pub fn is_real(&self) -> bool {
200 // XXX(nika): Support real files in the future?
201 false
202 }
203}
204
Nika Layzellb35a9a32017-12-30 14:34:35 -0500205impl AsRef<FileName> for SourceFile {
206 fn as_ref(&self) -> &FileName {
207 self.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500208 }
209}
210
211impl 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 Tolnay1ebe3972018-01-02 20:14:20 -0800226#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227thread_local! {
228 static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap {
229 // NOTE: We start with a single dummy file which all call_site() and
230 // def_site() spans reference.
231 files: vec![FileInfo {
232 name: "<unspecified>".to_owned(),
233 span: Span { lo: 0, hi: 0 },
234 lines: vec![0],
235 }],
236 });
237}
238
David Tolnay1ebe3972018-01-02 20:14:20 -0800239#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500240struct FileInfo {
241 name: String,
242 span: Span,
243 lines: Vec<usize>,
244}
245
David Tolnay1ebe3972018-01-02 20:14:20 -0800246#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500247impl FileInfo {
248 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200249 assert!(self.span_within(Span {
250 lo: offset as u32,
251 hi: offset as u32
252 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500253 let offset = offset - self.span.lo as usize;
254 match self.lines.binary_search(&offset) {
255 Ok(found) => LineColumn {
256 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200257 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500258 },
259 Err(idx) => LineColumn {
260 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200261 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500262 },
263 }
264 }
265
266 fn span_within(&self, span: Span) -> bool {
267 span.lo >= self.span.lo && span.hi <= self.span.hi
268 }
269}
270
Alex Crichtona914a612018-04-04 07:48:44 -0700271/// Computesthe offsets of each line in the given source string.
David Tolnay1ebe3972018-01-02 20:14:20 -0800272#[cfg(procmacro2_semver_exempt)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500273fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500274 let mut lines = vec![0];
275 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500276 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500277 prev += len + 1;
278 lines.push(prev);
279 }
280 lines
281}
282
David Tolnay1ebe3972018-01-02 20:14:20 -0800283#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500284struct Codemap {
285 files: Vec<FileInfo>,
286}
287
David Tolnay1ebe3972018-01-02 20:14:20 -0800288#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500289impl Codemap {
290 fn next_start_pos(&self) -> u32 {
291 // Add 1 so there's always space between files.
292 //
293 // We'll always have at least 1 file, as we initialize our files list
294 // with a dummy file.
295 self.files.last().unwrap().span.hi + 1
296 }
297
298 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500299 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500300 let lo = self.next_start_pos();
301 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200302 let span = Span {
303 lo: lo,
304 hi: lo + (src.len() as u32),
305 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500306
307 self.files.push(FileInfo {
308 name: name.to_owned(),
309 span: span,
310 lines: lines,
311 });
312
313 span
314 }
315
316 fn fileinfo(&self, span: Span) -> &FileInfo {
317 for file in &self.files {
318 if file.span_within(span) {
319 return file;
320 }
321 }
322 panic!("Invalid span with no related FileInfo!");
323 }
324}
325
David Tolnay034205f2018-04-22 16:45:28 -0700326#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500327pub struct Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800328 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500329 lo: u32,
David Tolnay1ebe3972018-01-02 20:14:20 -0800330 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500331 hi: u32,
332}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700333
334impl Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800335 #[cfg(not(procmacro2_semver_exempt))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700336 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500337 Span {}
338 }
339
David Tolnay1ebe3972018-01-02 20:14:20 -0800340 #[cfg(procmacro2_semver_exempt)]
David Tolnay79105e52017-12-31 11:03:04 -0500341 pub fn call_site() -> Span {
342 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700343 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800344
345 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500346 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500347 }
348
David Tolnay4e8e3972018-01-05 18:10:22 -0800349 pub fn resolved_at(&self, _other: Span) -> Span {
350 // Stable spans consist only of line/column information, so
351 // `resolved_at` and `located_at` only select which span the
352 // caller wants line/column information from.
353 *self
354 }
355
356 pub fn located_at(&self, other: Span) -> Span {
357 other
358 }
359
David Tolnay1ebe3972018-01-02 20:14:20 -0800360 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500361 pub fn source_file(&self) -> SourceFile {
362 CODEMAP.with(|cm| {
363 let cm = cm.borrow();
364 let fi = cm.fileinfo(*self);
365 SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500366 name: FileName(fi.name.clone()),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500367 }
368 })
369 }
370
David Tolnay1ebe3972018-01-02 20:14:20 -0800371 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500372 pub fn start(&self) -> LineColumn {
373 CODEMAP.with(|cm| {
374 let cm = cm.borrow();
375 let fi = cm.fileinfo(*self);
376 fi.offset_line_column(self.lo as usize)
377 })
378 }
379
David Tolnay1ebe3972018-01-02 20:14:20 -0800380 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500381 pub fn end(&self) -> LineColumn {
382 CODEMAP.with(|cm| {
383 let cm = cm.borrow();
384 let fi = cm.fileinfo(*self);
385 fi.offset_line_column(self.hi as usize)
386 })
387 }
388
David Tolnay1ebe3972018-01-02 20:14:20 -0800389 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500390 pub fn join(&self, other: Span) -> Option<Span> {
391 CODEMAP.with(|cm| {
392 let cm = cm.borrow();
393 // If `other` is not within the same FileInfo as us, return None.
394 if !cm.fileinfo(*self).span_within(other) {
395 return None;
396 }
397 Some(Span {
398 lo: cmp::min(self.lo, other.lo),
399 hi: cmp::max(self.hi, other.hi),
400 })
401 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800402 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700403}
404
David Tolnay034205f2018-04-22 16:45:28 -0700405impl fmt::Debug for Span {
406 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407 #[cfg(procmacro2_semver_exempt)]
408 return write!(f, "bytes({}..{})", self.lo, self.hi);
409
410 #[cfg(not(procmacro2_semver_exempt))]
411 write!(f, "Span")
412 }
413}
414
Alex Crichtonf3888432018-05-16 09:11:05 -0700415#[derive(Clone)]
416pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700417 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700418 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700419 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700420}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700421
Alex Crichtonf3888432018-05-16 09:11:05 -0700422impl Ident {
423 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700424 validate_term(string);
425
Alex Crichtonf3888432018-05-16 09:11:05 -0700426 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700427 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700428 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700429 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700430 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700431 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700432
Alex Crichtonf3888432018-05-16 09:11:05 -0700433 pub fn new(string: &str, span: Span) -> Ident {
434 Ident::_new(string, false, span)
435 }
436
437 pub fn new_raw(string: &str, span: Span) -> Ident {
438 Ident::_new(string, true, span)
439 }
440
Alex Crichtonb2c94622018-04-04 07:36:41 -0700441 pub fn span(&self) -> Span {
442 self.span
443 }
444
445 pub fn set_span(&mut self, span: Span) {
446 self.span = span;
447 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700448}
449
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000450#[inline]
451fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700452 ('a' <= c && c <= 'z')
453 || ('A' <= c && c <= 'Z')
454 || c == '_'
455 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000456}
457
458#[inline]
459fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700460 ('a' <= c && c <= 'z')
461 || ('A' <= c && c <= 'Z')
462 || c == '_'
463 || ('0' <= c && c <= '9')
464 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000465}
466
David Tolnay489c6422018-04-07 08:37:28 -0700467fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700468 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700469 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700470 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700471 }
472
473 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700474 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700475 }
476
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000477 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700478 let mut chars = string.chars();
479 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000480 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700481 return false;
482 }
483 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000484 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700485 return false;
486 }
487 }
488 true
489 }
490
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000491 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700492 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700493 }
494}
495
Alex Crichtonf3888432018-05-16 09:11:05 -0700496impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700498 if self.raw {
499 "r#".fmt(f)?;
500 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700501 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700502 }
503}
504
505impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700506 // Ident(proc_macro), Ident(r#union)
507 #[cfg(not(procmacro2_semver_exempt))]
508 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
509 let mut debug = f.debug_tuple("Ident");
510 debug.field(&format_args!("{}", self));
511 debug.finish()
512 }
513
514 // Ident {
515 // sym: proc_macro,
516 // span: bytes(128..138)
517 // }
518 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700519 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
520 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700521 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700522 debug.field("span", &self.span);
523 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700524 }
525}
526
David Tolnay034205f2018-04-22 16:45:28 -0700527#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700528pub struct Literal {
529 text: String,
530 span: Span,
531}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700532
Alex Crichtona914a612018-04-04 07:48:44 -0700533macro_rules! suffixed_numbers {
534 ($($name:ident => $kind:ident,)*) => ($(
535 pub fn $name(n: $kind) -> Literal {
536 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
537 }
538 )*)
539}
540
541macro_rules! unsuffixed_numbers {
542 ($($name:ident => $kind:ident,)*) => ($(
543 pub fn $name(n: $kind) -> Literal {
544 Literal::_new(n.to_string())
545 }
546 )*)
547}
548
Alex Crichton852d53d2017-05-19 19:25:08 -0700549impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700550 fn _new(text: String) -> Literal {
551 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700552 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700553 span: Span::call_site(),
554 }
555 }
556
Alex Crichtona914a612018-04-04 07:48:44 -0700557 suffixed_numbers! {
558 u8_suffixed => u8,
559 u16_suffixed => u16,
560 u32_suffixed => u32,
561 u64_suffixed => u64,
562 usize_suffixed => usize,
563 i8_suffixed => i8,
564 i16_suffixed => i16,
565 i32_suffixed => i32,
566 i64_suffixed => i64,
567 isize_suffixed => isize,
568
569 f32_suffixed => f32,
570 f64_suffixed => f64,
571 }
572
573 unsuffixed_numbers! {
574 u8_unsuffixed => u8,
575 u16_unsuffixed => u16,
576 u32_unsuffixed => u32,
577 u64_unsuffixed => u64,
578 usize_unsuffixed => usize,
579 i8_unsuffixed => i8,
580 i16_unsuffixed => i16,
581 i32_unsuffixed => i32,
582 i64_unsuffixed => i64,
583 isize_unsuffixed => isize,
584 }
585
586 pub fn f32_unsuffixed(f: f32) -> Literal {
587 let mut s = f.to_string();
588 if !s.contains(".") {
589 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700590 }
Alex Crichtona914a612018-04-04 07:48:44 -0700591 Literal::_new(s)
592 }
593
594 pub fn f64_unsuffixed(f: f64) -> Literal {
595 let mut s = f.to_string();
596 if !s.contains(".") {
597 s.push_str(".0");
598 }
599 Literal::_new(s)
600 }
601
602 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700603 let mut s = t
604 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700605 .flat_map(|c| c.escape_default())
606 .collect::<String>();
607 s.push('"');
608 s.insert(0, '"');
609 Literal::_new(s)
610 }
611
612 pub fn character(t: char) -> Literal {
613 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700614 }
615
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700616 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700617 let mut escaped = "b\"".to_string();
618 for b in bytes {
619 match *b {
620 b'\0' => escaped.push_str(r"\0"),
621 b'\t' => escaped.push_str(r"\t"),
622 b'\n' => escaped.push_str(r"\n"),
623 b'\r' => escaped.push_str(r"\r"),
624 b'"' => escaped.push_str("\\\""),
625 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200626 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700627 _ => escaped.push_str(&format!("\\x{:02X}", b)),
628 }
629 }
630 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700631 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700632 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700633
Alex Crichtonb2c94622018-04-04 07:36:41 -0700634 pub fn span(&self) -> Span {
635 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700636 }
637
Alex Crichtonb2c94622018-04-04 07:36:41 -0700638 pub fn set_span(&mut self, span: Span) {
639 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700640 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700641}
642
Alex Crichton44bffbc2017-05-19 17:51:59 -0700643impl fmt::Display for Literal {
644 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700645 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700646 }
647}
648
David Tolnay034205f2018-04-22 16:45:28 -0700649impl fmt::Debug for Literal {
650 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
651 let mut debug = fmt.debug_struct("Literal");
652 debug.field("lit", &format_args!("{}", self.text));
653 #[cfg(procmacro2_semver_exempt)]
654 debug.field("span", &self.span);
655 debug.finish()
656 }
657}
658
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700659fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700660 let mut trees = Vec::new();
661 loop {
662 let input_no_ws = skip_whitespace(input);
663 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700664 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700665 }
666 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
667 input = a;
668 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700669 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700670 }
671
672 let (a, tt) = match token_tree(input_no_ws) {
673 Ok(p) => p,
674 Err(_) => break,
675 };
676 trees.push(tt);
677 input = a;
678 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700679 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700680}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700681
David Tolnay1ebe3972018-01-02 20:14:20 -0800682#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700683fn spanned<'a, T>(
684 input: Cursor<'a>,
685 f: fn(Cursor<'a>) -> PResult<'a, T>,
686) -> PResult<'a, (T, ::Span)> {
687 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700688 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500689}
690
David Tolnay1ebe3972018-01-02 20:14:20 -0800691#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700692fn spanned<'a, T>(
693 input: Cursor<'a>,
694 f: fn(Cursor<'a>) -> PResult<'a, T>,
695) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500696 let input = skip_whitespace(input);
697 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700698 let (a, b) = f(input)?;
699 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700700 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700701 Ok((a, (b, span)))
702}
703
704fn token_tree(input: Cursor) -> PResult<TokenTree> {
705 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
706 tt.set_span(span);
707 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500708}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700709
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700710named!(token_kind -> TokenTree, alt!(
711 map!(group, TokenTree::Group)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700712 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700713 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700714 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700715 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700716 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700717 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700718));
719
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700720named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700721 delimited!(
722 punct!("("),
723 token_stream,
724 punct!(")")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700725 ) => { |ts| Group::new(Delimiter::Parenthesis, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700726 |
727 delimited!(
728 punct!("["),
729 token_stream,
730 punct!("]")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700731 ) => { |ts| Group::new(Delimiter::Bracket, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700732 |
733 delimited!(
734 punct!("{"),
735 token_stream,
736 punct!("}")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700737 ) => { |ts| Group::new(Delimiter::Brace, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700738));
739
Alex Crichtonf3888432018-05-16 09:11:05 -0700740fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
741 symbol(skip_whitespace(input))
742}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700743
Alex Crichtonf3888432018-05-16 09:11:05 -0700744fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700745 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700746
Alex Crichtonf3888432018-05-16 09:11:05 -0700747 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200748 if raw {
749 chars.next();
750 chars.next();
751 }
752
Alex Crichton44bffbc2017-05-19 17:51:59 -0700753 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000754 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700755 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700756 }
757
David Tolnay214c94c2017-06-01 12:42:56 -0700758 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700759 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000760 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700761 end = i;
762 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700763 }
764 }
765
David Tolnaya13d1422018-03-31 21:27:48 +0200766 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700767 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700768 Err(LexError)
769 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700770 let ident = if raw {
771 ::Ident::_new_raw(&a[2..], ::Span::call_site())
772 } else {
773 ::Ident::new(a, ::Span::call_site())
774 };
775 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700776 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700777}
778
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700779fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700780 let input_no_ws = skip_whitespace(input);
781
782 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700783 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700784 let start = input.len() - input_no_ws.len();
785 let len = input_no_ws.len() - a.len();
786 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700787 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700788 }
David Tolnay1218e122017-06-01 11:13:45 -0700789 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700790 }
791}
792
793named!(literal_nocapture -> (), alt!(
794 string
795 |
796 byte_string
797 |
798 byte
799 |
800 character
801 |
802 float
803 |
804 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700805));
806
807named!(string -> (), alt!(
808 quoted_string
809 |
810 preceded!(
811 punct!("r"),
812 raw_string
813 ) => { |_| () }
814));
815
816named!(quoted_string -> (), delimited!(
817 punct!("\""),
818 cooked_string,
819 tag!("\"")
820));
821
Nika Layzellf8d5f212017-12-11 14:07:02 -0500822fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700823 let mut chars = input.char_indices().peekable();
824 while let Some((byte_offset, ch)) = chars.next() {
825 match ch {
826 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500827 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700828 }
829 '\r' => {
830 if let Some((_, '\n')) = chars.next() {
831 // ...
832 } else {
833 break;
834 }
835 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200836 '\\' => match chars.next() {
837 Some((_, 'x')) => {
838 if !backslash_x_char(&mut chars) {
839 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700840 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700841 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200842 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
843 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
844 Some((_, 'u')) => {
845 if !backslash_u(&mut chars) {
846 break;
847 }
848 }
849 Some((_, '\n')) | Some((_, '\r')) => {
850 while let Some(&(_, ch)) = chars.peek() {
851 if ch.is_whitespace() {
852 chars.next();
853 } else {
854 break;
855 }
856 }
857 }
858 _ => break,
859 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700860 _ch => {}
861 }
862 }
David Tolnay1218e122017-06-01 11:13:45 -0700863 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700864}
865
866named!(byte_string -> (), alt!(
867 delimited!(
868 punct!("b\""),
869 cooked_byte_string,
870 tag!("\"")
871 ) => { |_| () }
872 |
873 preceded!(
874 punct!("br"),
875 raw_string
876 ) => { |_| () }
877));
878
Nika Layzellf8d5f212017-12-11 14:07:02 -0500879fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700880 let mut bytes = input.bytes().enumerate();
881 'outer: while let Some((offset, b)) = bytes.next() {
882 match b {
883 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500884 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700885 }
886 b'\r' => {
887 if let Some((_, b'\n')) = bytes.next() {
888 // ...
889 } else {
890 break;
891 }
892 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200893 b'\\' => match bytes.next() {
894 Some((_, b'x')) => {
895 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700896 break;
897 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700898 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200899 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
900 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
901 Some((newline, b'\n')) | Some((newline, b'\r')) => {
902 let rest = input.advance(newline + 1);
903 for (offset, ch) in rest.char_indices() {
904 if !ch.is_whitespace() {
905 input = rest.advance(offset);
906 bytes = input.bytes().enumerate();
907 continue 'outer;
908 }
909 }
910 break;
911 }
912 _ => break,
913 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700914 b if b < 0x80 => {}
915 _ => break,
916 }
917 }
David Tolnay1218e122017-06-01 11:13:45 -0700918 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700919}
920
Nika Layzellf8d5f212017-12-11 14:07:02 -0500921fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700922 let mut chars = input.char_indices();
923 let mut n = 0;
924 while let Some((byte_offset, ch)) = chars.next() {
925 match ch {
926 '"' => {
927 n = byte_offset;
928 break;
929 }
930 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -0700931 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700932 }
933 }
934 for (byte_offset, ch) in chars {
935 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500936 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
937 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +0200938 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700939 }
940 '\r' => {}
941 _ => {}
942 }
943 }
David Tolnay1218e122017-06-01 11:13:45 -0700944 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700945}
946
947named!(byte -> (), do_parse!(
948 punct!("b") >>
949 tag!("'") >>
950 cooked_byte >>
951 tag!("'") >>
952 (())
953));
954
Nika Layzellf8d5f212017-12-11 14:07:02 -0500955fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700956 let mut bytes = input.bytes().enumerate();
957 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +0200958 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
959 Some(b'x') => backslash_x_byte(&mut bytes),
960 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
961 | Some(b'"') => true,
962 _ => false,
963 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700964 b => b.is_some(),
965 };
966 if ok {
967 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -0800968 Some((offset, _)) => {
969 if input.chars().as_str().is_char_boundary(offset) {
970 Ok((input.advance(offset), ()))
971 } else {
972 Err(LexError)
973 }
974 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500975 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700976 }
977 } else {
David Tolnay1218e122017-06-01 11:13:45 -0700978 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700979 }
980}
981
982named!(character -> (), do_parse!(
983 punct!("'") >>
984 cooked_char >>
985 tag!("'") >>
986 (())
987));
988
Nika Layzellf8d5f212017-12-11 14:07:02 -0500989fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700990 let mut chars = input.char_indices();
991 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +0200992 Some('\\') => match chars.next().map(|(_, ch)| ch) {
993 Some('x') => backslash_x_char(&mut chars),
994 Some('u') => backslash_u(&mut chars),
995 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
996 true
Alex Crichton44bffbc2017-05-19 17:51:59 -0700997 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200998 _ => false,
999 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001000 ch => ch.is_some(),
1001 };
1002 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001003 match chars.next() {
1004 Some((idx, _)) => Ok((input.advance(idx), ())),
1005 None => Ok((input.advance(input.len()), ())),
1006 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001007 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001008 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001009 }
1010}
1011
1012macro_rules! next_ch {
1013 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1014 match $chars.next() {
1015 Some((_, ch)) => match ch {
1016 $pat $(| $rest)* => ch,
1017 _ => return false,
1018 },
1019 None => return false
1020 }
1021 };
1022}
1023
1024fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001025where
1026 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001027{
1028 next_ch!(chars @ '0'...'7');
1029 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1030 true
1031}
1032
1033fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001034where
1035 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001036{
1037 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1038 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1039 true
1040}
1041
1042fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001043where
1044 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001045{
1046 next_ch!(chars @ '{');
1047 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001048 loop {
1049 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1050 if c == '}' {
1051 return true;
1052 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001053 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001054}
1055
Nika Layzellf8d5f212017-12-11 14:07:02 -05001056fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001057 let (rest, ()) = float_digits(input)?;
1058 for suffix in &["f32", "f64"] {
1059 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001060 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001061 }
1062 }
1063 word_break(rest)
1064}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001065
Nika Layzellf8d5f212017-12-11 14:07:02 -05001066fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001067 let mut chars = input.chars().peekable();
1068 match chars.next() {
1069 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001070 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001071 }
1072
1073 let mut len = 1;
1074 let mut has_dot = false;
1075 let mut has_exp = false;
1076 while let Some(&ch) = chars.peek() {
1077 match ch {
1078 '0'...'9' | '_' => {
1079 chars.next();
1080 len += 1;
1081 }
1082 '.' => {
1083 if has_dot {
1084 break;
1085 }
1086 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001087 if chars
1088 .peek()
1089 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1090 .unwrap_or(false)
1091 {
David Tolnay1218e122017-06-01 11:13:45 -07001092 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001093 }
1094 len += 1;
1095 has_dot = true;
1096 }
1097 'e' | 'E' => {
1098 chars.next();
1099 len += 1;
1100 has_exp = true;
1101 break;
1102 }
1103 _ => break,
1104 }
1105 }
1106
Nika Layzellf8d5f212017-12-11 14:07:02 -05001107 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001108 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001109 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001110 }
1111
1112 if has_exp {
1113 let mut has_exp_value = false;
1114 while let Some(&ch) = chars.peek() {
1115 match ch {
1116 '+' | '-' => {
1117 if has_exp_value {
1118 break;
1119 }
1120 chars.next();
1121 len += 1;
1122 }
1123 '0'...'9' => {
1124 chars.next();
1125 len += 1;
1126 has_exp_value = true;
1127 }
1128 '_' => {
1129 chars.next();
1130 len += 1;
1131 }
1132 _ => break,
1133 }
1134 }
1135 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001136 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001137 }
1138 }
1139
Nika Layzellf8d5f212017-12-11 14:07:02 -05001140 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001141}
1142
Nika Layzellf8d5f212017-12-11 14:07:02 -05001143fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001144 let (rest, ()) = digits(input)?;
1145 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001146 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001147 ] {
1148 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001149 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001150 }
1151 }
1152 word_break(rest)
1153}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001154
Nika Layzellf8d5f212017-12-11 14:07:02 -05001155fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001156 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001157 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001158 16
1159 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001160 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001161 8
1162 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001163 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001164 2
1165 } else {
1166 10
1167 };
1168
Alex Crichton44bffbc2017-05-19 17:51:59 -07001169 let mut len = 0;
1170 let mut empty = true;
1171 for b in input.bytes() {
1172 let digit = match b {
1173 b'0'...b'9' => (b - b'0') as u64,
1174 b'a'...b'f' => 10 + (b - b'a') as u64,
1175 b'A'...b'F' => 10 + (b - b'A') as u64,
1176 b'_' => {
1177 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001178 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001179 }
1180 len += 1;
1181 continue;
1182 }
1183 _ => break,
1184 };
1185 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001186 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001187 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001188 len += 1;
1189 empty = false;
1190 }
1191 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001192 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001193 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001194 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001195 }
1196}
1197
Alex Crichtonf3888432018-05-16 09:11:05 -07001198fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001199 let input = skip_whitespace(input);
1200 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001201 Ok((rest, '\'')) => {
1202 symbol(rest)?;
1203 Ok((rest, Punct::new('\'', Spacing::Joint)))
1204 }
David Tolnay1218e122017-06-01 11:13:45 -07001205 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001206 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001207 Ok(_) => Spacing::Joint,
1208 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001209 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001210 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001211 }
David Tolnay1218e122017-06-01 11:13:45 -07001212 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001213 }
1214}
1215
Nika Layzellf8d5f212017-12-11 14:07:02 -05001216fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001217 if input.starts_with("//") || input.starts_with("/*") {
1218 // Do not accept `/` of a comment as an op.
1219 return Err(LexError);
1220 }
1221
David Tolnayea75c5f2017-05-31 23:40:33 -07001222 let mut chars = input.chars();
1223 let first = match chars.next() {
1224 Some(ch) => ch,
1225 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001226 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001227 }
1228 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001229 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001230 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001231 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001232 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001233 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001234 }
1235}
1236
Alex Crichton1eb96a02018-04-04 13:07:35 -07001237fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1238 let mut trees = Vec::new();
1239 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001240 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001241 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001242 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001243 }
1244 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001245 TokenTree::Ident(::Ident::new("doc", span)),
1246 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001247 TokenTree::Literal(::Literal::string(comment)),
1248 ];
1249 for tt in stream.iter_mut() {
1250 tt.set_span(span);
1251 }
1252 trees.push(Group::new(Delimiter::Bracket, stream.into_iter().collect()).into());
1253 for tt in trees.iter_mut() {
1254 tt.set_span(span);
1255 }
1256 Ok((rest, trees))
1257}
1258
1259named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001260 do_parse!(
1261 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001262 s: take_until_newline_or_eof!() >>
1263 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001264 )
1265 |
1266 do_parse!(
1267 option!(whitespace) >>
1268 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001269 s: block_comment >>
1270 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001271 )
1272 |
1273 do_parse!(
1274 punct!("///") >>
1275 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001276 s: take_until_newline_or_eof!() >>
1277 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001278 )
1279 |
1280 do_parse!(
1281 option!(whitespace) >>
1282 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001283 s: block_comment >>
1284 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001285 )
1286));