1use std::marker::PhantomData;
2
3use facet::{Facet, Shape};
4use xur_resolve::NativeTypeId;
5
6use super::hooks::TypeHooks;
7use super::into_native::{
8 IntoBuiltinMethod, IntoBuiltinMethodMut, IntoNativeFn, IntoNativeMethod, IntoNativeMethodMut,
9};
10use super::{CallFn, Context, NativeType, Registry, Signature};
11use crate::{BuiltinType, RunResult, Value};
12use xur_resolve::{NativeVariantDecl, NativeVariantKind};
13
14pub trait Returns {
19 const RET: &'static Shape;
20}
21
22impl<T: Facet<'static>> Returns for T {
23 const RET: &'static Shape = T::SHAPE;
24}
25
26#[derive(Clone, Copy)]
29pub enum ElemHint {
30 Shape(&'static Shape),
32 Name(&'static str),
34 Param(u8),
36}
37
38#[derive(Clone, Copy)]
40pub enum XurType {
41 Ptr(Option<&'static Shape>),
43 List(Option<ElemHint>),
45 Map(Option<&'static Shape>, Option<&'static Shape>),
47 Named(&'static str, &'static [ElemHint]),
49 Record,
50 Module,
51 Unit,
52}
53
54impl XurType {
55 pub const PTR: Self = Self::Ptr(None);
56 pub const LIST: Self = Self::List(None);
57 pub const MAP: Self = Self::Map(None, None);
58 pub const UNIT: Self = Self::Unit;
59
60 pub fn ptr<T: Facet<'static>>() -> Self {
61 Self::Ptr(Some(T::SHAPE))
62 }
63 pub fn list<T: Facet<'static>>() -> Self {
64 Self::List(Some(ElemHint::Shape(T::SHAPE)))
65 }
66 pub fn list_named(name: &'static str) -> Self {
67 Self::List(Some(ElemHint::Name(name)))
68 }
69 pub fn map<K: Facet<'static>, V: Facet<'static>>() -> Self {
70 Self::Map(Some(K::SHAPE), Some(V::SHAPE))
71 }
72 pub fn map_keys<K: Facet<'static>>() -> Self {
73 Self::Map(Some(K::SHAPE), None)
74 }
75 pub fn map_values<V: Facet<'static>>() -> Self {
76 Self::Map(None, Some(V::SHAPE))
77 }
78}
79
80#[derive(Clone, Copy)]
83pub enum ReturnHint {
84 Shape(&'static Shape),
85 Xur(XurType),
86}
87
88pub struct ModuleBuilder<'r> {
90 registry: &'r Registry,
91 pub(super) module: usize,
92}
93
94impl<'r> ModuleBuilder<'r> {
95 pub(super) fn new(registry: &'r Registry, module: usize) -> Self {
96 Self { registry, module }
97 }
98
99 pub fn registry(&self) -> &'r Registry {
101 self.registry
102 }
103
104 pub fn submodule(&self, name: &str) -> ModuleBuilder<'r> {
107 let parent = self.module;
108 let module = self
109 .registry
110 .with_inner(|inner| inner.child(Some(parent), name));
111 ModuleBuilder::new(self.registry, module)
112 }
113}
114
115impl ModuleBuilder<'_> {
116 pub fn register_macro(
119 &mut self,
120 name: &str,
121 expander: impl xur_resolve::macros::MacroExpander + 'static,
122 ) -> &mut Self {
123 self.registry.with_inner(|inner| {
124 inner.modules[self.module]
125 .macros
126 .insert(name.to_owned(), std::sync::Arc::new(expander));
127 });
128 self
129 }
130
131 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
134 let (signature, call) = f.into_native();
135 self.add_module_fn(name, Some(signature), Vec::new(), call, None)
136 }
137
138 pub fn named_function<Marker>(
141 &mut self,
142 name: &str,
143 params: &[&str],
144 f: impl IntoNativeFn<Marker>,
145 ) -> &mut Self {
146 let (signature, call) = f.into_native();
147 let names = params.iter().map(|s| s.to_string()).collect();
148 self.add_module_fn(name, Some(signature), names, call, None)
149 }
150
151 pub fn raw_function(
154 &mut self,
155 name: &str,
156 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
157 ) -> &mut Self {
158 self.add_module_fn(name, None, Vec::new(), Box::new(f), None)
159 }
160
161 pub fn raw_function_returns<R: Returns>(
164 &mut self,
165 name: &str,
166 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
167 ) -> &mut Self {
168 self.add_module_fn(
169 name,
170 None,
171 Vec::new(),
172 Box::new(f),
173 Some(ReturnHint::Shape(R::RET)),
174 )
175 }
176
177 pub fn raw_function_returns_xur(
180 &mut self,
181 name: &str,
182 ret: XurType,
183 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
184 ) -> &mut Self {
185 self.add_module_fn(
186 name,
187 None,
188 Vec::new(),
189 Box::new(f),
190 Some(ReturnHint::Xur(ret)),
191 )
192 }
193
194 pub fn named_raw_function(
197 &mut self,
198 name: &str,
199 params: &[&str],
200 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
201 ) -> &mut Self {
202 let names = params.iter().map(|s| s.to_string()).collect();
203 self.add_module_fn(name, None, names, Box::new(f), None)
204 }
205
206 pub fn named_raw_function_returns<R: Returns>(
209 &mut self,
210 name: &str,
211 params: &[&str],
212 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
213 ) -> &mut Self {
214 let names = params.iter().map(|s| s.to_string()).collect();
215 self.add_module_fn(
216 name,
217 None,
218 names,
219 Box::new(f),
220 Some(ReturnHint::Shape(R::RET)),
221 )
222 }
223
224 pub fn named_raw_function_returns_xur(
227 &mut self,
228 name: &str,
229 params: &[&str],
230 ret: XurType,
231 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
232 ) -> &mut Self {
233 let names = params.iter().map(|s| s.to_string()).collect();
234 self.add_module_fn(name, None, names, Box::new(f), Some(ReturnHint::Xur(ret)))
235 }
236
237 fn add_module_fn(
238 &mut self,
239 name: &str,
240 signature: Option<Signature>,
241 names: Vec<String>,
242 call: Box<CallFn>,
243 return_hint: Option<ReturnHint>,
244 ) -> &mut Self {
245 let decl = self.registry.add_fn(name, signature, names, call);
246 if let Some(hint) = return_hint {
247 self.registry.set_return_hint(decl.id, hint);
248 }
249 let module = self.module;
250 self.registry
251 .with_inner(|inner| inner.modules[module].functions.push(decl));
252 self
253 }
254
255 pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
261 let module = self.module;
262 self.registry.with_inner(|inner| {
263 let id = NativeTypeId(inner.types.len() as u32);
264 inner.types.push(NativeType {
265 name: name.to_owned(),
266 shape,
267 functions: Vec::new(),
268 hooks: None,
269 explicit_variants: None,
270 });
271 inner.modules[module].types.push(id);
272 id
273 })
274 }
275
276 pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
280 let module = self.module;
281 let variant_decls: Vec<NativeVariantDecl> = variants
282 .iter()
283 .map(|(vname, value)| NativeVariantDecl {
284 name: vname.to_string(),
285 kind: NativeVariantKind::Unit,
286 repr_value: Some(*value),
287 })
288 .collect();
289 self.registry.with_inner(|inner| {
290 let id = NativeTypeId(inner.types.len() as u32);
291 inner.types.push(NativeType {
292 name: name.to_owned(),
293 shape: <()>::SHAPE,
294 functions: Vec::new(),
295 hooks: None,
296 explicit_variants: Some(variant_decls),
297 });
298 inner.modules[module].types.push(id);
299 });
300 self
301 }
302
303 pub fn ty_existing<T: Facet<'static> + Clone + Send + 'static>(
308 &mut self,
309 ) -> TypeBuilder<'_, T> {
310 let id = self
311 .registry
312 .type_of_shape(T::SHAPE)
313 .expect("ty_existing: type not registered");
314 TypeBuilder {
315 registry: self.registry,
316 ty: id,
317 _ty: PhantomData,
318 }
319 }
320
321 pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
324 &mut self,
325 name: &str,
326 ) -> TypeBuilder<'_, T> {
327 let module = self.module;
328 let id = self.registry.with_inner(|inner| {
329 let id = NativeTypeId(inner.types.len() as u32);
330 inner.types.push(NativeType {
331 name: name.to_owned(),
332 shape: T::SHAPE,
333 functions: Vec::new(),
334 hooks: Some(TypeHooks::new::<T>()),
335 explicit_variants: None,
336 });
337 inner.modules[module].types.push(id);
338 id
339 });
340 TypeBuilder {
341 registry: self.registry,
342 ty: id,
343 _ty: PhantomData,
344 }
345 }
346
347 pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
352 &mut self,
353 name: &str,
354 ) -> TypeBuilder<'_, T> {
355 let module = self.module;
356 let id = self.registry.with_inner(|inner| {
357 let id = NativeTypeId(inner.types.len() as u32);
358 inner.types.push(NativeType {
359 name: name.to_owned(),
360 shape: T::SHAPE,
361 functions: Vec::new(),
362 hooks: Some(TypeHooks::borrowing::<T>()),
363 explicit_variants: None,
364 });
365 inner.modules[module].types.push(id);
366 id
367 });
368 TypeBuilder {
369 registry: self.registry,
370 ty: id,
371 _ty: PhantomData,
372 }
373 }
374}
375
376pub struct TypeBuilder<'r, T> {
378 registry: &'r Registry,
379 ty: NativeTypeId,
380 _ty: PhantomData<T>,
381}
382
383impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
384 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
387 let (signature, call) = f.into_native();
388 self.add(name, Some(signature), call, None)
389 }
390
391 pub fn raw_function(
395 &mut self,
396 name: &str,
397 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
398 ) -> &mut Self {
399 self.add(name, None, Box::new(f), None)
400 }
401
402 pub fn raw_function_returns<R: Returns>(
405 &mut self,
406 name: &str,
407 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
408 ) -> &mut Self {
409 self.add(name, None, Box::new(f), Some(ReturnHint::Shape(R::RET)))
410 }
411
412 pub fn raw_function_returns_xur(
415 &mut self,
416 name: &str,
417 ret: XurType,
418 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
419 ) -> &mut Self {
420 self.add(name, None, Box::new(f), Some(ReturnHint::Xur(ret)))
421 }
422
423 pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
425 let (signature, call) = f.into_native();
426 self.add(name, Some(signature), call, None)
427 }
428
429 pub fn method_mut<Marker>(
432 &mut self,
433 name: &str,
434 f: impl IntoNativeMethodMut<T, Marker>,
435 ) -> &mut Self {
436 let (signature, call) = f.into_native();
437 self.add(name, Some(signature), call, None)
438 }
439
440 fn add(
441 &mut self,
442 name: &str,
443 signature: Option<Signature>,
444 call: Box<CallFn>,
445 return_hint: Option<ReturnHint>,
446 ) -> &mut Self {
447 let decl = self.registry.add_fn(name, signature, Vec::new(), call);
448 if let Some(hint) = return_hint {
449 self.registry.set_return_hint(decl.id, hint);
450 }
451 let ty = self.ty;
452 self.registry
453 .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
454 self
455 }
456}
457
458pub struct BuiltinBuilder<'r> {
460 registry: &'r Registry,
461 ty: BuiltinType,
462}
463
464impl<'r> BuiltinBuilder<'r> {
465 pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
466 Self { registry, ty }
467 }
468
469 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
476 let (signature, call) = f.into_native();
477 self.add(name, Some(signature), call, None)
478 }
479
480 pub fn method<Recv: ?Sized + 'static, Marker>(
486 &mut self,
487 name: &str,
488 f: impl IntoBuiltinMethod<Recv, Marker>,
489 ) -> &mut Self {
490 let (signature, call) = f.into_native();
491 self.add(name, Some(signature), call, None)
492 }
493
494 pub fn method_mut<Recv: 'static, Marker>(
497 &mut self,
498 name: &str,
499 f: impl IntoBuiltinMethodMut<Recv, Marker>,
500 ) -> &mut Self {
501 let (signature, call) = f.into_native();
502 self.add(name, Some(signature), call, None)
503 }
504
505 pub fn raw_function(
508 &mut self,
509 name: &str,
510 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
511 ) -> &mut Self {
512 self.add(name, None, Box::new(f), None)
513 }
514
515 pub fn raw_function_returns<R: Returns>(
518 &mut self,
519 name: &str,
520 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
521 ) -> &mut Self {
522 self.add(name, None, Box::new(f), Some(ReturnHint::Shape(R::RET)))
523 }
524
525 pub fn raw_function_returns_xur(
528 &mut self,
529 name: &str,
530 ret: XurType,
531 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
532 ) -> &mut Self {
533 self.add(name, None, Box::new(f), Some(ReturnHint::Xur(ret)))
534 }
535
536 fn add(
537 &mut self,
538 name: &str,
539 signature: Option<Signature>,
540 call: Box<CallFn>,
541 return_hint: Option<ReturnHint>,
542 ) -> &mut Self {
543 let decl = self.registry.add_fn(name, signature, Vec::new(), call);
544 if let Some(hint) = return_hint {
545 self.registry.set_return_hint(decl.id, hint);
546 }
547 let key = (self.ty, name.to_owned());
548 self.registry
549 .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
550 self
551 }
552}