1use std::marker::PhantomData;
2
3use facet::{Facet, Shape};
4use xur_resolve::{NativeFnId, 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 pub(super) fn add_raw(
238 &mut self,
239 name: &str,
240 names: Vec<String>,
241 call: Box<CallFn>,
242 ) -> NativeFnId {
243 let decl = self.registry.add_fn(name, None, names, call);
244 let id = decl.id;
245 let module = self.module;
246 self.registry
247 .with_inner(|inner| inner.modules[module].functions.push(decl));
248 id
249 }
250
251 fn add_module_fn(
252 &mut self,
253 name: &str,
254 signature: Option<Signature>,
255 names: Vec<String>,
256 call: Box<CallFn>,
257 return_hint: Option<ReturnHint>,
258 ) -> &mut Self {
259 let decl = self.registry.add_fn(name, signature, names, call);
260 if let Some(hint) = return_hint {
261 self.registry.set_return_hint(decl.id, hint);
262 }
263 let module = self.module;
264 self.registry
265 .with_inner(|inner| inner.modules[module].functions.push(decl));
266 self
267 }
268
269 pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
275 let module = self.module;
276 self.registry.with_inner(|inner| {
277 let id = NativeTypeId(inner.types.len() as u32);
278 inner.types.push(NativeType {
279 name: name.to_owned(),
280 shape,
281 functions: Vec::new(),
282 hooks: None,
283 explicit_variants: None,
284 });
285 inner.modules[module].types.push(id);
286 id
287 })
288 }
289
290 pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
294 let module = self.module;
295 let variant_decls: Vec<NativeVariantDecl> = variants
296 .iter()
297 .map(|(vname, value)| NativeVariantDecl {
298 name: vname.to_string(),
299 kind: NativeVariantKind::Unit,
300 repr_value: Some(*value),
301 })
302 .collect();
303 self.registry.with_inner(|inner| {
304 let id = NativeTypeId(inner.types.len() as u32);
305 inner.types.push(NativeType {
306 name: name.to_owned(),
307 shape: <()>::SHAPE,
308 functions: Vec::new(),
309 hooks: None,
310 explicit_variants: Some(variant_decls),
311 });
312 inner.modules[module].types.push(id);
313 });
314 self
315 }
316
317 pub fn ty_existing<T: Facet<'static> + Clone + Send + 'static>(
322 &mut self,
323 ) -> TypeBuilder<'_, T> {
324 let id = self
325 .registry
326 .type_of_shape(T::SHAPE)
327 .expect("ty_existing: type not registered");
328 TypeBuilder {
329 registry: self.registry,
330 ty: id,
331 _ty: PhantomData,
332 }
333 }
334
335 pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
338 &mut self,
339 name: &str,
340 ) -> TypeBuilder<'_, T> {
341 let module = self.module;
342 let id = self.registry.with_inner(|inner| {
343 let id = NativeTypeId(inner.types.len() as u32);
344 inner.types.push(NativeType {
345 name: name.to_owned(),
346 shape: T::SHAPE,
347 functions: Vec::new(),
348 hooks: Some(TypeHooks::new::<T>()),
349 explicit_variants: None,
350 });
351 inner.modules[module].types.push(id);
352 id
353 });
354 TypeBuilder {
355 registry: self.registry,
356 ty: id,
357 _ty: PhantomData,
358 }
359 }
360
361 pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
366 &mut self,
367 name: &str,
368 ) -> TypeBuilder<'_, T> {
369 let module = self.module;
370 let id = self.registry.with_inner(|inner| {
371 let id = NativeTypeId(inner.types.len() as u32);
372 inner.types.push(NativeType {
373 name: name.to_owned(),
374 shape: T::SHAPE,
375 functions: Vec::new(),
376 hooks: Some(TypeHooks::borrowing::<T>()),
377 explicit_variants: None,
378 });
379 inner.modules[module].types.push(id);
380 id
381 });
382 TypeBuilder {
383 registry: self.registry,
384 ty: id,
385 _ty: PhantomData,
386 }
387 }
388}
389
390pub struct TypeBuilder<'r, T> {
392 registry: &'r Registry,
393 ty: NativeTypeId,
394 _ty: PhantomData<T>,
395}
396
397impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
398 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
401 let (signature, call) = f.into_native();
402 self.add(name, Some(signature), Vec::new(), call, None)
403 }
404
405 pub fn raw_function(
409 &mut self,
410 name: &str,
411 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
412 ) -> &mut Self {
413 self.add(name, None, Vec::new(), Box::new(f), None)
414 }
415
416 pub fn raw_function_returns<R: Returns>(
419 &mut self,
420 name: &str,
421 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
422 ) -> &mut Self {
423 self.add(
424 name,
425 None,
426 Vec::new(),
427 Box::new(f),
428 Some(ReturnHint::Shape(R::RET)),
429 )
430 }
431
432 pub fn raw_function_returns_xur(
435 &mut self,
436 name: &str,
437 ret: XurType,
438 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
439 ) -> &mut Self {
440 self.add(
441 name,
442 None,
443 Vec::new(),
444 Box::new(f),
445 Some(ReturnHint::Xur(ret)),
446 )
447 }
448
449 pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
451 let (signature, call) = f.into_native();
452 self.add(name, Some(signature), Vec::new(), call, None)
453 }
454
455 pub fn method_mut<Marker>(
458 &mut self,
459 name: &str,
460 f: impl IntoNativeMethodMut<T, Marker>,
461 ) -> &mut Self {
462 let (signature, call) = f.into_native();
463 self.add(name, Some(signature), Vec::new(), call, None)
464 }
465
466 pub fn named_function<Marker>(
469 &mut self,
470 name: &str,
471 params: &[&str],
472 f: impl IntoNativeFn<Marker>,
473 ) -> &mut Self {
474 let (signature, call) = f.into_native();
475 self.add(name, Some(signature), owned(params), call, None)
476 }
477
478 pub fn named_method<Marker>(
481 &mut self,
482 name: &str,
483 params: &[&str],
484 f: impl IntoNativeMethod<T, Marker>,
485 ) -> &mut Self {
486 let (signature, call) = f.into_native();
487 self.add(name, Some(signature), with_self(params), call, None)
488 }
489
490 pub fn named_method_mut<Marker>(
493 &mut self,
494 name: &str,
495 params: &[&str],
496 f: impl IntoNativeMethodMut<T, Marker>,
497 ) -> &mut Self {
498 let (signature, call) = f.into_native();
499 self.add(name, Some(signature), with_self(params), call, None)
500 }
501
502 pub fn registry(&self) -> &Registry {
504 self.registry
505 }
506
507 pub(super) fn add_raw(
508 &mut self,
509 name: &str,
510 names: Vec<String>,
511 call: Box<CallFn>,
512 ) -> NativeFnId {
513 let decl = self.registry.add_fn(name, None, names, call);
514 let id = decl.id;
515 let ty = self.ty;
516 self.registry
517 .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
518 id
519 }
520
521 fn add(
522 &mut self,
523 name: &str,
524 signature: Option<Signature>,
525 param_names: Vec<String>,
526 call: Box<CallFn>,
527 return_hint: Option<ReturnHint>,
528 ) -> &mut Self {
529 let decl = self.registry.add_fn(name, signature, param_names, call);
530 if let Some(hint) = return_hint {
531 self.registry.set_return_hint(decl.id, hint);
532 }
533 let ty = self.ty;
534 self.registry
535 .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
536 self
537 }
538}
539
540pub struct BuiltinBuilder<'r> {
542 registry: &'r Registry,
543 ty: BuiltinType,
544}
545
546impl<'r> BuiltinBuilder<'r> {
547 pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
548 Self { registry, ty }
549 }
550
551 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
558 let (signature, call) = f.into_native();
559 self.add(name, Some(signature), Vec::new(), call, None)
560 }
561
562 pub fn method<Recv: ?Sized + 'static, Marker>(
568 &mut self,
569 name: &str,
570 f: impl IntoBuiltinMethod<Recv, Marker>,
571 ) -> &mut Self {
572 let (signature, call) = f.into_native();
573 self.add(name, Some(signature), Vec::new(), call, None)
574 }
575
576 pub fn method_mut<Recv: 'static, Marker>(
579 &mut self,
580 name: &str,
581 f: impl IntoBuiltinMethodMut<Recv, Marker>,
582 ) -> &mut Self {
583 let (signature, call) = f.into_native();
584 self.add(name, Some(signature), Vec::new(), call, None)
585 }
586
587 pub fn raw_function(
590 &mut self,
591 name: &str,
592 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
593 ) -> &mut Self {
594 self.add(name, None, Vec::new(), Box::new(f), None)
595 }
596
597 pub fn raw_function_returns<R: Returns>(
600 &mut self,
601 name: &str,
602 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
603 ) -> &mut Self {
604 self.add(
605 name,
606 None,
607 Vec::new(),
608 Box::new(f),
609 Some(ReturnHint::Shape(R::RET)),
610 )
611 }
612
613 pub fn raw_function_returns_xur(
616 &mut self,
617 name: &str,
618 ret: XurType,
619 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
620 ) -> &mut Self {
621 self.add(
622 name,
623 None,
624 Vec::new(),
625 Box::new(f),
626 Some(ReturnHint::Xur(ret)),
627 )
628 }
629
630 pub fn named_function<Marker>(
633 &mut self,
634 name: &str,
635 params: &[&str],
636 f: impl IntoNativeFn<Marker>,
637 ) -> &mut Self {
638 let (signature, call) = f.into_native();
639 self.add(name, Some(signature), owned(params), call, None)
640 }
641
642 pub fn named_method<Recv: ?Sized + 'static, Marker>(
645 &mut self,
646 name: &str,
647 params: &[&str],
648 f: impl IntoBuiltinMethod<Recv, Marker>,
649 ) -> &mut Self {
650 let (signature, call) = f.into_native();
651 self.add(name, Some(signature), owned(params), call, None)
652 }
653
654 pub fn named_method_mut<Recv: 'static, Marker>(
657 &mut self,
658 name: &str,
659 params: &[&str],
660 f: impl IntoBuiltinMethodMut<Recv, Marker>,
661 ) -> &mut Self {
662 let (signature, call) = f.into_native();
663 self.add(name, Some(signature), owned(params), call, None)
664 }
665
666 pub fn registry(&self) -> &'r Registry {
668 self.registry
669 }
670
671 pub(super) fn add_raw(
672 &mut self,
673 name: &str,
674 names: Vec<String>,
675 call: Box<CallFn>,
676 ) -> NativeFnId {
677 let decl = self.registry.add_fn(name, None, names, call);
678 let key = (self.ty, name.to_owned());
679 self.registry
680 .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
681 decl.id
682 }
683
684 fn add(
685 &mut self,
686 name: &str,
687 signature: Option<Signature>,
688 param_names: Vec<String>,
689 call: Box<CallFn>,
690 return_hint: Option<ReturnHint>,
691 ) -> &mut Self {
692 let decl = self.registry.add_fn(name, signature, param_names, call);
693 if let Some(hint) = return_hint {
694 self.registry.set_return_hint(decl.id, hint);
695 }
696 let key = (self.ty, name.to_owned());
697 self.registry
698 .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
699 self
700 }
701}
702
703fn owned(names: &[&str]) -> Vec<String> {
704 names.iter().map(|s| s.to_string()).collect()
705}
706
707fn with_self(params: &[&str]) -> Vec<String> {
710 std::iter::once("self")
711 .chain(params.iter().copied())
712 .map(String::from)
713 .collect()
714}