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
use core::fmt;

use crate as rune;
use crate::alloc::prelude::*;
use crate::ast::{Span, Spanned};
use crate::SourceId;

/// A fully descriptive location which is a combination of a [SourceId] and a
/// [Span].
#[derive(Default, TryClone, Clone, Copy)]
#[try_clone(copy)]
#[non_exhaustive]
pub struct Location {
    /// The source id of the file of the location.
    pub source_id: SourceId,
    /// The span of the location.
    pub span: Span,
}

impl Location {
    /// Construct a new location.
    pub const fn new(source_id: SourceId, span: Span) -> Self {
        Self { source_id, span }
    }
}

impl Spanned for Location {
    #[inline]
    fn span(&self) -> Span {
        self.span
    }
}

impl Located for Location {
    #[inline]
    fn location(&self) -> Location {
        *self
    }

    #[inline]
    fn as_spanned(&self) -> &dyn Spanned {
        self
    }
}

impl Spanned for dyn Located {
    #[inline]
    fn span(&self) -> Span {
        self.as_spanned().span()
    }
}

/// Trait for things that have a [Location].
pub trait Located {
    /// Get the assocaited location.
    fn location(&self) -> Location;

    /// Get located item as spanned.
    fn as_spanned(&self) -> &dyn Spanned;
}

pub(crate) struct DynLocation<S> {
    source_id: SourceId,
    span: S,
}

impl<S> DynLocation<S> {
    #[inline(always)]
    pub(crate) const fn new(source_id: SourceId, span: S) -> Self {
        Self { source_id, span }
    }
}

impl<S> Spanned for DynLocation<S>
where
    S: Spanned,
{
    #[inline]
    fn span(&self) -> Span {
        self.span.span()
    }
}

impl<S> Located for DynLocation<S>
where
    S: Spanned,
{
    #[inline]
    fn location(&self) -> Location {
        Location {
            source_id: self.source_id,
            span: self.span.span(),
        }
    }

    #[inline]
    fn as_spanned(&self) -> &dyn Spanned {
        self
    }
}

impl fmt::Debug for Location {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Location")
            .field(&self.source_id)
            .field(&self.span)
            .finish()
    }
}