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
#![feature(specialization)]
#![feature(const_fn)]

use lark_debug_derive::DebugWith;
use lark_debug_with::{DebugWith, FmtWithSpecialized};
use lark_error::{ErrorReported, ErrorSentinel};
use lark_intern::{Intern, Untern};
use lark_span::FileName;
use lark_string::{GlobalIdentifier, GlobalIdentifierTables};
use std::path::PathBuf;

lark_collections::index_type! {
    pub struct Entity { .. }
}

impl Entity {
    /// When we are dumping debug information about an entity, this
    /// method gives the directory (a relative path) where such files
    /// should be stored.
    pub fn dump_dir(
        &self,
        db: &(impl AsRef<EntityTables> + AsRef<GlobalIdentifierTables>),
    ) -> PathBuf {
        match self.untern(db) {
            EntityData::Error(err) => {
                let mut dir = PathBuf::new();
                dir.push("error");
                dir.push(format!("{}", err.span().file().id.untern(db)));
                dir
            }

            EntityData::LangItem(lang_item) => {
                let mut dir = PathBuf::new();
                dir.push(format!("{:?}", lang_item));
                dir
            }

            EntityData::InputFile { file } => {
                let mut dir = PathBuf::new();
                dir.push(format!("{}", file.untern(db)));
                dir
            }

            EntityData::ItemName { base, kind, id } => {
                let mut dir = base.dump_dir(db);
                dir.push(format!("{:?}", kind));
                dir.push(format!("{}", id.untern(db)));
                dir
            }

            EntityData::MemberName { base, kind, id } => {
                let mut dir = base.dump_dir(db);
                dir.push(format!("{:?}", kind));
                dir.push(format!("{}", id.untern(db)));
                dir
            }
        }
    }
}

#[derive(Clone, Debug, DebugWith, PartialEq, Eq, Hash)]
pub enum EntityData {
    /// Indicates that fetching the entity somehow failed with an
    /// error (which has been separately reported).
    Error(ErrorReported),

    LangItem(LangItem),

    InputFile {
        file: FileName,
    },
    ItemName {
        base: Entity,
        kind: ItemKind,
        id: GlobalIdentifier,
    },
    MemberName {
        base: Entity,
        kind: MemberKind,
        id: GlobalIdentifier,
    },
}

impl EntityData {
    /// Returns the parent entity, if any. This will be `Some` for
    /// items, members, etc.
    pub fn parent(&self) -> Option<Entity> {
        match self {
            EntityData::Error(_) | EntityData::LangItem(_) | EntityData::InputFile { .. } => None,
            EntityData::ItemName { base, .. } | EntityData::MemberName { base, .. } => Some(*base),
        }
    }

    /// Returns the file in which this entity is located (if
    /// any). This is none for lang items, errors.
    pub fn file_name(&self, db: &dyn AsRef<EntityTables>) -> Option<FileName> {
        match self {
            EntityData::InputFile { file } => Some(*file),
            _ => match self.parent() {
                None => None,
                Some(base) => base.untern(db).file_name(db),
            },
        }
    }

    /// Gives a little information about the name/kind of this entity,
    /// without dumping the whole tree. Meant for debugging.
    pub fn relative_name(self, db: &impl AsRef<GlobalIdentifierTables>) -> String {
        match self {
            EntityData::Error(_) => String::from("<error>"),
            EntityData::LangItem(li) => format!("{:?}", li),
            EntityData::InputFile { file } => format!("InputFile({})", file.untern(db)),
            EntityData::ItemName { id, .. } => format!("ItemName({})", id.untern(db)),
            EntityData::MemberName { id, .. } => format!("MemberName({})", id.untern(db)),
        }
    }

    /// True if this entity represents a value that the user could
    /// store into a variable (or might, in the case of error
    /// entities).
    pub fn is_value(&self) -> bool {
        match self {
            EntityData::InputFile { .. }
            | EntityData::ItemName {
                kind: ItemKind::Struct,
                ..
            }
            | EntityData::LangItem(LangItem::Int)
            | EntityData::LangItem(LangItem::Tuple(_))
            | EntityData::LangItem(LangItem::String)
            | EntityData::LangItem(LangItem::Uint)
            | EntityData::LangItem(LangItem::Boolean) => false,

            EntityData::ItemName {
                kind: ItemKind::Function,
                ..
            }
            | EntityData::MemberName {
                kind: MemberKind::Method,
                ..
            }
            | EntityData::MemberName {
                kind: MemberKind::Field,
                ..
            }
            | EntityData::LangItem(LangItem::True)
            | EntityData::LangItem(LangItem::False)
            | EntityData::LangItem(LangItem::Debug)
            | EntityData::Error(_) => true,
        }
    }

    /// True if this entity has a fn body associated with it.
    pub fn has_fn_body(&self) -> bool {
        match self {
            EntityData::InputFile { .. }
            | EntityData::ItemName {
                kind: ItemKind::Struct,
                ..
            }
            | EntityData::MemberName {
                kind: MemberKind::Field,
                ..
            }
            | EntityData::LangItem(_)
            | EntityData::Error(_) => false,

            EntityData::ItemName {
                kind: ItemKind::Function,
                ..
            }
            | EntityData::MemberName {
                kind: MemberKind::Method,
                ..
            } => true,
        }
    }
}

/// Struct definitions that are built-in to Lark.
///
/// Eventually, I would like these to be structs declared in some kind
/// of libcore -- though I'm not sure how tuple would work there.
#[derive(Copy, Clone, Debug, DebugWith, PartialEq, Eq, Hash)]
pub enum LangItem {
    Boolean,
    Int,
    Uint,
    Tuple(usize),
    String,
    True,
    False,
    Debug,
}

#[derive(Copy, Clone, Debug, DebugWith, PartialEq, Eq, Hash)]
pub enum ItemKind {
    Struct,
    Function,
}

#[derive(Copy, Clone, Debug, DebugWith, PartialEq, Eq, Hash)]
pub enum MemberKind {
    Field,
    Method,
}

lark_intern::intern_tables! {
    pub struct EntityTables {
        struct EntityTablesData {
            item_ids: map(Entity, EntityData),
        }
    }
}

lark_debug_with::debug_fallback_impl!(Entity);

impl<Cx> FmtWithSpecialized<Cx> for Entity
where
    Cx: AsRef<EntityTables>,
{
    fn fmt_with_specialized(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let data = self.untern(cx);
        data.fmt_with(cx, fmt)
    }
}

impl Entity {
    /// The input file in which an entity appears (if any).
    pub fn input_file(self, db: &dyn AsRef<EntityTables>) -> Option<FileName> {
        match self.untern(db) {
            EntityData::LangItem(_) => None,
            EntityData::InputFile { file } => Some(file),
            EntityData::ItemName { base, .. } => base.input_file(db),
            EntityData::MemberName { base, .. } => base.input_file(db),
            EntityData::Error(_span) => {
                // FIXME we could recover a file here
                None
            }
        }
    }
}

impl<DB> ErrorSentinel<&DB> for Entity
where
    DB: AsRef<EntityTables>,
{
    fn error_sentinel(db: &DB, report: ErrorReported) -> Self {
        EntityData::Error(report).intern(db)
    }
}