-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
2158 lines (2033 loc) · 68.2 KB
/
Copy pathbuild.rs
File metadata and controls
2158 lines (2033 loc) · 68.2 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, HashSet};
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use syn::{Attribute, FnArg, Item, ItemFn, Meta, Pat, ReturnType, Type};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SourceCategory {
DefaultHost,
NamespacedBuiltin,
MetadataOnlyBuiltin,
}
#[derive(Clone, Debug)]
struct SourceSpec {
path: String,
module: String,
category: SourceCategory,
}
#[derive(Clone, Debug)]
struct CallableParamDecl {
name: String,
ty_label: String,
optional: bool,
}
#[derive(Clone, Debug)]
struct WrapperDecl {
fn_name: String,
mut_fn_name: String,
params: Vec<WrapperParamKind>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WrapperParamKind {
Vm,
SliceArgs,
}
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HostBindingKind {
StaticStack,
StaticArgs,
StaticNonYieldingArgs,
}
impl HostBindingKind {
pub(crate) fn render_bind_static_call(&self, name: &str, function_name: &str) -> String {
let method = match self {
Self::StaticStack => "bind_static_stack_function",
Self::StaticNonYieldingArgs => "bind_static_non_yielding_args_function",
Self::StaticArgs => "bind_static_args_function",
};
format!("vm.{method}({name:?}, {function_name});")
}
}
#[derive(Clone, Debug)]
struct CallableDecl {
rust_ident: String,
module: String,
name: String,
docs: String,
params: Vec<CallableParamDecl>,
return_label: String,
static_return_type: String,
wrapper: Option<WrapperDecl>,
host_binding_kind: HostBindingKind,
}
#[derive(Clone, Debug)]
struct NamespaceDecl {
namespace: String,
module: String,
docs: String,
runtime_supported_on_wasm: bool,
}
#[derive(Clone, Debug)]
struct Group<'a> {
key: String,
items: Vec<&'a CallableDecl>,
}
fn main() {
emit_git_build_metadata();
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("missing manifest dir"));
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("missing OUT_DIR"));
let namespace_manifest = manifest_dir
.join("src")
.join("builtins")
.join("runtime")
.join("namespaces.rs");
println!("cargo:rerun-if-changed={}", namespace_manifest.display());
let namespaces = parse_namespace_manifest(&namespace_manifest);
let host_sources = [SourceSpec {
path: "src/builtins/runtime/host.rs".to_string(),
module: "host".to_string(),
category: SourceCategory::DefaultHost,
}];
let builtin_sources = builtin_source_specs(&namespaces);
let core_sources = [SourceSpec {
path: "src/builtins/runtime/core.rs".to_string(),
module: "core".to_string(),
category: SourceCategory::MetadataOnlyBuiltin,
}];
let mut next_order = 0usize;
let host_callables = parse_sources(&manifest_dir, &host_sources, &mut next_order);
let builtin_callables = parse_sources(&manifest_dir, &builtin_sources, &mut next_order);
let core_callables = parse_sources(&manifest_dir, &core_sources, &mut next_order);
let metadata_callables = core_callables.clone();
validate_namespace_roots(&builtin_callables, &namespaces);
validate_known_language_builtins(&core_callables);
validate_wrapper_shapes(&host_callables, SourceCategory::DefaultHost);
validate_wrapper_shapes(&builtin_callables, SourceCategory::NamespacedBuiltin);
write_generated_file(
&out_dir.join("builtin_catalog_generated.rs"),
&render_builtin_catalog(
&namespaces,
&host_callables,
&builtin_callables,
&metadata_callables,
),
);
write_generated_file(
&out_dir.join("builtin_runtime_dispatch_generated.rs"),
&render_builtin_runtime_dispatch(&host_callables, &builtin_callables),
);
}
fn emit_git_build_metadata() {
println!("cargo:rerun-if-env-changed=PD_BUILD_GIT_TAG");
println!("cargo:rerun-if-env-changed=PD_BUILD_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=PD_BUILD_GIT_DIRTY");
let git_tag = env::var("PD_BUILD_GIT_TAG").unwrap_or_else(|_| {
run_git(["describe", "--tags", "--exact-match"]).unwrap_or_else(|| "untagged".to_string())
});
let git_commit = env::var("PD_BUILD_GIT_COMMIT").unwrap_or_else(|_| {
run_git(["rev-parse", "--short=12", "HEAD"]).unwrap_or_else(|| "unknown".to_string())
});
let git_dirty = env::var("PD_BUILD_GIT_DIRTY").unwrap_or_else(|_| {
match run_git(["status", "--porcelain", "--untracked-files=no"]) {
Some(output) if !output.trim().is_empty() => "true".to_string(),
_ => "false".to_string(),
}
});
println!("cargo:rustc-env=PD_BUILD_GIT_TAG={git_tag}");
println!("cargo:rustc-env=PD_BUILD_GIT_COMMIT={git_commit}");
println!("cargo:rustc-env=PD_BUILD_GIT_DIRTY={git_dirty}");
}
fn run_git<const N: usize>(args: [&str; N]) -> Option<String> {
let output = Command::new("git").args(args).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
}
fn write_generated_file(path: &Path, contents: &str) {
fs::write(path, contents)
.unwrap_or_else(|err| panic!("failed to write {}: {err}", path.display()));
}
fn builtin_source_specs(namespaces: &[NamespaceDecl]) -> Vec<SourceSpec> {
namespaces
.iter()
.map(|namespace| SourceSpec {
path: format!("src/builtins/runtime/{}.rs", namespace.module),
module: namespace.module.clone(),
category: SourceCategory::NamespacedBuiltin,
})
.collect()
}
fn parse_sources(
manifest_dir: &Path,
specs: &[SourceSpec],
next_order: &mut usize,
) -> Vec<CallableDecl> {
let mut out = Vec::new();
for spec in specs {
let path = manifest_dir.join(&spec.path);
println!("cargo:rerun-if-changed={}", path.display());
let mut file_callables = parse_source_file(&path, spec, *next_order);
*next_order += file_callables.len();
out.append(&mut file_callables);
}
out
}
pub(crate) fn classify_host_binding(function: &ItemFn) -> HostBindingKind {
if function.sig.inputs.iter().any(|input| match input {
FnArg::Typed(pat_type) => is_vm_context_type(&pat_type.ty),
_ => false,
}) {
return HostBindingKind::StaticStack;
}
let return_type = normalized_return_type(&function.sig.output);
if matches!(
plain_path_type(&return_type).as_deref(),
Some("CallOutcome")
) {
return HostBindingKind::StaticArgs;
}
if sole_type_argument(&return_type, "VmResult")
.or_else(|| sole_type_argument(&return_type, "HostResult"))
.is_some_and(|inner| matches!(plain_path_type(&inner).as_deref(), Some("CallOutcome")))
{
return HostBindingKind::StaticArgs;
}
if is_supported_ordinary_return_type(&return_type) {
return HostBindingKind::StaticNonYieldingArgs;
}
HostBindingKind::StaticArgs
}
fn is_supported_ordinary_return_type(ty: &Type) -> bool {
match ty {
Type::Group(group) => is_supported_ordinary_return_type(&group.elem),
Type::Paren(paren) => is_supported_ordinary_return_type(&paren.elem),
Type::Reference(reference) => is_supported_ordinary_return_type(&reference.elem),
Type::Path(path) => {
let Some(segment) = path.path.segments.last() else {
return false;
};
match segment.ident.to_string().as_str() {
"Option" | "VmResult" | "HostResult" => {
sole_type_argument(ty, &segment.ident.to_string())
.is_some_and(|inner| is_supported_ordinary_return_type(&inner))
}
"Vec" => sole_type_argument(ty, "Vec")
.is_some_and(|inner| is_supported_vec_return_type(&inner)),
"Value" | "bool" | "i64" | "u32" | "usize" | "f64" | "String" | "str"
| "SharedArray" | "VmBytes" | "SharedBytes" | "VmMap" | "SharedMap"
| "NumberValue" => matches!(segment.arguments, syn::PathArguments::None),
_ => false,
}
}
Type::Tuple(tuple) => tuple.elems.is_empty(),
_ => false,
}
}
fn is_supported_vec_return_type(ty: &Type) -> bool {
if is_plain_path_type(ty, "Value") {
return true;
}
let Type::Tuple(tuple) = unwrap_surface_type(ty) else {
return false;
};
tuple.elems.len() == 2
&& tuple
.elems
.iter()
.all(|elem| is_plain_path_type(elem, "Value"))
}
fn is_plain_path_type(ty: &Type, expected: &str) -> bool {
let ty = unwrap_surface_type(ty);
let Type::Path(path) = &ty else {
return false;
};
path.path.segments.last().is_some_and(|segment| {
segment.ident == expected && matches!(segment.arguments, syn::PathArguments::None)
})
}
fn normalized_return_type(output: &ReturnType) -> Type {
match output {
ReturnType::Default => syn::parse_quote!(()),
ReturnType::Type(_, ty) => unwrap_surface_type(ty),
}
}
fn unwrap_surface_type(ty: &Type) -> Type {
match ty {
Type::Group(group) => unwrap_surface_type(&group.elem),
Type::Paren(paren) => unwrap_surface_type(&paren.elem),
Type::Reference(reference) => unwrap_surface_type(&reference.elem),
_ => ty.clone(),
}
}
fn plain_path_type(ty: &Type) -> Option<String> {
match ty {
Type::Group(group) => plain_path_type(&group.elem),
Type::Paren(paren) => plain_path_type(&paren.elem),
Type::Reference(reference) => plain_path_type(&reference.elem),
Type::Path(path) => path.path.segments.last().map(|seg| seg.ident.to_string()),
_ => None,
}
}
fn sole_type_argument(ty: &Type, wrapper: &str) -> Option<Type> {
let ty = unwrap_surface_type(ty);
match &ty {
Type::Path(path) => {
let segment = path.path.segments.last()?;
if segment.ident != wrapper {
return None;
}
let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
return None;
};
if args.args.len() != 1 {
return None;
}
let arg = args.args.first()?;
match arg {
syn::GenericArgument::Type(inner) => Some(inner.clone()),
_ => None,
}
}
_ => None,
}
}
fn parse_source_file(path: &Path, spec: &SourceSpec, _order_offset: usize) -> Vec<CallableDecl> {
let source = fs::read_to_string(path)
.unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
let parsed = syn::parse_file(&source)
.unwrap_or_else(|err| panic!("failed to parse {}: {err}", path.display()));
let mut out = Vec::new();
for item in parsed.items.iter() {
let Item::Fn(function) = item else {
continue;
};
let Some(name) = pd_host_function_name(&function.attrs) else {
continue;
};
let params = parse_callable_params(function);
let rust_ident = function.sig.ident.to_string();
let docs = callable_docs(&name, &function.attrs);
let wrapper = match spec.category {
SourceCategory::MetadataOnlyBuiltin => None,
_ => Some(generated_wrapper_decl(function)),
};
out.push(CallableDecl {
rust_ident,
module: spec.module.clone(),
name,
docs,
params,
return_label: return_type_label(&function.sig.output),
static_return_type: static_return_type_label(&function.sig.output),
wrapper,
host_binding_kind: classify_host_binding(function),
});
}
out
}
fn parse_namespace_manifest(path: &Path) -> Vec<NamespaceDecl> {
let source = fs::read_to_string(path)
.unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
let mut decls = Vec::new();
let mut rest = source.as_str();
loop {
let Some(index) = rest.find("builtin_namespace!(") else {
break;
};
rest = &rest[index + "builtin_namespace!(".len()..];
let end = find_matching_paren(rest);
let args = &rest[..end];
let (namespace, rest_after_namespace) = parse_string(args);
let rest_after_namespace = expect_comma(rest_after_namespace);
let (module, rest_after_module) = parse_string(rest_after_namespace);
let rest_after_module = expect_comma(rest_after_module);
let (docs, rest_after_docs) = parse_string(rest_after_module);
let rest_after_docs = expect_comma(rest_after_docs);
let (runtime_supported_on_wasm, rest_after_wasm) = parse_bool(rest_after_docs);
if !skip_ws(rest_after_wasm).is_empty() {
panic!("unexpected trailing tokens in namespace declaration: {rest_after_wasm}");
}
decls.push(NamespaceDecl {
namespace,
module,
docs,
runtime_supported_on_wasm,
});
rest = &rest[end + 1..];
}
decls
}
fn validate_namespace_roots(callables: &[CallableDecl], namespaces: &[NamespaceDecl]) {
let declared = namespaces
.iter()
.map(|namespace| namespace.namespace.as_str())
.collect::<HashSet<_>>();
let used = callables
.iter()
.filter_map(|callable| callable.name.split_once("::").map(|(root, _)| root))
.collect::<HashSet<_>>();
if declared != used {
panic!(
"builtin namespace declarations do not match annotated callables: declared={declared:?}, used={used:?}"
);
}
}
fn validate_known_language_builtins(callables: &[CallableDecl]) {
let known = callables
.iter()
.map(|callable| callable.name.as_str())
.collect::<HashSet<_>>();
for name in required_language_builtin_stubs() {
if !known.contains(name) {
panic!("missing lowering stub for language builtin '{name}'");
}
}
for name in required_internal_builtin_stubs() {
if !known.contains(name) {
panic!("missing lowering stub for internal builtin '{name}'");
}
}
}
fn validate_wrapper_shapes(callables: &[CallableDecl], category: SourceCategory) {
for callable in callables {
let Some(_wrapper) = callable.wrapper.as_ref() else {
continue;
};
validate_optional_param_layout(callable);
match category {
SourceCategory::DefaultHost | SourceCategory::NamespacedBuiltin => {}
SourceCategory::MetadataOnlyBuiltin => {}
}
}
}
fn validate_optional_param_layout(callable: &CallableDecl) {
let mut saw_optional = false;
for param in &callable.params {
if param.optional {
saw_optional = true;
continue;
}
if saw_optional {
panic!(
"callable '{}' has a required parameter after an optional parameter",
callable.name
);
}
}
}
fn render_builtin_catalog(
namespaces: &[NamespaceDecl],
host_callables: &[CallableDecl],
builtin_callables: &[CallableDecl],
metadata_callables: &[CallableDecl],
) -> String {
let language_group_input = metadata_callables
.iter()
.filter(|callable| is_language_builtin_stub_name(&callable.name))
.cloned()
.collect::<Vec<_>>();
let language_groups = stable_groups(&language_group_input, |callable| callable.name.clone());
let language_builtin_order = language_groups
.iter()
.map(|group| group.key.clone())
.collect::<Vec<_>>();
let host_group_input = host_callables.to_vec();
let host_groups = stable_groups(&host_group_input, |callable| callable.name.clone());
let (builtin_variant_order, actual_builtin_by_variant) =
ordered_actual_builtin_variants(namespaces, builtin_callables, metadata_callables);
let builtin_call_count = u16::try_from(
builtin_variant_order
.len()
.checked_sub(appended_builtin_order().len())
.expect("appended builtin count should fit catalog"),
)
.expect("builtin function count should fit in u16");
let builtin_call_base = u16::MAX
.checked_sub(builtin_call_count)
.and_then(|value| value.checked_add(1))
.expect("builtin call base should fit in u16");
assert!(
builtin_call_base >= 15,
"builtin call base must leave room for reserved special builtins"
);
let namespace_member_group_input = builtin_callables
.iter()
.chain(
metadata_callables
.iter()
.filter(|callable| callable.name.contains("::")),
)
.cloned()
.collect::<Vec<_>>();
let namespace_member_groups = stable_groups(&namespace_member_group_input, |callable| {
callable.name.clone()
});
for variant in &builtin_variant_order {
if !actual_builtin_by_variant.contains_key(variant) {
panic!("missing callable signatures for builtin variant '{variant}'");
}
}
let mut out = String::new();
out.push_str(&render_callable_consts(
&host_callables
.iter()
.chain(builtin_callables.iter())
.chain(metadata_callables.iter())
.collect::<Vec<_>>(),
));
writeln!(
&mut out,
"#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]"
)
.unwrap();
writeln!(&mut out, "#[repr(u16)]").unwrap();
writeln!(&mut out, "pub enum BuiltinFunction {{").unwrap();
for (index, variant) in builtin_variant_order.iter().enumerate() {
if index == 0 {
writeln!(&mut out, " {variant} = 0,").unwrap();
} else {
writeln!(&mut out, " {variant},").unwrap();
}
}
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"const MAIN_RANGE_BUILTINS: &[BuiltinFunction] = &["
)
.unwrap();
for variant in main_range_builtin_variants(&builtin_variant_order) {
writeln!(&mut out, " BuiltinFunction::{variant},").unwrap();
}
writeln!(&mut out, "];").unwrap();
writeln!(&mut out).unwrap();
for group in &language_groups {
render_signature_group_const(
&mut out,
group,
&language_signature_group_const_name(&group.key),
);
}
for variant in &builtin_variant_order {
let items = actual_builtin_by_variant
.get(variant)
.unwrap_or_else(|| panic!("missing builtin variant group '{variant}'"));
render_signature_group_const(
&mut out,
&Group {
key: variant.clone(),
items: items.clone(),
},
&variant_signature_group_const_name(variant),
);
}
for group in &namespace_member_groups {
render_signature_group_const(
&mut out,
group,
&namespace_member_signature_group_const_name(&group.key),
);
}
render_namespace_metadata(&mut out, namespaces, &namespace_member_groups);
render_default_host_array(&mut out, &host_groups);
render_language_builtin_specs(&mut out, &language_builtin_order, &language_groups);
render_namespace_member_signature_lookup(&mut out, &namespace_member_groups);
writeln!(
&mut out,
"pub(crate) const BUILTIN_CALL_BASE: u16 = 0x{builtin_call_base:04X};"
)
.unwrap();
writeln!(
&mut out,
"pub(crate) const BUILTIN_CALL_COUNT: u16 = MAIN_RANGE_BUILTINS.len() as u16;"
)
.unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"const SPECIAL_CALL_BUILTINS: &[(u16, BuiltinFunction)] = &["
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 4, BuiltinFunction::FormatTemplate),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 3, BuiltinFunction::ToString),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 2, BuiltinFunction::TypeOf),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 1, BuiltinFunction::Assert),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 7, BuiltinFunction::StringContains),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 6, BuiltinFunction::StringReplaceLiteral),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 5, BuiltinFunction::StringLowerAscii),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 8, BuiltinFunction::StringSplitLiteral),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 9, BuiltinFunction::MapIterInit),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 10, BuiltinFunction::MapIterNext),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 11, BuiltinFunction::MapIterTakeKey),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 12, BuiltinFunction::MapIterTakeValue),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 13, BuiltinFunction::MapIterClose),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 14, BuiltinFunction::BindCallable),"
)
.unwrap();
writeln!(
&mut out,
" (BUILTIN_CALL_BASE - 15, BuiltinFunction::DetachLocal),"
)
.unwrap();
writeln!(&mut out, "];").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub fn language_builtin_specs() -> &'static [LanguageBuiltinSpec] {{"
)
.unwrap();
writeln!(&mut out, " &LANGUAGE_BUILTIN_SPECS").unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub fn default_host_callables() -> &'static [CallableDef] {{"
)
.unwrap();
writeln!(&mut out, " &DEFAULT_HOST_CALLABLES").unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub(crate) fn default_host_callable(name: &str) -> Option<&'static CallableDef> {{"
)
.unwrap();
writeln!(
&mut out,
" DEFAULT_HOST_CALLABLES.iter().find(|callable| callable.name == name)"
)
.unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub fn builtin_namespace_specs() -> &'static [BuiltinNamespaceSpec] {{"
)
.unwrap();
writeln!(&mut out, " BUILTIN_NAMESPACE_SPECS").unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub fn is_builtin_namespace(namespace: &str) -> bool {{"
)
.unwrap();
writeln!(
&mut out,
" BUILTIN_NAMESPACE_SPECS.iter().any(|entry| entry.namespace == namespace)"
)
.unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub fn resolve_builtin_namespace_call(namespace: &str, member: &str) -> Option<BuiltinFunction> {{"
)
.unwrap();
writeln!(
&mut out,
" let entry = BUILTIN_NAMESPACE_LOOKUPS.iter().find(|entry| entry.name == namespace)?;"
)
.unwrap();
writeln!(
&mut out,
" entry.members.iter().find(|item| item.name == member).map(|item| item.builtin)"
)
.unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub(crate) fn builtin_namespace_hint() -> String {{"
)
.unwrap();
writeln!(
&mut out,
" BUILTIN_NAMESPACE_SPECS.iter().map(|entry| entry.namespace).collect::<Vec<_>>().join(\"/\")"
)
.unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
"pub(crate) fn resolve_namespaced_builtin(name: &str) -> Option<BuiltinFunction> {{"
)
.unwrap();
writeln!(&mut out, " let mut parts = name.trim().split(\"::\");").unwrap();
writeln!(&mut out, " let namespace = parts.next()?;").unwrap();
writeln!(&mut out, " let member = parts.next()?;").unwrap();
writeln!(&mut out, " if parts.next().is_some() {{ return None; }}").unwrap();
writeln!(
&mut out,
" resolve_builtin_namespace_call(namespace, member)"
)
.unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
writeln!(&mut out, "impl BuiltinFunction {{").unwrap();
render_builtin_name_method(&mut out, &builtin_variant_order, &actual_builtin_by_variant);
render_builtin_arity_method(&mut out, &builtin_variant_order, &actual_builtin_by_variant);
render_builtin_accepts_arity_method(
&mut out,
&builtin_variant_order,
&actual_builtin_by_variant,
);
render_builtin_static_return_type_method(
&mut out,
&builtin_variant_order,
&actual_builtin_by_variant,
);
render_builtin_signature_method(&mut out, &builtin_variant_order);
writeln!(
&mut out,
" pub fn from_namespaced_name(name: &str) -> Option<Self> {{"
)
.unwrap();
writeln!(&mut out, " resolve_namespaced_builtin(name)").unwrap();
writeln!(&mut out, " }}").unwrap();
writeln!(&mut out).unwrap();
writeln!(&mut out, " pub fn call_index(self) -> u16 {{").unwrap();
writeln!(&mut out, " match self {{").unwrap();
writeln!(
&mut out,
" BuiltinFunction::FormatTemplate => BUILTIN_CALL_BASE - 4,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::ToString => BUILTIN_CALL_BASE - 3,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::TypeOf => BUILTIN_CALL_BASE - 2,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::Assert => BUILTIN_CALL_BASE - 1,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::StringContains => BUILTIN_CALL_BASE - 7,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::StringReplaceLiteral => BUILTIN_CALL_BASE - 6,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::StringLowerAscii => BUILTIN_CALL_BASE - 5,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::StringSplitLiteral => BUILTIN_CALL_BASE - 8,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::MapIterInit => BUILTIN_CALL_BASE - 9,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::MapIterNext => BUILTIN_CALL_BASE - 10,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::MapIterTakeKey => BUILTIN_CALL_BASE - 11,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::MapIterTakeValue => BUILTIN_CALL_BASE - 12,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::MapIterClose => BUILTIN_CALL_BASE - 13,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::BindCallable => BUILTIN_CALL_BASE - 14,"
)
.unwrap();
writeln!(
&mut out,
" BuiltinFunction::DetachLocal => BUILTIN_CALL_BASE - 15,"
)
.unwrap();
writeln!(
&mut out,
" _ => BUILTIN_CALL_BASE + self as u16,"
)
.unwrap();
writeln!(&mut out, " }}").unwrap();
writeln!(&mut out, " }}").unwrap();
writeln!(&mut out).unwrap();
writeln!(
&mut out,
" pub(crate) fn from_call_index(index: u16) -> Option<Self> {{"
)
.unwrap();
writeln!(
&mut out,
" if let Some((_, builtin)) = SPECIAL_CALL_BUILTINS.iter().find(|(call_index, _)| *call_index == index) {{"
)
.unwrap();
writeln!(&mut out, " return Some(*builtin);").unwrap();
writeln!(&mut out, " }}").unwrap();
writeln!(
&mut out,
" let offset = index.checked_sub(BUILTIN_CALL_BASE)?;"
)
.unwrap();
writeln!(
&mut out,
" if offset >= BUILTIN_CALL_COUNT {{ return None; }}"
)
.unwrap();
writeln!(
&mut out,
" MAIN_RANGE_BUILTINS.get(offset as usize).copied()"
)
.unwrap();
writeln!(&mut out, " }}").unwrap();
writeln!(&mut out, "}}").unwrap();
out
}
fn render_builtin_runtime_dispatch(
host_callables: &[CallableDecl],
builtin_callables: &[CallableDecl],
) -> String {
let mut out = String::new();
for callable in host_callables {
let wrapper = callable
.wrapper
.as_ref()
.expect("host wrappers should exist");
let adapter_name = host_wrapper_adapter_name(callable);
if callable.host_binding_kind == HostBindingKind::StaticStack {
writeln!(
&mut out,
"fn {adapter_name}(vm: &mut Vm, args: &[Value]) -> VmResult<CallOutcome> {{"
)
.unwrap();
} else {
writeln!(
&mut out,
"fn {adapter_name}(args: &[Value]) -> VmResult<CallOutcome> {{"
)
.unwrap();
}
writeln!(
&mut out,
" {}",
render_wrapper_call(
&callable.module,
wrapper,
SourceCategory::DefaultHost,
"args",
)
)
.unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();
}
writeln!(
&mut out,
"pub(crate) fn register_default_host_functions(registry: &mut super::HostFunctionRegistry) {{"
)
.unwrap();
for callable in host_callables {
if callable.host_binding_kind == HostBindingKind::StaticStack {
writeln!(
&mut out,
" registry.register_static_stack({:?}, {}, {});",
callable.name,
callable.params.len(),
host_wrapper_adapter_name(callable)
)
.unwrap();
} else if callable.host_binding_kind == HostBindingKind::StaticNonYieldingArgs {
writeln!(
&mut out,
" registry.register_static_non_yielding_args({:?}, {}, {});",
callable.name,
callable.params.len(),
host_wrapper_adapter_name(callable)
)
.unwrap();
} else {
writeln!(
&mut out,
" registry.register_static_args({:?}, {}, {});",
callable.name,
callable.params.len(),
host_wrapper_adapter_name(callable)
)
.unwrap();
}
}
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();