pliron 0.15.0

Programming Languages Intermediate RepresentatiON
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Utilities for error handling
//!
//! - [ErrorKind] describes the kind of error.
//! - [struct@Error] is the main error type used throughout the compiler. This `struct` contains
//!   the field `err` which holds the actual error that implements [AnyError]. [AnyError] is an
//!   extension trait to enforce [std::error::Error] + [Downcast].
//! - [Result] is an alias for `std::result::Result` with the error type set to [struct@Error].
//!   [Result] implements [ExpectOk], which provides a method [expect_ok](ExpectOk::expect_ok)
//!   to `unwrap` the result, and if that fails, panics with the error message printed using
//!   [Printable].
//!
//! The following macros are provided to conveniently create [struct@Error] and [Result] objects.
//!   - [input_error_noloc]: Create [struct@Error] for input errors without location information
//!   - [input_error]: Create [struct@Error] for input errors with location information
//!   - [input_err_noloc]: Create [Result] for input errors without location information
//!   - [input_err]: Create [Result] for input errors with location information
//!   - [verify_error_noloc]: Create [struct@Error] for verification errors without location information
//!   - [verify_error]: Create [struct@Error] for verification errors with location information
//!   - [verify_err_noloc]: Create [Result] for verification errors without location information
//!   - [verify_err]: Create [Result] for verification errors with location information
//!   - [arg_error_noloc]: Create [struct@Error] for argument errors without location information
//!   - [arg_error]: Create [struct@Error] for argument errors with location information
//!   - [arg_err_noloc]: Create [Result] for argument errors without location information
//!   - [arg_err]: Create [Result] for argument errors with location information
//!
//! The inner `err` when constructing [struct@Error] is typically a custom error type
//! that derives [std::error::Error] using [thiserror].
//!
//! ```
//! use thiserror::Error;
//! use expect_test::expect;
//! use pliron::{
//!     context::Context,
//!     input_error_noloc, result::Error
//! };
//!
//! #[derive(Error, Debug)]
//! #[error("This is my error: {0}")]
//! pub struct MyError(String);
//!
//! let err: Error = input_error_noloc!(MyError("Something went wrong".to_string()));
//! expect![[r#"
//!     Compilation error: invalid input program.
//!     This is my error: Something went wrong"#
//! ]].assert_eq(&err.to_string());
//! ```
//!
//! The [struct@Error] type can be printed without [Context], as in the example above.
//! For more informational error messages (such as including a source location),
//! it should be printed using [Printable], passing the [Context].
//!
//! Sometimes the error object may need [Context] for better / more convenient
//! formatting. In such cases, they can implement [Printable] and mark themselves
//! using [type_to_trait]. [struct@Error]'s [Printable] implementation will check if
//! the inner error implements [Printable] and use it if available.
//!
//! ```rust
//! use std::fmt::Display;
//! use expect_test::expect;
//! use thiserror::Error;
//! use pliron::{
//!     context::Context,
//!     printable::{State, Printable},
//!     type_to_trait, input_error_noloc, result::Error
//! };
//!
//! #[derive(Debug, Error)]
//! #[error("Error displayed using std::fmt::Display: {0}")]
//! pub struct PrintableErr(String);

//! impl Printable for PrintableErr {
//!     fn fmt(
//!         &self,
//!         ctx: &Context,
//!         state: &State,
//!         f: &mut std::fmt::Formatter<'_>,
//!     ) -> std::fmt::Result {
//!         write!(f, "Error printed using Printable: {}", self.0)
//!     }
//! }
//!
//! /// Marking `PrintableErr` as implementing `Printable` enables
//! /// `dyn AnyError` to be downcasted to `dyn Printable`.
//! type_to_trait!(PrintableErr, Printable);
//!
//! let ctx = &mut Context::new();
//! let res: Error = input_error_noloc!(PrintableErr("Test error".to_string()));
//! expect![[r#"
//!     Compilation error: invalid input program.
//!     Error printed using Printable: Test error"#
//! ]].assert_eq(&res.disp(ctx).to_string());
//! ```

