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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! TCL List Parsing and Formatting

use crate::molt_err;
use crate::tokenizer::Tokenizer;
use crate::types::*;
use crate::value::Value;

//--------------------------------------------------------------------------
// List Parsing

/// Parses a list-formatted string into a vector, throwing
/// a Molt error if the list cannot be parsed as a list.
pub(crate) fn get_list(str: &str) -> Result<MoltList, ResultCode> {
    let mut ctx = Tokenizer::new(str);

    parse_list(&mut ctx)
}

// Is the character a valid whitespace character in list syntax?
fn is_list_white(ch: char) -> bool {
    match ch {
        ' ' => true,
        '\n' => true,
        '\r' => true,
        '\t' => true,
        '\x0B' => true, // Vertical Tab
        '\x0C' => true, // Form Feed
        _ => false,
    }
}

fn parse_list(ctx: &mut Tokenizer) -> Result<MoltList, ResultCode> {
    // FIRST, skip any list whitespace.
    ctx.skip_while(|ch| is_list_white(*ch));

    // Read words until we get to the end of the input or hit an error
    let mut items = Vec::new();
    while !ctx.at_end() {
        // FIRST, get the next item; there has to be one.
        // Throw an error if there's a formatting problem.
        items.push(parse_item(ctx)?);

        // NEXT, skip whitespace to the end or the next item.
        ctx.skip_while(|ch| is_list_white(*ch));
    }

    // NEXT, return the items.
    Ok(items)
}

/// We're at the beginning of an item in the list.
/// It's either a bare word, a braced string, or a quoted string--or there's
/// an error in the input.  Whichever it is, get it.
fn parse_item(ctx: &mut Tokenizer) -> MoltResult {
    if ctx.is('{') {
        Ok(parse_braced_item(ctx)?)
    } else if ctx.is('"') {
        Ok(parse_quoted_item(ctx)?)
    } else {
        Ok(parse_bare_item(ctx)?)
    }
}

/// Parse a braced item.  We need to count braces, so that they balance; and
/// we need to handle backslashes in the input, so that quoted braces don't count.
fn parse_braced_item(ctx: &mut Tokenizer) -> MoltResult {
    // FIRST, we have to count braces.  Skip the first one, and count it.
    // Also, mark the following character, as we'll be accumulating a
    // token.
    ctx.next();
    let mut count = 1;

    // NEXT, mark the start of the token, and skip characters until we find the end.
    let mark = ctx.mark();
    while let Some(c) = ctx.peek() {
        if c == '\\' {
            // Backslash handling. Retain backslashes as is.
            // Note: this means that escaped '{' and '}' characters
            // don't affect the count.
            ctx.skip();
            ctx.skip();
        } else if c == '{' {
            count += 1;
            ctx.skip();
        } else if c == '}' {
            count -= 1;

            if count > 0 {
                ctx.skip();
            } else {
                // We've found and consumed the closing brace.  We should either
                // see more more whitespace, or we should be at the end of the list
                // Otherwise, there are incorrect characters following the close-brace.
                let result = Ok(Value::from(ctx.token(mark)));
                ctx.skip(); // Skip the closing brace

                if ctx.at_end() || ctx.has(|ch| is_list_white(*ch)) {
                    return result;
                } else {
                    return molt_err!("extra characters after close-brace");
                }
            }
        } else {
            ctx.skip();
        }
    }

    assert!(count > 0);
    molt_err!("unmatched open brace in list")
}

/// Parse a quoted item.  Does backslash substitution.
fn parse_quoted_item(ctx: &mut Tokenizer) -> MoltResult {
    // FIRST, consume the the opening quote.
    ctx.skip();

    let mut item = String::new();
    let mut start = ctx.mark();

    while !ctx.at_end() {
        ctx.skip_while(|ch| *ch != '"' && *ch != '\\');
        item.push_str(ctx.token(start));

        match ctx.peek() {
            Some('"') => {
                ctx.skip();
                return Ok(Value::from(item));
            }
            Some('\\') => {
                item.push(ctx.backslash_subst());
                start = ctx.mark();
            }
            _ => unreachable!(),
        }
    }

    molt_err!("unmatched open quote in list")
}

