pintc 0.14.0

Compiler for the Pint language
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
use crate::{
    error::{ErrorLabel, ReportableError},
    lexer::{self, Token},
    span::{Span, Spanned},
};
use fxhash::FxHashSet;
use std::{path::Path, sync::Arc};
use thiserror::Error;
use yansi::Color;

/// An error originating from the parser
#[derive(Error, Debug, PartialEq, Clone, Default)]
pub enum ParseError {
    // This is the default error which can be generated by the Logos lexer on a non-match.
    #[default]
    #[error("invalid token")]
    InvalidToken,
    #[error("invalid token")]
    Lex { span: Span },

    #[error("{}", format_expected_found_error(&mut expected.clone(), found))]
    ExpectedFound {
        span: Span,
        expected: Vec<Option<String>>,
        found: Option<String>,
    },
    #[error("missing array or map index")]
    EmptyIndexAccess { span: Span },
    #[error("invalid integer `{}` as tuple index", index)]
    InvalidIntegerTupleIndex { span: Span, index: String },
    #[error("invalid value `{}` as tuple index", index)]
    InvalidTupleIndex { span: Span, index: String },
    #[error("empty tuple expressions are not allowed")]
    EmptyTupleExpr { span: Span },
    #[error("empty tuple types are not allowed")]
    EmptyTupleType { span: Span },
    #[error("symbol `{sym}` has already been declared")]
    NameClash {
        sym: String,
        span: Span,      // Actual error location
        prev_span: Span, // Span of the previous occurrence
    },
    #[error("leading `+` is not supported")]
    UnsupportedLeadingPlus { span: Span },
    #[error("`self` import can only appear in an import list with a non-empty prefix")]
    SelfWithEmptyPrefix { span: Span },
    #[error("`self` is only allowed at the end of a use path")]
    SelfNotAtTheEnd { span: Span },
    #[error("unexpected binary integer literal length")]
    BinaryLiteralLength { digits: usize, span: Span },
    #[error("unexpected hexadecimal integer literal length")]
    HexLiteralLength { digits: usize, span: Span },
    #[error("integer literal is too large")]
    IntLiteralTooLarge { span: Span },
    #[error("`storage` block has already been declared")]
    TooManyStorageBlocks {
        span: Span,      // Actual error location
        prev_span: Span, // Span of the previous occurrence
    },
    #[error("a `storage` block can only appear in the top level module")]
    StorageDirectiveMustBeTopLevel { span: Span },
    #[error("`storage` access expressions can only appear in the top level module")]
    StorageAccessMustBeTopLevel { span: Span },
    #[error("bad argument splice")]
    BadSplice(Span),
    #[error("no intrinsic named `{name}` is found")]
    MissingIntrinsic { name: String, span: Span },
    #[error("Unsupported type")]
    TypeNotSupported { ty: String, span: Span },
    #[error("Unsupported literal")]
    LiteralNotSupported { kind: String, span: Span },
    #[error("`consts` must be declared outside of a `predicate`")]
    UnsupportedConstLocation { span: Span },
    #[error("assembly instruction can only have a 64-bit integer argument")]
    ExpectedIntegerLiteral { span: Span },
}

