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
pub mod diagnostic;
/// The stringable module provides the Stringable enumerated type.
/// This type makes it easier to represent varied formattable values.
pub mod stringable;

use codespan_reporting::{
    files::SimpleFiles,
    term::{
        self,
        termcolor::{ColorChoice, StandardStream},
    },
};
use diagnostic::Diagnostic;
use linked_hash_set::LinkedHashSet;
use stringable::Stringable;

/// This type is used in lew of `Result` or `Option`.
/// It provides for fallible return types with the possibility for
/// multiple causes of failure and for embedding the hierarchical context
/// of failures in the result.
///
/// A CompilerResult that is returned from a function is considered to have failed
/// if it either has no value or encountered an error in trying to obtain one.
#[derive(Debug)]
pub struct CompilerResult<T> {
    /// The name for the current task being undertaken in
    /// the function returning this value
    task_name: Option<Stringable>,
    /// The result value, if one exists.
    value: Option<T>,
    /// Whether the result has irrecoverably failed.
    status: Status,
    /// Whether the result contains warnings.
    contains_warnings: bool,
    /// The compiler results this one depends on.
    children: Vec<CompilerResult<()>>,
    /// The errors encountered in performing the task.
    errors: LinkedHashSet<Diagnostic>,
    /// The warnings encountered in performing the task.
    warnings: LinkedHashSet<Diagnostic>,
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Status {
    Unresolved,
    Passed,
    Failed,
}

impl CompilerResult<()> {
    /// Creates a compiler result that's return type is (), the unit type.
    /// This differs from creating a normal result, because you never expect to set the value.
    /// Instead, it is initialized for you to nothing.
    pub fn status_only<M>(task_name: M) -> Self
    where
        M: Into<Stringable>,
    {
        CompilerResult {
            task_name: Some(task_name.into()),
            status: Status::Unresolved,
            contains_warnings: false,
            children: Vec::new(),
            errors: LinkedHashSet::new(),
            warnings: LinkedHashSet::new(),

            // Initialization to this value indicates the expected value (nothing) was found
            value: Some(()),
        }
    }
}

impl<T> CompilerResult<T> {
    /// Creates a compiler result with the task name and initializes all fields.
    pub fn new<M>(task_name: M) -> Self
    where
        M: Into<Stringable>,
    {
        CompilerResult {
            task_name: Some(task_name.into()),
            value: None,
            status: Status::Unresolved,
            contains_warnings: false,
            children: Vec::new(),
            errors: LinkedHashSet::new(),
            warnings: LinkedHashSet::new(),
        }
    }

    /// Creates a compiler result that has no name.
    /// This is useful if you have a helper task,
    /// but that isn't worth displaying in itself in the output.
    /// Such tasks do not have real names anyway.
    pub fn unnamed() -> Self {
        CompilerResult {
            task_name: None,
            value: None,
            status: Status::Unresolved,
            contains_warnings: false,
            children: Vec::new(),
            errors: LinkedHashSet::new(),
            warnings: LinkedHashSet::new(),
        }
    }

    /// Return the status of this CompilerResult
    pub fn get_status(&self) -> Status {
        self.status
    }

    /// Fails and releases the value associated with this compiler result
    fn fail(&mut self) {
        self.status = Status::Failed;
        self.value = None;
    }

    /// Passes this compiler result
    fn pass(&mut self) {
        self.status = Status::Passed;
    }

    /// This method means "I depend on this thing and if it failed, then I have failed for that reason".
    /// It accepts anything that can be made Reportable (check the From implementations in this module).
    /// If the provided reportable failed, it causes this compiler result to fail and the message to be correctly attached.
    /// If the reportable succeeded and has a value, this is provided to the caller, if not, None is returned.
    pub fn require<R, T2>(&mut self, other: R) -> Option<T2>
    where
        R: Into<Reportable<T2>>,
    {
        match other.into() {
            Reportable::CompilerResult(cres) => {
                // This conversion into diagnostic mainly exists to separate the value from the result.
                let (value, status_only) = cres.into_status_only();

                if status_only.get_status() == Status::Failed {
                    self.fail();
                }
                if status_only.contains_warnings {
                    self.contains_warnings = true;
                }
                self.children.push(status_only);
                value
            }
            Reportable::Value(val) => Some(val),
            Reportable::Failure(message) => {
                self.error(message);
                None
            }
        }
    }

