nickel-lang-parser 0.3.0

The Nickel parser
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
use codespan::ByteIndex;
use codespan_reporting::{diagnostic::Label, files::Files as _};
use lalrpop_util::ErrorRecovery;

use crate::{
    files::{FileId, Files},
    identifier::{Ident, LocIdent},
    lexer::Token,
    position::RawSpan,
    utils::mk_span,
};
use std::ops::Range;

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum LexicalError {
    /// A closing brace '}' does not match an opening brace '{'.
    UnmatchedCloseBrace(usize),
    /// Invalid escape sequence in a string literal.
    InvalidEscapeSequence(usize),
    /// Invalid escape ASCII code in a string literal.
    InvalidAsciiEscapeCode(usize),
    /// Invalid unicode escape code in a string literal.
    InvalidUnicodeEscapeCode(Range<usize>),
    /// A multiline string was closed with a delimiter which has a `%` count higher than the
    /// opening delimiter.
    StringDelimiterMismatch {
        opening_delimiter: Range<usize>,
        closing_delimiter: Range<usize>,
    },
    /// Generic lexer error
    Generic(Range<usize>),
}

/// Error indicating that a construct is not allowed when trying to interpret a `UniRecord` as a
/// record type in a strict way.
///
/// See `parser::uniterm::UniRecord::into_type_strict`.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum InvalidRecordTypeError {
    /// The record type had an invalid field, for example because it had a contract,
    /// an assigned value, or lacked a type annotation.
    InvalidField(RawSpan),
    /// The record had an ellipsis.
    IsOpen(RawSpan),
    /// The record has `include` statements.
    HasInclude(RawSpan),
    /// The record type had a field whose name used string interpolation.
    InterpolatedField(RawSpan),
    /// A field name was repeated.
    RepeatedField { orig: RawSpan, dup: RawSpan },
}

impl InvalidRecordTypeError {
    pub fn labels(&self) -> Vec<Label<FileId>> {
        let label = |span: &RawSpan| {
            Label::secondary(span.src_id, span.start.to_usize()..span.end.to_usize())
        };
        match self {
            InvalidRecordTypeError::InvalidField(pos) => {
                vec![label(pos).with_message("invalid field for a record type literal")]
            }
            InvalidRecordTypeError::IsOpen(pos) => {
                vec![label(pos).with_message("cannot have ellipsis in a record type literal")]
            }
            InvalidRecordTypeError::HasInclude(pos) => {
                vec![label(pos).with_message("cannot have `include` statements in a record type")]
            }
            InvalidRecordTypeError::InterpolatedField(pos) => {
                vec![label(pos).with_message("this field uses interpolation")]
            }
            InvalidRecordTypeError::RepeatedField { orig, dup } => {
                vec![
                    label(orig).with_message("first occurrence"),
                    label(dup).with_message("second occurrence"),
                ]
            }
        }
    }

    pub fn notes(&self) -> Option<String> {
        match self {
            InvalidRecordTypeError::InvalidField(_) => Some(
                "Value assignments such as `<field> = <expr>`, and metadata \
                    annotation (annotation, documentation, etc.) are forbidden."
                    .into(),
            ),
            InvalidRecordTypeError::InterpolatedField(_) => {
                Some("String interpolation in field names is forbidden in record types".into())
            }
            InvalidRecordTypeError::RepeatedField { .. } => {
                Some("Repeated field names are forbidden".into())
            }
            _ => None,
        }
    }
}

