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 register_attribute<T>(
136 &mut self,
137 name: &str,
138 kind: xur_resolve::AttributeKind,
139 ) -> &mut Self
140 where
141 T: Facet<'static> + Send + Sync,
142 {
143 let spec = super::attribute::spec::<T>(kind);
144 self.registry.with_inner(|inner| {
145 inner.modules[self.module]
146 .attributes
147 .insert(name.to_owned(), spec);
148 });
149 self
150 }
151
152 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
155 let (signature, call) = f.into_native();
156 self.add_module_fn(name, Some(signature), Vec::new(), call, None)
157 }
158
159 pub fn named_function<Marker>(
162 &mut self,
163 name: &str,
164 params: &[&str],
165 f: impl IntoNativeFn<Marker>,
166 ) -> &mut Self {
167 let (signature, call) = f.into_native();
168 let names = params.iter().map(|s| s.to_string()).collect();
169 self.add_module_fn(name, Some(signature), names, call, None)
170 }
171
172 pub fn raw_function(
175 &mut self,
176 name: &str,
177 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
178 ) -> &mut Self {
179 self.add_module_fn(name, None, Vec::new(), Box::new(f), None)
180 }
181
182 pub fn raw_function_returns<R: Returns>(
185 &mut self,
186 name: &str,
187 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
188 ) -> &mut Self {
189 self.add_module_fn(
190 name,
191 None,
192 Vec::new(),
193 Box::new(f),
194 Some(ReturnHint::Shape(R::RET)),
195 )
196 }
197
198 pub fn raw_function_returns_xur(
201 &mut self,
202 name: &str,
203 ret: XurType,
204 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
205 ) -> &mut Self {
206 self.add_module_fn(
207 name,
208 None,
209 Vec::new(),
210 Box::new(f),
211 Some(ReturnHint::Xur(ret)),
212 )
213 }
214
215 pub fn named_raw_function(
218 &mut self,
219 name: &str,
220 params: &[&str],
221 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
222 ) -> &mut Self {
223 let names = params.iter().map(|s| s.to_string()).collect();
224 self.add_module_fn(name, None, names, Box::new(f), None)
225 }
226
227 pub fn named_raw_function_returns<R: Returns>(
230 &mut self,
231 name: &str,
232 params: &[&str],
233 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
234 ) -> &mut Self {
235 let names = params.iter().map(|s| s.to_string()).collect();
236 self.add_module_fn(
237 name,
238 None,
239 names,
240 Box::new(f),
241 Some(ReturnHint::Shape(R::RET)),
242 )
243 }
244
245 pub fn named_raw_function_returns_xur(
248 &mut self,
249 name: &str,
250 params: &[&str],
251 ret: XurType,
252 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
253 ) -> &mut Self {
254 let names = params.iter().map(|s| s.to_string()).collect();
255 self.add_module_fn(name, None, names, Box::new(f), Some(ReturnHint::Xur(ret)))
256 }
257
258 pub(super) fn add_raw(
259 &mut self,
260 name: &str,
261 names: Vec<String>,
262 call: Box<CallFn>,
263 ) -> NativeFnId {
264 let decl = self.registry.add_fn(name, None, names, call);
265 let id = decl.id;
266 let module = self.module;
267 self.registry
268 .with_inner(|inner| inner.modules[module].functions.push(decl));
269 id
270 }
271
272 fn add_module_fn(
273 &mut self,
274 name: &str,
275 signature: Option<Signature>,
276 names: Vec<String>,
277 call: Box<CallFn>,
278 return_hint: Option<ReturnHint>,
279 ) -> &mut Self {
280 let decl = self.registry.add_fn(name, signature, names, call);
281 if let Some(hint) = return_hint {
282 self.registry.set_return_hint(decl.id, hint);
283 }
284 let module = self.module;
285 self.registry
286 .with_inner(|inner| inner.modules[module].functions.push(decl));
287 self
288 }
289
290 pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
296 let module = self.module;
297 self.registry.with_inner(|inner| {
298 let id = NativeTypeId(inner.types.len() as u32);
299 inner.types.push(NativeType {
300 name: name.to_owned(),
301 shape,
302 functions: Vec::new(),
303 hooks: None,
304 explicit_variants: None,
305 });
306 inner.modules[module].types.push(id);
307 id
308 })
309 }
310
311 pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
315 let module = self.module;
316 let variant_decls: Vec<NativeVariantDecl> = variants
317 .iter()
318 .map(|(vname, value)| NativeVariantDecl {
319 name: vname.to_string(),
320 kind: NativeVariantKind::Unit,
321 repr_value: Some(*value),
322 })
323 .collect();
324 self.registry.with_inner(|inner| {
325 let id = NativeTypeId(inner.types.len() as u32);
326 inner.types.push(NativeType {
327 name: name.to_owned(),
328 shape: <()>::SHAPE,
329 functions: Vec::new(),
330 hooks: None,
331 explicit_variants: Some(variant_decls),
332 });
333 inner.modules[module].types.push(id);
334 });
335 self
336 }
337
338 pub fn ty_existing<T: Facet<'static> + Clone + Send + 'static>(
343 &mut self,
344 ) -> TypeBuilder<'_, T> {
345 let id = self
346 .registry
347 .type_of_shape(T::SHAPE)
348 .expect("ty_existing: type not registered");
349 TypeBuilder {
350 registry: self.registry,
351 ty: id,
352 _ty: PhantomData,
353 }
354 }
355
356 pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
359 &mut self,
360 name: &str,
361 ) -> TypeBuilder<'_, T> {
362 let module = self.module;
363 let id = self.registry.with_inner(|inner| {
364 let id = NativeTypeId(inner.types.len() as u32);
365 inner.types.push(NativeType {
366 name: name.to_owned(),
367 shape: T::SHAPE,
368 functions: Vec::new(),
369 hooks: Some(TypeHooks::new::<T>()),
370 explicit_variants: None,
371 });
372 inner.modules[module].types.push(id);
373 id
374 });
375 TypeBuilder {
376 registry: self.registry,
377 ty: id,
378 _ty: PhantomData,
379 }
380 }
381
382 pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
387 &mut self,
388 name: &str,
389 ) -> TypeBuilder<'_, T> {
390 let module = self.module;
391 let id = self.registry.with_inner(|inner| {
392 let id = NativeTypeId(inner.types.len() as u32);
393 inner.types.push(NativeType {
394 name: name.to_owned(),
395 shape: T::SHAPE,
396 functions: Vec::new(),
397 hooks: Some(TypeHooks::borrowing::<T>()),
398 explicit_variants: None,
399 });
400 inner.modules[module].types.push(id);
401 id
402 });
403 TypeBuilder {
404 registry: self.registry,
405 ty: id,
406 _ty: PhantomData,
407 }
408 }
409}
410
411pub struct TypeBuilder<'r, T> {
413 registry: &'r Registry,
414 ty: NativeTypeId,
415 _ty: PhantomData<T>,
416}
417
418impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
419 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
422 let (signature, call) = f.into_native();
423 self.add(name, Some(signature), Vec::new(), call, None)
424 }
425
426 pub fn raw_function(
430 &mut self,
431 name: &str,
432 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
433 ) -> &mut Self {
434 self.add(name, None, Vec::new(), Box::new(f), None)
435 }
436
437 pub fn raw_function_returns<R: Returns>(
440 &mut self,
441 name: &str,
442 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
443 ) -> &mut Self {
444 self.add(
445 name,
446 None,
447 Vec::new(),
448 Box::new(f),
449 Some(ReturnHint::Shape(R::RET)),
450 )
451 }
452
453 pub fn raw_function_returns_xur(
456 &mut self,
457 name: &str,
458 ret: XurType,
459 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
460 ) -> &mut Self {
461 self.add(
462 name,
463 None,
464 Vec::new(),
465 Box::new(f),
466 Some(ReturnHint::Xur(ret)),
467 )
468 }
469
470 pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
472 let (signature, call) = f.into_native();
473 self.add(name, Some(signature), Vec::new(), call, None)
474 }
475
476 pub fn method_mut<Marker>(
479 &mut self,
480 name: &str,
481 f: impl IntoNativeMethodMut<T, Marker>,
482 ) -> &mut Self {
483 let (signature, call) = f.into_native();
484 self.add(name, Some(signature), Vec::new(), call, None)
485 }
486
487 pub fn named_function<Marker>(
490 &mut self,
491 name: &str,
492 params: &[&str],
493 f: impl IntoNativeFn<Marker>,
494 ) -> &mut Self {
495 let (signature, call) = f.into_native();
496 self.add(name, Some(signature), owned(params), call, None)
497 }
498
499 pub fn named_method<Marker>(
502 &mut self,
503 name: &str,
504 params: &[&str],
505 f: impl IntoNativeMethod<T, Marker>,
506 ) -> &mut Self {
507 let (signature, call) = f.into_native();
508 self.add(name, Some(signature), with_self(params), call, None)
509 }
510
511 pub fn named_method_mut<Marker>(
514 &mut self,
515 name: &str,
516 params: &[&str],
517 f: impl IntoNativeMethodMut<T, Marker>,
518 ) -> &mut Self {
519 let (signature, call) = f.into_native();
520 self.add(name, Some(signature), with_self(params), call, None)
521 }
522
523 pub fn registry(&self) -> &Registry {
525 self.registry
526 }
527
528 pub(super) fn add_raw(
529 &mut self,
530 name: &str,
531 names: Vec<String>,
532 call: Box<CallFn>,
533 ) -> NativeFnId {
534 let decl = self.registry.add_fn(name, None, names, call);
535 let id = decl.id;
536 let ty = self.ty;
537 self.registry
538 .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
539 id
540 }
541
542 fn add(
543 &mut self,
544 name: &str,
545 signature: Option<Signature>,
546 param_names: Vec<String>,
547 call: Box<CallFn>,
548 return_hint: Option<ReturnHint>,
549 ) -> &mut Self {
550 let decl = self.registry.add_fn(name, signature, param_names, call);
551 if let Some(hint) = return_hint {
552 self.registry.set_return_hint(decl.id, hint);
553 }
554 let ty = self.ty;
555 self.registry
556 .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
557 self
558 }
559}
560
561pub struct BuiltinBuilder<'r> {
563 registry: &'r Registry,
564 ty: BuiltinType,
565}
566
567impl<'r> BuiltinBuilder<'r> {
568 pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
569 Self { registry, ty }
570 }
571
572 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
579 let (signature, call) = f.into_native();
580 self.add(name, Some(signature), Vec::new(), call, None)
581 }
582
583 pub fn method<Recv: ?Sized + 'static, Marker>(
589 &mut self,
590 name: &str,
591 f: impl IntoBuiltinMethod<Recv, Marker>,
592 ) -> &mut Self {
593 let (signature, call) = f.into_native();
594 self.add(name, Some(signature), Vec::new(), call, None)
595 }
596
597 pub fn method_mut<Recv: 'static, Marker>(
600 &mut self,
601 name: &str,
602 f: impl IntoBuiltinMethodMut<Recv, Marker>,
603 ) -> &mut Self {
604 let (signature, call) = f.into_native();
605 self.add(name, Some(signature), Vec::new(), call, None)
606 }
607
608 pub fn raw_function(
611 &mut self,
612 name: &str,
613 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
614 ) -> &mut Self {
615 self.add(name, None, Vec::new(), Box::new(f), None)
616 }
617
618 pub fn raw_function_returns<R: Returns>(
621 &mut self,
622 name: &str,
623 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
624 ) -> &mut Self {
625 self.add(
626 name,
627 None,
628 Vec::new(),
629 Box::new(f),
630 Some(ReturnHint::Shape(R::RET)),
631 )
632 }
633
634 pub fn raw_function_returns_xur(
637 &mut self,
638 name: &str,
639 ret: XurType,
640 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
641 ) -> &mut Self {
642 self.add(
643 name,
644 None,
645 Vec::new(),
646 Box::new(f),
647 Some(ReturnHint::Xur(ret)),
648 )
649 }
650
651 pub fn named_function<Marker>(
654 &mut self,
655 name: &str,
656 params: &[&str],
657 f: impl IntoNativeFn<Marker>,
658 ) -> &mut Self {
659 let (signature, call) = f.into_native();
660 self.add(name, Some(signature), owned(params), call, None)
661 }
662
663 pub fn named_method<Recv: ?Sized + 'static, Marker>(
666 &mut self,
667 name: &str,
668 params: &[&str],
669 f: impl IntoBuiltinMethod<Recv, Marker>,
670 ) -> &mut Self {
671 let (signature, call) = f.into_native();
672 self.add(name, Some(signature), owned(params), call, None)
673 }
674
675 pub fn named_method_mut<Recv: 'static, Marker>(
678 &mut self,
679 name: &str,
680 params: &[&str],
681 f: impl IntoBuiltinMethodMut<Recv, Marker>,
682 ) -> &mut Self {
683 let (signature, call) = f.into_native();
684 self.add(name, Some(signature), owned(params), call, None)
685 }
686
687 pub fn registry(&self) -> &'r Registry {
689 self.registry
690 }
691
692 pub(super) fn add_raw(
693 &mut self,
694 name: &str,
695 names: Vec<String>,
696 call: Box<CallFn>,
697 ) -> NativeFnId {
698 let decl = self.registry.add_fn(name, None, names, call);
699 let key = (self.ty, name.to_owned());
700 self.registry
701 .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
702 decl.id
703 }
704
705 fn add(
706 &mut self,
707 name: &str,
708 signature: Option<Signature>,
709 param_names: Vec<String>,
710 call: Box<CallFn>,
711 return_hint: Option<ReturnHint>,
712 ) -> &mut Self {
713 let decl = self.registry.add_fn(name, signature, param_names, call);
714 if let Some(hint) = return_hint {
715 self.registry.set_return_hint(decl.id, hint);
716 }
717 let key = (self.ty, name.to_owned());
718 self.registry
719 .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
720 self
721 }
722}
723
724fn owned(names: &[&str]) -> Vec<String> {
725 names.iter().map(|s| s.to_string()).collect()
726}
727
728fn with_self(params: &[&str]) -> Vec<String> {
731 std::iter::once("self")
732 .chain(params.iter().copied())
733 .map(String::from)
734 .collect()
735}