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
//! Error structures

use ast;
use std::fmt;
use std::error;
use colored::*;
use util;
use grammar;

/// The number of lines to display as error context.
const ERROR_CONTEXT_LINES: usize = 5;

/// Generic error type for high-level errors of this libaray.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase", deny_unknown_fields)]
pub enum MWError {
    ParseError(ParseError),
    TransformationError(TransformationError),
}

/// The parser error with source code context.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase", deny_unknown_fields)]
pub struct ParseError {
    pub position: ast::Position,
    pub expected: Vec<String>,
    pub context: Vec<String>,
    pub context_start: usize,
    pub context_end: usize,
}

/// Error structure for syntax tree transformations.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase", deny_unknown_fields)]
pub struct TransformationError {
    pub cause: String,
    pub position: ast::Span,
    pub transformation_name: String,
    pub tree: ast::Element,
}

impl ParseError {
    pub fn from(err: &grammar::ParseError, input: &str) -> Self {

        let source_lines = util::get_source_lines(input);
        let line_count = source_lines.len();

        let line = if err.line <= line_count {
            err.line
        } else {
            source_lines.len()
        } - 1;

        let start = if line < ERROR_CONTEXT_LINES {
            0
        } else {
            line - ERROR_CONTEXT_LINES
        };

        let end = if line + ERROR_CONTEXT_LINES >= line_count {
            line_count - 1
        } else {
            line + ERROR_CONTEXT_LINES
        };

        let mut token_str = vec![];
        for token in &err.expected {
            token_str.push(String::from(*token));
        }


        let mut context = vec![];
        for sloc in source_lines[start..end + 1].iter() {
            context.push(String::from(sloc.content));
        }

        ParseError {
            position: ast::Position::new(err.offset, &source_lines),
            context: context,
            expected: token_str,
            context_start: start,
            context_end: end,
        }
    }
}

impl error::Error for ParseError {
    fn description(&self) -> &str {
        "Could not continue to parse, because no rules could be matched."
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let error_message = format!(
            "ERROR in line {} at column {}: Could not continue to parse, expected one of: ",
            self.position.line,
            self.position.col
        ).red()
            .bold();

        let mut token_str = vec![];
        for token in &self.expected {
            if util::is_whitespace(token) {
                token_str.push(format!("{:?}", token));
            } else {
                token_str.push(format!("{}", token));
            }
        }

        write!(f, "{}", error_message)?;
        write!(f, "{}\n", token_str.join(", ").blue().bold())?;

        for (i, content) in self.context.iter().enumerate() {

            let lineno = format!("{} |", self.context_start + i + 1);
            let lineno_col;

            let formatted_content;
            // the erroneous line
            if self.context_start + i + 1 == self.position.line {
                formatted_content = content.red();
                lineno_col = lineno.red().bold();
            } else {
                formatted_content = util::shorten_str(content).normal();
                lineno_col = lineno.blue().bold()
            }

            writeln!(f, "{} {}", lineno_col, formatted_content)?;
        }

        Ok(())
    }
}

impl error::Error for TransformationError {
    fn description(&self) -> &str {
        &self.cause
    }
}

impl fmt::Display for TransformationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let message = format!(
            "ERROR applying transformation \"{}\" to Elemtn at {}:{} to {}:{}: {}",
            self.transformation_name,
            self.position.start.line,
            self.position.start.col,
            self.position.end.line,
            self.position.end.col,
            self.cause
        );
        writeln!(f, "{}", message.red().bold())
    }
}

impl error::Error for MWError {
    fn description(&self) -> &str {
        match *self {
            MWError::ParseError(ref e) => e.description(),
            MWError::TransformationError(ref e) => e.description(),
        }
    }
}

impl fmt::Display for MWError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            MWError::ParseError(ref e) => write!(f, "{}", e),
            MWError::TransformationError(ref e) => write!(f, "{}", e),
        }
    }
}