/// An error occurring during parsing.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ParseError {
    /// Unexpected end of file.
    UnexpectedEOF(FileId, /* tokens expected by the parser */ Vec<String>),
    /// Unexpected token.
    UnexpectedToken(
        RawSpan,
        /* tokens expected by the parser */ Vec<String>,
    ),
    /// Superfluous, unexpected token.
    ExtraToken(RawSpan),
    /// A closing brace '}' does not match an opening brace '{'. This rather precise error is
    /// detected because of how interpolated strings are lexed.
    UnmatchedCloseBrace(RawSpan),
    /// Invalid escape sequence in a string literal.
    InvalidEscapeSequence(RawSpan),
    /// Invalid ASCII escape code in a string literal.
    InvalidAsciiEscapeCode(RawSpan),
    /// Invalid unicode escape code in a string literal.
    InvalidUnicodeEscapeCode(RawSpan),
    /// A multiline string was closed with a delimiter which has a `%` count higher than the
    /// opening delimiter.
    StringDelimiterMismatch {
        opening_delimiter: RawSpan,
        closing_delimiter: RawSpan,
    },
    /// Error when parsing an external format such as JSON, YAML, etc.
    ExternalFormatError(
        String, /* format */
        String, /* error message */
        Option<RawSpan>,
    ),
    /// Unbound type variable
    UnboundTypeVariables(Vec<LocIdent>),
    /// Illegal record type literal.
    ///
    /// This occurs when failing to convert from the uniterm syntax to a record type literal.
    /// See [RFC002](../../rfcs/002-merge-types-terms-syntax.md) for more details.
    InvalidRecordType {
        /// The position of the invalid record.
        record_span: RawSpan,
        /// Position of the tail, if there was one.
        tail_span: Option<RawSpan>,
        /// The reason that interpretation as a record type failed.
        cause: InvalidRecordTypeError,
    },
    /// A recursive let pattern was encountered. They are not currently supported because we
    /// decided it was too involved to implement them.
    RecursiveLetPattern(RawSpan),
    /// Let blocks can currently only contain plain bindings, not pattern bindings.
    PatternInLetBlock(RawSpan),
    /// A type variable is used in ways that imply it has multiple different kinds.
    ///
    /// This can happen in several situations, for example:
    /// - a variable is used as both a type variable and a row type variable,
    ///   e.g. in the signature `forall r. { ; r } -> r`,
    /// - a variable is used as both a record and enum row variable, e.g. in the
    ///   signature `forall r. [| ; r |] -> { ; r }`.
    TypeVariableKindMismatch { ty_var: LocIdent, span: RawSpan },
    /// A record literal, which isn't a record type, has a field with a type annotation but without
    /// a definition. While we could technically handle this situation, this is most probably an
    /// error from the user, because this type annotation is useless and, maybe non-intuitively,
    /// won't have any effect as part of a larger contract:
    ///
    /// ```nickel
    /// let MixedContract = {foo : String, bar | Number} in
    /// { foo = 1, bar = 2} | MixedContract
    /// ```
    ///
    /// This example works, because the `foo : String` annotation doesn't propagate, and contract
    /// application is mostly merging, which is probably not the intent. It might become a warning
    /// in a future version, but we don't have warnings for now, so we rather forbid such
    /// constructions.
    TypedFieldWithoutDefinition {
        /// The position of the field definition.
        field_span: RawSpan,
        /// The position of the type annotation.
        annot_span: RawSpan,
    },
    /// The user provided a field path on the CLI, which is expected to be only composed of
    /// literals, but the parsed field path contains string interpolation.
    InterpolationInStaticPath {
        input: String,
        path_elem_span: RawSpan,
    },
    /// A duplicate binding was encountered in a record destructuring pattern.
    DuplicateIdentInRecordPattern {
        /// The duplicate identifier.
        ident: LocIdent,
        /// The previous instance of the duplicated identifier.
        prev_ident: LocIdent,
    },
    /// A duplicate binding was encountered in a let block.
    DuplicateIdentInLetBlock {
        /// The duplicate identifier.
        ident: LocIdent,
        /// The previous instance of the duplicated identifier.
        prev_ident: LocIdent,
    },
    /// There was an attempt to use a feature that hasn't been enabled.
    DisabledFeature { feature: String, span: RawSpan },
    /// A term was used as a contract in type position, but this term has no chance to make any
    /// sense as a contract. What terms make sense might evolve with time, but any given point in
    /// time, there are a set of expressions that can be excluded syntactically. Currently, it's
    /// mostly constants.
    InvalidContract(RawSpan),
    /// Unrecognized explicit import format tag
    InvalidImportFormat { span: RawSpan },
    /// A CLI sigil expression such as `@env:FOO` is invalid because no `:` separator was found.
    SigilExprMissingColon(RawSpan),
    /// A CLI sigil expression is unknown or unsupported, such as `@unknown:value`.
    UnknownSigilSelector { selector: String, span: RawSpan },
    /// A CLI sigil attribute is unknown or unsupported, such as `@file/unsupported:value`.
    UnknownSigilAttribute {
        selector: String,
        attribute: String,
        span: RawSpan,
    },
    /// An included field has several definitions. While we could just merge both at runtime like a
    /// piecewise field definition, we entirely forbid this situation for now.
    MultipleFieldDecls {
        /// The identifier.
        ident: Ident,
        /// The identifier and the position of the include expression. The ident part is the same
        /// as the ident part of `ident`.
        include_span: RawSpan,
        /// The span of the other declaration, which can be either a field
        /// definition or an include expression as well.
        other_span: RawSpan,
    },
}

