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
/*
    This file is part of Donet.

    Copyright © 2024 Max Rodriguez

    Donet is free software; you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License,
    as published by the Free Software Foundation, either version 3
    of the License, or (at your option) any later version.

    Donet is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public
    License along with Donet. If not, see <https://www.gnu.org/licenses/>.
*/

//! Errors that can be returned by the DC parser pipeline.

use super::lexer::{DCToken, Span};
use super::pipeline::{PipelineData, PipelineStage};
use codespan_diag::Label;
use codespan_diag::LabelStyle;
use codespan_reporting::diagnostic as codespan_diag;
use std::mem::discriminant;
use thiserror::Error;

/// Convert `self` type to an error code.
/// Used with DC parser pipeline error types.
pub trait ToErrorCode
where
    Self: std::error::Error,
{
    fn error_code(&self) -> &str;
}

#[derive(Debug, Error)]
#[error(transparent)]
pub enum DCReadError {
    #[error("parser error")]
    Syntax,
    #[error("semantics error")]
    Semantic,
    IO(#[from] std::io::Error),
}

#[derive(Debug, Error)]
#[error(transparent)]
pub enum PipelineError {
    Parser(#[from] ParseError),
    Semantics(#[from] SemanticError),
}

impl ToErrorCode for PipelineError {
    fn error_code(&self) -> &str {
        // Get the error code from the underlying error type.
        match self {
            Self::Parser(err) => err.error_code(),
            Self::Semantics(err) => err.error_code(),
        }
    }
}

/// Error type for the semantic analysis stage of the pipeline.
#[derive(Debug, Error)]
pub enum SemanticError {
    // generic
    #[error("`{0}` is already defined")]
    AlreadyDefined(String),
    #[error("`{0}` is not defined")]
    NotDefined(String),

    // dc file
    #[error("multiple inheritance is not allowed")]
    MultipleInheritanceDisabled,
    #[error("maximum number of dclasses declared")]
    DClassOverflow,
    #[error("maximum number of fields declared")]
    FieldOverflow,

    // python-style imports
    #[error("redundant view suffix `{0}`")]
    RedundantViewSuffix(String),

    // keywords
    #[error("redundant keyword `{0}`")]
    RedundantKeyword(String),

    // structs
    #[error("dc keywords are not allowed in struct fields")]
    KeywordsInStructField,

    // switches
    #[error("duplicate case value")]
    RedundantCase,
    #[error("default case already defined")]
    RedundantDefault,
    #[error("case value type does not match key value type")]
    InvalidCaseValueType,

    // molecular fields
    #[error("`mismatched dc keywords in molecule between `{atom1}` and `{atom2}`")]
    MismatchedKeywords { atom1: String, atom2: String },
    #[error("`{0}` is not an atomic field")]
    ExpectedAtomic(String),

    // numeric ranges
    #[error("invalid range for type")]
    InvalidRange,
    #[error("overlapping range")]
    OverlappingRange,
    #[error("value out of range")]
    ValueOutOfRange,

    // transforms
    #[error("invalid divisor")]
    InvalidDivisor,
    #[error("invalid modulus")]
    InvalidModulus,

    // default
    #[error("invalid default value for type")]
    InvalidDefault,

    // struct type
    #[error("`{0}` is not a struct")]
    ExpectedStruct(String),
}

impl ToErrorCode for SemanticError {
    fn error_code(&self) -> &str {
        match self {
            // generic
            Self::AlreadyDefined(_) => "E0200",
            Self::NotDefined(_) => "E0201",
            // dc file
            Self::MultipleInheritanceDisabled => "E0210",
            Self::DClassOverflow => "E0211",
            Self::FieldOverflow => "E0212",
            // python-style imports
            Self::RedundantViewSuffix(_) => "E0220",
            // keywords
            Self::RedundantKeyword(_) => "E0230",
            // structs
            Self::KeywordsInStructField => "E0240",
            // switches
            Self::RedundantCase => "E0250",
            Self::RedundantDefault => "E0251",
            Self::InvalidCaseValueType => "E0252",
            // molecular fields
            Self::MismatchedKeywords { atom1: _, atom2: _ } => "E0260",
            Self::ExpectedAtomic(_) => "E0261",
            // numeric ranges
            Self::InvalidRange => "E0270",
            Self::OverlappingRange => "E0271",
            Self::ValueOutOfRange => "E0272",
            // transforms
            Self::InvalidDivisor => "E0280",
            Self::InvalidModulus => "E0281",
            // default
            Self::InvalidDefault => "E0290",
            // struct type
            Self::ExpectedStruct(_) => "E0300",
        }
    }
}

/// Error type for the parser stage of the pipeline.
/// Currently, it only stores one error type, which is
/// the standard error type for the parser. Due to a
/// plex limitation, I am unable to propagate custom
/// errors from grammar productions. See Donet issue #19.
#[derive(Debug, Error)]
pub enum ParseError {
    #[error("syntax error; {1}, found `{0:?}`")]
    Error(DCToken, String),
}

impl ToErrorCode for ParseError {
    fn error_code(&self) -> &str {
        match self {
            Self::Error(_, _) => "E0100",
        }
    }
}

pub(crate) struct Diagnostic {
    span: Span,
    stage: PipelineStage,
    file_id: usize,
    severity: codespan_diag::Severity,
    error: PipelineError,
}

impl Diagnostic {
    pub fn error(span: Span, pipeline: &mut PipelineData, err: impl Into<PipelineError>) -> Self {
        Self {
            span,
            stage: pipeline.current_stage(),
            file_id: pipeline.current_file(),
            severity: codespan_diag::Severity::Error,
            error: err.into(),
        }
    }
}

/// Allows converting our Diagnostic type into a codespan Diagnostic type.
impl From<Diagnostic> for codespan_diag::Diagnostic<usize> {
    fn from(val: Diagnostic) -> codespan_diag::Diagnostic<usize> {
        codespan_diag::Diagnostic::new(val.severity)
            .with_message(val.error.to_string())
            .with_code(val.error.error_code())
            .with_labels(vec![Label::new(
                LabelStyle::Primary,
                val.file_id,
                val.span.min..val.span.max,
            )])
            .with_notes({
                // If error type is from the Plex parser stage, emit the following notice.
                if discriminant(&val.stage) == discriminant(&PipelineStage::Parser) {
                    vec![
                        "Syntax errors are limited. Please see issue #19.".into(),
                        "https://gitlab.com/donet-server/donet/-/issues/19".into(),
                    ]
                } else {
                    vec![]
                }
            })
    }
}