#[cfg(doc)]
use crate::{
    arg_err, arg_err_noloc, arg_error, arg_error_noloc, input_err, input_err_noloc, input_error,
    input_error_noloc, type_to_trait, verify_err, verify_err_noloc, verify_error,
    verify_error_noloc,
};

use std::{
    backtrace::{Backtrace, BacktraceStatus},
    fmt::Display,
};

use downcast_rs::{Downcast, impl_downcast};
use thiserror::Error;

use crate::{
    context::Context,
    location::{Located, Location},
    printable::{Printable, State},
    utils::trait_cast::any_to_trait,
};

/// A wrapper trait combining [`std::error::Error`] and [`downcast_rs::Downcast`]
/// to allow upcasting to [Any](std::any::Any), so that, we can downcast it
/// to the [Printable] trait if the error implements it.
pub trait AnyError: std::error::Error + Send + Sync + 'static + Downcast {}
impl<T: std::error::Error + Send + Sync + 'static> AnyError for T {}
impl_downcast!(AnyError);

/// The kinds of errors we have during compilation.
#[derive(Debug, Error)]
pub enum ErrorKind {
    /// Something's wrong with the program being compiled
    #[error("invalid input program")]
    InvalidInput,
    /// The IR was found to be inconsistent or invalid during verification
    #[error("verification failed")]
    VerificationFailed,
    /// Inconsistent or invalid argument(s) passed to a pliron function.
    #[error("invalid argument")]
    InvalidArgument,
}

/// An error object that can hold any [std::error::Error].
#[derive(Debug)]
pub struct Error {
    /// The kind of error this is
    pub kind: ErrorKind,
    /// The actual error object describing the error
    pub err: Box<dyn AnyError>,
    /// Location of this error in the code being compiled
    pub loc: Location,
    /// Details of how this error occurred
    pub backtrace: Backtrace,
}

impl std::error::Error for Error {}

/// This does not print [Location] or [Backtrace]. Use [Printable::disp] for that.
impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Compilation error: {}.\n{}", self.kind, self.err)
    }
}

impl Printable for Error {
    fn fmt(
        &self,
        ctx: &Context,
        _state: &State,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        if self.loc.is_unknown() {
            writeln!(f, "Compilation error: {}.", self.kind,)
        } else {
            writeln!(
                f,
                "[{}] Compilation error: {}.",
                self.loc.disp(ctx),
                self.kind,
            )
        }?;

        if let Some(self_val) = self.err.downcast_ref::<Error>() {
            write!(f, "{}", self_val.disp(ctx))?;
        } else if let Some(self_val) = any_to_trait::<dyn Printable>((*self.err).as_any()) {
            write!(f, "{}", self_val.disp(ctx))?;
        } else {
            write!(f, "{}", self.err)?;
            if self.backtrace.status() == BacktraceStatus::Captured {
                write!(f, "\nError backtrace:\n{}", self.backtrace)?;
            }
        }

        Ok(())
    }
}

impl Located for Error {
    fn loc(&self) -> Location {
        self.loc.clone()
    }

    fn set_loc(&mut self, loc: Location) {
        self.loc = loc;
    }
}

/// Type alias for [std::result::Result] with the error type set to [struct@Error]
pub type Result<T> = std::result::Result<T, Error>;

impl<T: Printable> Printable for Result<T> {
    fn fmt(
        &self,
        ctx: &Context,
        state: &State,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Ok(val) => val.fmt(ctx, state, f),
            Err(err) => Printable::fmt(err, ctx, state, f),
        }
    }
}

/// Same as `unwrap`, but with the panic message printed using [Printable].
pub trait ExpectOk<T> {
    /// Unwraps the result, panicking if it is an error.
    #[track_caller]
    fn expect_ok(self, ctx: &Context) -> T;
}

impl<T> ExpectOk<T> for Result<T> {
    fn expect_ok(self, ctx: &Context) -> T {
        match self {
            Ok(val) => val,
            Err(err) => {
                panic!("{}", err.disp(ctx))
            }
        }
    }
}

#[doc(hidden)]
#[derive(Debug, Error)]
#[error("{0}")]
pub struct StringError(pub String);