    /// Assert acts as a way to make this compiler result conditional on some check.
    /// This could be a bounds check or any other computation producing a boolean value.
    pub fn assert<M>(&mut self, condition: bool, message: M)
    where
        M: Into<Diagnostic>,
    {
        if !condition {
            self.fail();
            self.errors.insert(message.into());
        }
    }

    /// This function fails the compiler result and attaches the associated error.
    pub fn error<M>(&mut self, message: M)
    where
        M: Into<Diagnostic>,
    {
        self.fail();
        self.errors.insert(message.into());
    }

    /// This function attaches the associated warning to the compiler result.
    pub fn warning<M>(&mut self, message: M)
    where
        M: Into<Diagnostic>,
    {
        self.contains_warnings = true;
        self.warnings.insert(message.into());
    }

    /// Assigns a value to this compiler result.
    /// Note: it only actually stores the value if the result might eventually be used.
    pub fn set_value(&mut self, value: T) {
        if self.get_status() != Status::Failed {
            self.value = Some(value);
            self.pass();
        }
    }

    /// A version of `set_value` that can be used to make simpler returns.
    pub fn with_value(mut self, value: T) -> Self {
        self.set_value(value);
        self
    }

    /// Splits a compiler result into its value and diagnostic.
    fn into_status_only(self) -> (Option<T>, CompilerResult<()>) {
        let status = self.get_status();
        let value = self.value;
        let diagnostic = CompilerResult {
            task_name: self.task_name,
            value: Some(()),
            status: status.clone(),
            contains_warnings: self.contains_warnings,
            children: self.children,
            errors: self.errors,
            warnings: self.warnings,
        };
        (value, diagnostic)
    }

    /// Takes another compiler result, requires it, and then uses its value.
    pub fn set(&mut self, other: CompilerResult<T>) {
        if let Some(value) = self.require(other) {
            self.set_value(value);
        }
    }

    /// Effectively requires a Result and uses its value
    /// as the compiler results own value
    pub fn set_res<E>(&mut self, res: Result<T, E>)
    where
        E: Into<Diagnostic>,
    {
        match res {
            Ok(value) => self.set_value(value),
            Err(error) => self.error(error),
        }
    }

    /// Converts this compiler result into an option.
    /// Warning: This destroys all error messages and context.
    pub fn to_option(self) -> Option<T> {
        self.value
    }

    /// Wraps the print function by creating an empty definition of codespan simplefiles
    /// Used primarily in unit tests where there are no files which are read from or maintained
    /// in a SimpleFiles database
    pub fn print_dummy_files(&self) -> Result<(), codespan_reporting::files::Error> {
        let files: SimpleFiles<String, String> = SimpleFiles::new();
        self.print(&files)
    }

    /// Prints out the result and all of its context and messages.
    pub fn print(
        &self,
        files: &SimpleFiles<String, String>,
    ) -> Result<(), codespan_reporting::files::Error> {
        let writer = StandardStream::stderr(ColorChoice::Always);
        let config = codespan_reporting::term::Config::default();

        if let Some(name) = &self.task_name {
            println!("{}", name);
        }

        for error in self.errors.iter() {
            let diagnostic = error.print_error();
            term::emit(&mut writer.lock(), &config, files, &diagnostic)?;
        }

        for warning in self.warnings.iter() {
            let diagnostic = warning.print_warning();
            term::emit(&mut writer.lock(), &config, files, &diagnostic)?;
        }

        for child in self.children.iter() {
            child.print_helper(0, files)?;
        }

        if self.get_status() == Status::Failed {
            println!("FAILED")
        } else {
            print!("SUCCEEDED");
            if !self.warnings.is_empty() {
                print!(" with {} warnings", self.warnings.len());
            }
            println!("");
        }
        Ok(())
    }