impl ReportableError for ParseError {
    fn labels(&self) -> Vec<ErrorLabel> {
        use ParseError::*;
        match self {
            InvalidToken => Vec::new(),
            Lex { span } => {
                vec![ErrorLabel {
                    message: "tokenization failure, unmatched input".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            ExpectedFound { span, expected, .. } => {
                vec![ErrorLabel {
                    message: format_expected_tokens_message(&mut expected.clone()),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            EmptyIndexAccess { span } => {
                vec![ErrorLabel {
                    message: "missing array or map element index".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            InvalidIntegerTupleIndex { span, .. } => {
                vec![ErrorLabel {
                    message: "invalid integer as tuple index".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            InvalidTupleIndex { span, .. } => {
                vec![ErrorLabel {
                    message: "invalid value as tuple index".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            EmptyTupleExpr { span } => {
                vec![ErrorLabel {
                    message: "empty tuple expression found".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            EmptyTupleType { span } => {
                vec![ErrorLabel {
                    message: "empty tuple type found".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            NameClash {
                sym,
                span,
                prev_span,
            } => {
                vec![
                    ErrorLabel {
                        message: format!("previous declaration of the symbol `{sym}` here"),
                        span: prev_span.clone(),
                        color: Color::Blue,
                    },
                    ErrorLabel {
                        message: format!("`{sym}` redeclared here"),
                        span: span.clone(),
                        color: Color::Red,
                    },
                ]
            }
            UnsupportedLeadingPlus { span } => {
                vec![ErrorLabel {
                    message: "unexpected `+`".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            SelfWithEmptyPrefix { span } => {
                vec![ErrorLabel {
                    message: "can only appear in an import list with a non-empty prefix"
                        .to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            SelfNotAtTheEnd { span } => {
                vec![ErrorLabel {
                    message: "`self` can only appear at the end of a use path".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            BinaryLiteralLength { digits, span } => {
                vec![ErrorLabel {
                    message: format!(
                        "{digits} is not a valid number of digits in a binary integer literal"
                    ),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            HexLiteralLength { digits, span } => {
                vec![ErrorLabel {
                    message: format!(
                        "{digits} is not a valid number of digits in a hexadecimal integer literal"
                    ),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            IntLiteralTooLarge { span } => {
                vec![ErrorLabel {
                    message: "integer literal is too large".to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            TooManyStorageBlocks { span, prev_span } => {
                vec![
                    ErrorLabel {
                        message: "previous declaration of a `storage` block here".to_string(),
                        span: prev_span.clone(),
                        color: Color::Blue,
                    },
                    ErrorLabel {
                        message: "another `storage` block is declared here".to_string(),
                        span: span.clone(),
                        color: Color::Red,
                    },
                ]
            }
            StorageDirectiveMustBeTopLevel { span } => {
                vec![ErrorLabel {
                    message: "a `storage` block can only appear in the top level module"
                        .to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            StorageAccessMustBeTopLevel { span } => {
                vec![ErrorLabel {
                    message: "`storage` access expressions can only appear in the top level module"
                        .to_string(),
                    span: span.clone(),
                    color: Color::Red,
                }]
            }
            BadSplice(span) => vec![ErrorLabel {
                message: "the macro argument splice operator `~` must be applied to an identifier"
                    .to_string(),
                span: span.clone(),
                color: Color::Red,
            }],
            MissingIntrinsic { span, .. } => vec![ErrorLabel {
                message: "intrinsic not found".to_string(),
                span: span.clone(),
                color: Color::Red,
            }],
            TypeNotSupported { ty, span } => vec![ErrorLabel {
                message: format!("type `{ty}` is not currently supported in Pint"),
                span: span.clone(),
                color: Color::Red,
            }],
            LiteralNotSupported { kind, span } => vec![ErrorLabel {
                message: format!("\"{kind}\" literals are not currently supported in Pint"),
                span: span.clone(),
                color: Color::Red,
            }],
            UnsupportedConstLocation { span } => vec![ErrorLabel {
                message: "unexpected `const`".to_string(),
                span: span.clone(),
                color: Color::Red,
            }],
            ExpectedIntegerLiteral { span } => vec![ErrorLabel {
                message: "expecting a 64-bit integer here".to_string(),
                span: span.clone(),
                color: Color::Red,
            }],
        }
    }

    fn note(&self) -> Option<String> {
        use ParseError::*;
        match self {
            NameClash { sym, .. } => Some(format!(
                "`{sym}` must be declared or imported only once in this scope"
            )),
            BinaryLiteralLength { .. } => {
                Some("number of digits must be either 256 or between 1 and 64".to_string())
            }
            HexLiteralLength { .. } => {
                Some("number of digits must be either 64 or between 1 and 16".to_string())
            }
            IntLiteralTooLarge { .. } => {
                Some("value exceeds limit of `9,223,372,036,854,775,807`".to_string())
            }
            _ => None,
        }
    }

    fn code(&self) -> Option<String> {
        None
    }

    fn help(&self) -> Option<String> {
        use ParseError::*;
        match self {
            UnsupportedLeadingPlus { .. } => Some("try removing the `+`".to_string()),
            UnsupportedConstLocation { .. } => {
                Some("try declaring the const outside the body of the `predicate`".to_string())
            }
            _ => None,
        }
    }
}

fn format_optional_token(token: &Option<String>) -> String {
    match &token {
        Some(token) => format!("`{token}`"),
        None => "\"end of input\"".into(),
    }
}

fn format_expected_tokens_message(expected: &mut [Option<String>]) -> String {
    format!(
        "expected {}",
        match expected {
            [] => "something else".to_string(),
            [expected] => format_optional_token(&lexer::get_token_error_category(expected)),
            _ => {
                let mut expected: Vec<Option<String>> = expected
                    .iter()
                    .map(lexer::get_token_error_category)
                    .collect::<FxHashSet<_>>() // Remove duplicates
                    .into_iter()
                    .collect();

                // Make sure that the list of expected tokens is printed in a deterministic order
                expected.sort();

                let mut token_list = String::new();
                for expected in &expected[..expected.len() - 1] {
                    token_list = format!("{token_list}{}, ", format_optional_token(expected));
                }
                format!(
                    "{token_list}or {}",
                    format_optional_token(expected.last().unwrap())
                )
            }
        }
    )
}

fn format_expected_found_error(expected: &mut [Option<String>], found: &Option<String>) -> String {
    format!(
        "{}, found {}",
        format_expected_tokens_message(expected),
        format_optional_token(found),
    )
}

impl Spanned for ParseError {
    fn span(&self) -> &Span {
        use ParseError::*;
        match self {
            ExpectedFound { span, .. }
            | EmptyIndexAccess { span }
            | InvalidIntegerTupleIndex { span, .. }
            | InvalidTupleIndex { span, .. }
            | EmptyTupleExpr { span, .. }
            | EmptyTupleType { span, .. }
            | NameClash { span, .. }
            | UnsupportedLeadingPlus { span, .. }
            | SelfWithEmptyPrefix { span, .. }
            | SelfNotAtTheEnd { span, .. }
            | BinaryLiteralLength { span, .. }
            | HexLiteralLength { span, .. }
            | IntLiteralTooLarge { span, .. }
            | TooManyStorageBlocks { span, .. }
            | StorageDirectiveMustBeTopLevel { span, .. }
            | StorageAccessMustBeTopLevel { span, .. }
            | BadSplice(span)
            | MissingIntrinsic { span, .. }
            | TypeNotSupported { span, .. }
            | LiteralNotSupported { span, .. }
            | UnsupportedConstLocation { span, .. }
            | ExpectedIntegerLiteral { span, .. }
            | Lex { span } => span,

            InvalidToken => unreachable!("The `InvalidToken` error is always wrapped in `Lex`."),
        }
    }
}

type LalrpopError = lalrpop_util::ParseError<usize, Token, ParseError>;

impl From<(LalrpopError, &Arc<Path>)> for ParseError {
    fn from(err_and_path: (LalrpopError, &Arc<Path>)) -> Self {
        fn span_at(src_path: &Arc<Path>, start: usize, end: usize) -> Span {
            Span {
                context: src_path.clone(),
                range: start..end,
            }
        }

        let parse_err = err_and_path.0;
        let src_path = err_and_path.1;

        match parse_err {
            lalrpop_util::ParseError::InvalidToken { location } => ParseError::Lex {
                span: span_at(src_path, location, location + 1),
            },
            lalrpop_util::ParseError::UnrecognizedEof { location, expected } => {
                ParseError::ExpectedFound {
                    span: span_at(src_path, location, location), // Not going to send span beyond EOF..?
                    expected: expected
                        .into_iter()
                        .map(|mut expected| {
                            expected.retain(|c| c != '\"');
                            Some(expected)
                        })
                        .collect(),
                    found: Some("end of file".to_owned()),
                }
            }
            lalrpop_util::ParseError::UnrecognizedToken {
                token: (start, tok, end),
                expected,
            } => ParseError::ExpectedFound {
                span: span_at(src_path, start, end),
                expected: expected
                    .into_iter()
                    .map(|mut expected| {
                        expected.retain(|c| c != '\"');
                        Some(expected)
                    })
                    .collect(),
                found: Some(tok.to_string()),
            },
            lalrpop_util::ParseError::ExtraToken {
                token: (start, tok, end),
            } => ParseError::ExpectedFound {
                span: span_at(src_path, start, end),
                expected: vec![Some("end of file".to_string())],
                found: Some(tok.to_string()),
            },
            lalrpop_util::ParseError::User { error } => error,
        }
    }
}