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
//! The OftLisp reader.
//!
//! Note that this is typically known as a parser, but Lisp tradition is to
//! refer to the parser for the language as "the reader", especially when it
//! does not perform advanced processing (e.g. macro expansion) automatically.
//!
//! The grammar of OftLisp is:
//!
//! ```ebnf
//! value = { comment }, byteString
//!       | { comment }, string
//!       | { comment }, symbolish
//!       | { comment }, "(", { value }, ")"
//!       | { comment }, "(", value, { value }, "\u{2022}", value ")"
//!       | { comment }, "[", { value }, "]"
//!       | { comment }, readerMacro, { comment }, value;
//! comment = ";", { ? all characters ? - "\n" }, "\n";
//! byteString = "b", '"', { stringChar }, '"'
//! string = '"', { stringChar }, '"'
//! symbolish = symbolChar, { symbolChar }
//! stringChar = ? all characters ? - ( "\\" | '"' )
//!            | "\\", escape;
//! escape = "a" | "b" | "e" | "n" | "r" | "t" | '"'
//!        | "x", hex, hex
//!        | "u", hex, hex, hex, hex
//!        | "U", hex, hex, hex, hex, hex, hex, hex, hex;
//! hex = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
//!     | "a" | "b" | "c" | "d" | "e" | "f"
//!     | "A" | "B" | "C" | "D" | "E" | "F";
//! symbolChar = ? an ASCII letter ?
//!            | ? an ASCII digit ?
//!            | "+" | "-" | "." | "/" | "$" | "?" | "*" | "#" | "=" | "<"
//!            | ">" | "_";
//! readerMacro = "'" | "`" | ",@" | ",";
//! ```

pub mod lexer;
pub mod symbolish;

use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::fs::File;
use std::io::{Error as IoError, Read};
use std::iter::Peekable;
use std::path::PathBuf;

use either::{Either, Left, Right};
use gc::Gc;

use context::Context;
use reader::lexer::{Lexeme, Lexer, Token};
use reader::symbolish::read_symbolish;
use value::Value;

/// An error that occurs while reading.
#[derive(Clone, Debug, Eq, Finalize, Hash, PartialEq, Trace)]
pub struct ReadError {
    kind: ReadErrorKind,
    location: SourceLocation,
}

impl ReadError {
    /// Returns the [`ReadErrorKind`](enum.ReadErrorKind.html) associated with
    /// the error.
    pub fn kind(&self) -> &ReadErrorKind {
        &self.kind
    }

    /// Returns the [`SourceLocation`](struct.SourceLocation.html) associated with
    /// the error.
    pub fn location(&self) -> &SourceLocation {
        &self.location
    }
}

impl Display for ReadError {
    fn fmt(&self, _fmt: &mut Formatter) -> FmtResult {
        unimplemented!("display ReadError")
    }
}

impl Error for ReadError {
    fn description(&self) -> &str {
        self.kind.description()
    }
}

/// The kind of the error.
///
/// TODO: There should probably be a separate lexer AcceptSet.
#[derive(Clone, Debug, Eq, Finalize, Hash, PartialEq, Trace)]
pub enum ReadErrorKind {
    /// A character was encountered that was not expected. The first value is
    /// the character, the second is a representation of the expected value.
    Char(String, AcceptSet),

    /// An unexpected EOF was encountered.
    EOF(AcceptSet),

    /// A token was encountered that was not expected. The first value is
    /// the token, the second is a representation of the expected value.
    Token(String, AcceptSet),
}

impl ReadErrorKind {
    fn description(&self) -> &'static str {
        match *self {
            ReadErrorKind::Char(..) => "unexpected character",
            ReadErrorKind::EOF(..) => "unexpected EOF",
            ReadErrorKind::Token(..) => "unexpected token",
        }
    }
}

impl Display for ReadErrorKind {
    fn fmt(&self, _fmt: &mut Formatter) -> FmtResult {
        unimplemented!("display ReadErrorKind")
    }
}

