blob: 2e67d82c1781d82a44a574e7b58769c733be3d71 [file] [log] [blame]
David Tolnayf4bbbd92016-09-23 14:41:55 -07001/// Literal kind.
2///
3/// E.g. `"foo"`, `42`, `12.34` or `bool`
4#[derive(Debug, Clone, Eq, PartialEq)]
5pub enum Lit {
6 /// A string literal (`"foo"`)
7 Str(String, StrStyle),
8 /// A byte string (`b"foo"`)
9 ByteStr(Vec<u8>),
10 /// A byte char (`b'f'`)
11 Byte(u8),
12 /// A character literal (`'a'`)
13 Char(char),
14 /// An integer literal (`1`)
15 Int(u64, IntTy),
16 /// A float literal (`1f64` or `1E10f64` or `1.0E10`)
17 Float(String, FloatTy),
18 /// A boolean literal
19 Bool(bool),
20}
21
22#[derive(Debug, Copy, Clone, Eq, PartialEq)]
23pub enum StrStyle {
24 /// A regular string, like `"foo"`
25 Cooked,
26 /// A raw string, like `r##"foo"##`
27 ///
28 /// The uint is the number of `#` symbols used
29 Raw(usize)
30}
31
32#[derive(Debug, Copy, Clone, Eq, PartialEq)]
33pub enum IntTy {
34 Isize,
35 I8,
36 I16,
37 I32,
38 I64,
39 Usize,
40 U8,
41 U16,
42 U32,
43 U64,
44 Unsuffixed
45}
46
47#[derive(Debug, Copy, Clone, Eq, PartialEq)]
48pub enum FloatTy {
49 F32,
50 F64,
51 Unsuffixed,
52}
53
54#[cfg(feature = "parsing")]
55pub mod parsing {
56 use super::*;
David Tolnay210884d2016-10-01 08:18:42 -070057 use escape::{cooked_string, raw_string};
David Tolnay14cbdeb2016-10-01 12:13:59 -070058 use space::whitespace;
David Tolnayde206222016-09-30 11:47:01 -070059 use nom::IResult;
David Tolnayf4bbbd92016-09-23 14:41:55 -070060
61 named!(pub lit -> Lit, alt!(
David Tolnay210884d2016-10-01 08:18:42 -070062 string
David Tolnay56d62132016-10-01 16:14:54 -070063 |
64 byte_string
David Tolnay7de67d22016-09-24 07:23:32 -070065 // TODO: Byte
66 // TODO: Char
David Tolnayf4bbbd92016-09-23 14:41:55 -070067 |
68 int => { |(value, ty)| Lit::Int(value, ty) }
David Tolnay7de67d22016-09-24 07:23:32 -070069 // TODO: Float
David Tolnay759d2ff2016-10-01 16:18:15 -070070 |
71 keyword!("true") => { |_| Lit::Bool(true) }
72 |
73 keyword!("false") => { |_| Lit::Bool(false) }
David Tolnayf4bbbd92016-09-23 14:41:55 -070074 ));
75
David Tolnay210884d2016-10-01 08:18:42 -070076 named!(string -> Lit, alt!(
David Tolnay42602292016-10-01 22:25:45 -070077 quoted_string => { |s| Lit::Str(s, StrStyle::Cooked) }
David Tolnay210884d2016-10-01 08:18:42 -070078 |
79 preceded!(
80 punct!("r"),
81 raw_string
82 ) => { |(s, n)| Lit::Str(s, StrStyle::Raw(n)) }
David Tolnayf4bbbd92016-09-23 14:41:55 -070083 ));
84
David Tolnay42602292016-10-01 22:25:45 -070085 named!(pub quoted_string -> String, delimited!(
86 punct!("\""),
87 cooked_string,
88 tag!("\"")
89 ));
90
David Tolnay56d62132016-10-01 16:14:54 -070091 named!(byte_string -> Lit, alt!(
92 delimited!(
93 punct!("b\""),
94 cooked_string,
95 tag!("\"")
96 ) => { |s: String| Lit::ByteStr(s.into_bytes()) }
97 |
98 preceded!(
99 punct!("br"),
100 raw_string
101 ) => { |(s, _): (String, _)| Lit::ByteStr(s.into_bytes()) }
102 ));
103
David Tolnayde206222016-09-30 11:47:01 -0700104 named!(pub int -> (u64, IntTy), tuple!(
David Tolnay14cbdeb2016-10-01 12:13:59 -0700105 preceded!(
106 option!(whitespace),
107 digits
108 ),
David Tolnayde206222016-09-30 11:47:01 -0700109 alt!(
110 tag!("isize") => { |_| IntTy::Isize }
111 |
112 tag!("i8") => { |_| IntTy::I8 }
113 |
114 tag!("i16") => { |_| IntTy::I16 }
115 |
116 tag!("i32") => { |_| IntTy::I32 }
117 |
118 tag!("i64") => { |_| IntTy::I64 }
119 |
120 tag!("usize") => { |_| IntTy::Usize }
121 |
122 tag!("u8") => { |_| IntTy::U8 }
123 |
124 tag!("u16") => { |_| IntTy::U16 }
125 |
126 tag!("u32") => { |_| IntTy::U32 }
127 |
128 tag!("u64") => { |_| IntTy::U64 }
129 |
130 epsilon!() => { |_| IntTy::Unsuffixed }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700131 )
132 ));
133
David Tolnayde206222016-09-30 11:47:01 -0700134 pub fn digits(input: &str) -> IResult<&str, u64> {
David Tolnayf4bbbd92016-09-23 14:41:55 -0700135 let mut value = 0u64;
136 let mut len = 0;
137 let mut bytes = input.bytes().peekable();
138 while let Some(&b) = bytes.peek() {
139 match b {
140 b'0' ... b'9' => {
141 value = match value.checked_mul(10) {
142 Some(value) => value,
143 None => return IResult::Error,
144 };
145 value = match value.checked_add((b - b'0') as u64) {
146 Some(value) => value,
147 None => return IResult::Error,
148 };
149 bytes.next();
150 len += 1;
151 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700152 _ => break,
David Tolnayf4bbbd92016-09-23 14:41:55 -0700153 }
154 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700155 if len > 0 {
156 IResult::Done(&input[len..], value)
157 } else {
158 IResult::Error
159 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700160 }
161}
162
163#[cfg(feature = "printing")]
164mod printing {
165 use super::*;
166 use quote::{Tokens, ToTokens};
David Tolnay56d62132016-10-01 16:14:54 -0700167 use std::{ascii, iter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700168 use std::fmt::{self, Display};
169
170 impl ToTokens for Lit {
171 fn to_tokens(&self, tokens: &mut Tokens) {
172 match *self {
173 Lit::Str(ref s, StrStyle::Cooked) => s.to_tokens(tokens),
David Tolnay627e3d52016-10-01 08:27:31 -0700174 Lit::Str(ref s, StrStyle::Raw(n)) => {
David Tolnay56d62132016-10-01 16:14:54 -0700175 tokens.append(&format!("r{delim}\"{string}\"{delim}",
176 delim = iter::repeat("#").take(n).collect::<String>(),
177 string = s));
178 }
179 Lit::ByteStr(ref v) => {
180 let mut escaped = "b\"".to_string();
181 for &ch in v.iter() {
182 escaped.extend(ascii::escape_default(ch).map(|c| c as char));
David Tolnay627e3d52016-10-01 08:27:31 -0700183 }
David Tolnay56d62132016-10-01 16:14:54 -0700184 escaped.push('"');
185 tokens.append(&escaped);
David Tolnay627e3d52016-10-01 08:27:31 -0700186 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700187 Lit::Int(value, ty) => tokens.append(&format!("{}{}", value, ty)),
David Tolnay759d2ff2016-10-01 16:18:15 -0700188 Lit::Bool(true) => tokens.append("true"),
189 Lit::Bool(false) => tokens.append("false"),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700190 _ => unimplemented!(),
191 }
192 }
193 }
194
195 impl Display for IntTy {
196 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
197 match *self {
198 IntTy::Isize => formatter.write_str("isize"),
199 IntTy::I8 => formatter.write_str("i8"),
200 IntTy::I16 => formatter.write_str("i16"),
201 IntTy::I32 => formatter.write_str("i32"),
202 IntTy::I64 => formatter.write_str("i64"),
203 IntTy::Usize => formatter.write_str("usize"),
204 IntTy::U8 => formatter.write_str("u8"),
205 IntTy::U16 => formatter.write_str("u16"),
206 IntTy::U32 => formatter.write_str("u32"),
207 IntTy::U64 => formatter.write_str("u64"),
208 IntTy::Unsuffixed => Ok(()),
209 }
210 }
211 }
212}