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
use std::error::Error as StdError;
use std::fmt::Display;
use std::str::FromStr;

use indexmap::{IndexMap, IndexSet};

use super::{Access, Dict, Function, FunctionDescriptor, Str};
use crate::ctx::Context;
use crate::util::JoinIter;
use crate::value::handle::Handle;
use crate::value::Value;
use crate::{Error, Result};

// TODO: all descriptor should store `String` for names, because `Handle<Str>`
// may be mutated maybe this can be solved another way, like making Str a
// primitive?

pub trait ModuleLoader {
  /// Load a module at the `path`, returning its source code.
  fn load(&mut self, path: &[String]) -> Result<&str, Box<dyn StdError + 'static>>;
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModuleId(usize);

pub struct ModuleRegistry {
  next_module_id: usize,
  index: IndexMap<Vec<String>, ModuleId>,
  modules: IndexMap<ModuleId, Handle<Module>>,
}

impl ModuleRegistry {
  pub fn new() -> Self {
    Self {
      next_module_id: 1,
      index: IndexMap::new(),
      modules: IndexMap::new(),
    }
  }

  pub fn next_module_id(&mut self) -> ModuleId {
    let temp = ModuleId(self.next_module_id);
    self.next_module_id += 1;
    temp
  }

  pub fn add(&mut self, id: ModuleId, path: &[String], module: Handle<Module>) {
    self.index.insert(path.to_vec(), id);
    self.modules.insert(id, module);
  }

  pub fn remove(&mut self, id: ModuleId) -> Option<Handle<Module>> {
    self.modules.remove(&id)
  }

  pub fn by_id(&self, id: ModuleId) -> Option<Handle<Module>> {
    self.modules.get(&id).cloned()
  }

  pub fn by_path(&self, path: &[String]) -> Option<(ModuleId, Handle<Module>)> {
    let id = self.index.get(path).cloned()?;
    let module = self.modules.get(&id).cloned()?;
    Some((id, module))
  }
}

impl Default for ModuleRegistry {
  fn default() -> Self {
    Self::new()
  }
}

pub struct ModuleDescriptor {
  name: Handle<Str>,
  root: Handle<FunctionDescriptor>,
  module_vars: IndexSet<String>,
}

impl ModuleDescriptor {
  pub fn new(
    name: Handle<Str>,
    root: Handle<FunctionDescriptor>,
    module_vars: IndexSet<String>,
  ) -> Self {
    Self {
      name,
      root,
      module_vars,
    }
  }
}

#[derive::delegate_to_handle]
impl ModuleDescriptor {
  pub fn instance(&self, ctx: &Context, module_id: Option<ModuleId>) -> Handle<Module> {
    let name = self.name();
    let root = Function::new(ctx, self.root(), module_id);

    ctx.alloc(Module {
      name,
      root,
      module_vars: ctx.alloc(Dict::from_iter(
        self
          .module_vars()
          .iter()
          .map(|k| (ctx.alloc(Str::from(k.clone())), Value::none())),
      )),
    })
  }

  pub fn name(&self) -> Handle<Str> {
    self.name.clone()
  }

  pub fn root(&self) -> Handle<FunctionDescriptor> {
    self.root.clone()
  }

  pub(crate) fn module_vars(&self) -> &IndexSet<String> {
    &self.module_vars
  }
}

impl Display for ModuleDescriptor {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "<module descriptor {}>", self.name.as_str())
  }
}

impl Access for ModuleDescriptor {}

pub struct Module {
  name: Handle<Str>,
  root: Handle<Function>,
  module_vars: Handle<Dict>,
}

#[derive::delegate_to_handle]
impl Module {
  pub fn name(&self) -> Handle<Str> {
    self.name.clone()
  }

  pub fn root(&self) -> Handle<Function> {
    self.root.clone()
  }

  pub fn module_vars(&self) -> Handle<Dict> {
    self.module_vars.clone()
  }
}

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

impl Access for Module {
  fn is_frozen(&self) -> bool {
    true
  }

  fn should_bind_methods(&self) -> bool {
    false
  }

  // TODO: tests

  fn field_get(&self, _: &Context, key: &str) -> crate::Result<Option<Value>> {
    Ok(self.module_vars.get(key).cloned())
  }

  fn field_set(&mut self, _: &Context, key: Handle<Str>, value: Value) -> crate::Result<()> {
    let Some(slot) = self.module_vars.get_mut(&key) else {
      return Err(Error::runtime(format!("cannot set field `{key}`")));
    };
    *slot = value;
    Ok(())
  }

  impl_index_via_field!(mut);
}

/// A path composed of segments. Paths are made of alphanumeric ASCII,
/// underscores, and periods.
///
/// Examples:
/// - `module`
/// - `module.nested.another_module`
#[derive(Debug, PartialEq, Eq)]
pub struct Path {
  segments: Vec<String>,
}

impl Path {
  /// # Panics
  /// If `segments` is empty.
  pub fn new(segments: Vec<String>) -> Self {
    assert!(!segments.is_empty());
    Self { segments }
  }
}

impl FromStr for Path {
  type Err = InvalidPathError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    if s.is_empty() {
      return Err(InvalidPathError::EmptySegment { pos: 0 });
    }
    if let Some(pos) = s.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.') {
      return Err(InvalidPathError::InvalidCharacter { pos });
    }

    let mut segments = vec![];
    let mut pos = 0;
    for segment in s.split('.') {
      if segment.is_empty() {
        return Err(InvalidPathError::EmptySegment { pos });
      }
      segments.push(String::from(segment));
      pos += segment.len() + 1;
    }
    Ok(Path { segments })
  }
}

#[derive(Debug, PartialEq, Eq)]
pub enum InvalidPathError {
  EmptySegment { pos: usize },
  InvalidCharacter { pos: usize },
}

impl Display for InvalidPathError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      InvalidPathError::EmptySegment { pos } => write!(f, "empty segment at {pos}"),
      InvalidPathError::InvalidCharacter { pos } => write!(f, "invalid character at {pos}"),
    }
  }
}

impl StdError for InvalidPathError {}

#[derive::delegate_to_handle]
impl Path {
  pub fn segments(&self) -> &[String] {
    &self.segments
  }
}

impl Display for Path {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "<path {}>", self.segments().iter().join("."))
  }
}

impl Access for Path {}

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

  #[test]
  fn parse_path() {
    assert_eq!(
      Ok(Path {
        segments: vec!["a".into()]
      }),
      Path::from_str("a")
    );
    assert_eq!(
      Ok(Path {
        segments: vec!["a".into(), "b".into()]
      }),
      Path::from_str("a.b")
    );
    assert_eq!(
      Ok(Path {
        segments: vec!["a".into(), "b".into(), "c".into()]
      }),
      Path::from_str("a.b.c")
    );
    assert_eq!(
      Ok(Path {
        segments: vec!["with_underscore".into(), "b".into(), "c".into()]
      }),
      Path::from_str("with_underscore.b.c")
    );
    assert_eq!(
      Err(InvalidPathError::InvalidCharacter { pos: 3 }),
      Path::from_str("bad . bad")
    );
    assert_eq!(
      Err(InvalidPathError::EmptySegment { pos: 0 }),
      Path::from_str("")
    );
    assert_eq!(
      Err(InvalidPathError::EmptySegment { pos: 5 }),
      Path::from_str("test.")
    );
  }
}