/// Parse a bare item.
fn parse_bare_item(ctx: &mut Tokenizer) -> MoltResult {
    let mut item = String::new();
    let mut start = ctx.mark();

    while !ctx.at_end() {
        // Note: the while condition ensures that there's a character.
        ctx.skip_while(|ch| !is_list_white(*ch) && *ch != '\\');

        item.push_str(ctx.token(start));
        start = ctx.mark();

        if ctx.has(|ch| is_list_white(*ch)) {
            break;
        }

        if ctx.is('\\') {
            item.push(ctx.backslash_subst());
            start = ctx.mark();
        }
    }

    Ok(Value::from(item))
}

//--------------------------------------------------------------------------
// List Formatting

/// Converts a list, represented as a vector of `Value`s, into a string, doing
/// all necessary quoting and escaping.
pub fn list_to_string(list: &[Value]) -> String {
    let mut vec: Vec<String> = Vec::new();

    let mut hash = !list.is_empty() && list[0].as_str().starts_with('#');

    for item in list {
        let item = item.to_string();
        match get_mode(&item) {
            Mode::AsIs => {
                if hash {
                    vec.push(brace_item(&item));
                    hash = false;
                } else {
                    vec.push(item)
                }
            }
            Mode::Brace => {
                vec.push(brace_item(&item));
            }
            Mode::Escape => {
                vec.push(escape_item(hash, &item));
                hash = false;
            }
        }
    }

    vec.join(" ")
}

fn brace_item(item: &str) -> String {
    let mut word = String::new();
    word.push('{');
    word.push_str(item);
    word.push('}');
    word
}

fn escape_item(hash: bool, item: &str) -> String {
    let mut word = String::new();

    // If hash, the first character is a "#" that must be escaped.
    // Just push the backslash on the front.
    if hash {
        word.push('\\');
    }

    for ch in item.chars() {
        if ch.is_whitespace() {
            word.push('\\');
            word.push(ch);
            continue;
        }

        match ch {
            '{' | ';' | '$' | '[' | ']' | '\\' => {
                word.push('\\');
                word.push(ch);
            }
            _ => word.push(ch),
        }
    }

    word
}

#[derive(Eq, PartialEq, Debug)]
enum Mode {
    AsIs,
    Brace,
    Escape,
}