    /// A recursive helper that uses the `level` parameter to
    /// keep track of the amount of nesting in the hierarchy.
    fn print_helper(
        &self,
        level: usize,
        files: &SimpleFiles<String, String>,
    ) -> Result<(), codespan_reporting::files::Error> {
        let writer = StandardStream::stderr(ColorChoice::Always);
        let config = codespan_reporting::term::Config::default();

        let mut next_level = level;

        if self.get_status() == Status::Failed || self.contains_warnings {
            if let Some(name) = &self.task_name {
                println!("+{} {}", "+".repeat(level), name);
                next_level += 1;
            }
        }

        for error in self.errors.iter() {
            let diagnostic = error.print_error();
            term::emit(&mut writer.lock(), &config, files, &diagnostic)?;
        }

        for warning in self.warnings.iter() {
            let diagnostic = warning.print_warning();
            term::emit(&mut writer.lock(), &config, files, &diagnostic)?;
        }

        for child in self.children.iter() {
            child.print_helper(next_level, files)?;
        }

        Ok(())
    }
}

/// An experimental implementation to provide iterator features.
/// Use with cautions.
impl<T> CompilerResult<Vec<T>> {
    fn push_other(&mut self, other: CompilerResult<T>) {
        if let Some(other_val) = self.require(other) {
            if let Some(current_val) = &mut self.value {
                current_val.push(other_val);
            }
        }
    }