/// A set of acceptable characters.
#[derive(Clone, Debug, Eq, Finalize, Hash, PartialEq, Trace)]
pub enum AcceptSet {
    /// A closing bracket.
    CloseBracket,

    /// A closing parenthesis.
    CloseParenthesis,

    /// A dot for a dotted list.
    Dot,

    /// A hexadecimal digit.
    HexChar,

    /// A character in the body of a string.
    StringChar,

    /// A string escape character.
    StringEscape,

    /// A value.
    Value,

    /// The end of the input stream.
    EOF,
}

impl Display for AcceptSet {
    fn fmt(&self, _fmt: &mut Formatter) -> FmtResult {
        unimplemented!("display AcceptSet")
    }
}

/// The location of an error (or of anything else).
#[derive(Clone, Debug, Eq, Finalize, Hash, PartialEq, Trace)]
pub struct SourceLocation {
    /// The start byte of the location.
    pub start: usize,

    /// The ending byte of the location.
    pub end: usize,

    /// The path which the location is associated with.
    pub path: Option<Gc<PathBuf>>,
}

impl Display for SourceLocation {
    fn fmt(&self, _fmt: &mut Formatter) -> FmtResult {
        /*
        fn write_loc(fmt: &mut Formatter, pos: Option<(usize, usize)>, idx: usize) -> FmtResult {
            if let Some((r, c)) = pos {
                write!(fmt, "{}:{}", r, c)
            } else {
                write!(fmt, "<invalid {}>", idx)
            }
        }

        fmt.write_char('[')?;
        if let Some(ref path) = self.path {
            path.display().fmt(fmt)?;
            fmt.write_str(": ")?;
        }
        write_loc(fmt, self.idx_to_pos(self.start), self.start)?;


        if self.end != self.start {
            fmt.write_str(" to ")?;
            write_loc(fmt, self.idx_to_pos(self.end), self.end)?;
        }

        fmt.write_char(']')
        */
        unimplemented!("display SourceLocation")
    }
}

fn build_reader_macro<C: 'static + Context>(name: &str, value: Gc<Value<C>>) -> Gc<Value<C>> {
    Gc::new(Value::Cons(
        Gc::new(Value::Symbol(name.into(), Default::default())),
        Gc::new(Value::Cons(
            value,
            Gc::new(Value::Nil(Default::default())),
            Default::default(),
        )),
        Default::default(),
    ))
}

/// Reads zero or more [`Value`](../enum.Value.html)s from a file.
pub fn read_file<C: 'static + Context>(
    path: Gc<PathBuf>,
) -> Result<Vec<Gc<Value<C>>>, Either<IoError, ReadError>> {
    debug!("Reading file {}", path.display());
    let mut buf = String::new();
    File::open(&*path)
        .and_then(|mut f| f.read_to_string(&mut buf))
        .map_err(Left)?;
    read_many(buf, Some(path)).map_err(Right)
}

fn must_read<'a>(lexer: &mut Peekable<Lexer<'a>>, lexeme: Lexeme<'a>) -> Result<(), ReadError> {
    let next = lexer.next();
    match next {
        Some(Ok(token)) => {
            if token.lexeme == lexeme {
                Ok(())
            } else {
                unimplemented!("failed to must_read: token")
            }
        }
        Some(Err(err)) => Err(err),
        None => unimplemented!("failed to must_read: eof"),
    }
}

fn unexpected_tok_val<'a>(token: Token<'a>, path: Option<Gc<PathBuf>>) -> ReadError {
    ReadError {
        kind: ReadErrorKind::Token(token.lexeme.to_string(), AcceptSet::Value),
        location: SourceLocation {
            start: token.start,
            end: token.end,
            path,
        },
    }
}