fn get_mode(word: &str) -> Mode {
    // FIRST, if it's the empty string, just brace it.
    if word.is_empty() {
        return Mode::Brace;
    }

    // NEXT, inspect the content.
    let mut mode = Mode::AsIs;
    let mut brace_count = 0;

    let mut iter = word.chars().peekable();

    while let Some(ch) = iter.next() {
        if ch.is_whitespace() {
            mode = Mode::Brace;
            continue;
        }
        match ch {
            ';' | '$' | '[' | ']' => {
                mode = Mode::Brace;
            }
            '{' => brace_count += 1,
            '}' => brace_count -= 1,
            '\\' => {
                if iter.peek() == Some(&'\n') {
                    return Mode::Escape;
                } else {
                    mode = Mode::Brace;
                }
            }
            _ => (),
        }
    }

    if brace_count != 0 {
        Mode::Escape
    } else {
        mode
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_list_to_string() {
        assert_eq!(list_to_string(&[Value::from("a")]), "a");
        assert_eq!(list_to_string(&[Value::from("a"), Value::from("b")]), "a b");
        assert_eq!(
            list_to_string(&[Value::from("a"), Value::from("b"), Value::from("c")]),
            "a b c"
        );
        assert_eq!(
            list_to_string(&[Value::from("a"), Value::from(" "), Value::from("c")]),
            "a { } c"
        );
        assert_eq!(
            list_to_string(&[Value::from("a"), Value::from(""), Value::from("c")]),
            "a {} c"
        );
        assert_eq!(list_to_string(&[Value::from("a;b")]), "{a;b}");
        assert_eq!(list_to_string(&[Value::from("a$b")]), "{a$b}");
        assert_eq!(list_to_string(&[Value::from("a[b")]), "{a[b}");
        assert_eq!(list_to_string(&[Value::from("a]b")]), "{a]b}");
        assert_eq!(list_to_string(&[Value::from("a\\nb")]), "{a\\nb}");
        assert_eq!(
            list_to_string(&[Value::from("{ "), Value::from("abc")]),
            r#"\{\  abc"#
        );
    }

    #[test]
    fn test_parse_braced_item() {
        assert_eq!(pbi("{}"), "|".to_string());
        assert_eq!(pbi("{abc}"), "abc|".to_string());
        assert_eq!(pbi("{abc}  "), "abc|  ".to_string());
        assert_eq!(pbi("{a{b}c}"), "a{b}c|".to_string());
        assert_eq!(pbi("{a{b}{c}}"), "a{b}{c}|".to_string());
        assert_eq!(pbi("{a{b}{c}d}"), "a{b}{c}d|".to_string());
        assert_eq!(pbi("{a{b}{c}d} efg"), "a{b}{c}d| efg".to_string());
        assert_eq!(pbi("{a\\{bc}"), "a\\{bc|".to_string());
    }

    fn pbi(input: &str) -> String {
        let mut ctx = Tokenizer::new(input);
        if let Ok(val) = parse_braced_item(&mut ctx) {
            format!("{}|{}", val.as_str(), ctx.as_str())
        } else {
            String::from("Err")
        }
    }

    #[test]
    fn test_parse_quoted_item() {
        assert_eq!(pqi("\"abc\""), "abc|".to_string());
        assert_eq!(pqi("\"abc\"  "), "abc|  ".to_string());
        assert_eq!(pqi("\"a\\x77-\""), "aw-|".to_string());
    }

    fn pqi(input: &str) -> String {
        let mut ctx = Tokenizer::new(input);
        if let Ok(val) = parse_quoted_item(&mut ctx) {
            format!("{}|{}", val.as_str(), ctx.as_str())
        } else {
            String::from("Err")
        }
    }

    #[test]
    fn test_parse_bare_item() {
        println!("test_parse_bare_item");
        assert_eq!(pbare("abc"), "abc|".to_string());
        assert_eq!(pbare("abc def"), "abc| def".to_string());
        assert_eq!(pbare("abc\ndef"), "abc|\ndef".to_string());
        assert_eq!(pbare("abc\rdef"), "abc|\rdef".to_string());
        assert_eq!(pbare("abc\tdef"), "abc|\tdef".to_string());
        assert_eq!(pbare("abc\x0Bdef"), "abc|\x0Bdef".to_string());
        assert_eq!(pbare("abc\x0Cdef"), "abc|\x0Cdef".to_string());
        assert_eq!(pbare("a\\x77-"), "aw-|".to_string());
        assert_eq!(pbare("a\\x77- def"), "aw-| def".to_string());
        assert_eq!(pbare("a\\x77"), "aw|".to_string());
        assert_eq!(pbare("a\\x77 "), "aw| ".to_string());
    }

    fn pbare(input: &str) -> String {
        let mut ctx = Tokenizer::new(input);
        if let Ok(val) = parse_bare_item(&mut ctx) {
            format!("{}|{}", val.as_str(), ctx.as_str())
        } else {
            String::from("Err")
        }
    }

    // Most list parsing is tested in the Molt test suite.

    #[test]
    fn test_issue_43() {
        let list = get_list("a ;b c").unwrap();

        // If the list breaks on the semi-colon, the bug still exists.
        assert_eq!(list.len(), 3);
    }
}