/// Specify [ErrorKind] and create [struct@Error] from any [std::error::Error] object.
/// To create [Result], use [create_err!](crate::create_err) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// It may be shorter to just use [verify_error!](crate::verify_error),
/// [input_error!](crate::input_error) or [arg_error!](crate::arg_error) instead.
#[macro_export]
macro_rules! create_error {
    ($loc: expr, $kind: expr, $str: literal $($t:tt)*) => {
        $crate::create_error!($loc, $kind, $crate::result::StringError(format!($str $($t)*)))
    };
    ($loc: expr, $kind: expr, $err: expr) => {
        $crate::result::Error {
            kind: $kind,
            err: Box::new($err),
            loc: $loc,
            backtrace: std::backtrace::Backtrace::capture(),
        }
    };
}

/// Specify [ErrorKind] and create [Result] from any [std::error::Error] object.
/// To create [struct@Error], use [create_error!](crate::create_error) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// It may be shorter to just use [verify_err!](crate::verify_err),
/// [input_err!](crate::input_err) or [arg_err!](crate::arg_err) instead.
#[macro_export]
macro_rules! create_err {
    ($loc: expr, $kind: expr, $str: literal $($t:tt)*) => {
        $crate::create_err!($loc, $kind, $crate::result::StringError(format!($str $($t)*)))
    };
    ($loc: expr, $kind: expr, $err: expr) => {
        Err($crate::create_error!($loc, $kind, $err))
    };
}

// Create [ErrorKind::VerificationFailed] [struct@Error] from any [std::error::Error] object.
/// To create [Result], use [verify_err!](crate::verify_err) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// ```rust
/// use thiserror::Error;
/// use pliron::{verify_error, result::{Result, ErrorKind, Error}, location::Location};
///
/// #[derive(Error, Debug)]
/// #[error("sample error")]
/// pub struct SampleErr;
///
/// assert!(
///     matches!(
///         verify_error!(Location::Unknown, SampleErr),
///         Error {
///            kind: ErrorKind::VerificationFailed,
///            err,
///            ..
///         } if err.is::<SampleErr>()
/// ));
///
/// let res_msg: Error = verify_error!(Location::Unknown, "Some formatted {}", 0);
/// assert_eq!(
///     res_msg.err.to_string(),
///     "Some formatted 0"
/// );
/// ```
#[macro_export]
macro_rules! verify_error {
    ($loc: expr, $($t:tt)*) => {
        $crate::create_error!($loc, $crate::result::ErrorKind::VerificationFailed, $($t)*)
    }
}

/// Create [ErrorKind::VerificationFailed] [Result] from any [std::error::Error] object.
/// To create [struct@Error], use [verify_error!](crate::verify_error) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// ```rust
/// use thiserror::Error;
/// use pliron::{verify_err, result::{Result, ErrorKind, Error}, location::Location};
///
/// #[derive(Error, Debug)]
/// #[error("sample error")]
/// pub struct SampleErr;
///
/// assert!(
///     matches!(
///         verify_err!(Location::Unknown, SampleErr),
///         Result::<()>::Err(Error {
///            kind: ErrorKind::VerificationFailed,
///            err,
///            ..
///         }) if err.is::<SampleErr>()
/// ));
///
/// let res_msg: Result<()> = verify_err!(Location::Unknown, "Some formatted {}", 0);
/// assert_eq!(
///     res_msg.unwrap_err().err.to_string(),
///     "Some formatted 0"
/// );
/// ```
#[macro_export]
macro_rules! verify_err {
    ($loc: expr, $($t:tt)*) => {
        $crate::create_err!($loc, $crate::result::ErrorKind::VerificationFailed, $($t)*)
    }
}