/// Reads a single [`Value`](../enum.Value.html) from the lexer.
pub fn read_one<'a, C: 'static + Context>(
    s: &'a str,
    lexer: &mut Peekable<Lexer<'a>>,
    path: Option<Gc<PathBuf>>,
) -> Result<Gc<Value<C>>, ReadError> {
    let mut comments = Vec::new();
    loop {
        let was_value = match lexer.peek() {
            Some(&Ok(ref tok)) => {
                if let Lexeme::Comment(l, ref n) = tok.lexeme {
                    comments.push((l, n.to_string()));
                    false
                } else {
                    true
                }
            }
            Some(&Err(_)) => false,
            None => true,
        };
        if was_value {
            break;
        } else if let Some(Err(err)) = lexer.next() {
            return Err(err);
        }
    }

    match lexer.next() {
        Some(Ok(tok)) => {
            match tok.lexeme {
                Lexeme::BracketClose => Err(unexpected_tok_val(tok, path)),
                Lexeme::BracketOpen => {
                    let mut values = Vec::new();
                    loop {
                        let peek = lexer.peek().map(|r| r.clone());
                        match peek {
                            Some(Ok(tok)) => {
                                match tok.lexeme {
                                    Lexeme::BracketClose => break,
                                    _ => {}
                                }
                            }
                            _ => {}
                        }
                        values.push(read_one(s, lexer, path.clone())?);
                    }
                    must_read(lexer, Lexeme::BracketClose)?;
                    Ok(Value::vector(values))
                }
                Lexeme::Comment(..) => unreachable!(),
                Lexeme::Dot => Err(unexpected_tok_val(tok, path)),
                Lexeme::ParenClose => Err(unexpected_tok_val(tok, path)),
                Lexeme::ParenOpen => {
                    let mut values = Vec::new();
                    let last = loop {
                        let peek = lexer.peek().map(|r| r.clone());
                        match peek {
                            Some(Ok(tok)) => {
                                match tok.lexeme {
                                    Lexeme::Dot => {
                                        must_read(lexer, Lexeme::Dot)?;
                                        let value = read_one(s, lexer, path)?;
                                        break value;
                                    }
                                    Lexeme::ParenClose => {
                                        break Gc::new(Value::Nil(Default::default()));
                                    }
                                    _ => {}
                                }
                            }
                            _ => {}
                        }
                        values.push(read_one(s, lexer, path.clone())?);
                    };
                    must_read(lexer, Lexeme::ParenClose)?;
                    Ok(Value::improper_list(values, last, Default::default()))
                }
                Lexeme::Quasiquote => {
                    read_one(s, lexer, path.clone()).map(|v| build_reader_macro("quasiquote", v))
                }
                Lexeme::Quote => {
                    read_one(s, lexer, path.clone()).map(|v| build_reader_macro("quote", v))
                }
                Lexeme::String(s) => Ok(Gc::new(
                    Value::String(Gc::new(s.to_string()), Default::default()),
                )),
                Lexeme::Symbolish(s) => Ok(Gc::new(read_symbolish(s))),
                Lexeme::Unquote(b) => {
                    let name = if b { "unquote-splicing" } else { "unquote" };
                    read_one(s, lexer, path.clone()).map(|v| build_reader_macro(name, v))
                }
            }
        }
        Some(Err(err)) => Err(err),
        None => Err(ReadError {
            kind: ReadErrorKind::EOF(AcceptSet::Value),
            location: SourceLocation {
                start: s.len(),
                end: s.len(),
                path,
            },
        }),
    }
}

/// Reads zero or more [`Value`](../enum.Value.html)s.
pub fn read_many<B, C>(buf: B, path: Option<Gc<PathBuf>>) -> Result<Vec<Gc<Value<C>>>, ReadError>
where
    B: AsRef<str>,
    C: 'static + Context,
{
    let buf = buf.as_ref();
    let mut lexer = Lexer::new_path(buf, path.clone()).peekable();
    let mut vals = Vec::new();
    while lexer.peek().is_some() {
        vals.push(read_one(buf, &mut lexer, path.clone())?);
    }
    Ok(vals)
}