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
use std::any::Any;
use std::ops::Deref;
use std::rc::Rc;
use mica_language::ast::DumpAst;
use mica_language::bytecode::{
BuiltinDispatchTables, Chunk, DispatchTable, Environment, Function, FunctionKind, Opr24,
};
use mica_language::codegen::CodeGenerator;
use mica_language::lexer::Lexer;
use mica_language::parser::Parser;
use mica_language::value::{Closure, Value};
use mica_language::vm::{self, Globals};
use crate::{
ffvariants, BuiltType, Error, Fiber, ForeignFunction, IntoValue, StandardLibrary, TryFromValue,
TypeBuilder, UserData,
};
pub use mica_language::bytecode::ForeignFunction as RawForeignFunction;
#[derive(Debug, Clone, Copy, Default)]
pub struct DebugOptions {
pub dump_ast: bool,
pub dump_bytecode: bool,
}
pub struct Engine {
pub(crate) env: Environment,
pub(crate) globals: Globals,
debug_options: DebugOptions,
}
impl Engine {
pub fn new(stdlib: impl StandardLibrary) -> Self {
Self::with_debug_options(stdlib, Default::default())
}
pub fn with_debug_options(
mut stdlib: impl StandardLibrary,
debug_options: DebugOptions,
) -> Self {
let mut env = Environment::new(Default::default());
macro_rules! get_dtables {
($type_name:tt, $define:tt) => {{
let tb = TypeBuilder::new($type_name);
let tb = stdlib.$define(tb);
tb.build(&mut env).unwrap()
}};
}
let nil = get_dtables!("Nil", define_nil);
let boolean = get_dtables!("Boolean", define_boolean);
let number = get_dtables!("Number", define_number);
let string = get_dtables!("String", define_string);
env.builtin_dtables = BuiltinDispatchTables {
nil: Rc::clone(&nil.instance_dtable),
boolean: Rc::clone(&boolean.instance_dtable),
number: Rc::clone(&number.instance_dtable),
string: Rc::clone(&string.instance_dtable),
function: Rc::new(DispatchTable::new_for_instance("Function")),
};
let mut engine = Self {
env,
globals: Globals::new(),
debug_options,
};
engine.set_built_type(&nil).unwrap();
engine.set_built_type(&boolean).unwrap();
engine.set_built_type(&number).unwrap();
engine.set_built_type(&string).unwrap();
engine
}
pub fn compile(
&mut self,
filename: impl AsRef<str>,
source: impl Into<String>,
) -> Result<Script, Error> {
let module_name = Rc::from(filename.as_ref());
let lexer = Lexer::new(Rc::clone(&module_name), source.into());
let (ast, root_node) = Parser::new(lexer).parse()?;
if self.debug_options.dump_ast {
eprintln!("Mica - AST dump:");
eprintln!("{:?}", DumpAst(&ast, root_node));
}
let main_chunk = CodeGenerator::new(module_name, &mut self.env).generate(&ast, root_node)?;
if self.debug_options.dump_bytecode {
eprintln!("Mica - global environment:");
eprintln!("{:#?}", self.env);
eprintln!("Mica - main chunk disassembly:");
eprintln!("{:#?}", main_chunk);
}
Ok(Script {
engine: self,
main_chunk,
})
}
pub fn start(
&mut self,
filename: impl AsRef<str>,
source: impl Into<String>,
) -> Result<Fiber, Error> {
let script = self.compile(filename, source)?;
Ok(script.into_fiber())
}
pub fn global_id(&mut self, name: &str) -> Result<GlobalId, Error> {
if let Some(slot) = self.env.get_global(name) {
Ok(GlobalId(slot))
} else {
Ok(GlobalId(
self.env.create_global(name).map_err(|_| Error::TooManyGlobals)?,
))
}
}
pub fn set<G, T>(&mut self, id: G, value: T) -> Result<(), Error>
where
G: ToGlobalId,
T: IntoValue,
{
let id = id.to_global_id(&mut self.env)?;
self.globals.set(id.0, value.into_value());
Ok(())
}
pub fn get<G, T>(&self, id: G) -> Result<T, Error>
where
G: TryToGlobalId,
T: TryFromValue,
{
if let Some(id) = id.try_to_global_id(&self.env) {
T::try_from_value(&self.globals.get(id.0))
} else {
T::try_from_value(&Value::Nil)
}
}
pub fn add_raw_function(
&mut self,
name: &str,
parameter_count: impl Into<Option<u16>>,
f: RawForeignFunction,
) -> Result<(), Error> {
let global_id = name.to_global_id(&mut self.env)?;
let function_id = self
.env
.create_function(Function {
name: Rc::from(name),
parameter_count: parameter_count.into(),
kind: FunctionKind::Foreign(f),
})
.map_err(|_| Error::TooManyFunctions)?;
let function = Value::Function(Rc::new(Closure {
function_id,
captures: Vec::new(),
}));
self.globals.set(global_id.0, function);
Ok(())
}
pub fn add_function<F, V>(&mut self, name: &str, f: F) -> Result<(), Error>
where
V: ffvariants::Bare,
F: ForeignFunction<V>,
{
self.add_raw_function(name, F::parameter_count(), f.into_raw_foreign_function())
}
pub fn add_type<T>(&mut self, builder: TypeBuilder<T>) -> Result<(), Error>
where
T: Any + UserData,
{
let built = builder.build(&mut self.env)?;
self.set_built_type(&built)?;
Ok(())
}
pub(crate) fn set_built_type<T>(&mut self, typ: &BuiltType<T>) -> Result<(), Error>
where
T: Any,
{
self.set(typ.type_name.deref(), typ.make_type())
}
}
pub struct Script<'e> {
engine: &'e mut Engine,
main_chunk: Rc<Chunk>,
}
impl<'e> Script<'e> {
pub fn start(&mut self) -> Fiber {
Fiber {
engine: self.engine,
inner: vm::Fiber::new(Rc::clone(&self.main_chunk)),
}
}
pub fn into_fiber(self) -> Fiber<'e> {
Fiber {
engine: self.engine,
inner: vm::Fiber::new(Rc::clone(&self.main_chunk)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct GlobalId(Opr24);
mod global_id {
use crate::GlobalId;
pub trait Sealed {}
impl Sealed for GlobalId {}
impl Sealed for &str {}
}
pub trait ToGlobalId: global_id::Sealed {
#[doc(hidden)]
fn to_global_id(&self, env: &mut Environment) -> Result<GlobalId, Error>;
}
impl ToGlobalId for GlobalId {
fn to_global_id(&self, _: &mut Environment) -> Result<GlobalId, Error> {
Ok(*self)
}
}
impl ToGlobalId for &str {
fn to_global_id(&self, env: &mut Environment) -> Result<GlobalId, Error> {
Ok(if let Some(slot) = env.get_global(*self) {
GlobalId(slot)
} else {
env.create_global(*self).map(GlobalId).map_err(|_| Error::TooManyGlobals)?
})
}
}
pub trait TryToGlobalId {
#[doc(hidden)]
fn try_to_global_id(&self, env: &Environment) -> Option<GlobalId>;
}
impl TryToGlobalId for GlobalId {
fn try_to_global_id(&self, _: &Environment) -> Option<GlobalId> {
Some(*self)
}
}
impl TryToGlobalId for &str {
fn try_to_global_id(&self, env: &Environment) -> Option<GlobalId> {
env.get_global(*self).map(GlobalId)
}
}