/// Create [ErrorKind::InvalidInput] [struct@Error] from any [std::error::Error] object.
/// To create [Result], use [input_err!](crate::input_err) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// ```rust
/// use thiserror::Error;
/// use pliron::{input_error, result::{Result, ErrorKind, Error}, location::Location};
///
/// #[derive(Error, Debug)]
/// #[error("sample error")]
/// pub struct SampleErr;
///
/// assert!(
///     matches!(
///         input_error!(Location::Unknown, SampleErr),
///         Error {
///            kind: ErrorKind::InvalidInput,
///            err,
///            ..
///         } if err.is::<SampleErr>()
/// ));
///
/// let res_msg: Error = input_error!(Location::Unknown, "Some formatted {}", 0);
/// assert_eq!(
///     res_msg.err.to_string(),
///     "Some formatted 0"
/// );
/// ```
#[macro_export]
macro_rules! input_error {
    ($loc: expr, $($t:tt)*) => {
        $crate::create_error!($loc, $crate::result::ErrorKind::InvalidInput, $($t)*)
    }
}

/// Create [ErrorKind::InvalidInput] [Result] from any [std::error::Error] object.
/// To create [struct@Error], use [input_error!](crate::input_error) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// ```rust
/// use thiserror::Error;
/// use pliron::{input_err, result::{Result, ErrorKind, Error}, location::Location};
///
/// #[derive(Error, Debug)]
/// #[error("sample error")]
/// pub struct SampleErr;
///
/// assert!(
///     matches!(
///         input_err!(Location::Unknown, SampleErr),
///         Result::<()>::Err(Error {
///            kind: ErrorKind::InvalidInput,
///            err,
///            ..
///         }) if err.is::<SampleErr>()
/// ));
///
/// let res_msg: Result<()> = input_err!(Location::Unknown, "Some formatted {}", 0);
/// assert_eq!(
///     res_msg.unwrap_err().err.to_string(),
///     "Some formatted 0"
/// );
/// ```
#[macro_export]
macro_rules! input_err {
    ($loc: expr, $($t:tt)*) => {
        $crate::create_err!($loc, $crate::result::ErrorKind::InvalidInput, $($t)*)
    }
}

/// Create [ErrorKind::InvalidArgument] [struct@Error] from any [std::error::Error] object.
/// To create [Result], use [arg_err!](crate::arg_err) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// ```rust
/// use thiserror::Error;
/// use pliron::{arg_error, result::{Result, ErrorKind, Error}, location::Location};
///
/// #[derive(Error, Debug)]
/// #[error("sample error")]
/// pub struct SampleErr;
///
/// assert!(
///     matches!(
///         arg_error!(Location::Unknown, SampleErr),
///         Error {
///            kind: ErrorKind::InvalidArgument,
///            err,
///            ..
///         } if err.is::<SampleErr>()
/// ));
///
/// let res_msg: Error = arg_error!(Location::Unknown, "Some formatted {}", 0);
/// assert_eq!(
///     res_msg.err.to_string(),
///     "Some formatted 0"
/// );
/// ```
#[macro_export]
macro_rules! arg_error {
    ($loc: expr, $($t:tt)*) => {
        $crate::create_error!($loc, $crate::result::ErrorKind::InvalidArgument, $($t)*)
    }
}

/// Create [ErrorKind::InvalidArgument] [Result] from any [std::error::Error] object.
/// To create [struct@Error], use [arg_error!](crate::arg_error) instead.
/// The macro also accepts [format!] like arguments to create one-off errors.
/// ```rust
/// use thiserror::Error;
/// use pliron::{arg_err, result::{Result, ErrorKind, Error}, location::Location};
///
/// #[derive(Error, Debug)]
/// #[error("sample error")]
/// pub struct SampleErr;
///
/// assert!(
///     matches!(
///         arg_err!(Location::Unknown, SampleErr),
///         Result::<()>::Err(Error {
///            kind: ErrorKind::InvalidArgument,
///            err,
///            ..
///         }) if err.is::<SampleErr>()
/// ));
///
/// let res_msg: Result<()> = arg_err!(Location::Unknown, "Some formatted {}", 0);
/// assert_eq!(
///     res_msg.unwrap_err().err.to_string(),
///     "Some formatted 0"
/// );
/// ```
#[macro_export]
macro_rules! arg_err {
    ($loc: expr, $($t:tt)*) => {
        $crate::create_err!($loc, $crate::result::ErrorKind::InvalidArgument, $($t)*)
    }
}

