1use crate::translation::Language;
5use crate::translation::check::check_program;
6use crate::translation::emit_common::{Assumption, Encoding, Mapping, TheoremRecord};
7use crate::translation::emit_javascript::{
8 JavaScriptEmissionOptions, emit_javascript_with_options,
9};
10use crate::translation::emit_rust::{RustEmissionOptions, emit_rust_with_array_consumption};
11use crate::translation::ir::Program;
12use crate::translation::javascript::{parse_javascript, parse_javascript_with_scalar_loop_model};
13use crate::translation::rust::{
14 parse_rust, parse_rust_with_const_function_model, parse_rust_with_empty_option_source_model,
15 parse_rust_with_loop_profiles, parse_rust_with_owned_local_state_model,
16 parse_rust_with_primitive_owner_model, parse_rust_with_pure_unit_call_model,
17 parse_rust_with_runtime_shell_model, parse_rust_with_type_namespace_model,
18};
19use crate::{LinkId, LinkMetadata, LinkNetwork, LinkType};
20use serde_json::Value;
21use std::fmt;
22use std::sync::OnceLock;
23
24mod borrowed_call_diagnostics;
25mod callables;
26mod checked;
27mod codec;
28pub mod program_numeric_metadata;
29pub mod program_numeric_metadata_rules;
30mod projection;
31pub mod source_span_rules;
32pub mod source_spans;
33
34#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct TypedProgramLinksError {
37 pub message: String,
39}
40impl fmt::Display for TypedProgramLinksError {
41 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
42 formatter.write_str(&self.message)
43 }
44}
45impl std::error::Error for TypedProgramLinksError {}
46type Result<T> = std::result::Result<T, TypedProgramLinksError>;
47fn error(message: impl Into<String>) -> TypedProgramLinksError {
48 TypedProgramLinksError {
49 message: message.into(),
50 }
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct TypedProgramLinks {
56 pub network: LinkNetwork,
58 pub root: LinkId,
60}
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct TypedProgramLinksLimits {
64 pub node_limit: usize,
66 pub depth_limit: usize,
68}
69impl Default for TypedProgramLinksLimits {
70 fn default() -> Self {
71 Self {
72 node_limit: 100_000,
73 depth_limit: 256,
74 }
75 }
76}
77#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct TypedProgramLinksEmission {
80 pub code: String,
82 pub language: Language,
84 pub mappings: Vec<Mapping>,
86 pub assumptions: Vec<Assumption>,
88 pub encodings: Vec<Encoding>,
90 pub theorems: Vec<TheoremRecord>,
92}
93
94#[derive(Clone, Debug, Default, PartialEq, Eq)]
96pub struct TypedProgramLinksEmissionOptions {
97 pub rust_source_header_emission_model: Option<String>,
99 pub java_script_scoped_binding_emission_model: Option<String>,
101}
102
103pub fn validate_checked_program(program: &Program) -> Result<()> {
104 checked::validate(program)
105}
106#[must_use]
108pub fn typed_program_links_schema() -> &'static Value {
109 static SCHEMA: OnceLock<Value> = OnceLock::new();
110 SCHEMA.get_or_init(|| {
111 crate::read_structured_data_lino(include_str!("data/typed-program-links-schema.lino"))
112 .expect("generated typed schema is structured Links data")
113 })
114}
115fn metadata(term: &str, definition: Option<&str>) -> LinkMetadata {
116 let result = LinkMetadata::new()
117 .with_link_type(LinkType::Semantic)
118 .with_named(true)
119 .with_language(typed_program_links_schema()["language"].as_str().unwrap())
120 .with_term(term);
121 if let Some(definition) = definition {
122 result.with_definition(definition)
123 } else {
124 result
125 }
126}
127pub fn label_of(name: &str) -> String {
128 typed_program_links_schema()["fields"][name]
129 .as_str()
130 .map_or_else(
131 || {
132 let mut label = String::new();
133 for character in name.chars() {
134 if character.is_ascii_uppercase() {
135 label.push(' ');
136 label.push(character.to_ascii_lowercase());
137 } else {
138 label.push(character);
139 }
140 }
141 label
142 },
143 str::to_owned,
144 )
145}
146pub fn field_of(label: &str) -> String {
147 if let Some((field, _)) = typed_program_links_schema()["fields"]
148 .as_object()
149 .unwrap()
150 .iter()
151 .find(|(_, value)| value.as_str() == Some(label))
152 {
153 return field.clone();
154 }
155 let mut name = String::new();
156 let mut uppercase = false;
157 for character in label.chars() {
158 if character == ' ' {
159 uppercase = true;
160 } else {
161 name.push(if uppercase {
162 character.to_ascii_uppercase()
163 } else {
164 character
165 });
166 uppercase = false;
167 }
168 }
169 name
170}
171pub fn encode_typed_program_links(program: &Program) -> Result<TypedProgramLinks> {
176 encode_typed_program_links_with_provenance(program, None)
177}
178pub fn encode_typed_program_links_with_provenance(
183 program: &Program,
184 provenance: Option<&Value>,
185) -> Result<TypedProgramLinks> {
186 checked::validate(program)?;
187 codec::encode(program, provenance)
188}
189pub fn decode_typed_program_links(network: &LinkNetwork, root: LinkId) -> Result<Program> {
195 decode_typed_program_links_with_limits(network, root, TypedProgramLinksLimits::default())
196}
197pub fn decode_typed_program_links_with_limits(
202 network: &LinkNetwork,
203 root: LinkId,
204 limits: TypedProgramLinksLimits,
205) -> Result<Program> {
206 let program = codec::decode(network, root, limits)?;
207 checked::validate(&program)?;
208 Ok(program)
209}
210
211pub fn read_typed_program_binding_identities(
212 network: &LinkNetwork,
213 root: LinkId,
214) -> Result<Vec<LinkId>> {
215 let (program, identities) =
216 codec::decode_with_binding_identities(network, root, TypedProgramLinksLimits::default())?;
217 checked::validate(&program)?;
218 Ok(identities)
219}
220pub fn create_typed_program_links(source: &str, language: &str) -> Result<TypedProgramLinks> {
225 let surface = match language.to_ascii_lowercase().as_str() {
226 "javascript" | "js" | "mjs" => parse_javascript(source),
227 "rust" | "rs" => parse_rust(source),
228 _ => {
229 return Err(error(
230 "typed linked source import currently reads JavaScript and Rust",
231 ));
232 }
233 }
234 .map_err(|failure| error(failure.to_string()))?;
235 encode_typed_program_links(
236 &check_program(&surface).map_err(|failure| error(failure.to_string()))?,
237 )
238}
239pub fn create_typed_program_links_with_rust_array_result_model(
249 source: &str,
250 language: &str,
251 model: &str,
252 provenance: Option<&Value>,
253) -> Result<TypedProgramLinks> {
254 create_typed_program_links_with_rust_source_models(
255 source,
256 language,
257 Some(model),
258 None,
259 provenance,
260 )
261}
262
263pub fn create_typed_program_links_with_rust_completion_model(
268 source: &str,
269 language: &str,
270 model: &str,
271 provenance: Option<&Value>,
272) -> Result<TypedProgramLinks> {
273 create_typed_program_links_with_rust_source_models(
274 source,
275 language,
276 None,
277 Some(model),
278 provenance,
279 )
280}
281
282pub fn create_typed_program_links_with_rust_source_models(
290 source: &str,
291 language: &str,
292 array_result_model: Option<&str>,
293 completion_model: Option<&str>,
294 provenance: Option<&Value>,
295) -> Result<TypedProgramLinks> {
296 create_typed_program_links_with_rust_source_profiles(
297 source,
298 language,
299 array_result_model,
300 completion_model,
301 None,
302 provenance,
303 )
304}
305
306pub fn create_typed_program_links_with_rust_source_signature_model(
311 source: &str,
312 language: &str,
313 model: &str,
314 provenance: Option<&Value>,
315) -> Result<TypedProgramLinks> {
316 create_typed_program_links_with_rust_source_profiles(
317 source,
318 language,
319 None,
320 None,
321 Some(model),
322 provenance,
323 )
324}
325
326pub fn create_typed_program_links_with_rust_primitive_owner_model(
335 source: &str,
336 language: &str,
337 model: &str,
338 source_signature_model: Option<&str>,
339 provenance: Option<&Value>,
340) -> Result<TypedProgramLinks> {
341 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
342 return Err(error("a Rust primitive owner model requires Rust source"));
343 }
344 let surface =
345 parse_rust_with_primitive_owner_model(source, model, source_signature_model.unwrap_or(""))
346 .map_err(|failure| error(failure.to_string()))?;
347 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
348 let mut profile = serde_json::Map::new();
349 profile.insert("language".into(), Value::String("Rust".into()));
350 profile.insert(
351 "rustPrimitiveOwnerModel".into(),
352 Value::String(model.into()),
353 );
354 if let Some(model) = source_signature_model {
355 profile.insert(
356 "rustSourceSignatureModel".into(),
357 Value::String(model.into()),
358 );
359 }
360 let selected = serde_json::json!({
361 "sourceProfile": profile,
362 "userProvenance": provenance,
363 });
364 encode_typed_program_links_with_provenance(&program, Some(&selected))
365}
366
367pub fn create_typed_program_links_with_rust_pure_unit_call_model(
372 source: &str,
373 language: &str,
374 model: &str,
375 provenance: Option<&Value>,
376) -> Result<TypedProgramLinks> {
377 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
378 return Err(error("a Rust pure Unit-call model requires Rust source"));
379 }
380 let surface = parse_rust_with_pure_unit_call_model(source, model)
381 .map_err(|failure| error(failure.to_string()))?;
382 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
383 let selected = serde_json::json!({"sourceProfile":{"language":"Rust","rustPureUnitCallModel":model},"userProvenance":provenance});
384 encode_typed_program_links_with_provenance(&program, Some(&selected))
385}
386
387pub fn create_typed_program_links_with_rust_runtime_shell_model(
392 source: &str,
393 language: &str,
394 model: &str,
395 provenance: Option<&Value>,
396) -> Result<TypedProgramLinks> {
397 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
398 return Err(error("a Rust runtime shell model requires Rust source"));
399 }
400 let surface = parse_rust_with_runtime_shell_model(source, model)
401 .map_err(|failure| error(failure.to_string()))?;
402 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
403 let selected = serde_json::json!({"sourceProfile":{"language":"Rust","rustRuntimeShellModel":model},"userProvenance":provenance});
404 encode_typed_program_links_with_provenance(&program, Some(&selected))
405}
406
407pub fn create_typed_program_links_with_rust_const_function_model(
412 source: &str,
413 language: &str,
414 model: &str,
415 source_signature_model: Option<&str>,
416 provenance: Option<&Value>,
417) -> Result<TypedProgramLinks> {
418 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
419 return Err(error("a Rust const function model requires Rust source"));
420 }
421 let surface =
422 parse_rust_with_const_function_model(source, model, source_signature_model.unwrap_or(""))
423 .map_err(|failure| error(failure.to_string()))?;
424 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
425 let mut profile = serde_json::Map::new();
426 profile.insert("language".into(), Value::String("Rust".into()));
427 profile.insert("rustConstFunctionModel".into(), Value::String(model.into()));
428 if let Some(model) = source_signature_model {
429 profile.insert(
430 "rustSourceSignatureModel".into(),
431 Value::String(model.into()),
432 );
433 }
434 let selected = serde_json::json!({"sourceProfile":profile,"userProvenance":provenance});
435 encode_typed_program_links_with_provenance(&program, Some(&selected))
436}
437
438pub fn create_typed_program_links_with_rust_owned_local_state_model(
443 source: &str,
444 language: &str,
445 model: &str,
446 source_signature_model: Option<&str>,
447 provenance: Option<&Value>,
448) -> Result<TypedProgramLinks> {
449 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
450 return Err(error("a Rust owned local state model requires Rust source"));
451 }
452 let surface = parse_rust_with_owned_local_state_model(
453 source,
454 model,
455 source_signature_model.unwrap_or(""),
456 )
457 .map_err(|failure| error(failure.to_string()))?;
458 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
459 let mut profile = serde_json::Map::new();
460 profile.insert("language".into(), Value::String("Rust".into()));
461 profile.insert(
462 "rustOwnedLocalStateModel".into(),
463 Value::String(model.into()),
464 );
465 if let Some(model) = source_signature_model {
466 profile.insert(
467 "rustSourceSignatureModel".into(),
468 Value::String(model.into()),
469 );
470 }
471 let selected = serde_json::json!({"sourceProfile":profile,"userProvenance":provenance});
472 encode_typed_program_links_with_provenance(&program, Some(&selected))
473}
474
475pub fn create_typed_program_links_with_rust_type_namespace_model(
483 source: &str,
484 language: &str,
485 model: &str,
486 source_signature_model: Option<&str>,
487 provenance: Option<&Value>,
488) -> Result<TypedProgramLinks> {
489 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
490 return Err(error("a Rust type namespace model requires Rust source"));
491 }
492 let surface =
493 parse_rust_with_type_namespace_model(source, model, source_signature_model.unwrap_or(""))
494 .map_err(|failure| error(failure.to_string()))?;
495 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
496 let mut profile = serde_json::Map::new();
497 profile.insert("language".into(), Value::String("Rust".into()));
498 profile.insert("rustTypeNamespaceModel".into(), Value::String(model.into()));
499 if let Some(model) = source_signature_model {
500 profile.insert(
501 "rustSourceSignatureModel".into(),
502 Value::String(model.into()),
503 );
504 }
505 let selected = serde_json::json!({"sourceProfile":profile,"userProvenance":provenance});
506 encode_typed_program_links_with_provenance(&program, Some(&selected))
507}
508
509pub fn create_typed_program_links_with_rust_empty_option_source_model(
517 source: &str,
518 language: &str,
519 model: &str,
520 provenance: Option<&Value>,
521) -> Result<TypedProgramLinks> {
522 if !matches!(language.to_ascii_lowercase().as_str(), "rust" | "rs") {
523 return Err(error(
524 "a Rust empty option source model requires Rust source",
525 ));
526 }
527 let surface = parse_rust_with_empty_option_source_model(source, model)
528 .map_err(|failure| error(failure.to_string()))?;
529 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
530 let selected = serde_json::json!({
531 "sourceProfile":{"language":"Rust","rustEmptyOptionSourceModel":model},
532 "userProvenance":provenance,
533 });
534 encode_typed_program_links_with_provenance(&program, Some(&selected))
535}
536
537pub fn create_typed_program_links_with_rust_source_profiles(
542 source: &str,
543 language: &str,
544 array_result_model: Option<&str>,
545 completion_model: Option<&str>,
546 source_signature_model: Option<&str>,
547 provenance: Option<&Value>,
548) -> Result<TypedProgramLinks> {
549 create_typed_program_links_with_scalar_loop_profiles(
550 source,
551 language,
552 array_result_model,
553 completion_model,
554 source_signature_model,
555 (None, None),
556 provenance,
557 )
558}
559
560pub fn create_typed_program_links_with_rust_scalar_loop_model(
565 source: &str,
566 language: &str,
567 model: &str,
568 provenance: Option<&Value>,
569) -> Result<TypedProgramLinks> {
570 create_typed_program_links_with_scalar_loop_profiles(
571 source,
572 language,
573 None,
574 None,
575 None,
576 (Some(model), None),
577 provenance,
578 )
579}
580
581pub fn create_typed_program_links_with_javascript_scalar_loop_model(
586 source: &str,
587 language: &str,
588 model: &str,
589 provenance: Option<&Value>,
590) -> Result<TypedProgramLinks> {
591 create_typed_program_links_with_scalar_loop_profiles(
592 source,
593 language,
594 None,
595 None,
596 None,
597 (None, Some(model)),
598 provenance,
599 )
600}
601
602pub fn create_typed_program_links_with_scalar_loop_profiles(
610 source: &str,
611 language: &str,
612 array_result_model: Option<&str>,
613 completion_model: Option<&str>,
614 source_signature_model: Option<&str>,
615 scalar_loop_models: (Option<&str>, Option<&str>),
616 provenance: Option<&Value>,
617) -> Result<TypedProgramLinks> {
618 let (rust_scalar_loop_model, javascript_scalar_loop_model) = scalar_loop_models;
619 let canonical = match language.to_ascii_lowercase().as_str() {
620 "rust" | "rs" => "Rust",
621 "javascript" | "js" | "mjs" => "JavaScript",
622 _ => {
623 return Err(error(
624 "typed linked source import currently reads JavaScript and Rust",
625 ));
626 }
627 };
628 if canonical != "Rust" {
629 if array_result_model.is_some() {
630 return Err(error("a Rust array result model requires Rust source"));
631 }
632 if completion_model.is_some() {
633 return Err(error("a Rust completion model requires Rust source"));
634 }
635 if source_signature_model.is_some() {
636 return Err(error("a Rust source signature model requires Rust source"));
637 }
638 if rust_scalar_loop_model.is_some() {
639 return Err(error("a Rust scalar loop model requires Rust source"));
640 }
641 }
642 if javascript_scalar_loop_model.is_some() && canonical != "JavaScript" {
643 return Err(error(
644 "a JavaScript scalar loop model requires JavaScript source",
645 ));
646 }
647 let surface = if canonical == "Rust" {
648 parse_rust_with_loop_profiles(
649 source,
650 array_result_model.unwrap_or(""),
651 completion_model.unwrap_or(""),
652 source_signature_model.unwrap_or(""),
653 rust_scalar_loop_model.unwrap_or(""),
654 )
655 } else if let Some(model) = javascript_scalar_loop_model {
656 parse_javascript_with_scalar_loop_model(source, model)
657 } else {
658 parse_javascript(source)
659 }
660 .map_err(|failure| error(failure.to_string()))?;
661 let program = check_program(&surface).map_err(|failure| error(failure.to_string()))?;
662 if array_result_model.is_none()
663 && completion_model.is_none()
664 && source_signature_model.is_none()
665 && rust_scalar_loop_model.is_none()
666 && javascript_scalar_loop_model.is_none()
667 {
668 return encode_typed_program_links_with_provenance(&program, provenance);
669 }
670 let mut profile = serde_json::Map::new();
671 profile.insert("language".into(), Value::String(canonical.into()));
672 if let Some(model) = array_result_model {
673 profile.insert("rustArrayResultModel".into(), Value::String(model.into()));
674 }
675 if let Some(model) = completion_model {
676 profile.insert("rustCompletionModel".into(), Value::String(model.into()));
677 }
678 if let Some(model) = source_signature_model {
679 profile.insert(
680 "rustSourceSignatureModel".into(),
681 Value::String(model.into()),
682 );
683 }
684 if let Some(model) = rust_scalar_loop_model {
685 profile.insert("rustScalarLoopModel".into(), Value::String(model.into()));
686 }
687 if let Some(model) = javascript_scalar_loop_model {
688 profile.insert(
689 "javaScriptScalarLoopModel".into(),
690 Value::String(model.into()),
691 );
692 }
693 let selected_provenance = serde_json::json!({
694 "sourceProfile": profile,
695 "userProvenance": provenance,
696 });
697 encode_typed_program_links_with_provenance(&program, Some(&selected_provenance))
698}
699
700pub fn emit_typed_program_links(
705 network: &LinkNetwork,
706 root: LinkId,
707 target: &str,
708) -> Result<TypedProgramLinksEmission> {
709 emit_typed_program_links_with_options(
710 network,
711 root,
712 target,
713 &TypedProgramLinksEmissionOptions::default(),
714 )
715}
716
717pub fn emit_typed_program_links_with_options(
722 network: &LinkNetwork,
723 root: LinkId,
724 target: &str,
725 options: &TypedProgramLinksEmissionOptions,
726) -> Result<TypedProgramLinksEmission> {
727 let source_header_model = options.rust_source_header_emission_model.as_deref();
728 let rust_target = matches!(target.to_ascii_lowercase().as_str(), "rust" | "rs");
729 if rust_target
730 && options.java_script_scoped_binding_emission_model.is_none()
731 && let Some(model) = source_header_model
732 {
733 crate::translation::source_header_emission::validate_rust_source_header_emission_model(
734 model,
735 )
736 .map_err(|failure| error(failure.to_string()))?;
737 crate::shared_numeric_function_model::validate_shared_numeric_origin_context(network, root)
738 .map_err(|failure| error(format!("Rust source header emission: {failure}")))?;
739 }
740 if matches!(
741 target.to_ascii_lowercase().as_str(),
742 "javascript" | "js" | "mjs"
743 ) && options.rust_source_header_emission_model.is_none()
744 && let Some(model) = options.java_script_scoped_binding_emission_model.as_deref()
745 {
746 crate::translation::scoped_binding_emission::validate_raw_program(network, root, model)
747 .map_err(|failure| error(failure.to_string()))?;
748 }
749 let decoded = if rust_target
750 && options.java_script_scoped_binding_emission_model.is_none()
751 && let Some(model) = source_header_model.filter(|model| {
752 crate::translation::borrowed_call_interface_rules::accept_rust_borrowed_call_interface_model(model)
753 })
754 {
755 borrowed_call_diagnostics::decode(network, root, model)
756 } else {
757 decode_typed_program_links(network, root).map_err(|failure| (failure, false))
758 };
759 let program = decoded.map_err(|(failure, refined)| {
760 if !refined
761 && rust_target
762 && options.java_script_scoped_binding_emission_model.is_none()
763 && source_header_model.is_some()
764 {
765 error(format!("Rust source header emission: {failure}"))
766 } else {
767 failure
768 }
769 })?;
770 let emitted = match target.to_ascii_lowercase().as_str() {
771 "javascript" | "js" | "mjs" => {
772 if source_header_model.is_some() {
773 return Err(error(
774 "a Rust source header emission model requires Rust target",
775 ));
776 }
777 let scoped_binding_model = options.java_script_scoped_binding_emission_model.as_deref();
778 if let Some(model) = scoped_binding_model {
779 crate::translation::scoped_binding_emission::validate_program(&program, model)
780 .map_err(|failure| error(failure.to_string()))?;
781 crate::translation::scoped_binding_emission::validate_origin_context(
782 network, root, &program,
783 )
784 .map_err(|failure| error(failure.to_string()))?;
785 }
786 emit_javascript_with_options(
787 &program,
788 JavaScriptEmissionOptions {
789 scoped_binding_model,
790 identifier_model: None,
791 },
792 )
793 }
794 "rust" | "rs" => {
795 if options.java_script_scoped_binding_emission_model.is_some() {
796 return Err(error(
797 "a JavaScript scoped binding emission model requires JavaScript target",
798 ));
799 }
800 emit_rust_with_array_consumption(
801 &program,
802 RustEmissionOptions {
803 source_header_model,
804 },
805 )
806 }
807 _ => {
808 return Err(error(
809 "typed linked emission currently writes JavaScript and Rust",
810 ));
811 }
812 }
813 .map_err(|failure| error(failure.to_string()))?;
814 Ok(TypedProgramLinksEmission {
815 code: emitted.text,
816 language: emitted.language,
817 mappings: emitted.mappings,
818 assumptions: emitted.assumptions,
819 encodings: emitted.encodings,
820 theorems: emitted.theorems,
821 })
822}