    /// Allows you to convert an iterator of CompilerResult<T> into a single CompilerResult<Vec<T>>.
    pub fn collect<I>(&mut self, iter: I)
    where
        I: Iterator<Item = CompilerResult<T>>,
    {
        for other in iter {
            self.push_other(other);
        }
    }
}

pub enum Reportable<T> {
    /// Complex compiler results
    CompilerResult(CompilerResult<T>),
    /// Successfully produced values.
    Value(T),
    /// Failures with messages
    Failure(Diagnostic),
}

// Allows Options with Stringable messages to be considered reportable
impl<T, M> From<(Option<T>, M)> for Reportable<T>
where
    M: Into<Diagnostic>,
{
    fn from(other: (Option<T>, M)) -> Self {
        match other {
            (Some(val), _) => Reportable::Value(val),
            (None, message) => Reportable::Failure(message.into()),
        }
    }
}

// Allows Results where the error value is Stringable to be considered reportable
impl<T, M> From<Result<T, M>> for Reportable<T>
where
    M: Into<Diagnostic>,
{
    fn from(other: Result<T, M>) -> Self {
        match other {
            Ok(val) => Reportable::Value(val),
            Err(message) => Reportable::Failure(message.into()),
        }
    }
}

// Allows Results with Stringable messages to be considered reportable.
// This ignores the results Err(v) value and instead uses the message.
impl<T, M, N> From<(Result<T, N>, M)> for Reportable<T>
where
    M: Into<Diagnostic>,
{
    fn from(other: (Result<T, N>, M)) -> Self {
        match other {
            (Ok(val), _) => Reportable::Value(val),
            (Err(_), message) => Reportable::Failure(message.into()),
        }
    }
}

// Allows compiler results to be reportable.
impl<T> From<CompilerResult<T>> for Reportable<T> {
    fn from(other: CompilerResult<T>) -> Self {
        Reportable::CompilerResult(other)
    }
}

/// The check! macro fills the same role as the "?" operator,
/// but for CompilerResults instead of Option or Result.
/// This means that it returns the unwrapped value behind a result,
/// and causes the function to return early with a failed result if it cannot.
///
/// This macro is called with two or three parameters.
/// The first parameter is always the CompilerResult for the current function.
/// The second parameter is the CompilerResult, Result, or Option being checked.
/// The third parameter (only used with Result or Option) is the optional message.
#[macro_export]
macro_rules! check {
    ($res:ident, $other:expr) => {{
        use crate::result::Reportable;

        if let Some(value) = $res.require(Reportable::from($other)) {
            value
        } else {
            return $res;
        }
    }};
    ($res:ident, $other:expr, $message:expr) => {{
        use crate::result::Reportable;

        if let Some(value) = $res.require(Reportable::from(($other, $message))) {
            value
        } else {
            return $res;
        }
    }};
}

/// Assign is a macro that provides enhanced features similar to set() and set_value().
macro_rules! assign {
    ($res:ident, $other:expr) => {{
        use crate::result::Reportable;

        if let Some(value) = $res.require(Reportable::from($other)) {
            $res.set_value(value);
        }
    }};
    ($res:ident, $other:expr, $message:expr) => {{
        use crate::result::Reportable;

        if let Some(value) = $res.require(Reportable::from(($other, $message))) {
            $res.set_value(value);
        }
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_status_passed() {
        let mut res = CompilerResult::status_only("Test True");
        res.assert(true, "asserting true");
        // TODO: Determine what assert will return
        assert_eq!(res.get_status(), Status::Unresolved);
    }

    #[test]
    fn test_assert_false() {
        let mut res = CompilerResult::status_only("Test False");
        res.assert(false, "asserting false");
        assert_eq!(res.get_status(), Status::Failed);
    }

    #[test]
    fn test_require_passed() {
        let mut res: CompilerResult<i32> = CompilerResult::new("Test i32");
        res.set_value(8);
        let mut res_2: CompilerResult<u32> = CompilerResult::new("Test u32");
        res_2.set_value(10);
        res.require(res_2);
        assert_eq!(res.get_status(), Status::Passed);
    }

    #[test]
    fn test_require_failed() {
        let mut res: CompilerResult<i32> = CompilerResult::new("Test i32");
        let mut res_2: CompilerResult<u32> = CompilerResult::new("Test u32");
        res_2.assert(false, "asserting false");
        res.require(res_2);
        assert_eq!(res.get_status(), Status::Failed);
    }

    #[test]
    fn test_collect_all_failed() {
        let mut failed_result: CompilerResult<i32> = CompilerResult::unnamed();
        let mut failed_result2: CompilerResult<i32> = CompilerResult::unnamed();

        failed_result.fail();
        failed_result2.fail();

        let list_results = vec![failed_result, failed_result2];
        let mut cr_result: CompilerResult<Vec<i32>> = CompilerResult::new("Task name");
        cr_result.set_value(Vec::new());
        cr_result.collect(list_results.into_iter());

        assert_eq!(Status::Failed, cr_result.get_status());
    }

    #[test]
    fn test_collect_one_failed() {
        let mut failed_result: CompilerResult<i32> = CompilerResult::unnamed();
        let mut passed_result: CompilerResult<i32> = CompilerResult::unnamed();
        let mut passed_result2: CompilerResult<i32> = CompilerResult::unnamed();

        failed_result.fail();
        passed_result.set_value(0);
        passed_result2.set_value(1);

        let list_results = vec![failed_result, passed_result, passed_result2];
        let mut cr_result: CompilerResult<Vec<i32>> = CompilerResult::new("Task name");
        cr_result.set_value(Vec::new());
        cr_result.collect(list_results.into_iter());

        assert_eq!(Status::Failed, cr_result.get_status());
    }

    #[test]
    fn test_collect_some_failed() {
        let mut failed_result: CompilerResult<i32> = CompilerResult::unnamed();
        let mut failed_result2: CompilerResult<i32> = CompilerResult::unnamed();
        let mut passed_result: CompilerResult<i32> = CompilerResult::unnamed();

        failed_result.fail();
        failed_result2.fail();
        passed_result.set_value(0);

        let list_results = vec![failed_result, failed_result2, passed_result];
        let mut cr_result: CompilerResult<Vec<i32>> = CompilerResult::new("Task name");
        cr_result.set_value(Vec::new());
        cr_result.collect(list_results.into_iter());

        assert_eq!(Status::Failed, cr_result.get_status());
    }

    #[test]
    fn test_collect_all_passed() {
        let mut passed_result: CompilerResult<i32> = CompilerResult::unnamed();
        let mut passed_result2: CompilerResult<i32> = CompilerResult::unnamed();

        passed_result.set_value(1);
        passed_result2.set_value(2);

        let list_results = vec![passed_result, passed_result2];
        let mut cr_result: CompilerResult<Vec<i32>> = CompilerResult::new("Task name");
        cr_result.set_value(Vec::new());
        cr_result.collect(list_results.into_iter());

        assert_eq!(Status::Passed, cr_result.get_status());
    }
}