blob: 4859dd34118d414ecb398bfb05aa3c99bbe5c073 [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,
David Tolnay1596a8c2019-07-19 11:45:26 -0700684 u128_suffixed => u128,
Alex Crichtona914a612018-04-04 07:48:44 -0700685 usize_suffixed => usize,
686 i8_suffixed => i8,
687 i16_suffixed => i16,
688 i32_suffixed => i32,
689 i64_suffixed => i64,
David Tolnay1596a8c2019-07-19 11:45:26 -0700690 i128_suffixed => i128,
Alex Crichtona914a612018-04-04 07:48:44 -0700691 isize_suffixed => isize,
692
693 f32_suffixed => f32,
694 f64_suffixed => f64,
695 }
696
697 unsuffixed_numbers! {
698 u8_unsuffixed => u8,
699 u16_unsuffixed => u16,
700 u32_unsuffixed => u32,
701 u64_unsuffixed => u64,
David Tolnay1596a8c2019-07-19 11:45:26 -0700702 u128_unsuffixed => u128,
Alex Crichtona914a612018-04-04 07:48:44 -0700703 usize_unsuffixed => usize,
704 i8_unsuffixed => i8,
705 i16_unsuffixed => i16,
706 i32_unsuffixed => i32,
707 i64_unsuffixed => i64,
Alex Crichton69385662018-11-08 06:30:04 -0800708 i128_unsuffixed => i128,
David Tolnay1596a8c2019-07-19 11:45:26 -0700709 isize_unsuffixed => isize,
Alex Crichton69385662018-11-08 06:30:04 -0800710 }
711
Alex Crichtona914a612018-04-04 07:48:44 -0700712 pub fn f32_unsuffixed(f: f32) -> Literal {
713 let mut s = f.to_string();
714 if !s.contains(".") {
715 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700716 }
Alex Crichtona914a612018-04-04 07:48:44 -0700717 Literal::_new(s)
718 }
719
720 pub fn f64_unsuffixed(f: f64) -> Literal {
721 let mut s = f.to_string();
722 if !s.contains(".") {
723 s.push_str(".0");
724 }
725 Literal::_new(s)
726 }
727
728 pub fn string(t: &str) -> Literal {
David Tolnaye4482f42019-04-22 16:15:14 -0700729 let mut text = String::with_capacity(t.len() + 2);
730 text.push('"');
731 for c in t.chars() {
732 if c == '\'' {
733 // escape_default turns this into "\'" which is unnecessary.
734 text.push(c);
735 } else {
736 text.extend(c.escape_default());
737 }
738 }
739 text.push('"');
740 Literal::_new(text)
Alex Crichtona914a612018-04-04 07:48:44 -0700741 }
742
743 pub fn character(t: char) -> Literal {
David Tolnaye4482f42019-04-22 16:15:14 -0700744 let mut text = String::new();
745 text.push('\'');
746 if t == '"' {
747 // escape_default turns this into '\"' which is unnecessary.
748 text.push(t);
749 } else {
750 text.extend(t.escape_default());
751 }
752 text.push('\'');
753 Literal::_new(text)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700754 }
755
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700756 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700757 let mut escaped = "b\"".to_string();
758 for b in bytes {
759 match *b {
760 b'\0' => escaped.push_str(r"\0"),
761 b'\t' => escaped.push_str(r"\t"),
762 b'\n' => escaped.push_str(r"\n"),
763 b'\r' => escaped.push_str(r"\r"),
764 b'"' => escaped.push_str("\\\""),
765 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200766 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700767 _ => escaped.push_str(&format!("\\x{:02X}", b)),
768 }
769 }
770 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700771 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700772 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700773
Alex Crichtonb2c94622018-04-04 07:36:41 -0700774 pub fn span(&self) -> Span {
775 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700776 }
777
Alex Crichtonb2c94622018-04-04 07:36:41 -0700778 pub fn set_span(&mut self, span: Span) {
779 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700780 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700781}
782
Alex Crichton44bffbc2017-05-19 17:51:59 -0700783impl fmt::Display for Literal {
784 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700785 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700786 }
787}
788
David Tolnay034205f2018-04-22 16:45:28 -0700789impl fmt::Debug for Literal {
790 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
791 let mut debug = fmt.debug_struct("Literal");
792 debug.field("lit", &format_args!("{}", self.text));
793 #[cfg(procmacro2_semver_exempt)]
794 debug.field("span", &self.span);
795 debug.finish()
796 }
797}
798
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700799fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700800 let mut trees = Vec::new();
801 loop {
802 let input_no_ws = skip_whitespace(input);
803 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700804 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700805 }
806 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
807 input = a;
808 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700809 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700810 }
811
812 let (a, tt) = match token_tree(input_no_ws) {
813 Ok(p) => p,
814 Err(_) => break,
815 };
816 trees.push(tt);
817 input = a;
818 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700819 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700820}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700821
David Tolnay3b1f7d22019-01-28 12:22:11 -0800822#[cfg(not(span_locations))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700823fn spanned<'a, T>(
824 input: Cursor<'a>,
825 f: fn(Cursor<'a>) -> PResult<'a, T>,
826) -> PResult<'a, (T, ::Span)> {
827 let (a, b) = f(skip_whitespace(input))?;
David Tolnay3b1f7d22019-01-28 12:22:11 -0800828 Ok((a, ((b, ::Span::_new_stable(Span::call_site())))))
David Tolnayddfca052017-12-31 10:41:24 -0500829}
830
David Tolnay3b1f7d22019-01-28 12:22:11 -0800831#[cfg(span_locations)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700832fn spanned<'a, T>(
833 input: Cursor<'a>,
834 f: fn(Cursor<'a>) -> PResult<'a, T>,
835) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500836 let input = skip_whitespace(input);
837 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700838 let (a, b) = f(input)?;
839 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700840 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700841 Ok((a, (b, span)))
842}
843
844fn token_tree(input: Cursor) -> PResult<TokenTree> {
845 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
846 tt.set_span(span);
847 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500848}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700849
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700850named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700851 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700852 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700853 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700854 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700855 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700856 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700857 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700858));
859
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700860named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700861 delimited!(
862 punct!("("),
863 token_stream,
864 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700865 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700866 |
867 delimited!(
868 punct!("["),
869 token_stream,
870 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700871 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700872 |
873 delimited!(
874 punct!("{"),
875 token_stream,
876 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700877 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700878));
879
Alex Crichtonf3888432018-05-16 09:11:05 -0700880fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
881 symbol(skip_whitespace(input))
882}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700883
Alex Crichtonf3888432018-05-16 09:11:05 -0700884fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700885 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700886
Alex Crichtonf3888432018-05-16 09:11:05 -0700887 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200888 if raw {
889 chars.next();
890 chars.next();
891 }
892
Alex Crichton44bffbc2017-05-19 17:51:59 -0700893 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000894 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700895 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700896 }
897
David Tolnay214c94c2017-06-01 12:42:56 -0700898 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700899 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000900 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700901 end = i;
902 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700903 }
904 }
905
David Tolnaya13d1422018-03-31 21:27:48 +0200906 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700907 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700908 Err(LexError)
909 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700910 let ident = if raw {
911 ::Ident::_new_raw(&a[2..], ::Span::call_site())
912 } else {
913 ::Ident::new(a, ::Span::call_site())
914 };
915 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700916 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700917}
918
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700919fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700920 let input_no_ws = skip_whitespace(input);
921
922 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700923 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700924 let start = input.len() - input_no_ws.len();
925 let len = input_no_ws.len() - a.len();
926 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700927 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700928 }
David Tolnay1218e122017-06-01 11:13:45 -0700929 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700930 }
931}
932
933named!(literal_nocapture -> (), alt!(
934 string
935 |
936 byte_string
937 |
938 byte
939 |
940 character
941 |
942 float
943 |
944 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700945));
946
947named!(string -> (), alt!(
948 quoted_string
949 |
950 preceded!(
951 punct!("r"),
952 raw_string
953 ) => { |_| () }
954));
955
956named!(quoted_string -> (), delimited!(
957 punct!("\""),
958 cooked_string,
959 tag!("\"")
960));
961
Nika Layzellf8d5f212017-12-11 14:07:02 -0500962fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700963 let mut chars = input.char_indices().peekable();
964 while let Some((byte_offset, ch)) = chars.next() {
965 match ch {
966 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500967 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700968 }
969 '\r' => {
970 if let Some((_, '\n')) = chars.next() {
971 // ...
972 } else {
973 break;
974 }
975 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200976 '\\' => match chars.next() {
977 Some((_, 'x')) => {
978 if !backslash_x_char(&mut chars) {
979 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700980 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700981 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200982 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
983 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
984 Some((_, 'u')) => {
985 if !backslash_u(&mut chars) {
986 break;
987 }
988 }
989 Some((_, '\n')) | Some((_, '\r')) => {
990 while let Some(&(_, ch)) = chars.peek() {
991 if ch.is_whitespace() {
992 chars.next();
993 } else {
994 break;
995 }
996 }
997 }
998 _ => break,
999 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001000 _ch => {}
1001 }
1002 }
David Tolnay1218e122017-06-01 11:13:45 -07001003 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001004}
1005
1006named!(byte_string -> (), alt!(
1007 delimited!(
1008 punct!("b\""),
1009 cooked_byte_string,
1010 tag!("\"")
1011 ) => { |_| () }
1012 |
1013 preceded!(
1014 punct!("br"),
1015 raw_string
1016 ) => { |_| () }
1017));
1018
Nika Layzellf8d5f212017-12-11 14:07:02 -05001019fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001020 let mut bytes = input.bytes().enumerate();
1021 'outer: while let Some((offset, b)) = bytes.next() {
1022 match b {
1023 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001024 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001025 }
1026 b'\r' => {
1027 if let Some((_, b'\n')) = bytes.next() {
1028 // ...
1029 } else {
1030 break;
1031 }
1032 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001033 b'\\' => match bytes.next() {
1034 Some((_, b'x')) => {
1035 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001036 break;
1037 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001038 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001039 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1040 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1041 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1042 let rest = input.advance(newline + 1);
1043 for (offset, ch) in rest.char_indices() {
1044 if !ch.is_whitespace() {
1045 input = rest.advance(offset);
1046 bytes = input.bytes().enumerate();
1047 continue 'outer;
1048 }
1049 }
1050 break;
1051 }
1052 _ => break,
1053 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001054 b if b < 0x80 => {}
1055 _ => break,
1056 }
1057 }
David Tolnay1218e122017-06-01 11:13:45 -07001058 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001059}
1060
Nika Layzellf8d5f212017-12-11 14:07:02 -05001061fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001062 let mut chars = input.char_indices();
1063 let mut n = 0;
1064 while let Some((byte_offset, ch)) = chars.next() {
1065 match ch {
1066 '"' => {
1067 n = byte_offset;
1068 break;
1069 }
1070 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001071 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001072 }
1073 }
1074 for (byte_offset, ch) in chars {
1075 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001076 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1077 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001078 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001079 }
1080 '\r' => {}
1081 _ => {}
1082 }
1083 }
David Tolnay1218e122017-06-01 11:13:45 -07001084 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001085}
1086
1087named!(byte -> (), do_parse!(
1088 punct!("b") >>
1089 tag!("'") >>
1090 cooked_byte >>
1091 tag!("'") >>
1092 (())
1093));
1094
Nika Layzellf8d5f212017-12-11 14:07:02 -05001095fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001096 let mut bytes = input.bytes().enumerate();
1097 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001098 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1099 Some(b'x') => backslash_x_byte(&mut bytes),
1100 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1101 | Some(b'"') => true,
1102 _ => false,
1103 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001104 b => b.is_some(),
1105 };
1106 if ok {
1107 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001108 Some((offset, _)) => {
1109 if input.chars().as_str().is_char_boundary(offset) {
1110 Ok((input.advance(offset), ()))
1111 } else {
1112 Err(LexError)
1113 }
1114 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001115 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001116 }
1117 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001118 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001119 }
1120}
1121
1122named!(character -> (), do_parse!(
1123 punct!("'") >>
1124 cooked_char >>
1125 tag!("'") >>
1126 (())
1127));
1128
Nika Layzellf8d5f212017-12-11 14:07:02 -05001129fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001130 let mut chars = input.char_indices();
1131 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001132 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1133 Some('x') => backslash_x_char(&mut chars),
1134 Some('u') => backslash_u(&mut chars),
1135 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1136 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001137 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001138 _ => false,
1139 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001140 ch => ch.is_some(),
1141 };
1142 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001143 match chars.next() {
1144 Some((idx, _)) => Ok((input.advance(idx), ())),
1145 None => Ok((input.advance(input.len()), ())),
1146 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001147 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001148 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001149 }
1150}
1151
1152macro_rules! next_ch {
1153 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1154 match $chars.next() {
1155 Some((_, ch)) => match ch {
1156 $pat $(| $rest)* => ch,
1157 _ => return false,
1158 },
1159 None => return false
1160 }
1161 };
1162}
1163
1164fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001165where
1166 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001167{
1168 next_ch!(chars @ '0'...'7');
1169 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1170 true
1171}
1172
1173fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001174where
1175 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001176{
1177 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1178 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1179 true
1180}
1181
1182fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001183where
1184 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001185{
1186 next_ch!(chars @ '{');
1187 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001188 loop {
1189 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1190 if c == '}' {
1191 return true;
1192 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001193 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001194}
1195
Nika Layzellf8d5f212017-12-11 14:07:02 -05001196fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001197 let (rest, ()) = float_digits(input)?;
1198 for suffix in &["f32", "f64"] {
1199 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001200 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001201 }
1202 }
1203 word_break(rest)
1204}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001205
Nika Layzellf8d5f212017-12-11 14:07:02 -05001206fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001207 let mut chars = input.chars().peekable();
1208 match chars.next() {
1209 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001210 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001211 }
1212
1213 let mut len = 1;
1214 let mut has_dot = false;
1215 let mut has_exp = false;
1216 while let Some(&ch) = chars.peek() {
1217 match ch {
1218 '0'...'9' | '_' => {
1219 chars.next();
1220 len += 1;
1221 }
1222 '.' => {
1223 if has_dot {
1224 break;
1225 }
1226 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001227 if chars
1228 .peek()
1229 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1230 .unwrap_or(false)
1231 {
David Tolnay1218e122017-06-01 11:13:45 -07001232 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001233 }
1234 len += 1;
1235 has_dot = true;
1236 }
1237 'e' | 'E' => {
1238 chars.next();
1239 len += 1;
1240 has_exp = true;
1241 break;
1242 }
1243 _ => break,
1244 }
1245 }
1246
Nika Layzellf8d5f212017-12-11 14:07:02 -05001247 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001248 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001249 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001250 }
1251
1252 if has_exp {
1253 let mut has_exp_value = false;
1254 while let Some(&ch) = chars.peek() {
1255 match ch {
1256 '+' | '-' => {
1257 if has_exp_value {
1258 break;
1259 }
1260 chars.next();
1261 len += 1;
1262 }
1263 '0'...'9' => {
1264 chars.next();
1265 len += 1;
1266 has_exp_value = true;
1267 }
1268 '_' => {
1269 chars.next();
1270 len += 1;
1271 }
1272 _ => break,
1273 }
1274 }
1275 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001276 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001277 }
1278 }
1279
Nika Layzellf8d5f212017-12-11 14:07:02 -05001280 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001281}
1282
Nika Layzellf8d5f212017-12-11 14:07:02 -05001283fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001284 let (rest, ()) = digits(input)?;
1285 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001286 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001287 ] {
1288 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001289 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001290 }
1291 }
1292 word_break(rest)
1293}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001294
Nika Layzellf8d5f212017-12-11 14:07:02 -05001295fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001296 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001297 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001298 16
1299 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001300 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001301 8
1302 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001303 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001304 2
1305 } else {
1306 10
1307 };
1308
Alex Crichton44bffbc2017-05-19 17:51:59 -07001309 let mut len = 0;
1310 let mut empty = true;
1311 for b in input.bytes() {
1312 let digit = match b {
1313 b'0'...b'9' => (b - b'0') as u64,
1314 b'a'...b'f' => 10 + (b - b'a') as u64,
1315 b'A'...b'F' => 10 + (b - b'A') as u64,
1316 b'_' => {
1317 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001318 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001319 }
1320 len += 1;
1321 continue;
1322 }
1323 _ => break,
1324 };
1325 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001326 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001327 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001328 len += 1;
1329 empty = false;
1330 }
1331 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001332 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001333 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001334 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001335 }
1336}
1337
Alex Crichtonf3888432018-05-16 09:11:05 -07001338fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001339 let input = skip_whitespace(input);
1340 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001341 Ok((rest, '\'')) => {
1342 symbol(rest)?;
1343 Ok((rest, Punct::new('\'', Spacing::Joint)))
1344 }
David Tolnay1218e122017-06-01 11:13:45 -07001345 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001346 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001347 Ok(_) => Spacing::Joint,
1348 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001349 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001350 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001351 }
David Tolnay1218e122017-06-01 11:13:45 -07001352 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001353 }
1354}
1355
Nika Layzellf8d5f212017-12-11 14:07:02 -05001356fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001357 if input.starts_with("//") || input.starts_with("/*") {
1358 // Do not accept `/` of a comment as an op.
1359 return Err(LexError);
1360 }
1361
David Tolnayea75c5f2017-05-31 23:40:33 -07001362 let mut chars = input.chars();
1363 let first = match chars.next() {
1364 Some(ch) => ch,
1365 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001366 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001367 }
1368 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001369 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001370 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001371 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001372 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001373 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001374 }
1375}
1376
Alex Crichton1eb96a02018-04-04 13:07:35 -07001377fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1378 let mut trees = Vec::new();
1379 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001380 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001381 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001382 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001383 }
1384 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001385 TokenTree::Ident(::Ident::new("doc", span)),
1386 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001387 TokenTree::Literal(::Literal::string(comment)),
1388 ];
1389 for tt in stream.iter_mut() {
1390 tt.set_span(span);
1391 }
David Tolnayf14813f2018-09-08 17:14:07 -07001392 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1393 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001394 for tt in trees.iter_mut() {
1395 tt.set_span(span);
1396 }
1397 Ok((rest, trees))
1398}
1399
1400named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001401 do_parse!(
1402 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001403 s: take_until_newline_or_eof!() >>
1404 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001405 )
1406 |
1407 do_parse!(
1408 option!(whitespace) >>
1409 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001410 s: block_comment >>
1411 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001412 )
1413 |
1414 do_parse!(
1415 punct!("///") >>
1416 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001417 s: take_until_newline_or_eof!() >>
1418 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001419 )
1420 |
1421 do_parse!(
1422 option!(whitespace) >>
1423 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001424 s: block_comment >>
1425 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001426 )
1427));