1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
use std::mem;
use std::str::FromStr;

use combine::easy::Error;
use combine::error::StreamError;

use format::{Displayable, Formatter};
use position::Pos;
use tokenizer::Token;

/// Generic string value
///
/// It may consist of strings and variable references
///
/// Some string parts might originally be escaped or quoted. We get rid of
/// quotes when parsing
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Value {
    position: Pos,
    pub(crate) data: Vec<Item>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Item {
    Literal(String),
    Variable(String),
}


impl Value {
    pub(crate) fn parse<'a>(position: Pos, tok: Token<'a>)
        -> Result<Value, Error<Token<'a>, Token<'a>>>
    {
        Value::parse_str(position, tok.value)
    }
    pub(crate) fn parse_str<'a>(position: Pos, token: &str)
        -> Result<Value, Error<Token<'a>, Token<'a>>>
    {
        let data = if token.starts_with('"') {
            Value::scan_quoted('"', token)?
        } else if token.starts_with("'") {
            Value::scan_quoted('\'', token)?
        } else {
            Value::scan_raw(token)?
        };
        Ok(Value { position, data })
    }

    fn scan_raw<'a>(value: &str)
        -> Result<Vec<Item>, Error<Token<'a>, Token<'a>>>
    {
        use self::Item::*;
        let mut buf = Vec::new();
        let mut chiter = value.char_indices().peekable();
        let mut prev_char = ' ';  // any having no special meaning
        let mut cur_slice = 0;
        // TODO(unquote) single and double quotes
        while let Some((idx, cur_char)) = chiter.next() {
            match cur_char {
                _ if prev_char == '\\' => {
                    prev_char = ' ';
                    continue;
                }
                '$' => {
                    let vstart = idx + 1;
                    if idx != cur_slice {
                        buf.push(Literal(value[cur_slice..idx].to_string()));
                    }
                    let fchar = chiter.next().map(|(_, c)| c)
                        .ok_or_else(|| Error::unexpected_message(
                            "bare $ in expression"))?;
                    match fchar {
                        '{' => {
                            while let Some(&(_, c)) = chiter.peek() {
                                match c {
                                    'a'...'z' | 'A'...'Z' | '_' | '0'...'9'
                                    => chiter.next(),
                                    '}' => break,
                                    _ => {
                                        return Err(Error::expected("}".into()));
                                    }
                                };
                            }
                            let now = chiter.peek().map(|&(idx, _)| idx)
                                .unwrap();
                            buf.push(Variable(
                                value[vstart+1..now].to_string()));
                            cur_slice = now+1;
                        }
                        'a'...'z' | 'A'...'Z' | '_' | '0'...'9' => {
                            while let Some(&(_, c)) = chiter.peek() {
                                match c {
                                    'a'...'z' | 'A'...'Z' | '_' | '0'...'9'
                                    => chiter.next(),
                                    _ => break,
                                };
                            }
                            let now = chiter.peek().map(|&(idx, _)| idx)
                                .unwrap_or(value.len());
                            buf.push(Variable(
                                value[vstart..now].to_string()));
                            cur_slice = now;
                        }
                        _ => {
                            return Err(Error::unexpected_message(
                                format!("variable name starts with \
                                    bad char {:?}", fchar)));
                        }
                    }
                }
                _ => {}
            }
            prev_char = cur_char;
        }
        if cur_slice != value.len() {
            buf.push(Literal(value[cur_slice..].to_string()));
        }
        Ok(buf)
    }

    fn scan_quoted<'a>(quote: char, value: &str)
        -> Result<Vec<Item>, Error<Token<'a>, Token<'a>>>
    {
        use self::Item::*;
        let mut buf = Vec::new();
        let mut chiter = value.char_indices().peekable();
        chiter.next(); // skip quote
        let mut prev_char = ' ';  // any having no special meaning
        let mut cur_slice = String::new();
        while let Some((idx, cur_char)) = chiter.next() {
            match cur_char {
                _ if prev_char == '\\' => {
                    cur_slice.push(cur_char);
                    continue;
                }
                '"' | '\'' if cur_char == quote => {
                    if cur_slice.len() > 0 {
                        buf.push(Literal(cur_slice));
                    }
                    if idx + 1 != value.len() {
                        // TODO(tailhook) figure out maybe this is actually a
                        // tokenizer error, or maybe make this cryptic message
                        // better
                        return Err(Error::unexpected_message(
                            "quote closes prematurely"));
                    }
                    return Ok(buf);
                }
                '$' => {
                    let vstart = idx + 1;
                    if cur_slice.len() > 0 {
                        buf.push(Literal(
                            mem::replace(&mut cur_slice, String::new())));
                    }
                    let fchar = chiter.next().map(|(_, c)| c)
                        .ok_or_else(|| Error::unexpected_message(
                            "bare $ in expression"))?;
                    match fchar {
                        '{' => {
                            unimplemented!();
                        }
                        'a'...'z' | 'A'...'Z' | '_' | '0'...'9' => {
                            while let Some(&(_, c)) = chiter.peek() {
                                match c {
                                    'a'...'z' | 'A'...'Z' | '_' | '0'...'9'
                                    => chiter.next(),
                                    _ => break,
                                };
                            }
                            let now = chiter.peek().map(|&(idx, _)| idx)
                                .ok_or_else(|| {
                                    Error::unexpected_message("unclosed quote")
                                })?;
                            buf.push(Variable(
                                value[vstart..now].to_string()));
                        }
                        _ => {
                            return Err(Error::unexpected_message(
                                format!("variable name starts with \
                                    bad char {:?}", fchar)));
                        }
                    }
                }
                _ => cur_slice.push(cur_char),
            }
            prev_char = cur_char;
        }
        return Err(Error::unexpected_message("unclosed quote"));
    }
}