impl ParseError {
    pub(crate) fn from_lalrpop<T>(
        error: lalrpop_util::ParseError<usize, T, ParseOrLexError>,
        file_id: FileId,
    ) -> ParseError {
        match error {
            lalrpop_util::ParseError::InvalidToken { location } => {
                ParseError::UnexpectedToken(mk_span(file_id, location, location + 1), Vec::new())
            }
            lalrpop_util::ParseError::UnrecognizedToken {
                token: (start, _, end),
                expected,
            } => ParseError::UnexpectedToken(mk_span(file_id, start, end), expected),
            lalrpop_util::ParseError::UnrecognizedEof { expected, .. } => {
                ParseError::UnexpectedEOF(file_id, expected)
            }
            lalrpop_util::ParseError::ExtraToken {
                token: (start, _, end),
            } => ParseError::ExtraToken(mk_span(file_id, start, end)),
            lalrpop_util::ParseError::User {
                error: ParseOrLexError::Lexical(e),
            } => Self::from_lexical(e, file_id),
            lalrpop_util::ParseError::User {
                error: ParseOrLexError::Parse(e),
            } => e,
        }
    }

    fn from_lexical(error: LexicalError, file_id: FileId) -> ParseError {
        match error {
            LexicalError::Generic(range) => {
                ParseError::UnexpectedToken(mk_span(file_id, range.start, range.end), Vec::new())
            }
            LexicalError::UnmatchedCloseBrace(location) => {
                ParseError::UnmatchedCloseBrace(mk_span(file_id, location, location + 1))
            }
            LexicalError::InvalidEscapeSequence(location) => {
                ParseError::InvalidEscapeSequence(mk_span(file_id, location, location + 1))
            }
            LexicalError::InvalidAsciiEscapeCode(location) => {
                ParseError::InvalidAsciiEscapeCode(mk_span(file_id, location, location + 2))
            }
            LexicalError::InvalidUnicodeEscapeCode(location) => {
                ParseError::InvalidUnicodeEscapeCode(mk_span(file_id, location.start, location.end))
            }
            LexicalError::StringDelimiterMismatch {
                opening_delimiter,
                closing_delimiter,
            } => ParseError::StringDelimiterMismatch {
                opening_delimiter: mk_span(file_id, opening_delimiter.start, opening_delimiter.end),
                closing_delimiter: mk_span(file_id, closing_delimiter.start, closing_delimiter.end),
            },
        }
    }