/// Same as [verify_error] but when no location is known.
#[macro_export]
macro_rules! verify_error_noloc {
    ($($t:tt)*) => {
        $crate::create_error!($crate::location::Location::Unknown, $crate::result::ErrorKind::VerificationFailed, $($t)*)
    }
}

/// Same as [verify_err] but when no location is known.
#[macro_export]
macro_rules! verify_err_noloc {
    ($($t:tt)*) => {
        $crate::create_err!($crate::location::Location::Unknown, $crate::result::ErrorKind::VerificationFailed, $($t)*)
    }
}

/// Same as [input_error] but when no location is known.
#[macro_export]
macro_rules! input_error_noloc {
    ($($t:tt)*) => {
        $crate::create_error!($crate::location::Location::Unknown, $crate::result::ErrorKind::InvalidInput, $($t)*)
    }
}

/// Same as [input_err] but when no location is known.
#[macro_export]
macro_rules! input_err_noloc {
    ($($t:tt)*) => {
        $crate::create_err!($crate::location::Location::Unknown, $crate::result::ErrorKind::InvalidInput, $($t)*)
    }
}

/// Same as [arg_error] but when no location is known.
#[macro_export]
macro_rules! arg_error_noloc {
    ($($t:tt)*) => {
        $crate::create_error!($crate::location::Location::Unknown, $crate::result::ErrorKind::InvalidArgument, $($t)*)
    }
}

/// Same as [arg_err] but when no location is known.
#[macro_export]
macro_rules! arg_err_noloc {
    ($($t:tt)*) => {
        $crate::create_err!($crate::location::Location::Unknown, $crate::result::ErrorKind::InvalidArgument, $($t)*)
    }
}

#[cfg(test)]
mod tests {

    use combine::stream::position::{Positioner, SourcePosition};
    use expect_test::expect;
    use thiserror::Error;

    use crate::{
        context::Context,
        location::{Location, Source},
        printable::Printable,
        type_to_trait,
    };

    #[derive(Debug, Error)]
    #[error("Test error")]
    pub struct TestErr;

    #[derive(Debug, Error)]
    pub struct PrintableErr(String);

    impl std::fmt::Display for PrintableErr {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "Display: {}", self.0)
        }
    }

    impl Printable for PrintableErr {
        fn fmt(
            &self,
            _ctx: &Context,
            _state: &crate::printable::State,
            f: &mut std::fmt::Formatter<'_>,
        ) -> std::fmt::Result {
            write!(f, "Printable: {}", self.0)
        }
    }
    // We want to be able to downcast `PrintableErr` as `Any` to `Printable`
    type_to_trait!(PrintableErr, Printable);

    #[test]
    fn wrapped_err() {
        let ctx = &mut Context::new();
        let src = Source::new_from_file(ctx, "/tmp/test.pliron".into());

        let pos1 = SourcePosition::default();
        let loc1 = Location::SrcPos { src, pos: pos1 };

        let mut pos2 = SourcePosition::default();
        pos2.update(&' ');
        let loc2 = Location::SrcPos { pos: pos2, src };

        let res = input_error!(loc2, TestErr);
        let wrapped_res = input_error!(loc1, res);
        let expected_err_msg = expect![[r#"
            ["/tmp/test.pliron": line: 1, column: 1] Compilation error: invalid input program.
            ["/tmp/test.pliron": line: 1, column: 2] Compilation error: invalid input program.
            Test error"#]];

        let actual_err = wrapped_res.disp(ctx).to_string();
        expected_err_msg.assert_eq(&actual_err);
    }

    #[test]
    fn printable_err() {
        let ctx = &mut Context::new();
        let src = Source::new_from_file(ctx, "/tmp/test.pliron".into());

        let pos = SourcePosition::default();
        let loc = Location::SrcPos { src, pos };

        let res = input_error!(loc, PrintableErr("Test error".to_string()));

        let expected_err_msg = expect![[r#"
            ["/tmp/test.pliron": line: 1, column: 1] Compilation error: invalid input program.
            Printable: Test error"#]];

        let actual_err = res.disp(ctx).to_string();
        expected_err_msg.assert_eq(&actual_err);
    }
}