sdcx 0.1.0

SDC (Synopsys Design Constraints) toolkit
Documentation
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use crate::file_db::{FileDb, Location};
use crate::sdc::{Argument, SdcVersion};
use codespan_reporting::diagnostic::{Diagnostic, Label};
use codespan_reporting::term::{self, termcolor::StandardStream};
use parol_runtime::{LexerError, ParolError, ParserError, Span, SyntaxError};
use std::ops::Range;
use thiserror::Error;

pub trait Report {
    fn report(self, files: &FileDb<String, &str>) -> anyhow::Result<()>;
}

/// Parse Error
#[derive(Debug, Error)]
pub enum ParseError {
    #[error("LexicalError")]
    LexicalError(#[from] LexerError),

    #[error("SyntaxError")]
    SyntaxError(#[from] ParserError),

    #[error("SemanticError")]
    SemanticError(#[from] SemanticError),
}

impl Report for ParseError {
    fn report(self, files: &FileDb<String, &str>) -> anyhow::Result<()> {
        let writer = StandardStream::stderr(term::termcolor::ColorChoice::Auto);
        let config = term::Config::default();

        match self {
            ParseError::LexicalError(x) => Self::report_lexical_error(&x, &writer, &config, files),
            ParseError::SyntaxError(x) => Self::report_syntax_error(&x, &writer, &config, files),
            ParseError::SemanticError(x) => x.report(files),
        }
    }
}

impl ParseError {
    fn report_lexical_error(
        err: &LexerError,
        writer: &StandardStream,
        config: &term::Config,
        files: &FileDb<String, &str>,
    ) -> anyhow::Result<()> {
        match err {
            LexerError::TokenBufferEmptyError => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message("No valid token read")
                    .with_code("parol_runtime::lexer::empty_token_buffer")
                    .with_notes(vec!["Token buffer is empty".to_string()]),
            )?),
            LexerError::InternalError(e) => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message(format!("Internal lexer error: {e}"))
                    .with_code("parol_runtime::lexer::internal_error"),
            )?),
            LexerError::LookaheadExceedsMaximum => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message("Lookahead exceeds maximum".to_string())
                    .with_code("parol_runtime::lexer::lookahead_exceeds_maximum"),
            )?),
            LexerError::LookaheadExceedsTokenBufferLength => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message("Lookahead exceeds token buffer length".to_string())
                    .with_code("parol_runtime::lexer::lookahead_exceeds_token_buffer_length"),
            )?),
            LexerError::ScannerStackEmptyError => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message("Tried to pop from empty scanner stack".to_string())
                    .with_code("parol_runtime::lexer::pop_from_empty_scanner_stack")
                    .with_notes(vec![
                        "Check balance of %push and %pop directives in your grammar".to_string(),
                    ]),
            )?),
            LexerError::RecoveryError(e) => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message(format!("Lexer recovery error: {e}"))
                    .with_code("parol_runtime::lexer::recovery"),
            )?),
        }
    }

    fn report_syntax_error(
        err: &ParserError,
        writer: &StandardStream,
        config: &term::Config,
        files: &FileDb<String, &str>,
    ) -> anyhow::Result<()> {
        match err {
            ParserError::TreeError { source } => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message(format!("Error from syntree crate: {}", source))
                    .with_code("parol_runtime::parser::syntree_error")
                    .with_notes(vec!["Internal error".to_string()]),
            )?),
            ParserError::DataError(e) => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message(format!("Data error: {e}"))
                    .with_code("parol_runtime::lexer::internal_error")
                    .with_notes(vec!["Error in generated source".to_string()]),
            )?),
            ParserError::PredictionError { cause } => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::error()
                    .with_message("Error in input")
                    .with_code("parol_runtime::lookahead::production_prediction_error")
                    .with_notes(vec![cause.to_string()]),
            )?),
            ParserError::SyntaxErrors { entries } => {
                entries.iter().try_for_each(
                    |SyntaxError {
                         cause,
                         error_location,
                         unexpected_tokens,
                         expected_tokens,
                         source,
                         ..
                     }|
                     -> anyhow::Result<()> {
                        if let Some(source) = source {
                            match source.as_ref() {
                                ParolError::LexerError(x) => {
                                    Self::report_lexical_error(x, writer, config, files)?
                                }
                                ParolError::ParserError(x) => {
                                    Self::report_syntax_error(x, writer, config, files)?
                                }
                                _ => (),
                            }
                        }

                        let (range, file_id): (Range<usize>, usize) =
                            if unexpected_tokens.is_empty() {
                                let location: Location = (&**error_location).into();
                                location.range_file(files)
                            } else {
                                let token = &unexpected_tokens[0].token;
                                let range = token.into();
                                let file_id = files
                                    .get_id(&token.file_name.display().to_string())
                                    .unwrap();
                                (range, file_id)
                            };

                        let unexpected_tokens_labels =
                            unexpected_tokens.iter().fold(vec![], |mut acc, un| {
                                acc.push(
                                    Label::secondary(
                                        file_id,
                                        Into::<Range<usize>>::into(&un.token),
                                    )
                                    .with_message(un.token_type.clone()),
                                );
                                acc
                            });
                        Ok(term::emit(
                            &mut writer.lock(),
                            config,
                            files,
                            &Diagnostic::error()
                                .with_message("Syntax error")
                                .with_code("parol_runtime::parser::syntax_error")
                                .with_labels(vec![
                                    Label::primary(file_id, range).with_message("Found")
                                ])
                                .with_labels(unexpected_tokens_labels)
                                .with_notes(vec![
                                    format!("Expecting {}", expected_tokens),
                                    cause.to_string(),
                                ]),
                        )?)
                    },
                )?;
                Ok(term::emit(
                    &mut writer.lock(),
                    config,
                    files,
                    &Diagnostic::error()
                        .with_message(format!("{} syntax error(s) found", entries.len())),
                )?)
            }
            ParserError::UnprocessedInput { last_token, .. } => {
                let un_span: Span = (Into::<Range<usize>>::into(&**last_token)).into();
                let file_id = files
                    .get_id(&last_token.file_name.display().to_string())
                    .unwrap();
                Ok(term::emit(
                    &mut writer.lock(),
                    config,
                    files,
                    &Diagnostic::error()
                        .with_message("Unprocessed input is left after parsing has finished")
                        .with_code("parol_runtime::parser::unprocessed_input")
                        .with_labels(vec![
                            Label::primary(file_id, un_span).with_message("Unprocessed")
                        ])
                        .with_notes(vec![
                            "Unprocessed input could be a problem in your grammar.".to_string(),
                        ]),
                )?)
            }
            ParserError::PopOnEmptyScannerStateStack {
                context, source, ..
            } => {
                Self::report_lexical_error(source, writer, config, files)?;

                Ok(term::emit(
                    &mut writer.lock(),
                    config,
                    files,
                    &Diagnostic::error()
                        .with_message(format!("{context}Tried to pop from an empty scanner stack"))
                        .with_code("parol_runtime::parser::pop_on_empty_scanner_stack"),
                )?)
            }
            ParserError::InternalError(e) => Ok(term::emit(
                &mut writer.lock(),
                config,
                files,
                &Diagnostic::bug()
                    .with_message(format!("Internal parser error: {e}"))
                    .with_code("parol_runtime::parser::internal_error")
                    .with_notes(vec!["This may be a bug. Please report it!".to_string()]),
            )?),
        }
    }
}