    pub fn from_serde_json(error: serde_json::Error, location: Option<(FileId, &Files)>) -> Self {
        use codespan::ByteOffset;

        // error.line() should start at `1` according to the documentation, but in practice, it may
        // be 0 for the error `json parse error: data did not match any variant of untagged enum
        // Term`. Although this error should not happen, if it does, it's better to get a message
        // than a panic message `subtract with overflow`.
        let line_span = if error.line() == 0 {
            None
        } else {
            location.and_then(|(file_id, files)| files.line_index(file_id, error.line() - 1).ok())
        };

        let start =
            line_span.map(|ls| ByteIndex::from(((ls + error.column()) as u32).saturating_sub(1)));
        ParseError::ExternalFormatError(
            String::from("json"),
            error.to_string(),
            start.map(|start| RawSpan {
                // unwrap: if start is Some, location was Some.
                src_id: location.unwrap().0,
                start,
                end: start + ByteOffset::from(1),
            }),
        )
    }

    pub fn from_yaml(error: saphyr_parser::ScanError, file_id: Option<FileId>) -> Self {
        use codespan::{ByteIndex, ByteOffset};

        let start = ByteIndex::from(error.marker().index() as u32);
        ParseError::ExternalFormatError(
            String::from("yaml"),
            error.to_string(),
            file_id.map(|src_id| RawSpan {
                src_id,
                start,
                end: start + ByteOffset::from(1),
            }),
        )
    }

    pub fn from_toml(error: toml_edit::TomlError, file_id: FileId) -> Self {
        use codespan::{ByteIndex, ByteOffset};

        let span = error.span();
        ParseError::ExternalFormatError(
            String::from("toml"),
            error.to_string(),
            span.map(|span| RawSpan {
                src_id: file_id,
                start: ByteIndex::from(span.start as u32),
                end: ByteIndex(span.end as u32) + ByteOffset::from(1),
            }),
        )
    }

    #[cfg(feature = "nix-experimental")]
    pub fn from_nix(error: &str, _file_id: FileId) -> Self {
        // Span is shown in the nix error message
        ParseError::ExternalFormatError(String::from("nix"), error.to_string(), None)
    }
}

// TODO: make this non-pub. It currently leaks out in some lalrpop-generated code and I haven't
// figured out how to make it not.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ParseOrLexError {
    Lexical(LexicalError),
    Parse(ParseError),
}

impl From<ParseError> for ParseOrLexError {
    fn from(e: ParseError) -> Self {
        Self::Parse(e)
    }
}

impl From<LexicalError> for ParseOrLexError {
    fn from(e: LexicalError) -> Self {
        Self::Lexical(e)
    }
}

impl<T> From<ParseError> for lalrpop_util::ParseError<usize, T, ParseOrLexError> {
    fn from(e: ParseError) -> Self {
        lalrpop_util::ParseError::User {
            error: ParseOrLexError::Parse(e),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct ParseErrors {
    pub errors: Vec<ParseError>,
}

impl ParseErrors {
    pub fn new(errors: Vec<ParseError>) -> ParseErrors {
        ParseErrors { errors }
    }

    pub fn errors(self) -> Option<Vec<ParseError>> {
        if self.errors.is_empty() {
            None
        } else {
            Some(self.errors)
        }
    }

    pub fn no_errors(&self) -> bool {
        self.errors.is_empty()
    }

    pub const fn none() -> ParseErrors {
        ParseErrors { errors: Vec::new() }
    }

    pub(crate) fn from_recoverable(
        errs: Vec<ErrorRecovery<usize, Token<'_>, ParseOrLexError>>,
        file_id: FileId,
    ) -> Self {
        ParseErrors {
            errors: errs
                .into_iter()
                .map(|e| ParseError::from_lalrpop(e.error, file_id))
                .collect(),
        }
    }
}

impl From<ParseError> for ParseErrors {
    fn from(e: ParseError) -> ParseErrors {
        ParseErrors { errors: vec![e] }
    }
}

impl From<Vec<ParseError>> for ParseErrors {
    fn from(errors: Vec<ParseError>) -> ParseErrors {
        ParseErrors { errors }
    }
}