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
// Copyright 2015 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A parsing state indicates the current status of the parsing. It is mainly used by compiled PEG combinators.

use stream::*;
use self::ParseResult::*;
use std::collections::hash_set::HashSet;
use std::cmp::Ord;
use std::fmt::{Formatter, Debug, Error};

pub trait IntoState<S, T>
{
  fn into_state(self) -> ParseState<S, T>;
}

impl<S, T, R> IntoState<S, T> for R where
  R: Stream<Output=S>,
  S: Ord + Clone + HasNext
{
  fn into_state(self) -> ParseState<S, T> {
    ParseState::new(self.stream())
  }
}

pub struct ParseExpectation<S>
{
  expected: HashSet<&'static str>,
  farthest_read: S
}

impl<S> ParseExpectation<S>
{
  pub fn new(farthest_read: S, expected: Vec<&'static str>) -> ParseExpectation<S> {
    ParseExpectation {
      expected: expected.into_iter().collect(),
      farthest_read: farthest_read
    }
  }
}

impl<S> ParseExpectation<S> where
 S: Location + CodeSnippet
{
  pub fn expected_items(&self) -> String {
    let mut desc = String::new();
    if self.expected.len() > 0 {
      for expect in &self.expected {
        desc.push('`');
        desc.push_str(expect);
        desc.push_str("` or ");
      }
      let len_without_last_or = desc.len() - 4;
      desc.truncate(len_without_last_or);
    }
    desc
  }
}

/// Prints an error message of the form: ```1:1: unexpected `a+1`, expecting `(` or `["0-9"]`.``` where `1:1` is the line and the column where the error occurred.
impl<S> Debug for ParseExpectation<S> where
 S: Location + CodeSnippet
{
  fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
    let location = self.farthest_read.location();
    let expected = self.expected_items();
    let snippet = self.farthest_read.code_snippet(10usize);
    formatter.write_fmt(
      format_args!("{}: unexpected `{}`, expecting {}.", location, snippet, expected))
  }
}

pub enum ParseResult<S, T>
{
  Success(T),
  Partial(T, ParseExpectation<S>),
  Failure(ParseExpectation<S>)
}

impl<S, T> Debug for ParseResult<S, T> where
 T: Debug,
 S: HasNext + Location + CodeSnippet
{
  fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
    match self {
      &Success(ref data) => {
        formatter.write_fmt(format_args!(
          "Full match, got data `{:?}`.", data))
      }
      &Partial(ref data, ref expectation) => {
        try!(formatter.write_fmt(format_args!(
          "Partial match, got data `{:?}`. It stopped because:\n\t",
          data)));
        expectation.fmt(formatter)
      }
      &Failure(ref expectation) => {
        try!(formatter.write_str("Error:\n\t"));
        expectation.fmt(formatter)
      }
    }
  }
}

/// `ParseState<S, T>` reads value from the stream `S` and build an AST of type `T`.
/// Error strategy: Even in case of success, we keep error information in case we fail later. Think about parsing "abaa" with `"ab"* "c"`, it will directly fails on `"c"`, so it is better to report an error such as `expected "ab" but got "aa"` since the input partially matches "ab"`.
pub struct ParseState<S, T>
{
  /// The farthest read into the stream at which we encountered an error.
  pub farthest_read: S,
  /// Expected items at position `farthest_read`. Duplicate entries are possible.
  pub expected: Vec<&'static str>,
  pub failed: bool,
  /// The current stream that can be partially or fully consumed.
  pub current: S,
  /// Contains the AST if the current state is successful and `None` if it is erroneous.
  pub data: Option<T>
}

impl<S, T> ParseState<S, T> where
 S: Ord + Clone + HasNext
{
  #[inline]
  pub fn new(stream: S) -> ParseState<S, T> {
    ParseState {
      farthest_read: stream.clone(),
      expected: vec![],
      failed: false,
      current: stream,
      data: None
    }
  }

  pub fn is_failed(&self) -> bool {
    self.failed
  }

  pub fn is_successful(&self) -> bool {
    !self.is_failed()
  }

  #[inline]
  pub fn error(&mut self, expect: &'static str) {
    self.failed = true;
    if self.current > self.farthest_read {
      self.farthest_read = self.current.clone();
      self.expected = vec![expect];
    }
    else if self.current == self.farthest_read {
      self.expected.push(expect);
    }
  }

  // TODO: find a way to specialize success when U = T.
  #[inline]
  pub fn success<U>(self, data: U) -> ParseState<S, U> {
    ParseState {
      farthest_read: self.farthest_read,
      expected: self.expected,
      failed: false,
      current: self.current,
      data: Some(data)
    }
  }

  pub fn failure<U>(self) -> ParseState<S, U> {
    ParseState {
      farthest_read: self.farthest_read,
      expected: self.expected,
      failed: true,
      current: self.current,
      data: None
    }
  }

  pub fn mark(&self) -> S {
    assert!(!self.failed, "Marking a failed ParseState is not allowed.");
    self.current.clone()
  }

  pub fn restore_from_failure(self, mark: S) -> ParseState<S, ()> {
    assert!(self.failed, "Restoring a successful ParseState is not allowed.");
    self.restore(mark)
  }

  pub fn restore(self, mark: S) -> ParseState<S, ()> {
    assert!(self.data.is_none(), "Restoring a ParseState with data is not allowed.");
    ParseState {
      farthest_read: self.farthest_read,
      expected: self.expected,
      failed: false,
      current: mark,
      data: None
    }
  }

  /// Transforms `self` into a more usable `ParseResult` value. It is useful when the state is terminal or if the state will not be further transformed.
  pub fn into_result(self) -> ParseResult<S, T> {
    let expectation = ParseExpectation::new(self.farthest_read, self.expected);
    match self.data {
      Some(data) => {
        if self.current.has_next() {
          Partial(data, expectation)
        }
        else {
          Success(data)
        }
      }
      None => {
        assert!(self.failed, "Failure status must be true when extracting a failed result.");
        Failure(expectation)
      }
    }
  }

  pub fn extract_data(self) -> (ParseState<S, ()>, T) {
    assert!(self.is_successful() && self.data.is_some(),
      "Data extraction is only possible if the state is successful and contains data.");
    let data = self.data.unwrap();
    let state = ParseState {
      farthest_read: self.farthest_read,
      expected: self.expected,
      failed: self.failed,
      current: self.current,
      data: None
    };
    (state, data)
  }

  pub fn unwrap_data(self) -> T {
    self.data.expect("data in ParseState (unwrap_data)")
  }
}

impl<S> ParseState<S, ()>
{
  // This is specific to recognizer where unit data does not need to be extracted. We also want to preserve the "no-data" precondition of `restore`.
  pub fn discard_data(&mut self) {
    self.data = None;
  }
}

impl<S, T, I> Iterator for ParseState<S, T> where
 S: Iterator<Item=I>
{
  type Item = I;
  fn next(&mut self) -> Option<Self::Item> {
    self.current.next()
  }
}

impl<S, T, P> ConsumePrefix<P> for ParseState<S, T> where
  S: ConsumePrefix<P>
{
  fn consume_prefix(&mut self, prefix: P) -> bool {
    self.current.consume_prefix(prefix)
  }
}