-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathlib.rs
More file actions
2384 lines (2148 loc) · 84.7 KB
/
lib.rs
File metadata and controls
2384 lines (2148 loc) · 84.7 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#![doc = include_str!("../README.md")]
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use thiserror::Error;
use wasmparser::{Parser, Payload};
use wasmtime::component::types::{ComponentFunc, ComponentItem};
use wasmtime::component::{Component, Type, Val};
use wasmtime::Engine;
/// Function identifier for tools, containing WIT package, WIT interface, and function names.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionIdentifier {
pub package_name: Option<String>,
pub interface_name: Option<String>,
pub function_name: String,
}
/// Metadata for a tool, including its identifier, normalized name, and JSON schema.
#[derive(Debug, Clone)]
pub struct ToolMetadata {
/// Identifier for the tool, including package and interface names
pub identifier: FunctionIdentifier,
/// Normalized tool name that complies with MCP specification. "^[a-zA-Z0-9_-]{1,128}$"
pub normalized_name: String,
/// JSON schema for the tool's function, including input and output types
pub schema: Value,
}
/// Error type for tool name validation
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
#[error("Invalid tool name: {0}")]
InvalidToolName(String),
#[error("Tool name too long: {0} characters (max 128)")]
ToolNameTooLong(usize),
}
#[derive(Error, Debug)]
pub enum ValError {
/// The JSON number could not be interpreted as either an integer or a float.
#[error("cannot interpret number as i64 or f64: {0}")]
NumberError(String),
/// A character field was invalid, for example an empty or multi-character string
/// when you expected a single char.
#[error("invalid char: {0}")]
InvalidChar(String),
/// An object had an unexpected shape for a particular conceptual type.
#[error("expected object shape for {0}, found: {1}")]
ShapeError(&'static str, String),
/// A JSON object was recognized, but does not match any known variant shape.
#[error("unknown object shape: {0:?}")]
UnknownShape(serde_json::Map<String, Value>),
/// Could not interpret a resource from the JSON field(s).
#[error("cannot interpret resource from JSON")]
ResourceError,
}
/// Validates a tool name according to MCP specification
pub fn validate_tool_name(tool_name: &str) -> Result<(), ValidationError> {
if tool_name.len() > 128 {
return Err(ValidationError::ToolNameTooLong(tool_name.len()));
}
if tool_name.is_empty() {
return Err(ValidationError::InvalidToolName(
"Tool name cannot be empty".to_string(),
));
}
// Check if all characters are valid according to MCP specification: ^[a-zA-Z0-9_-]{1,128}$
for c in tool_name.chars() {
if !c.is_ascii_alphanumeric() && c != '_' && c != '-' {
return Err(ValidationError::InvalidToolName(format!(
"Invalid character '{c}' in tool name"
)));
}
}
Ok(())
}
/// Normalizes a tool name component by replacing invalid characters with underscores
fn normalize_name_component(name: &str) -> String {
name.to_lowercase()
.chars()
.map(|c| match c {
':' | '/' | '.' => '_',
c if c.is_ascii_alphanumeric() || c == '-' => c,
_ => '_',
})
.collect()
}
/// Generates a normalized tool name from a function identifier
pub fn normalize_tool_name(identifier: &FunctionIdentifier) -> String {
let mut parts = Vec::new();
if let Some(pkg) = &identifier.package_name {
parts.push(normalize_name_component(pkg));
}
if let Some(iface) = &identifier.interface_name {
parts.push(normalize_name_component(iface));
}
parts.push(normalize_name_component(&identifier.function_name));
let normalized = parts.join("_");
// Validate the result
validate_tool_name(&normalized).expect("Internal error: generated tool name failed validation");
normalized
}
/// Given a component and a wasmtime engine, return structured tool metadata with normalized names.
///
/// The `output` parameter determines whether to include the output schema for functions.
pub fn component_exports_to_tools(
component: &Component,
engine: &Engine,
output: bool,
) -> Vec<ToolMetadata> {
let mut tools = Vec::new();
for (export_name, export_item) in component.component_type().exports(engine) {
gather_exported_functions_with_metadata(
export_name,
None,
None,
&export_item,
engine,
&mut tools,
output,
);
}
tools
}
/// Given a component and a wasmtime engine, return a full JSON schema of the component's exports.
///
/// The `output` parameter determines whether to include the output schema for functions.
pub fn component_exports_to_json_schema(
component: &Component,
engine: &Engine,
output: bool,
) -> Value {
let tools = component_exports_to_tools(component, engine, output);
json!({ "tools": tools.into_iter().map(|t| t.schema).collect::<Vec<_>>() })
}
/// Extracts package-docs custom section from a WebAssembly component.
///
/// The package-docs section contains JSON-formatted documentation extracted from WIT source files.
/// Returns `None` if no package-docs section is found.
pub fn extract_package_docs(wasm_bytes: &[u8]) -> Option<Value> {
for payload in Parser::new(0).parse_all(wasm_bytes) {
match payload {
Ok(Payload::CustomSection(reader)) => {
if reader.name() == "package-docs" {
let data = reader.data();
// Skip the first byte (version) and parse the JSON
if data.len() > 1 {
let json_data = &data[1..];
return serde_json::from_slice(json_data).ok();
}
}
}
Err(_) => return None,
_ => continue,
}
}
None
}
/// Finds documentation for a specific exported function in package-docs.
///
/// Searches through all worlds in the package-docs structure to find documentation
/// for the given function name. Returns the documentation string if found.
fn find_function_docs(package_docs: &Value, function_name: &str) -> Option<String> {
let worlds = package_docs.get("worlds")?.as_object()?;
// Search through all worlds for the function
for (_world_name, world_data) in worlds {
// Check exported functions
if let Some(func_exports) = world_data.get("func_exports").and_then(|v| v.as_object()) {
if let Some(func_data) = func_exports.get(function_name) {
if let Some(docs) = func_data.get("docs").and_then(|d| d.as_str()) {
return Some(docs.to_string());
}
}
}
}
None
}
/// Given a component with package-docs and a wasmtime engine, return structured tool metadata with normalized names and documentation.
///
/// The `output` parameter determines whether to include the output schema for functions.
/// The `package_docs` parameter should be obtained via `extract_package_docs`.
pub fn component_exports_to_tools_with_docs(
component: &Component,
engine: &Engine,
output: bool,
package_docs: &Value,
) -> Vec<ToolMetadata> {
let mut tools = Vec::new();
let context = GatherMetadataContext {
engine,
output,
package_docs: Some(package_docs),
};
for (export_name, export_item) in component.component_type().exports(engine) {
gather_exported_functions_with_metadata_internal(
export_name,
None,
None,
&export_item,
&mut tools,
&context,
);
}
tools
}
/// Given a component with package-docs and a wasmtime engine, return a full JSON schema of the component's exports with documentation.
///
/// The `output` parameter determines whether to include the output schema for functions.
/// The `package_docs` parameter should be obtained via `extract_package_docs`.
pub fn component_exports_to_json_schema_with_docs(
component: &Component,
engine: &Engine,
output: bool,
package_docs: &Value,
) -> Value {
let tools = component_exports_to_tools_with_docs(component, engine, output, package_docs);
json!({ "tools": tools.into_iter().map(|t| t.schema).collect::<Vec<_>>() })
}
/// Converts a slice of component model [`Val`] objects into a JSON representation.
pub fn vals_to_json(vals: &[Val]) -> Value {
match vals.len() {
0 => Value::Null,
1 => {
let mut wrapper = Map::new();
wrapper.insert("result".to_string(), val_to_json(&vals[0]));
Value::Object(wrapper)
}
_ => {
let mut tuple_map = Map::new();
for (i, v) in vals.iter().enumerate() {
tuple_map.insert(format!("val{i}"), val_to_json(v));
}
let mut wrapper = Map::new();
wrapper.insert("result".to_string(), Value::Object(tuple_map));
Value::Object(wrapper)
}
}
}
/// Converts a JSON object to a vector of `Val` objects based on the provided type mappings for each
/// field.
pub fn json_to_vals(value: &Value, types: &[(String, Type)]) -> Result<Vec<Val>, ValError> {
match value {
Value::Object(obj) => {
let mut results = Vec::new();
for (name, ty) in types {
let value = obj.get(name).ok_or_else(|| {
ValError::ShapeError("object", format!("missing field {name}"))
})?;
results.push(json_to_val(value, ty)?);
}
Ok(results)
}
_ => Err(ValError::ShapeError(
"object",
format!("expected object, got {value:?}"),
)),
}
}
/// Prepares a placeholder `Vec<Val>` to receive the results of a component function call.
/// The vector will have the correct length and correctly-typed (but empty/zeroed) values.
pub fn create_placeholder_results(results: &[Type]) -> Vec<Val> {
results.iter().map(default_val_for_type).collect()
}
fn type_to_json_schema(t: &Type) -> Value {
match t {
Type::Bool => json!({ "type": "boolean" }),
Type::S8
| Type::S16
| Type::S32
| Type::S64
| Type::U8
| Type::U16
| Type::U32
| Type::U64
| Type::Float32
| Type::Float64 => json!({ "type": "number" }),
Type::Char => json!({
"type": "string",
"description": "1 unicode codepoint"
}),
Type::String => json!({ "type": "string" }),
// represent a `list<T>` as an array with items = schema-of-T
Type::List(list_handle) => {
let elem_schema = type_to_json_schema(&list_handle.ty());
json!({
"type": "array",
"items": elem_schema
})
}
Type::Record(r) => {
let mut props = serde_json::Map::new();
let mut required_fields = Vec::new();
for field in r.fields() {
required_fields.push(field.name.to_string());
props.insert(field.name.to_string(), type_to_json_schema(&field.ty));
}
json!({
"type": "object",
"properties": props,
"required": required_fields
})
}
Type::Tuple(tup) => {
let items: Vec<Value> = tup.types().map(|ty| type_to_json_schema(&ty)).collect();
json!({
"type": "array",
"prefixItems": items,
"minItems": items.len(),
"maxItems": items.len()
})
}
Type::Variant(variant_handle) => {
let mut cases_schema = Vec::new();
for case in variant_handle.cases() {
let case_name = case.name;
if let Some(ref payload_ty) = case.ty {
cases_schema.push(json!({
"type": "object",
"properties": {
"tag": { "const": case_name },
"val": type_to_json_schema(payload_ty)
},
"required": ["tag", "val"]
}));
} else {
cases_schema.push(json!({
"type": "object",
"properties": {
"tag": { "const": case_name },
},
"required": ["tag"]
}));
}
}
json!({ "oneOf": cases_schema })
}
Type::Enum(enum_handle) => {
let names: Vec<&str> = enum_handle.names().collect();
json!({
"type": "string",
"enum": names
})
}
Type::Option(opt_handle) => {
let inner_schema = type_to_json_schema(&opt_handle.ty());
json!({
"anyOf": [
{ "type": "null" },
inner_schema
]
})
}
Type::Result(res_handle) => {
let ok_schema = res_handle
.ok()
.map(|ok_ty| type_to_json_schema(&ok_ty))
.unwrap_or(json!({ "type": "null" }));
let err_schema = res_handle
.err()
.map(|err_ty| type_to_json_schema(&err_ty))
.unwrap_or(json!({ "type": "null" }));
json!({
"oneOf": [
{
"type": "object",
"properties": {
"ok": ok_schema
},
"required": ["ok"]
},
{
"type": "object",
"properties": {
"err": err_schema
},
"required": ["err"]
}
]
})
}
Type::Flags(flags_handle) => {
let mut props = serde_json::Map::new();
for name in flags_handle.names() {
props.insert(name.to_string(), json!({"type":"boolean"}));
}
json!({
"type": "object",
"properties": props
})
}
Type::Own(r) => {
json!({
"type": "string",
"description": format!("own'd resource: {:?}", r)
})
}
Type::Borrow(r) => {
json!({
"type": "string",
"description": format!("borrow'd resource: {:?}", r)
})
}
Type::Future(_) => {
json!({
"type": "object",
"description": "Future type (async operation)"
})
}
Type::Stream(_) => {
json!({
"type": "array",
"description": "Stream type (async iteration)"
})
}
Type::ErrorContext => {
json!({
"type": "object",
"description": "Error context type"
})
}
}
}
fn component_func_to_schema_with_docs(
name: &str,
func: &ComponentFunc,
output: bool,
function_id: Option<&FunctionIdentifier>,
package_docs: Option<&Value>,
) -> serde_json::Value {
let mut properties = serde_json::Map::new();
let mut required = Vec::new();
for (param_name, param_type) in func.params() {
required.push(param_name.to_string());
properties.insert(param_name.to_string(), type_to_json_schema(¶m_type));
}
let input_schema = json!({
"type": "object",
"properties": properties,
"required": required
});
let mut tool_obj = serde_json::Map::new();
tool_obj.insert("name".to_string(), json!(name));
// Look up documentation or fall back to auto-generated
let description = if let (Some(func_id), Some(docs)) = (function_id, package_docs) {
find_function_docs(docs, &func_id.function_name)
.unwrap_or_else(|| format!("Auto-generated schema for function '{name}'"))
} else {
format!("Auto-generated schema for function '{name}'")
};
tool_obj.insert("description".to_string(), json!(description));
tool_obj.insert("inputSchema".to_string(), input_schema);
if output {
let results: Vec<_> = func.results().collect();
if let Some(o) = canonical_output_schema_for_results(&results) {
tool_obj.insert("outputSchema".to_string(), o);
}
}
json!(tool_obj)
}
fn canonical_output_schema_for_results(results: &[Type]) -> Option<Value> {
if results.is_empty() {
return None;
}
let result_schema = if results.len() == 1 {
type_to_json_schema(&results[0])
} else {
let mut props = Map::new();
let mut required = Vec::new();
for (idx, ty) in results.iter().enumerate() {
let key = format!("val{idx}");
props.insert(key.clone(), type_to_json_schema(ty));
required.push(Value::String(key));
}
let mut tuple_schema = Map::new();
tuple_schema.insert("type".to_string(), Value::String("object".to_string()));
tuple_schema.insert("properties".to_string(), Value::Object(props));
tuple_schema.insert("required".to_string(), Value::Array(required));
Value::Object(tuple_schema)
};
Some(build_result_wrapper(result_schema))
}
fn build_result_wrapper(result_schema: Value) -> Value {
let mut props = Map::new();
props.insert("result".to_string(), result_schema);
let mut wrapper = Map::new();
wrapper.insert("type".to_string(), Value::String("object".to_string()));
wrapper.insert("properties".to_string(), Value::Object(props));
wrapper.insert(
"required".to_string(),
Value::Array(vec![Value::String("result".to_string())]),
);
Value::Object(wrapper)
}
struct GatherMetadataContext<'a> {
engine: &'a Engine,
output: bool,
package_docs: Option<&'a Value>,
}
fn gather_exported_functions_with_metadata(
export_name: &str,
previous_name: Option<String>,
package_name: Option<String>,
item: &ComponentItem,
engine: &Engine,
results: &mut Vec<ToolMetadata>,
output: bool,
) {
let context = GatherMetadataContext {
engine,
output,
package_docs: None,
};
gather_exported_functions_with_metadata_internal(
export_name,
previous_name,
package_name,
item,
results,
&context,
);
}
fn gather_exported_functions_with_metadata_internal(
export_name: &str,
previous_name: Option<String>,
package_name: Option<String>,
item: &ComponentItem,
results: &mut Vec<ToolMetadata>,
context: &GatherMetadataContext,
) {
match item {
ComponentItem::ComponentFunc(func) => {
let function_id = FunctionIdentifier {
package_name: package_name.clone(),
interface_name: previous_name,
function_name: export_name.to_string(),
};
let normalized_name = normalize_tool_name(&function_id);
let schema = component_func_to_schema_with_docs(
&normalized_name,
func,
context.output,
Some(&function_id),
context.package_docs,
);
results.push(ToolMetadata {
identifier: function_id,
normalized_name,
schema,
});
}
ComponentItem::Component(sub_component) => {
let previous_name = Some(export_name.to_string());
for (export_name, export_item) in sub_component.exports(context.engine) {
gather_exported_functions_with_metadata_internal(
export_name,
previous_name.clone(),
package_name.clone(),
&export_item,
results,
context,
);
}
}
ComponentItem::ComponentInstance(instance) => {
let previous_name = Some(export_name.to_string());
for (export_name, export_item) in instance.exports(context.engine) {
gather_exported_functions_with_metadata_internal(
export_name,
previous_name.clone(),
package_name.clone(),
&export_item,
results,
context,
);
}
}
ComponentItem::CoreFunc(_)
| ComponentItem::Module(_)
| ComponentItem::Type(_)
| ComponentItem::Resource(_) => {}
}
}
fn val_to_json(val: &Val) -> Value {
match val {
Val::Bool(b) => Value::Bool(*b),
Val::S8(n) => Value::Number((*n as i64).into()),
Val::U8(n) => Value::Number((*n as u64).into()),
Val::S16(n) => Value::Number((*n as i64).into()),
Val::U16(n) => Value::Number((*n as u64).into()),
Val::S32(n) => Value::Number((*n as i64).into()),
Val::U32(n) => Value::Number((*n as u64).into()),
Val::S64(n) => Value::Number((*n).into()),
Val::U64(n) => Value::Number((*n).into()),
Val::Float32(f) => serde_json::Number::from_f64(*f as f64)
.map(Value::Number)
.unwrap_or_else(|| Value::String(f.to_string())),
Val::Float64(f) => serde_json::Number::from_f64(*f)
.map(Value::Number)
.unwrap_or_else(|| Value::String(f.to_string())),
Val::Char(c) => Value::String(c.to_string()),
Val::String(s) => Value::String(s.clone()),
Val::List(list) => Value::Array(list.iter().map(val_to_json).collect()),
Val::Record(fields) => {
let mut map = Map::new();
for (k, v) in fields {
map.insert(k.clone(), val_to_json(v));
}
Value::Object(map)
}
Val::Tuple(items) => Value::Array(items.iter().map(val_to_json).collect()),
Val::Variant(tag, payload) => {
let mut obj = Map::new();
obj.insert("tag".to_string(), Value::String(tag.clone()));
if let Some(val_box) = payload {
obj.insert("val".to_string(), val_to_json(val_box));
}
Value::Object(obj)
}
Val::Enum(s) => Value::String(s.clone()),
Val::Option(None) => Value::Null,
Val::Option(Some(val_box)) => val_to_json(val_box),
Val::Result(Ok(opt_box)) => {
let mut obj = Map::new();
obj.insert(
"ok".to_string(),
match opt_box {
Some(v) => val_to_json(v),
None => Value::Null,
},
);
Value::Object(obj)
}
Val::Result(Err(opt_box)) => {
let mut obj = Map::new();
obj.insert(
"err".to_string(),
match opt_box {
Some(v) => val_to_json(v),
None => Value::Null,
},
);
Value::Object(obj)
}
Val::Flags(flags) => Value::Array(flags.iter().map(|f| Value::String(f.clone())).collect()),
Val::Resource(res) => Value::String(format!("resource: {res:?}")),
Val::Future(_) => Value::String("future value".to_string()),
Val::Stream(_) => Value::String("stream value".to_string()),
Val::ErrorContext(_) => Value::String("error context".to_string()),
}
}
fn json_to_val(value: &Value, ty: &Type) -> Result<Val, ValError> {
match ty {
Type::Bool => match value {
Value::Bool(b) => Ok(Val::Bool(*b)),
_ => Err(ValError::ShapeError("bool", format!("{value:?}"))),
},
Type::S8 => match value {
Value::Number(n) => n
.as_i64()
.and_then(|i| i8::try_from(i).ok())
.map(Val::S8)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("s8", format!("{value:?}"))),
},
Type::S16 => match value {
Value::Number(n) => n
.as_i64()
.and_then(|i| i16::try_from(i).ok())
.map(Val::S16)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("s16", format!("{value:?}"))),
},
Type::S32 => match value {
Value::Number(n) => n
.as_i64()
.and_then(|i| i32::try_from(i).ok())
.map(Val::S32)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("s32", format!("{value:?}"))),
},
Type::S64 => match value {
Value::Number(n) => n
.as_i64()
.map(Val::S64)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("s64", format!("{value:?}"))),
},
Type::U8 => match value {
Value::Number(n) => n
.as_u64()
.and_then(|i| u8::try_from(i).ok())
.map(Val::U8)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("u8", format!("{value:?}"))),
},
Type::U16 => match value {
Value::Number(n) => n
.as_u64()
.and_then(|i| u16::try_from(i).ok())
.map(Val::U16)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("u16", format!("{value:?}"))),
},
Type::U32 => match value {
Value::Number(n) => n
.as_u64()
.and_then(|i| u32::try_from(i).ok())
.map(Val::U32)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("u32", format!("{value:?}"))),
},
Type::U64 => match value {
Value::Number(n) => n
.as_u64()
.map(Val::U64)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("u64", format!("{value:?}"))),
},
Type::Float32 => match value {
Value::Number(n) => n
.as_f64()
.map(|f| Val::Float32(f as f32))
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("float32", format!("{value:?}"))),
},
Type::Float64 => match value {
Value::Number(n) => n
.as_f64()
.map(Val::Float64)
.ok_or_else(|| ValError::NumberError(format!("{n:?}"))),
_ => Err(ValError::ShapeError("float64", format!("{value:?}"))),
},
Type::Char => match value {
Value::String(s) => {
if s.chars().count() == 1 {
Ok(Val::Char(s.chars().next().unwrap()))
} else {
Err(ValError::InvalidChar(s.clone()))
}
}
_ => Err(ValError::ShapeError("char", format!("{value:?}"))),
},
Type::String => match value {
Value::String(s) => Ok(Val::String(s.clone())),
_ => Err(ValError::ShapeError("string", format!("{value:?}"))),
},
Type::List(list_handle) => match value {
Value::Array(arr) => {
let mut vals = Vec::new();
for item in arr {
vals.push(json_to_val(item, &list_handle.ty())?);
}
Ok(Val::List(vals))
}
_ => Err(ValError::ShapeError("list", format!("{value:?}"))),
},
Type::Record(r) => match value {
Value::Object(obj) => {
let mut fields = Vec::<(String, Val)>::new();
for field in r.fields() {
let value = obj.get(field.name).ok_or_else(|| {
ValError::ShapeError("record", format!("missing field {}", field.name))
})?;
fields.push((field.name.to_string(), json_to_val(value, &field.ty)?));
}
Ok(Val::Record(fields))
}
_ => Err(ValError::ShapeError("record", format!("{value:?}"))),
},
Type::Tuple(tup) => match value {
Value::Array(arr) => {
let types: Vec<_> = tup.types().collect();
if arr.len() != types.len() {
return Err(ValError::ShapeError(
"tuple",
format!("expected {} items, got {}", types.len(), arr.len()),
));
}
let mut items = Vec::new();
for (value, ty) in arr.iter().zip(types) {
items.push(json_to_val(value, &ty)?);
}
Ok(Val::Tuple(items))
}
_ => Err(ValError::ShapeError("tuple", format!("{value:?}"))),
},
Type::Variant(variant_handle) => match value {
Value::Object(obj) => {
let tag = obj
.get("tag")
.and_then(|v| v.as_str())
.ok_or_else(|| ValError::ShapeError("variant", "missing tag".to_string()))?;
let case = variant_handle
.cases()
.find(|c| c.name == tag)
.ok_or_else(|| ValError::UnknownShape(obj.clone()))?;
let payload = if let Some(payload_ty) = &case.ty {
let val = obj.get("val").ok_or_else(|| {
ValError::ShapeError("variant", "missing val".to_string())
})?;
Some(Box::new(json_to_val(val, payload_ty)?))
} else {
None
};
Ok(Val::Variant(tag.to_string(), payload))
}
_ => Err(ValError::ShapeError("variant", format!("{value:?}"))),
},
Type::Enum(enum_handle) => match value {
Value::String(s) => {
if enum_handle.names().any(|name| name == s) {
Ok(Val::Enum(s.clone()))
} else {
Err(ValError::ShapeError(
"enum",
format!("invalid enum value: {s}"),
))
}
}
_ => Err(ValError::ShapeError("enum", format!("{value:?}"))),
},
Type::Option(opt_handle) => match value {
Value::Null => Ok(Val::Option(None)),
v => Ok(Val::Option(Some(Box::new(json_to_val(
v,
&opt_handle.ty(),
)?)))),
},
Type::Result(res_handle) => match value {
Value::Object(obj) => {
if let Some(ok_val) = obj.get("ok") {
let ok_ty = res_handle.ok().unwrap_or(Type::Bool);
Ok(Val::Result(Ok(Some(Box::new(json_to_val(
ok_val, &ok_ty,
)?)))))
} else if let Some(err_val) = obj.get("err") {
let err_ty = res_handle.err().unwrap_or(Type::Bool);
Ok(Val::Result(Err(Some(Box::new(json_to_val(
err_val, &err_ty,
)?)))))
} else {
Err(ValError::ShapeError("result", format!("{value:?}")))
}
}
_ => Err(ValError::ShapeError("result", format!("{value:?}"))),
},
Type::Flags(flags_handle) => match value {
Value::Array(arr) => {
let mut flags = Vec::new();
for name in flags_handle.names() {
if arr.iter().any(|v| v.as_str() == Some(name)) {
flags.push(name.to_string());
}
}
Ok(Val::Flags(flags))
}
_ => Err(ValError::ShapeError("flags", format!("{value:?}"))),
},
Type::Own(_) | Type::Borrow(_) => Err(ValError::ResourceError),
Type::Future(_) => Err(ValError::ShapeError(
"future",
"Future types are not supported for input".to_string(),
)),
Type::Stream(_) => Err(ValError::ShapeError(
"stream",
"Stream types are not supported for input".to_string(),
)),
Type::ErrorContext => Err(ValError::ShapeError(
"error-context",
"ErrorContext types are not supported for input".to_string(),
)),
}
}
fn default_val_for_type(ty: &Type) -> Val {
match ty {
Type::Bool => Val::Bool(false),
Type::S8 => Val::S8(0),
Type::U8 => Val::U8(0),
Type::S16 => Val::S16(0),
Type::U16 => Val::U16(0),
Type::S32 => Val::S32(0),
Type::U32 => Val::U32(0),
Type::S64 => Val::S64(0),
Type::U64 => Val::U64(0),
Type::Float32 => Val::Float32(0.0),
Type::Float64 => Val::Float64(0.0),
Type::Char => Val::Char('\0'),
Type::String => Val::String("".to_string()),
Type::List(_) => Val::List(Vec::new()),
Type::Record(r) => {
let fields = r
.fields()
.map(|field| (field.name.to_string(), default_val_for_type(&field.ty)))
.collect();
Val::Record(fields)
}
Type::Tuple(t) => {
let vals = t.types().map(|ty| default_val_for_type(&ty)).collect();
Val::Tuple(vals)
}
Type::Variant(v) => {
// pick the first case as the default
if let Some(first_case) = v.cases().next() {
let payload = first_case
.ty
.map(|payload_ty| Box::new(default_val_for_type(&payload_ty)));
Val::Variant(first_case.name.to_string(), payload)
} else {
panic!("Cannot create a default for a variant with no cases.");
}
}
Type::Enum(e) => Val::Enum(e.names().next().unwrap_or("").to_string()),
Type::Option(_) => Val::Option(None),
Type::Result(_) => Val::Result(Ok(None)),
Type::Flags(_) => Val::Flags(Vec::new()),
// Resources cannot be created from scratch. This indicates a problem.
Type::Own(_) | Type::Borrow(_) => {
panic!("Cannot create a placeholder for a resource type.")