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), Vec::new(), 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, Vec::new(), 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(
410 name,
411 None,
412 Vec::new(),
413 Box::new(f),
414 Some(ReturnHint::Shape(R::RET)),
415 )
416 }
417
418 pub fn raw_function_returns_xur(
421 &mut self,
422 name: &str,
423 ret: XurType,
424 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
425 ) -> &mut Self {
426 self.add(
427 name,
428 None,
429 Vec::new(),
430 Box::new(f),
431 Some(ReturnHint::Xur(ret)),
432 )
433 }
434
435 pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
437 let (signature, call) = f.into_native();
438 self.add(name, Some(signature), Vec::new(), call, None)
439 }
440
441 pub fn method_mut<Marker>(
444 &mut self,
445 name: &str,
446 f: impl IntoNativeMethodMut<T, Marker>,
447 ) -> &mut Self {
448 let (signature, call) = f.into_native();
449 self.add(name, Some(signature), Vec::new(), call, None)
450 }
451
452 pub fn named_function<Marker>(
455 &mut self,
456 name: &str,
457 params: &[&str],
458 f: impl IntoNativeFn<Marker>,
459 ) -> &mut Self {
460 let (signature, call) = f.into_native();
461 self.add(name, Some(signature), owned(params), call, None)
462 }
463
464 pub fn named_method<Marker>(
467 &mut self,
468 name: &str,
469 params: &[&str],
470 f: impl IntoNativeMethod<T, Marker>,
471 ) -> &mut Self {
472 let (signature, call) = f.into_native();
473 self.add(name, Some(signature), with_self(params), call, None)
474 }
475
476 pub fn named_method_mut<Marker>(
479 &mut self,
480 name: &str,
481 params: &[&str],
482 f: impl IntoNativeMethodMut<T, Marker>,
483 ) -> &mut Self {
484 let (signature, call) = f.into_native();
485 self.add(name, Some(signature), with_self(params), call, None)
486 }
487
488 fn add(
489 &mut self,
490 name: &str,
491 signature: Option<Signature>,
492 param_names: Vec<String>,
493 call: Box<CallFn>,
494 return_hint: Option<ReturnHint>,
495 ) -> &mut Self {
496 let decl = self.registry.add_fn(name, signature, param_names, call);
497 if let Some(hint) = return_hint {
498 self.registry.set_return_hint(decl.id, hint);
499 }
500 let ty = self.ty;
501 self.registry
502 .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
503 self
504 }
505}
506
507pub struct BuiltinBuilder<'r> {
509 registry: &'r Registry,
510 ty: BuiltinType,
511}
512
513impl<'r> BuiltinBuilder<'r> {
514 pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
515 Self { registry, ty }
516 }
517
518 pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
525 let (signature, call) = f.into_native();
526 self.add(name, Some(signature), Vec::new(), call, None)
527 }
528
529 pub fn method<Recv: ?Sized + 'static, Marker>(
535 &mut self,
536 name: &str,
537 f: impl IntoBuiltinMethod<Recv, Marker>,
538 ) -> &mut Self {
539 let (signature, call) = f.into_native();
540 self.add(name, Some(signature), Vec::new(), call, None)
541 }
542
543 pub fn method_mut<Recv: 'static, Marker>(
546 &mut self,
547 name: &str,
548 f: impl IntoBuiltinMethodMut<Recv, Marker>,
549 ) -> &mut Self {
550 let (signature, call) = f.into_native();
551 self.add(name, Some(signature), Vec::new(), call, None)
552 }
553
554 pub fn raw_function(
557 &mut self,
558 name: &str,
559 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
560 ) -> &mut Self {
561 self.add(name, None, Vec::new(), Box::new(f), None)
562 }
563
564 pub fn raw_function_returns<R: Returns>(
567 &mut self,
568 name: &str,
569 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
570 ) -> &mut Self {
571 self.add(
572 name,
573 None,
574 Vec::new(),
575 Box::new(f),
576 Some(ReturnHint::Shape(R::RET)),
577 )
578 }
579
580 pub fn raw_function_returns_xur(
583 &mut self,
584 name: &str,
585 ret: XurType,
586 f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
587 ) -> &mut Self {
588 self.add(
589 name,
590 None,
591 Vec::new(),
592 Box::new(f),
593 Some(ReturnHint::Xur(ret)),
594 )
595 }
596
597 pub fn named_function<Marker>(
600 &mut self,
601 name: &str,
602 params: &[&str],
603 f: impl IntoNativeFn<Marker>,
604 ) -> &mut Self {
605 let (signature, call) = f.into_native();
606 self.add(name, Some(signature), owned(params), call, None)
607 }
608
609 pub fn named_method<Recv: ?Sized + 'static, Marker>(
612 &mut self,
613 name: &str,
614 params: &[&str],
615 f: impl IntoBuiltinMethod<Recv, Marker>,
616 ) -> &mut Self {
617 let (signature, call) = f.into_native();
618 self.add(name, Some(signature), owned(params), call, None)
619 }
620
621 pub fn named_method_mut<Recv: 'static, Marker>(
624 &mut self,
625 name: &str,
626 params: &[&str],
627 f: impl IntoBuiltinMethodMut<Recv, Marker>,
628 ) -> &mut Self {
629 let (signature, call) = f.into_native();
630 self.add(name, Some(signature), owned(params), call, None)
631 }
632
633 fn add(
634 &mut self,
635 name: &str,
636 signature: Option<Signature>,
637 param_names: Vec<String>,
638 call: Box<CallFn>,
639 return_hint: Option<ReturnHint>,
640 ) -> &mut Self {
641 let decl = self.registry.add_fn(name, signature, param_names, call);
642 if let Some(hint) = return_hint {
643 self.registry.set_return_hint(decl.id, hint);
644 }
645 let key = (self.ty, name.to_owned());
646 self.registry
647 .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
648 self
649 }
650}
651
652fn owned(names: &[&str]) -> Vec<String> {
653 names.iter().map(|s| s.to_string()).collect()
654}
655
656fn with_self(params: &[&str]) -> Vec<String> {
659 std::iter::once("self")
660 .chain(params.iter().copied())
661 .map(String::from)
662 .collect()
663}