impl FromStr for Value {
    type Err = String;
    fn from_str(s: &str) -> Result<Value, String> {
        Value::parse_str(Pos { line: 0, column: 0 }, s)
        .map_err(|e| e.to_string())
    }
}

impl Value {
    fn has_specials(&self) -> bool {
        use self::Item::*;
        for item in &self.data {
            match *item {
                Literal(ref x) => {
                    for c in x.chars() {
                        match c {
                            ' ' | ';' | '\r' | '\n' | '\t' | '{' | '}' => {
                                return true;
                            }
                            _ => {}
                        }
                    }
                }
                Variable(_) => {}
            }
        }
        return false;
    }

    /// Replace variable references in this string with literal values
    pub fn replace_vars<'a, F, S>(&mut self, mut f: F)
        where F: FnMut(&str) -> Option<S>,
              S: AsRef<str> + Into<String> + 'a,
    {
        use self::Item::*;
        // TODO(tailhook) join literal blocks
        for item in &mut self.data {
            let new_value = match *item {
                Literal(..) => continue,
                Variable(ref name) => match f(name) {
                    Some(value) => value.into(),
                    None => continue,
                },
            };
            *item = Literal(new_value);
        }
    }
}

fn next_alphanum(data: &Vec<Item>, index: usize) -> bool {
    use self::Item::*;
    data.get(index+1).and_then(|item| {
        match item {
            Literal(s) => Some(s),
            Variable(_) => None,
        }
    }).and_then(|s| {
        s.chars().next().map(|c| c.is_alphanumeric())
    }).unwrap_or(false)
}

impl Displayable for Value {
    fn display(&self, f: &mut Formatter) {
        use self::Item::*;
        if self.data.is_empty() || self.has_specials() {
            f.write("\"");
            for (index, item) in self.data.iter().enumerate() {
                match *item {
                    // TODO(tailhook) escape special chars
                    Literal(ref v) => f.write(v),
                    Variable(ref v) if next_alphanum(&self.data, index) => {
                        f.write("${");
                        f.write(v);
                        f.write("}");
                    }
                    Variable(ref v) => {
                        f.write("$");
                        f.write(v);
                    }
                }
            }
            f.write("\"");
        } else {
            for (index, item) in self.data.iter().enumerate() {
                match *item {
                    Literal(ref v) => f.write(v),
                    Variable(ref v) if next_alphanum(&self.data, index) => {
                        f.write("${");
                        f.write(v);
                        f.write("}");
                    }
                    Variable(ref v) => {
                        f.write("$");
                        f.write(v);
                    }
                }
            }
        }
    }
}