/// Semantic Error
#[derive(Debug, Error)]
pub enum SemanticError {
    #[error("WrongArgument: {0:?}")]
    WrongArgument(Argument),

    #[error("DuplicatedArgument")]
    DuplicatedArgument(Argument),

    #[error("MissingOptArgument: {0:?}")]
    MissingOptArgument(Argument),

    #[error("MissingPosArgument")]
    MissingPosArgument(Location),

    #[error("TooManyArgument")]
    TooManyArgument(Location),

    #[error("MissingMandatoryArgument: {0}")]
    MissingMandatoryArgument(String, Location),

    #[error("SdcVersionPlacement")]
    SdcVersionPlacement(Location),

    #[error("UnknownVersion")]
    UnknownVersion(Location),

    #[error("AmbiguousOption")]
    AmbiguousOption(Location),
}

impl Report for SemanticError {
    fn report(self, files: &FileDb<String, &str>) -> anyhow::Result<()> {
        let writer = StandardStream::stderr(term::termcolor::ColorChoice::Auto);
        let config = term::Config::default();

        match self {
            SemanticError::WrongArgument(x) => {
                let (range, file_id) = x.location().range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Wrong argument")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::DuplicatedArgument(x) => {
                let (range, file_id) = x.location().range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Duplicated arguments")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::MissingOptArgument(x) => {
                let (range, file_id) = x.location().range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Missing argument")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::MissingPosArgument(x) => {
                let (range, file_id) = x.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Missing positional argument")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::TooManyArgument(x) => {
                let (range, file_id) = x.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Too many argument")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::MissingMandatoryArgument(name, location) => {
                let (range, file_id) = location.range_file(files);
                let diag = Diagnostic::error()
                    .with_message(format!("Missing mandatory argument: {name}"))
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::SdcVersionPlacement(location) => {
                let (range, file_id) = location.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("SDC version should be set at the beginning of file")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::UnknownVersion(location) => {
                let (range, file_id) = location.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Unknown SDC version")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            SemanticError::AmbiguousOption(x) => {
                let (range, file_id) = x.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Ambiguous option")
                    .with_code("sdcx::errors::SemanticError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
        }
    }
}

/// Validate Error
#[derive(Debug, Error)]
pub enum ValidateError {
    #[error("UnknownCommand: {0}")]
    UnknownCommand(String, Location),

    #[error("CmdUnsupportedVersion")]
    CmdUnsupportedVersion(SdcVersion, Location),

    #[error("ArgUnsupportedVersion")]
    ArgUnsupportedVersion(SdcVersion, Location, String),

    #[error("ArgumentCombination")]
    ArgumentCombination(Location),
}

impl ValidateError {
    pub fn report(self, files: &FileDb<String, &str>) -> anyhow::Result<()> {
        let writer = StandardStream::stderr(term::termcolor::ColorChoice::Auto);
        let config = term::Config::default();

        match self {
            ValidateError::UnknownCommand(_, location) => {
                let (range, file_id) = location.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Unknown command")
                    .with_code("sdcx::errors::ValidateError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            ValidateError::CmdUnsupportedVersion(version, location) => {
                let (range, file_id) = location.range_file(files);
                let diag = Diagnostic::error()
                    .with_message(format!(
                        "Unsupported command at SDC {}",
                        version.version_string()
                    ))
                    .with_code("sdcx::errors::ValidateError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            ValidateError::ArgUnsupportedVersion(version, location, name) => {
                let (range, file_id) = location.range_file(files);
                let diag = Diagnostic::error()
                    .with_message(format!(
                        "Unsupported argument \"-{name}\" at {}",
                        version.version_string()
                    ))
                    .with_code("sdcx::errors::ValidateError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
            ValidateError::ArgumentCombination(x) => {
                let (range, file_id) = x.range_file(files);
                let diag = Diagnostic::error()
                    .with_message("Forbidden argument combination")
                    .with_code("sdcx::errors::ValidateError")
                    .with_labels(vec![Label::primary(file_id, range).with_message("Found")]);
                Ok(term::emit(&mut writer.lock(), &config, files, &diag)?)
            }
        }
    }
}