1use std::collections::{HashMap, HashSet};
78use std::fs;
79use std::io::Write;
80use std::path::Path;
81use std::process::Command;
82
83const CRATES_DATA_PATH: &str = "crates/logicaffeine_data";
85const CRATES_SYSTEM_PATH: &str = "crates/logicaffeine_system";
86
87use std::fmt::Write as FmtWrite;
88
89use crate::analysis::{DiscoveryPass, EscapeChecker, OwnershipChecker, PolicyRegistry};
90use crate::arena::Arena;
91use crate::arena_ctx::AstContext;
92use crate::ast::stmt::{
93 BinaryOpKind, ClosureBody, Literal, Pattern, ReadSource, SelectBranch, StringPart,
94};
95use crate::ast::{Expr, MatchArm, Stmt, TypeExpr};
96use crate::codegen::{
97 codegen_program, generate_c_header, generate_python_bindings, generate_typescript_bindings,
98};
99use crate::diagnostic::{parse_rustc_json, translate_diagnostics, LogosError};
100use crate::drs::WorldState;
101use crate::error::ParseError;
102use crate::intern::Interner;
103use crate::lexer::Lexer;
104use crate::parser::Parser;
105use crate::semantics::collections::with_reference_semantics;
106use crate::sourcemap::SourceMap;
107
108#[derive(Debug, Clone)]
110pub struct CrateDependency {
111 pub name: String,
112 pub version: String,
113 pub features: Vec<String>,
114}
115
116#[derive(Debug)]
118pub struct CompileOutput {
119 pub rust_code: String,
120 pub dependencies: Vec<CrateDependency>,
121 pub c_header: Option<String>,
123 pub python_bindings: Option<String>,
125 pub typescript_types: Option<String>,
127 pub typescript_bindings: Option<String>,
129}
130
131pub fn interpret_program(source: &str) -> Result<String, ParseError> {
149 let result = crate::ui_bridge::interpret_for_ui_sync(source);
150 if let Some(err) = result.error {
151 Err(ParseError {
152 kind: crate::error::ParseErrorKind::Custom(err),
153 span: crate::token::Span::default(),
154 })
155 } else {
156 Ok(result.lines.join("\n"))
157 }
158}
159
160pub fn interpret_bootstrap(source: &str) -> Result<String, ParseError> {
165 with_reference_semantics(|| interpret_program(source))
166}
167
168pub fn vm_run_source(source: &str) -> Result<String, String> {
175 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
176 Ok((stmts, types, policies)) => {
177 let (output, error) =
178 crate::vm::run_to_outcome(stmts, interner, Some(types), Some(&policies));
179 match error {
180 None => Ok(output),
181 Some(e) => Err(e),
182 }
183 }
184 Err(advice) => Err(advice),
185 })
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct RunOutcome {
193 pub output: String,
194 pub error: Option<String>,
195}
196
197pub const FIRST_CLASS_VALUE_KINDS: &[&str] = &[
207 "int",
208 "real",
209 "bool",
210 "text",
211 "seq_int",
212 "seq_text",
213 "seq_seq",
214 "set_int",
215 "struct",
216 "tuple_anon",
217 "multi_return",
218 "record_named",
219 "destructure",
220 "seq_tuple",
221];
222
223pub fn tw_outcome(source: &str) -> RunOutcome {
228 let result = tw_lines(source);
229 RunOutcome {
230 output: result.lines.join("\n"),
231 error: result.error,
232 }
233}
234
235pub fn tw_lines(source: &str) -> crate::interpreter::InterpreterResult {
239 tw_lines_with_args(source, &[])
240}
241
242pub fn tw_lines_with_args(
245 source: &str,
246 program_args: &[String],
247) -> crate::interpreter::InterpreterResult {
248 crate::concurrency::net_inbox::set_net_offline(true);
251 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
252 Ok((stmts, types, policies)) => {
253 let force_async = crate::interpreter::needs_async(stmts, interner);
254 crate::ui_bridge::run_treewalker(
255 stmts,
256 types,
257 policies,
258 interner,
259 force_async,
260 program_args,
261 )
262 }
263 Err(advice) => crate::interpreter::InterpreterResult {
264 lines: Vec::new(),
265 error: Some(advice),
266 },
267 })
268}
269
270fn main_drives_a_page(stmts: &[Stmt], interner: &Interner) -> Option<usize> {
283 let is_drive = |s: &Stmt| {
284 matches!(
285 crate::page_host::classify(s, interner),
286 crate::page_host::Classified::Drive(_)
287 )
288 };
289 let mut split = stmts.len();
290 while split > 0 && is_drive(&stmts[split - 1]) {
291 split -= 1;
292 }
293 if split == stmts.len() {
294 return None;
296 }
297 let mounts = stmts[split..].iter().any(|s| {
298 matches!(
299 crate::page_host::classify(s, interner),
300 crate::page_host::Classified::Drive(crate::page_host::Drive::Mount { .. })
301 )
302 });
303 mounts.then_some(split)
304}
305
306pub fn vm_outcome(source: &str) -> RunOutcome {
319 crate::semantics::storage::reset();
320 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
321 Ok((stmts, types, policies)) => {
322 if let Some(split) = main_drives_a_page(stmts, interner) {
323 return match crate::page_host::drive_main(
324 &stmts[..split],
325 &stmts[split..],
326 interner,
327 types,
328 &policies,
329 ) {
330 Ok(output) => RunOutcome {
331 output,
332 error: None,
333 },
334 Err(e) => RunOutcome {
335 output: String::new(),
336 error: Some(e),
337 },
338 };
339 }
340 let (output, error) =
341 crate::vm::run_to_outcome(stmts, interner, Some(types), Some(&policies));
342 RunOutcome { output, error }
343 }
344 Err(advice) => RunOutcome {
345 output: String::new(),
346 error: Some(advice),
347 },
348 })
349}
350
351fn locate_runtime_failure(
366 source: &str,
367 interner: &Interner,
368 site: Option<u32>,
369 message: &str,
370) -> String {
371 let Some(id) = site else {
372 return message.to_string();
373 };
374 let sites = crate::ui_bridge::failure_sites_of(source);
375 let Some(site) = sites.get(id as usize) else {
376 return message.to_string();
377 };
378 let (line, col) = logicaffeine_language::diagnostic::line_col(source, site.span.start);
379 format!("{line}:{col} — {}", site.render(interner, message))
380}
381
382pub fn tw_outcome_located(source: &str) -> RunOutcome {
388 crate::concurrency::net_inbox::set_net_offline(true);
389 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
390 Ok((stmts, types, policies)) => {
391 if crate::concurrency::uses_scheduler(stmts) {
392 let force_async = crate::interpreter::needs_async(stmts, interner);
393 let result = crate::ui_bridge::run_treewalker(
394 stmts,
395 types,
396 policies,
397 interner,
398 force_async,
399 &[],
400 );
401 return RunOutcome {
402 output: result.lines.join("\n"),
403 error: result.error,
404 };
405 }
406 let force_async = crate::interpreter::needs_async(stmts, interner);
407 let mut interp = crate::interpreter::Interpreter::new(interner)
408 .with_type_registry(types)
409 .with_policies(policies)
410 .with_vfs(std::sync::Arc::new(logicaffeine_system::fs::MemVfs::new()));
411 let run_result = if force_async {
412 futures::executor::block_on(interp.run(stmts))
413 } else {
414 interp.run_sync(stmts)
415 };
416 let site = interp.page_failure_site().or(interp.current_site);
417 let unhandled = interp.take_page_failure();
418 let (error, site) = match run_result {
419 Err(e) => (Some(e), interp.current_site),
420 Ok(()) => (unhandled, site),
421 };
422 let error = error.map(|msg| locate_runtime_failure(source, interner, site, &msg));
423 RunOutcome {
424 output: interp.output.join("\n"),
425 error,
426 }
427 }
428 Err(advice) => RunOutcome {
429 output: String::new(),
430 error: Some(advice),
431 },
432 })
433}
434
435pub fn vm_outcome_located(source: &str) -> RunOutcome {
441 crate::semantics::storage::reset();
442 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
443 Ok((stmts, types, policies)) => {
444 let (output, error, site) =
445 crate::vm::run_to_outcome_located(stmts, interner, Some(types), Some(&policies));
446 let error = error.map(|msg| locate_runtime_failure(source, interner, site, &msg));
447 RunOutcome { output, error }
448 }
449 Err(advice) => RunOutcome {
450 output: String::new(),
451 error: Some(advice),
452 },
453 })
454}
455
456#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub enum EngineId {
460 TreeWalker,
462 Vm,
464}
465
466impl EngineId {
467 pub fn label(self) -> &'static str {
469 match self {
470 EngineId::TreeWalker => "tree-walker",
471 EngineId::Vm => "vm",
472 }
473 }
474}
475
476#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct EngineOutcome {
483 pub engine_ran: Option<EngineId>,
485 pub output: String,
488 pub error: Option<String>,
490}
491
492impl EngineOutcome {
493 pub fn refused(&self) -> bool {
496 self.engine_ran.is_none()
497 }
498}
499
500fn strict_trace(engine: &str) {
503 if std::env::var_os("LOGOS_ENGINE_TRACE").is_some() {
504 eprintln!("logos-engine: {engine}");
505 }
506}
507
508pub fn run_strict_tw(source: &str) -> EngineOutcome {
514 run_strict_tw_with_args(source, &[])
515}
516
517pub fn run_strict_tw_with_args(source: &str, program_args: &[String]) -> EngineOutcome {
520 crate::concurrency::net_inbox::set_net_offline(true);
522 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
523 Ok((stmts, types, policies)) => {
524 let force_async = crate::interpreter::needs_async(stmts, interner);
525 strict_trace("strict treewalker");
526 let result = crate::ui_bridge::run_treewalker(
527 stmts,
528 types,
529 policies,
530 interner,
531 force_async,
532 program_args,
533 );
534 EngineOutcome {
535 engine_ran: Some(EngineId::TreeWalker),
536 output: result.lines.join("\n"),
537 error: result.error,
538 }
539 }
540 Err(advice) => EngineOutcome {
541 engine_ran: None,
542 output: String::new(),
543 error: Some(advice),
544 },
545 })
546}
547
548pub fn run_strict_vm(source: &str) -> EngineOutcome {
555 run_strict_vm_with_args(source, &[])
556}
557
558pub fn run_strict_vm_with_args(source: &str, program_args: &[String]) -> EngineOutcome {
562 let refusal = |why: String| {
563 strict_trace("strict vm (refused)");
564 EngineOutcome {
565 engine_ran: None,
566 output: String::new(),
567 error: Some(why),
568 }
569 };
570 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
571 Ok((stmts, types, policies)) => {
572 if crate::interpreter::needs_async(stmts, interner) {
576 return refusal(
577 "strict vm: refused — this program needs the async runtime (file I/O, \
578 sleep, serve, or networking); the bytecode VM is sync-only and the \
579 tree-walker is never silently substituted"
580 .to_string(),
581 );
582 }
583 if crate::concurrency::uses_scheduler(stmts) {
584 return refusal(
585 "strict vm: refused — this program uses tasks/channels, which need the \
586 scheduler driver; the plain bytecode VM cannot run it and the \
587 tree-walker is never silently substituted"
588 .to_string(),
589 );
590 }
591 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
592 let program = match crate::vm::Compiler::compile_with_oracle(
593 stmts,
594 interner,
595 Some(types),
596 Some(oracle),
597 ) {
598 Ok(p) => p,
599 Err(e) => {
600 return refusal(format!(
601 "strict vm: refused — the VM compiler cannot compile this program: {e}"
602 ))
603 }
604 };
605 strict_trace("strict vm");
606 let mut vm = crate::vm::Vm::new(&program)
607 .with_policy_ctx(&policies, interner)
608 .with_program_args(program_args.to_vec());
609 if crate::interpreter::active_fuel().is_none() {
613 if let Some(tier) = crate::vm::installed_native_tier() {
614 vm = vm.with_native_tier(tier);
615 }
616 }
617 let error = crate::vm::drive_vm(&mut vm);
618 EngineOutcome {
619 engine_ran: Some(EngineId::Vm),
620 output: vm.into_lines().join("\n"),
621 error,
622 }
623 }
624 Err(advice) => EngineOutcome {
625 engine_ran: None,
626 output: String::new(),
627 error: Some(advice),
628 },
629 })
630}
631
632pub fn vm_outcome_observed(source: &str) -> RunOutcome {
638 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
639 Ok((stmts, types, policies)) => {
640 let (output, error) =
641 crate::vm::run_to_outcome_observed(stmts, interner, Some(types), Some(&policies));
642 RunOutcome { output, error }
643 }
644 Err(advice) => RunOutcome {
645 output: String::new(),
646 error: Some(advice),
647 },
648 })
649}
650
651#[derive(Clone, Debug, PartialEq, Eq)]
656pub enum TierVerdict {
657 Agree {
659 output: String,
660 error: Option<String>,
661 },
662 Divergence { compiler_bug: bool, bundle: String },
666}
667
668pub fn tier_differential(source: &str) -> TierVerdict {
678 let tw = tw_outcome(source);
679 let vm = vm_outcome(source);
680
681 let vm_declined = vm
685 .error
686 .as_deref()
687 .map(|e| e.contains("scheduler driver"))
688 .unwrap_or(false);
689 if vm_declined {
690 return TierVerdict::Agree {
691 output: tw.output,
692 error: tw.error,
693 };
694 }
695
696 let outputs_agree = tw.output.trim_end() == vm.output.trim_end();
697 let errors_agree = tw.error == vm.error;
698 if outputs_agree && errors_agree {
699 TierVerdict::Agree {
700 output: tw.output,
701 error: tw.error,
702 }
703 } else {
704 let bundle = format!(
705 "TIER DIVERGENCE — a compiler bug (the framework's liability, never your program's).\n\
706 This is footgun F18: a 5-tier language must guarantee every tier agrees.\n\
707 --- source ---\n{source}\n\
708 --- tree-walker (oracle) ---\noutput={:?}\nerror={:?}\n\
709 --- register VM ---\noutput={:?}\nerror={:?}\n",
710 tw.output, tw.error, vm.output, vm.error
711 );
712 TierVerdict::Divergence {
713 compiler_bug: true,
714 bundle,
715 }
716 }
717}
718
719#[cfg(not(target_arch = "wasm32"))]
725pub fn vm_outcome_concurrent(source: &str) -> RunOutcome {
726 let r = crate::ui_bridge::run_vm_concurrent(source);
727 RunOutcome {
728 output: r.lines.join("\n"),
729 error: r.error,
730 }
731}
732
733#[cfg(not(target_arch = "wasm32"))]
738pub fn vm_outcome_net(source: &str) -> RunOutcome {
739 let r = vm_lines_net(source);
740 RunOutcome {
741 output: r.lines.join("\n"),
742 error: r.error,
743 }
744}
745
746#[cfg(not(target_arch = "wasm32"))]
748pub fn vm_lines_net(source: &str) -> crate::interpreter::InterpreterResult {
749 crate::concurrency::net_inbox::set_net_offline(true);
751 futures::executor::block_on(crate::ui_bridge::run_vm_net_async(source))
752}
753
754#[cfg(not(target_arch = "wasm32"))]
760pub fn program_outcome_scheduled(program: &crate::vm::CompiledProgram) -> RunOutcome {
761 match crate::vm::RevCoop::record(crate::vm::Vm::new(program)) {
762 Ok(coop) => RunOutcome {
763 output: coop.main_output(),
764 error: None,
765 },
766 Err(e) => RunOutcome {
767 output: String::new(),
768 error: Some(e),
769 },
770 }
771}
772
773#[cfg(not(target_arch = "wasm32"))]
778pub fn program_outcome_concurrent(program: &crate::vm::CompiledProgram) -> RunOutcome {
779 let r = program_lines_concurrent(program);
780 RunOutcome {
781 output: r.lines.join("\n"),
782 error: r.error,
783 }
784}
785
786#[cfg(not(target_arch = "wasm32"))]
788pub fn program_lines_concurrent(
789 program: &crate::vm::CompiledProgram,
790) -> crate::interpreter::InterpreterResult {
791 use crate::concurrency::vm_driver::VmTask;
792 use logicaffeine_runtime::{
793 run_with_seed, RunOutcome as RtOutcome, SchedSeed, SchedulerConfig,
794 };
795 use std::cell::RefCell;
796 use std::rc::Rc;
797
798 let output: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
799 let err_sink: crate::concurrency::driver::ErrSink = Rc::new(RefCell::new(None));
800 let main_task = VmTask::new(
801 crate::vm::Vm::new(program),
802 output.clone(),
803 Some(err_sink.clone()),
804 );
805 let (outcome, _trace) = run_with_seed(SchedulerConfig::default(), SchedSeed(0), move |sched| {
806 sched.spawn_main(Box::new(main_task));
807 });
808 let mut error = err_sink.borrow().clone();
809 if error.is_none() {
810 if let RtOutcome::Deadlock = outcome {
811 error = Some("deadlock: every task is blocked waiting".to_string());
812 }
813 }
814 let lines = output.borrow().clone();
815 crate::interpreter::InterpreterResult { lines, error }
816}
817
818#[cfg(not(target_arch = "wasm32"))]
824pub fn program_outcome(program: &crate::vm::CompiledProgram) -> RunOutcome {
825 let mut vm = crate::vm::Vm::new(program);
826 match vm.run() {
827 Ok(()) => RunOutcome {
828 output: vm.output(),
829 error: None,
830 },
831 Err(e) => RunOutcome {
832 output: vm.output(),
833 error: Some(e),
834 },
835 }
836}
837
838pub fn tw_outcome_with_args(source: &str, program_args: &[String]) -> RunOutcome {
843 let result = tw_lines_with_args(source, program_args);
844 RunOutcome {
845 output: result.lines.join("\n"),
846 error: result.error,
847 }
848}
849
850pub fn vm_outcome_with_args(
855 source: &str,
856 program_args: &[String],
857 tier: Option<&dyn crate::vm::NativeTier>,
858) -> RunOutcome {
859 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
860 Ok((stmts, types, policies)) => {
861 let (output, error) = crate::vm::run_to_outcome_with_args(
862 stmts,
863 interner,
864 Some(types),
865 Some(&policies),
866 program_args,
867 tier,
868 );
869 RunOutcome { output, error }
870 }
871 Err(advice) => RunOutcome {
872 output: String::new(),
873 error: Some(advice),
874 },
875 })
876}
877
878pub fn vm_outcome_tiered(
883 source: &str,
884 program_args: &[String],
885 tier: crate::optimization::Tier,
886 native_tier: Option<&dyn crate::vm::NativeTier>,
887) -> RunOutcome {
888 crate::ui_bridge::with_optimized_program_tiered(source, tier, |parsed, interner| match parsed {
889 Ok((stmts, types, policies)) => {
890 let (output, error) = crate::optimize::with_backend_lowering(|| {
897 crate::vm::run_to_outcome_with_args(
898 stmts,
899 interner,
900 Some(types),
901 Some(&policies),
902 program_args,
903 native_tier,
904 )
905 });
906 RunOutcome { output, error }
907 }
908 Err(advice) => RunOutcome {
909 output: String::new(),
910 error: Some(advice),
911 },
912 })
913}
914
915#[cfg(not(target_arch = "wasm32"))]
921pub fn vm_outcome_bg(source: &str, program_args: &[String]) -> RunOutcome {
922 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
923 Ok((stmts, types, policies)) => {
924 let (output, error) = crate::vm::run_to_outcome_bg(
925 stmts,
926 interner,
927 Some(types),
928 Some(&policies),
929 program_args,
930 );
931 RunOutcome { output, error }
932 }
933 Err(advice) => RunOutcome {
934 output: String::new(),
935 error: Some(advice),
936 },
937 })
938}
939
940fn refuse_browser_surface(source: &str, tier: &str) -> Result<(), ParseError> {
950 let Ok(program) = compile_to_program(source) else {
951 return Ok(());
952 };
953 if crate::aot_unsupported::first_reachable(&program)
956 == Some(crate::aot_unsupported::Offload::Dom)
957 {
958 return Err(ParseError {
959 kind: crate::error::ParseErrorKind::Custom(format!(
960 "{tier} cannot build a page: this program touches the DOM (a browser surface), \
961 and {tier} has no document to build. A `## Page` or a `## Component` runs on the \
962 tree-walker and in the browser through WebAssembly — build it for one of those, \
963 or move the part that is not about the page into a program of its own."
964 )),
965 span: crate::token::Span::default(),
966 });
967 }
968 Ok(())
969}
970
971fn lift_program_bindings<'a>(
975 stmts: Vec<Stmt<'a>>,
976 registry: crate::analysis::TypeRegistry,
977 interner: &mut Interner,
978 arenas: crate::ast_map::Arenas<'a>,
979) -> Result<(Vec<Stmt<'a>>, crate::analysis::TypeRegistry), ParseError> {
980 match crate::program_bindings::lift_program_bindings(&stmts, ®istry, interner, arenas) {
981 Ok(Some(lifted)) => Ok((lifted.stmts, lifted.registry)),
982 Ok(None) => Ok((stmts, registry)),
983 Err(why) => Err(ParseError {
984 kind: crate::error::ParseErrorKind::Custom(why),
985 span: crate::token::Span::default(),
986 }),
987 }
988}
989
990pub fn compile_to_rust(source: &str) -> Result<String, ParseError> {
1026 refuse_browser_surface(source, "the AOT-Rust backend")?;
1027 compile_program_full(source).map(|o| o.rust_code)
1028}
1029
1030pub fn compile_to_rust_deterministic(source: &str) -> Result<String, ParseError> {
1036 crate::codegen::with_deterministic_replay(|| compile_to_rust(source))
1037}
1038
1039pub fn compile_to_rust_observed(source: &str) -> Result<String, ParseError> {
1045 crate::codegen::with_observed_codegen(|| compile_to_rust(source))
1046}
1047
1048pub fn compile_to_rust_with_proven(source: &str, proven: &str) -> Result<String, ParseError> {
1053 compile_program_full_with_proven(source, Some(proven)).map(|o| o.rust_code)
1054}
1055
1056pub fn optimizations_used(source: &str) -> Vec<&'static str> {
1063 let base = match compile_to_rust(source) {
1064 Ok(r) => r,
1065 Err(_) => return Vec::new(),
1066 };
1067 crate::optimization::REGISTRY
1068 .iter()
1069 .filter(|m| {
1070 let decorated = crate::optimization::decorate_source(source, &[m.keyword]);
1071 compile_to_rust(&decorated)
1072 .map(|r| r != base)
1073 .unwrap_or(false)
1074 })
1075 .map(|m| m.keyword)
1076 .collect()
1077}
1078
1079pub fn compile_program_traced(
1086 source: &str,
1087) -> Result<(CompileOutput, crate::optimization::FiredOptimizations), ParseError> {
1088 crate::optimize::begin_fired_trace();
1089 let result = compile_program_full(source);
1090 let fired = crate::optimize::end_fired_trace().unwrap_or_default();
1093 result.map(|o| (o, fired))
1094}
1095
1096pub fn compile_program_backend_traced(
1100 source: &str,
1101) -> Result<(CompileOutput, crate::optimization::BackendOptimizationTrace), ParseError> {
1102 crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::RustAot);
1103 let result = compile_program_full(source);
1104 let trace = crate::optimize::end_backend_trace().expect("backend trace was just started");
1105 result.map(|o| (o, trace))
1106}
1107
1108pub fn optimizations_fired(source: &str) -> Vec<&'static str> {
1111 compile_program_traced(source)
1112 .map(|(_, fired)| fired.keywords())
1113 .unwrap_or_default()
1114}
1115
1116pub fn optimizations_fired_with(
1120 source: &str,
1121 cfg: &crate::optimization::OptimizationConfig,
1122) -> Vec<&'static str> {
1123 let disabled: Vec<&'static str> = cfg.disabled_keywords().collect();
1124 let decorated = crate::optimization::decorate_source(source, &disabled);
1125 optimizations_fired(&decorated)
1126}
1127
1128pub fn compile_to_rust_traced(
1132 source: &str,
1133) -> Result<(String, Vec<&'static str>, Vec<(&'static str, &'static str)>), ParseError> {
1134 crate::optimize::begin_fired_trace();
1135 let result = compile_program_full(source);
1136 let fired = crate::optimize::end_fired_trace()
1137 .unwrap_or_default()
1138 .keywords();
1139 let preempted = preempted_keywords();
1140 result.map(|o| (o.rust_code, fired, preempted))
1141}
1142
1143pub fn optimization_preemptions(source: &str) -> Vec<(&'static str, &'static str)> {
1146 crate::optimize::begin_fired_trace();
1147 let _ = compile_program_full(source);
1148 let _ = crate::optimize::end_fired_trace();
1149 preempted_keywords()
1150}
1151
1152fn preempted_keywords() -> Vec<(&'static str, &'static str)> {
1154 crate::optimize::end_preempted_trace()
1155 .into_iter()
1156 .map(|(w, l)| (w.meta().keyword, l.meta().keyword))
1157 .collect()
1158}
1159
1160pub fn optimization_dependencies(source: &str) -> Vec<(&'static str, &'static str)> {
1173 use crate::optimization::{by_keyword, decorate_source, OptimizationConfig};
1174 use std::collections::BTreeSet;
1175
1176 let base: Vec<&'static str> = optimizations_fired(source);
1177 let base_set: BTreeSet<&'static str> = base.iter().copied().collect();
1178 let mut out: Vec<(&'static str, &'static str)> = Vec::new();
1179 for &dep in &base {
1180 let dep_opt = match by_keyword(dep) {
1181 Some(o) => o,
1182 None => continue,
1183 };
1184 let mut cfg = OptimizationConfig::all_on();
1186 cfg.set(dep_opt, false);
1187 cfg.normalize();
1188 let off: BTreeSet<&'static str> = optimizations_fired(&decorate_source(source, &[dep]))
1189 .into_iter()
1190 .collect();
1191 for &dependent in &base_set {
1192 if dependent == dep || off.contains(dependent) {
1193 continue;
1194 }
1195 let dependent_opt = match by_keyword(dependent) {
1196 Some(o) => o,
1197 None => continue,
1198 };
1199 if cfg.is_on(dependent_opt) {
1201 out.push((dependent, dep));
1202 }
1203 }
1204 }
1205 out.sort();
1206 out.dedup();
1207 out
1208}
1209
1210pub fn optimization_graph(
1217 source: &str,
1218) -> (
1219 Vec<&'static str>,
1220 Vec<(&'static str, &'static str)>,
1221 Vec<(&'static str, &'static str)>,
1222) {
1223 (
1224 optimizations_fired(source),
1225 optimization_preemptions(source),
1226 optimization_dependencies(source),
1227 )
1228}
1229
1230pub fn optimization_trace_run(source: &str) -> crate::optimization::BackendOptimizationTrace {
1236 crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::TreeWalker);
1237 crate::ui_bridge::with_optimized_program(source, |_parsed, _interner| {});
1238 crate::optimize::end_backend_trace().expect("backend trace was just started")
1239}
1240
1241pub fn optimizations_fired_run(source: &str) -> Vec<&'static str> {
1242 optimization_trace_run(source).all_fired().keywords()
1243}
1244
1245pub fn optimization_trace_vm(source: &str) -> crate::optimization::BackendOptimizationTrace {
1251 crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::Vm);
1252 crate::ui_bridge::with_optimized_program(source, |parsed, interner| {
1253 if let Ok((stmts, types, _policies)) = parsed {
1254 let _ = crate::optimize::with_backend_lowering(|| {
1255 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1261 let program = crate::vm::Compiler::compile_with_oracle(
1262 stmts,
1263 interner,
1264 Some(types),
1265 Some(oracle),
1266 );
1267 if let Ok(program) = &program {
1275 if program.code.iter().any(|op| {
1276 matches!(
1277 op,
1278 crate::vm::Op::IndexUnchecked { .. }
1279 | crate::vm::Op::SetIndexUnchecked { .. }
1280 )
1281 }) {
1282 crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
1283 }
1284 }
1285 program
1286 });
1287 }
1288 });
1289 crate::optimize::end_backend_trace().expect("backend trace was just started")
1290}
1291
1292pub fn optimizations_fired_vm(source: &str) -> Vec<&'static str> {
1293 optimization_trace_vm(source).all_fired().keywords()
1294}
1295
1296pub fn compile_to_c(source: &str) -> Result<String, ParseError> {
1301 if let Some(refusal) = vm_refusal(source) {
1304 return Ok(crate::codegen_c::refused_program(&refusal));
1305 }
1306 compile_to_c_tiered(source, crate::codegen_c::TaskTier::Coroutines)
1307}
1308
1309pub fn compile_to_c_traced(
1313 source: &str,
1314) -> Result<(String, crate::optimization::BackendOptimizationTrace), ParseError> {
1315 let refusal = vm_refusal(source);
1316 crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::CAst);
1317 let result = match refusal {
1318 Some(refusal) => Ok(crate::codegen_c::refused_program(&refusal)),
1319 None => compile_to_c_tiered(source, crate::codegen_c::TaskTier::Coroutines),
1320 };
1321 let trace = crate::optimize::end_backend_trace().expect("backend trace was just started");
1322 result.map(|c| (c, trace))
1323}
1324
1325fn vm_refusal(source: &str) -> Option<String> {
1328 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
1329 Err(advice) => Some(advice),
1330 Ok((stmts, _, _)) if main_drives_a_page(stmts, interner).is_some() => None,
1331 Ok((stmts, types, _)) => {
1332 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1333 crate::vm::Compiler::compile_with_oracle(stmts, interner, Some(types), Some(oracle))
1334 .err()
1335 }
1336 })
1337}
1338
1339pub fn compile_to_c_stepped(source: &str) -> Result<String, ParseError> {
1342 compile_to_c_tiered(source, crate::codegen_c::TaskTier::Stepped)
1343}
1344
1345#[cfg(not(target_arch = "wasm32"))]
1348pub fn compile_to_c_stepped_with_knobs(
1349 source: &str,
1350 knobs: &crate::codegen_c::concurrency::SchedulerKnobs,
1351) -> Result<String, ParseError> {
1352 Ok(format!(
1353 "{}{}",
1354 knobs.emit_defines(),
1355 compile_to_c_stepped(source)?
1356 ))
1357}
1358
1359fn compile_to_c_tiered(
1360 source: &str,
1361 tier: crate::codegen_c::TaskTier,
1362) -> Result<String, ParseError> {
1363 refuse_browser_surface(source, "the AOT-C backend")?;
1364 let prelude_src = crate::loader::apply_prelude(source);
1370 let pruned = crate::loader::keep_reachable_functions(source, prelude_src.as_ref());
1375 let source = pruned.as_str();
1376 let library = crate::loader::LibraryProvenance::of(source);
1377
1378 let mut interner = Interner::new();
1379 let mut lexer = Lexer::new(source, &mut interner);
1380 let tokens = lexer.tokenize();
1381
1382 let (type_registry, policy_registry) = {
1383 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1384 let result = discovery.run_full();
1385 (result.types, result.policies)
1386 };
1387
1388 let mut world_state = WorldState::new();
1389 let expr_arena = Arena::new();
1390 let term_arena = Arena::new();
1391 let np_arena = Arena::new();
1392 let sym_arena = Arena::new();
1393 let role_arena = Arena::new();
1394 let pp_arena = Arena::new();
1395 let stmt_arena: Arena<Stmt> = Arena::new();
1396 let _compile_facts = crate::optimize::facts::scope();
1397 let imperative_expr_arena: Arena<Expr> = Arena::new();
1398 let type_expr_arena: Arena<TypeExpr> = Arena::new();
1399
1400 let ast_ctx = AstContext::with_types(
1401 &expr_arena,
1402 &term_arena,
1403 &np_arena,
1404 &sym_arena,
1405 &role_arena,
1406 &pp_arena,
1407 &stmt_arena,
1408 &imperative_expr_arena,
1409 &type_expr_arena,
1410 );
1411
1412 let mut parser = Parser::new(
1413 tokens,
1414 &mut world_state,
1415 &mut interner,
1416 ast_ctx,
1417 type_registry,
1418 );
1419 let stmts = parser.parse_program()?;
1420 let (opt_config, gate) = crate::optimize::install_decorators(
1424 crate::optimization::OptimizationConfig::from_env(),
1425 &parser.program_opt_flags(),
1426 parser.required_optimizations(),
1427 );
1428 let codegen_registry = parser.into_type_registry();
1429 if let Some(kernel) = stmts.iter().find_map(|s| match s {
1432 Stmt::FunctionDef {
1433 name,
1434 is_native: true,
1435 ..
1436 } => crate::semantics::native_kernels::NativeKernel::from_name(interner.resolve(*name)),
1437 _ => None,
1438 }) {
1439 return Err(ParseError {
1440 kind: crate::error::ParseErrorKind::Custom(kernel.refusal("C")),
1441 span: crate::token::Span::default(),
1442 });
1443 }
1444 if let Some(kind) = codegen_registry
1445 .iter_types()
1446 .find_map(|(_, def)| match def {
1447 crate::analysis::TypeDef::Struct { fields, .. } => fields.iter().find_map(|f| {
1448 crate::semantics::crdt::CrdtKind::of_type_name(field_type_base_name(
1449 &f.ty, &interner,
1450 ))
1451 .filter(|k| !k.lowered_by(Backend::CFromAst))
1452 }),
1453 _ => None,
1454 })
1455 {
1456 return Err(ParseError {
1457 kind: crate::error::ParseErrorKind::Custom(kind.refusal("C")),
1458 span: crate::token::Span::default(),
1459 });
1460 }
1461 let stmts = crate::analysis::pipes::declare_pipe_params(
1464 &stmts,
1465 crate::ast_map::Arenas {
1466 exprs: &imperative_expr_arena,
1467 stmts: &stmt_arena,
1468 types: &type_expr_arena,
1469 },
1470 &mut interner,
1471 );
1472 let stmts = crate::optimize::memoize_for_explicit_lowering(
1476 stmts,
1477 &imperative_expr_arena,
1478 &stmt_arena,
1479 &mut interner,
1480 &opt_config,
1481 );
1482 let resolved = crate::resolve_program::resolve_program(
1488 &stmts,
1489 crate::ast_map::Arenas {
1490 exprs: &imperative_expr_arena,
1491 stmts: &stmt_arena,
1492 types: &type_expr_arena,
1493 },
1494 &mut interner,
1495 opt_config.is_on(crate::optimization::Opt::Comptime),
1496 library.functions(),
1497 );
1498 let stmts: Vec<Stmt> = match resolved {
1499 Some(rw) => rw.to_vec(),
1500 None => stmts,
1501 };
1502 let stmts = crate::optimize::optimize_program(
1503 stmts,
1504 &imperative_expr_arena,
1505 &stmt_arena,
1506 &mut interner,
1507 &opt_config,
1508 );
1509 let effects = crate::codegen_c::call_effects(&stmts);
1512 let stmts = crate::optimize::sequence::sequence_operands(
1513 stmts,
1514 crate::ast_map::Arenas {
1515 exprs: &imperative_expr_arena,
1516 stmts: &stmt_arena,
1517 types: &type_expr_arena,
1518 },
1519 &mut interner,
1520 effects,
1521 );
1522 let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
1526 .map_err(|e| ParseError {
1527 kind: e.to_parse_error_kind(&interner, &stmts),
1528 span: crate::token::Span::default(),
1529 })?;
1530 let stmts = crate::optimize::version::version_stmts(
1531 stmts,
1532 crate::ast_map::Arenas {
1533 exprs: &imperative_expr_arena,
1534 stmts: &stmt_arena,
1535 types: &type_expr_arena,
1536 },
1537 &type_env,
1538 &interner,
1539 &opt_config,
1540 );
1541 let mono = crate::monomorphize::monomorphize(
1545 &stmts,
1546 &codegen_registry,
1547 &mut interner,
1548 crate::ast_map::Arenas {
1549 exprs: &imperative_expr_arena,
1550 stmts: &stmt_arena,
1551 types: &type_expr_arena,
1552 },
1553 crate::monomorphize::Options { lower_option: true },
1554 )
1555 .map_err(|m| ParseError {
1556 kind: crate::error::ParseErrorKind::Custom(format!(
1557 "the C backend cannot compile this program: {m}"
1558 )),
1559 span: crate::token::Span::default(),
1560 })?;
1561 let (stmts, codegen_registry, instances) = (mono.stmts, mono.registry, mono.instances);
1562 if std::env::var_os("LOGOS_DEBUG_C_TILE").is_some() {
1563 use logicaffeine_language::ast_depth::{for_each_node, Visited};
1564 let mut tile_facts = 0usize;
1565 for_each_node(&stmts, |node| {
1566 if let Visited::Expr(expr) = node {
1567 tile_facts += usize::from(crate::optimize::facts::holds_expr(
1568 crate::optimize::facts::Fact::TileLegal,
1569 expr,
1570 ));
1571 }
1572 });
1573 eprintln!("C TileLegal expressions before emission: {tile_facts}");
1574 }
1575 let c_code = crate::optimize::with_backend_lowering(|| {
1576 crate::codegen_c::codegen_monomorphic_program_c(
1577 &stmts,
1578 &codegen_registry,
1579 &interner,
1580 &policy_registry,
1581 &instances,
1582 tier,
1583 )
1584 });
1585 gate.verify().map_err(|m| ParseError {
1586 kind: crate::error::ParseErrorKind::Custom(m),
1587 span: crate::token::Span::default(),
1588 })?;
1589 Ok(c_code)
1590}
1591
1592pub fn compile_to_isa(source: &str) -> Result<String, ParseError> {
1606 fn custom(msg: String) -> ParseError {
1607 ParseError {
1608 kind: crate::error::ParseErrorKind::Custom(msg),
1609 span: crate::token::Span::default(),
1610 }
1611 }
1612 refuse_exact(source, "Silicon ISA", "the LOGOS chip")?;
1613 crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
1614 let (stmts, types, _policies) = parsed?;
1615 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1616 let program = crate::vm::Compiler::compile_with_oracle_located(
1617 stmts,
1618 interner,
1619 Some(types),
1620 Some(oracle),
1621 )?;
1622 Ok(crate::vm::isa::emit_isa(&program))
1623 })
1624}
1625
1626pub(crate) fn exact_refusal(source: &str, tier: &str, holder: &str) -> Option<String> {
1631 let reaches = crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
1632 let Ok((stmts, types, _policies)) = parsed else {
1633 return false;
1634 };
1635 crate::vm::Compiler::compile_with_oracle_located(stmts, interner, Some(types), None)
1636 .is_ok_and(|program| crate::vm::tower::reaches(&program))
1637 });
1638 reaches.then(|| {
1639 format!("the {tier} does not run the exact extension: its values live in a runtime {holder} cannot call")
1640 })
1641}
1642
1643pub(crate) fn refuse_exact(source: &str, tier: &str, holder: &str) -> Result<(), ParseError> {
1645 match exact_refusal(source, tier, holder) {
1646 None => Ok(()),
1647 Some(sentence) => Err(ParseError {
1648 kind: crate::error::ParseErrorKind::Custom(sentence),
1649 span: crate::token::Span::default(),
1650 }),
1651 }
1652}
1653
1654pub fn compile_to_program(source: &str) -> Result<crate::vm::CompiledProgram, ParseError> {
1671 fn custom(msg: String) -> ParseError {
1672 ParseError {
1673 kind: crate::error::ParseErrorKind::Custom(msg),
1674 span: crate::token::Span::default(),
1675 }
1676 }
1677 crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
1678 let (stmts, types, _policies) = parsed?;
1679 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1680 Ok(crate::vm::Compiler::compile_with_oracle_located(
1681 stmts,
1682 interner,
1683 Some(types),
1684 Some(oracle),
1685 )?)
1686 })
1687}
1688
1689#[cfg(not(target_arch = "wasm32"))]
1698pub fn compile_to_c_via_bytecode(source: &str) -> Result<String, ParseError> {
1699 compile_to_c_via_bytecode_with_knobs(
1700 source,
1701 &crate::codegen_c::concurrency::SchedulerKnobs::default(),
1702 )
1703}
1704
1705#[cfg(not(target_arch = "wasm32"))]
1708pub fn compile_to_c_via_bytecode_traced(
1709 source: &str,
1710) -> Result<(String, crate::optimization::BackendOptimizationTrace), ParseError> {
1711 crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::CBytecode);
1712 let result = compile_to_c_via_bytecode(source);
1713 let trace = crate::optimize::end_backend_trace().expect("backend trace was just started");
1714 result.map(|c| (c, trace))
1715}
1716
1717#[cfg(not(target_arch = "wasm32"))]
1725pub fn compile_to_c_via_bytecode_with_knobs(
1726 source: &str,
1727 knobs: &crate::codegen_c::concurrency::SchedulerKnobs,
1728) -> Result<String, ParseError> {
1729 compile_to_c_via_bytecode_offloaded_with_knobs(source, knobs, |_, _| Vec::new()).map(|o| o.c)
1730}
1731
1732#[cfg(not(target_arch = "wasm32"))]
1737pub fn compile_to_c_via_bytecode_offloaded(
1738 source: &str,
1739 offloads: impl FnOnce(
1740 &crate::vm::CompiledProgram,
1741 &Interner,
1742 ) -> Vec<crate::codegen_c::from_program::Offload>,
1743) -> Result<crate::codegen_c::from_program::OffloadedC, ParseError> {
1744 compile_to_c_via_bytecode_offloaded_with_knobs(
1745 source,
1746 &crate::codegen_c::concurrency::SchedulerKnobs::default(),
1747 offloads,
1748 )
1749}
1750
1751#[cfg(not(target_arch = "wasm32"))]
1752fn compile_to_c_via_bytecode_offloaded_with_knobs(
1753 source: &str,
1754 knobs: &crate::codegen_c::concurrency::SchedulerKnobs,
1755 offloads: impl FnOnce(
1756 &crate::vm::CompiledProgram,
1757 &Interner,
1758 ) -> Vec<crate::codegen_c::from_program::Offload>,
1759) -> Result<crate::codegen_c::from_program::OffloadedC, ParseError> {
1760 use crate::codegen_c::from_program::OffloadedC;
1761 fn custom(msg: String) -> ParseError {
1762 ParseError {
1763 kind: crate::error::ParseErrorKind::Custom(msg),
1764 span: crate::token::Span::default(),
1765 }
1766 }
1767 with_optimized_program(source, true, |stmts, interner, program, policies| {
1768 refuse_unlinkable(program, interner, Backend::C).map_err(custom)?;
1769 let table = offloads(program, interner);
1770 let on_the_host = |why: &str| {
1771 table
1772 .iter()
1773 .map(|o| (o.func, why.to_string()))
1774 .collect::<Vec<_>>()
1775 };
1776 if crate::codegen_c::program_needs_astc_delegation(program) {
1782 crate::optimize::mark_backend_fallback(
1783 crate::optimization::OptimizationBackend::CAst,
1784 "bytecode op outside the C Op-walker",
1785 );
1786 return Ok(OffloadedC {
1787 c: compile_to_c(source)?,
1788 kept: on_the_host("the program is lowered from its syntax tree"),
1789 });
1790 }
1791 if crate::codegen_c::program_uses_concurrency(stmts) {
1797 crate::optimize::mark_backend_fallback(
1798 crate::optimization::OptimizationBackend::CAst,
1799 "concurrency requires the stepped syntax-tree C tier",
1800 );
1801 Ok(OffloadedC {
1802 c: compile_to_c_stepped_with_knobs(source, knobs)?,
1803 kept: on_the_host("a concurrent program runs on the stepped tier"),
1804 })
1805 } else {
1806 crate::optimize::with_backend_lowering(|| {
1809 crate::codegen_c::from_program::compile_program_to_c_offloaded(
1810 program,
1811 Some((interner, policies)),
1812 &table,
1813 )
1814 })
1815 .map_err(custom)
1816 }
1817 })
1818}
1819
1820#[cfg(not(target_arch = "wasm32"))]
1828pub fn compile_to_program_optimized(
1829 source: &str,
1830) -> Result<crate::vm::CompiledProgram, ParseError> {
1831 with_optimized_program(source, false, |_stmts, _interner, program, _policies| {
1832 Ok(program.clone())
1833 })
1834}
1835
1836#[cfg(not(target_arch = "wasm32"))]
1839pub fn compile_to_program_optimized_named(
1840 source: &str,
1841) -> Result<(crate::vm::CompiledProgram, Vec<String>), ParseError> {
1842 with_optimized_program(source, false, |_stmts, interner, program, _policies| {
1843 let names = program
1844 .functions
1845 .iter()
1846 .map(|f| interner.resolve(f.name).to_string())
1847 .collect();
1848 Ok((program.clone(), names))
1849 })
1850}
1851
1852#[cfg(not(target_arch = "wasm32"))]
1859fn with_optimized_program<T>(
1860 source: &str,
1861 require_static_types: bool,
1862 finish: impl FnOnce(
1863 &[Stmt],
1864 &Interner,
1865 &crate::vm::CompiledProgram,
1866 &crate::analysis::PolicyRegistry,
1867 ) -> Result<T, ParseError>,
1868) -> Result<T, ParseError> {
1869 fn custom(msg: String) -> ParseError {
1870 ParseError {
1871 kind: crate::error::ParseErrorKind::Custom(msg),
1872 span: crate::token::Span::default(),
1873 }
1874 }
1875 let prelude_src = crate::loader::apply_prelude(source);
1876 let pruned = crate::loader::keep_reachable_functions(source, prelude_src.as_ref());
1877 let source = pruned.as_str();
1878 let library = crate::loader::LibraryProvenance::of(source);
1879
1880 let mut interner = Interner::new();
1881 let mut lexer = Lexer::new(source, &mut interner);
1882 let tokens = lexer.tokenize();
1883
1884 let (type_registry, policy_registry) = {
1885 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1886 let result = discovery.run_full();
1887 (result.types, result.policies)
1888 };
1889
1890 let mut world_state = WorldState::new();
1891 let expr_arena = Arena::new();
1892 let term_arena = Arena::new();
1893 let np_arena = Arena::new();
1894 let sym_arena = Arena::new();
1895 let role_arena = Arena::new();
1896 let pp_arena = Arena::new();
1897 let stmt_arena: Arena<Stmt> = Arena::new();
1898 let _compile_facts = crate::optimize::facts::scope();
1899 let imperative_expr_arena: Arena<Expr> = Arena::new();
1900 let type_expr_arena: Arena<TypeExpr> = Arena::new();
1901
1902 let ast_ctx = AstContext::with_types(
1903 &expr_arena,
1904 &term_arena,
1905 &np_arena,
1906 &sym_arena,
1907 &role_arena,
1908 &pp_arena,
1909 &stmt_arena,
1910 &imperative_expr_arena,
1911 &type_expr_arena,
1912 );
1913
1914 let mut parser = Parser::new(
1915 tokens,
1916 &mut world_state,
1917 &mut interner,
1918 ast_ctx,
1919 type_registry,
1920 );
1921 let stmts = parser.parse_program()?;
1922 let (opt_config, gate) = crate::optimize::install_decorators(
1923 crate::optimization::OptimizationConfig::from_env(),
1924 &parser.program_opt_flags(),
1925 parser.required_optimizations(),
1926 );
1927 let codegen_registry = parser.into_type_registry();
1928 let stmts = crate::optimize::memoize_for_explicit_lowering(
1935 stmts,
1936 &imperative_expr_arena,
1937 &stmt_arena,
1938 &mut interner,
1939 &opt_config,
1940 );
1941 let resolved = crate::resolve_program::resolve_program(
1942 &stmts,
1943 crate::ast_map::Arenas {
1944 exprs: &imperative_expr_arena,
1945 stmts: &stmt_arena,
1946 types: &type_expr_arena,
1947 },
1948 &mut interner,
1949 opt_config.is_on(crate::optimization::Opt::Comptime),
1950 library.functions(),
1951 );
1952 let stmts: Vec<Stmt> = match resolved {
1953 Some(rw) => rw.to_vec(),
1954 None => stmts,
1955 };
1956 let stmts = crate::optimize::optimize_program(
1957 stmts,
1958 &imperative_expr_arena,
1959 &stmt_arena,
1960 &mut interner,
1961 &opt_config,
1962 );
1963 let type_env = match crate::analysis::check_program_located(&stmts, &interner, &codegen_registry) {
1971 Ok(env) => Some(env),
1972 Err(e) if require_static_types => {
1973 return Err(ParseError {
1974 kind: e.to_parse_error_kind(&interner, &stmts),
1975 span: crate::token::Span::default(),
1976 });
1977 }
1978 Err(_) => None,
1979 };
1980 let stmts = if let Some(type_env) = type_env {
1981 crate::optimize::version::version_stmts(
1982 stmts,
1983 crate::ast_map::Arenas {
1984 exprs: &imperative_expr_arena,
1985 stmts: &stmt_arena,
1986 types: &type_expr_arena,
1987 },
1988 &type_env,
1989 &interner,
1990 &opt_config,
1991 )
1992 } else {
1993 stmts
1994 };
1995 let oracle = crate::optimize::oracle_analyze_with(&stmts, &interner);
1998 let program = crate::optimize::with_backend_lowering(|| {
1999 crate::vm::Compiler::compile_with_oracle_located(
2000 &stmts,
2001 &interner,
2002 Some(&codegen_registry),
2003 Some(oracle),
2004 )
2005 })?;
2006 gate.verify().map_err(|m| ParseError {
2007 kind: crate::error::ParseErrorKind::Custom(m),
2008 span: crate::token::Span::default(),
2009 })?;
2010 finish(&stmts, &interner, &program, &policy_registry)
2011}
2012
2013pub fn compile_to_riscv(source: &str) -> Result<String, ParseError> {
2019 fn custom(msg: String) -> ParseError {
2020 ParseError {
2021 kind: crate::error::ParseErrorKind::Custom(msg),
2022 span: crate::token::Span::default(),
2023 }
2024 }
2025 crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2026 let (stmts, types, policies) = parsed?;
2027 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2028 let mut program = crate::vm::Compiler::compile_with_oracle_located(
2029 stmts,
2030 interner,
2031 Some(types),
2032 Some(oracle),
2033 )?;
2034 crate::vm::peephole::peephole(&mut program);
2039 refuse_unlinkable(&program, interner, Backend::RiscV).map_err(custom)?;
2040 crate::codegen_riscv::codegen_program_riscv(&program, &policies, interner)
2041 .map_err(|e| custom(e.to_string()))
2042 })
2043}
2044
2045#[cfg(feature = "codegen")]
2055pub fn compile_to_tenstorrent(source: &str) -> Result<crate::codegen_tt::TtArtifact, ParseError> {
2056 fn custom(msg: String) -> ParseError {
2057 ParseError {
2058 kind: crate::error::ParseErrorKind::Custom(msg),
2059 span: crate::token::Span::default(),
2060 }
2061 }
2062 refuse_exact(source, "Tenstorrent tier", "a Tensix core")?;
2063 let refusal = crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2067 let (stmts, types, _policies) = parsed?;
2068 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2069 let program = crate::vm::Compiler::compile_with_oracle_located(
2070 stmts,
2071 interner,
2072 Some(types),
2073 Some(oracle),
2074 )?;
2075 Ok(crate::codegen_tt::unsupported_reason(&program))
2076 })?;
2077 if let Some(reason) = refusal {
2078 return Err(custom(format!(
2079 "tenstorrent AOT backend: unsupported {reason}"
2080 )));
2081 }
2082 let oracle_c = compile_to_c(source)?;
2084 Ok(crate::codegen_tt::wrap_as_tt(&oracle_c))
2085}
2086
2087#[cfg(feature = "codegen")]
2093pub fn compile_to_analog(source: &str) -> Result<crate::codegen_ana::AnalogArtifact, ParseError> {
2094 fn custom(msg: String) -> ParseError {
2095 ParseError {
2096 kind: crate::error::ParseErrorKind::Custom(msg),
2097 span: crate::token::Span::default(),
2098 }
2099 }
2100 refuse_exact(source, "analog tier", "an analog fabric")?;
2101 let gate = crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2102 let (stmts, types, _policies) = parsed?;
2103 let ranges = crate::codegen_ana::assumed_ranges_in(stmts, interner);
2104 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2105 let program = crate::vm::Compiler::compile_with_oracle_located(
2106 stmts,
2107 interner,
2108 Some(types),
2109 Some(oracle),
2110 )?;
2111 let refusal = crate::codegen_ana::analog_refusal(&program, &ranges);
2112 let region = stmts.iter().find_map(|s| match s {
2114 logicaffeine_language::ast::stmt::Stmt::FunctionDef { name, .. } => {
2115 Some(interner.resolve(*name).to_string())
2116 }
2117 _ => None,
2118 });
2119 Ok((refusal, region))
2120 })?;
2121 let target = crate::codegen_ana::AnalogTarget::sky130_fpaa();
2122 match gate {
2123 (Some(crate::codegen_ana::AnaLowerError::NoAnalogRegion), Some(fn_name))
2127 | (None, Some(fn_name)) => crate::codegen_ana::try_region(source, &fn_name, &target)
2128 .map(|(_lane, art)| art)
2129 .map_err(|e| custom(format!("analog backend: {e}"))),
2130 (Some(e), _) => Err(custom(format!("analog backend: {e}"))),
2131 (None, None) => Err(custom(
2132 "analog backend: no region function found (the analog region unit is a float function)"
2133 .to_string(),
2134 )),
2135 }
2136}
2137
2138#[cfg(feature = "codegen")]
2145pub fn compile_to_plasticine(
2146 source: &str,
2147) -> Result<crate::codegen_sva::plasticine_report::PlasticineArtifact, ParseError> {
2148 fn custom(msg: String) -> ParseError {
2149 ParseError {
2150 kind: crate::error::ParseErrorKind::Custom(msg),
2151 span: crate::token::Span::default(),
2152 }
2153 }
2154 refuse_exact(source, "Plasticine tier", "a dataflow fabric")?;
2155 let region = crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2156 let (stmts, _types, _policies) = parsed?;
2157 Ok(stmts.iter().find_map(|s| match s {
2158 Stmt::FunctionDef { name, params, .. } => {
2159 Some((interner.resolve(*name).to_string(), params.len()))
2160 }
2161 _ => None,
2162 }))
2163 })?;
2164 let Some((fn_name, arity)) = region else {
2165 return Err(custom("plasticine backend: no region function found (the Plasticine region unit is a counted-loop function)".to_string()));
2166 };
2167 let params: Vec<i64> = (0..arity).map(|i| 8 + i as i64).collect();
2169 let target = crate::codegen_sva::plasticine::PlasticineTarget::isca17();
2170 crate::codegen_sva::plasticine_report::lower_counted_loop(source, &fn_name, ¶ms, &target)
2171 .map_err(|e| custom(format!("plasticine backend: {e}")))
2172}
2173
2174#[cfg(feature = "codegen")]
2177pub use crate::spatial::lower::rdu_lanes::RduLane;
2178
2179#[cfg(feature = "codegen")]
2183#[derive(Clone, Debug)]
2184pub struct RduArtifact {
2185 pub chip: &'static str,
2186 pub lane: RduLane,
2187 pub neutral_json: String,
2188 pub placement_txt: String,
2189 pub certificate_json: String,
2190 pub report_json: String,
2191 pub spatial_source: Option<String>,
2192 pub neutral: Option<crate::spatial::lower::NeutralArtifact>,
2195 pub notes: Vec<String>,
2197}
2198
2199pub const RDU_EMIT_REPORT_SCHEMA: &str = "logos.rdu.emit_report";
2200
2201pub struct RduBundle {
2205 pub manifest: String,
2206 pub constants: Vec<(String, Vec<u8>)>,
2207 pub program: String,
2208}
2209
2210pub struct RduProgramFiles {
2212 pub dir: String,
2213 pub neutral_json: String,
2214 pub placement_txt: String,
2215 pub certificate_json: String,
2216}
2217
2218pub const RDU_STREAMED_MANIFEST_SCHEMA: &str = "logos.rdu.streamed_manifest";
2219
2220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2225pub struct StepShape {
2226 pub ctx: usize,
2227 pub batch: usize,
2228 pub tp: usize,
2229 pub prefill: Option<usize>,
2230}
2231
2232pub struct RduModel<'a> {
2236 pub spec: crate::model::spec::ModelSpec,
2237 pub name: String,
2238 pub storage: crate::spatial::streamed::Storage<'a>,
2239 pub rope_factors: Option<Vec<f64>>,
2240}
2241
2242impl<'a> RduModel<'a> {
2243 pub fn qwen38(cfg: &crate::codegen_cuda::qwen38::Qwen38Cfg) -> RduModel<'static> {
2245 RduModel { spec: cfg.spec(), name: "Qwen3.8".to_string(), storage: crate::spatial::streamed::Storage::AllQ8, rope_factors: None }
2246 }
2247
2248 pub fn from_checkpoint(name: &str, checkpoint: &'a mut dyn crate::model::Checkpoint) -> Result<RduModel<'a>, String> {
2251 use crate::model::bind::{values, Binding, View};
2252 use crate::model::reference::WeightSource;
2253 let spec = crate::model::spec::ModelSpec::from_source(&*checkpoint).map_err(|e| match e {
2254 crate::model::spec::SpecError::UnknownArchitecture(_) => format!("{name}: {}", crate::model::triage::refusal(&*checkpoint)),
2255 e => format!("{name}: {e:?}"),
2256 })?;
2257 let rope_factors = if WeightSource::has(&*checkpoint, "rope_freqs.weight") {
2258 let b = Binding { tensor: "rope_freqs.weight".to_string(), view: View::Same };
2259 Some(values(&b, &mut *checkpoint).map_err(|e| format!("{name}: rope_freqs.weight: {e}"))?)
2260 } else {
2261 None
2262 };
2263 let source: &'a dyn WeightSource = checkpoint;
2264 Ok(RduModel { spec, name: name.to_string(), storage: crate::spatial::streamed::Storage::Checkpoint(source), rope_factors })
2265 }
2266}
2267
2268pub fn compile_model_to_rdu_streamed(
2287 rdu: &RduModel,
2288 chip: crate::spatial::rdu_chip::RduChip,
2289 weights_dir: &str,
2290 decode: Option<StepShape>,
2291 mut sink: impl FnMut(RduProgramFiles) -> std::io::Result<()>,
2292) -> Result<RduBundle, String> {
2293 use crate::model::program::{written_in, written_split, Cut};
2294 use crate::spatial::lower::rdu::{certificate_summary, RduSpatialBackend};
2295 use crate::spatial::lower::{SpatialArtifact, SpatialBackend};
2296 use crate::spatial::streamed::rebind;
2297 use crate::spatial::streamed::{
2298 lower_batched_decode_streamed, lower_batched_tp_decode_streamed, lower_decode_streamed,
2299 lower_forward_streamed, lower_prefill_streamed, lower_tp_decode_streamed, StreamedReject,
2300 };
2301 let (spec, storage) = (&rdu.spec, rdu.storage);
2302 crate::model::author::check(spec).map_err(|e| format!("{}: {e}", rdu.name))?;
2303
2304 let facts = chip.facts();
2305 let target = facts.spatial_target();
2306 let model = match decode {
2307 None => lower_forward_streamed(spec, storage, &target, |s| s.to_string()),
2308 Some(StepShape { ctx, batch: 1, tp: 1, prefill: Some(chunk) }) => lower_prefill_streamed(spec, storage, ctx, chunk, &target, |s| s.to_string()),
2309 Some(StepShape { batch, tp, prefill: Some(chunk), .. }) => Err(StreamedReject {
2310 program: "bundle".into(),
2311 why: format!("a prefill chunk ({chunk} tokens) is one sequence on one chip — not {batch} sequences over {tp} chips"),
2312 }),
2313 Some(StepShape { ctx, batch: 1, tp: 1, prefill: None }) => lower_decode_streamed(spec, storage, ctx, &target, |s| s.to_string()),
2314 Some(StepShape { ctx, batch, tp: 1, prefill: None }) => lower_batched_decode_streamed(spec, storage, ctx, batch, &target, |s| s.to_string()),
2315 Some(StepShape { ctx, batch: 1, tp, prefill: None }) => lower_tp_decode_streamed(spec, storage, ctx, tp, &target, |s| s.to_string()),
2316 Some(StepShape { ctx, batch, tp, prefill: None }) => lower_batched_tp_decode_streamed(spec, storage, ctx, batch, tp, &target, |s| s.to_string()),
2317 }
2318 .map_err(|e| format!("rdu backend: {}: {e}", rdu.name))?;
2319 let ((_, f32w, q8w), _) = match decode {
2323 None => written_in(spec, Cut::Forward, weights_dir),
2324 Some(StepShape { ctx, batch: 1, .. }) => written_in(spec, Cut::Decode { ctx }, weights_dir),
2325 Some(StepShape { ctx, batch, .. }) => written_in(spec, Cut::Batch { rows: batch, ctx }, weights_dir),
2326 };
2327 let (whole_text, whole) = match decode {
2330 None => {
2331 let ((text, _, _), id) = written_in(spec, Cut::Forward, weights_dir);
2332 (text, id)
2333 }
2334 Some(StepShape { ctx, batch: 1, tp: 1, prefill: Some(rows) }) => {
2335 let ((text, _, _), id) = written_in(spec, Cut::Prefill { rows, ctx }, weights_dir);
2336 (text, id)
2337 }
2338 Some(StepShape { ctx, batch: 1, tp: 1, prefill: None }) => {
2339 let ((text, _, _), id) = written_in(spec, Cut::Decode { ctx }, weights_dir);
2340 (text, id)
2341 }
2342 Some(StepShape { ctx, batch, tp: 1, .. }) => {
2343 let ((text, _, _), id) = written_in(spec, Cut::Batch { rows: batch, ctx }, weights_dir);
2344 (text, id)
2345 }
2346 Some(StepShape { ctx, batch, tp, .. }) => {
2347 let cut = if batch == 1 { Cut::Decode { ctx } } else { Cut::Batch { rows: batch, ctx } };
2348 let ((text, _, _, _), id) =
2349 written_split(spec, cut, weights_dir, tp).map_err(|e| format!("rdu backend: {} over {tp} chips: {e}", rdu.name))?;
2350 (text, id)
2351 }
2352 };
2353 let file_of = |var: &str| -> Option<String> {
2354 f32w.get(var)
2355 .map(|(path, _)| path.clone())
2356 .or_else(|| q8w.get(var).cloned())
2357 };
2358 let role_of = |t: &crate::spatial::ir::TensorDecl,
2361 carried: &std::collections::BTreeSet<String>| match t.role {
2362 crate::spatial::ir::TensorRole::State if !carried.contains(&t.name) => {
2363 "activation".to_string()
2364 }
2365 r => format!("{r:?}").to_lowercase(),
2366 };
2367 let none = std::collections::BTreeSet::new();
2368 let bindings = |program: &crate::spatial::ir::SpatialProgram,
2371 rename: &dyn Fn(&str) -> String,
2372 tp: Option<&crate::spatial::tensor_parallel::TpManifest>,
2373 carried: &std::collections::BTreeSet<String>|
2374 -> Vec<serde_json::Value> {
2375 program
2376 .tensors
2377 .iter()
2378 .map(|t| {
2379 let to = rename(&t.name);
2380 let (stored, repack) = match crate::spatial::passes::from_q8::stored_part(&to) {
2383 Some((w, part)) => (w.to_string(), Some(part.repack())),
2384 None => (to.clone(), None),
2385 };
2386 let mut entry = serde_json::json!({ "program": t.name, "layer": to, "file": file_of(&stored), "role": role_of(t, carried) });
2387 if let Some(r) = repack {
2388 entry["repack"] = serde_json::json!(r);
2389 }
2390 if let Some(chip) = t.chip {
2391 entry["chip"] = serde_json::json!(chip.0);
2392 }
2393 if let Some(s) = tp.and_then(|m| m.slices.get(&t.name)) {
2394 let of = rename(&s.of);
2395 entry["slice"] = serde_json::json!({ "of": of, "file": file_of(&of), "axis": s.axis, "ranges": s.ranges, "of_shape": s.of_shape });
2396 }
2397 let plane = crate::spatial::passes::from_q8::stored_part(&t.name).and_then(|(w, part)| tp.and_then(|m| m.slices.get(w)).map(|s| (s, part)));
2400 if let Some((s, part)) = plane {
2401 use crate::spatial::passes::from_q8::{stored_name, Q8Part, Q8_BLOCK};
2402 use crate::spatial::tensor_parallel::SliceAxis;
2403 let of = rename(&s.of);
2404 let (ranges, of_shape): (Vec<(usize, usize)>, (usize, usize)) = match (part, s.axis) {
2405 (Q8Part::Values, _) => (s.ranges.clone(), s.of_shape),
2406 (Q8Part::Scales, SliceAxis::Rows) => (s.ranges.iter().map(|(a, n)| (a / Q8_BLOCK, n / Q8_BLOCK)).collect(), (s.of_shape.0 / Q8_BLOCK, s.of_shape.1)),
2407 (Q8Part::Scales, SliceAxis::Cols) => (s.ranges.clone(), (s.of_shape.0 / Q8_BLOCK, s.of_shape.1)),
2408 };
2409 entry["slice"] = serde_json::json!({ "of": stored_name(&of, part), "file": file_of(&of), "repack": part.repack(), "axis": s.axis, "ranges": ranges, "of_shape": of_shape });
2410 }
2411 entry
2412 })
2413 .collect()
2414 };
2415
2416 let mut render = |dir: &str,
2417 program: &crate::spatial::ir::SpatialProgram|
2418 -> Result<(u64, bool), String> {
2419 let artifact = match RduSpatialBackend::with_facts(facts.clone()).lower(program) {
2420 Ok(SpatialArtifact::SdkGated(a)) => a,
2421 other => {
2422 return Err(format!(
2423 "rdu backend: {dir}: the backend did not produce an SDK-gated artifact: {other:?}"
2424 ))
2425 }
2426 };
2427 let rechecked = artifact.rechecked || artifact.certificate.recheck(program);
2430 let mut cert = certificate_summary(&artifact.certificate);
2431 cert["digest_hex"] =
2432 serde_json::json!(format!("{:016x}", artifact.certificate.schedule_digest));
2433 cert["rechecked"] = serde_json::json!(rechecked);
2434 let digest = artifact.certificate.schedule_digest;
2435 sink(RduProgramFiles {
2436 dir: dir.to_string(),
2437 neutral_json: artifact.json,
2438 placement_txt: artifact.pretty,
2439 certificate_json: format!("{}\n", serde_json::to_string_pretty(&cert).expect("JSON")),
2440 })
2441 .map_err(|e| format!("rdu backend: writing {dir}: {e}"))?;
2442 Ok((digest, rechecked))
2443 };
2444
2445 let embed = match &model.embed {
2446 Some(p) => {
2447 let (digest, rechecked) = render("embed", p)?;
2448 let program = model.embed_identity.map(|id| id.line());
2449 Some(
2450 serde_json::json!({ "dir": "embed", "program": program, "schedule_digest": format!("{digest:016x}"), "rechecked": rechecked, "tensors": bindings(p, &|n| n.to_string(), None, &none) }),
2451 )
2452 }
2453 None => None,
2454 };
2455 let mut kinds = Vec::new();
2456 for k in &model.kinds {
2457 let dir = k.name.replace(' ', "_");
2458 let (digest, rechecked) = render(&dir, &k.program)?;
2459 kinds.push(serde_json::json!({
2460 "name": k.name, "dir": dir, "representative_layer": k.representative, "program": k.identity.line(),
2461 "schedule_digest": format!("{digest:016x}"), "rechecked": rechecked,
2462 "sections": k.program.sections.len(), "stages": k.program.stages.len(),
2463 }));
2464 }
2465 let (head_digest, head_rechecked) = render("head", &model.head)?;
2466 let layers: Vec<serde_json::Value> = model
2467 .layers
2468 .iter()
2469 .map(|b| {
2470 let kind = &model.kinds[b.kind];
2471 let mut map: HashMap<&str, &str> = HashMap::with_capacity(b.tensors.len());
2472 for (from, to) in &b.tensors {
2473 map.entry(from.as_str()).or_insert(to.as_str());
2474 }
2475 let (rep, layer) = (kind.representative, b.layer);
2476 let rename = |n: &str| {
2477 map.get(n)
2478 .map(|to| to.to_string())
2479 .unwrap_or_else(|| rebind(n, rep, layer))
2480 };
2481 let tensors = bindings(&kind.program, &rename, kind.tp.as_ref(), &kind.carried);
2482 serde_json::json!({ "layer": b.layer, "kind": b.kind, "program": b.identity.line(), "tensors": tensors })
2483 })
2484 .collect();
2485 let mut manifest = serde_json::json!({
2486 "schema": RDU_STREAMED_MANIFEST_SCHEMA,
2487 "version": 1,
2488 "chip": chip.as_str(),
2489 "target": target.name,
2490 "model": { "name": rdu.name, "arch": spec.arch, "layers": spec.layers.len(), "d": spec.d, "vocab": spec.vocab },
2491 "form": if decode.is_some() { "decode" } else { "forward" },
2492 "program": whole.line(),
2493 "provenance": crate::spatial::fit::PROVENANCE_MODELED,
2494 "no_speed_claim": true,
2495 "kinds": kinds,
2496 "head": { "dir": "head", "program": model.head_identity.line(), "schedule_digest": format!("{head_digest:016x}"), "rechecked": head_rechecked, "tensors": bindings(&model.head, &|n| n.to_string(), None, &none) },
2497 "layers": layers,
2498 });
2499 let r = &model.residency;
2502 let tier_name = |t: &crate::spatial::ir::TensorSpace| match t {
2503 crate::spatial::ir::TensorSpace::Sram => "sram",
2504 crate::spatial::ir::TensorSpace::Hbm => "hbm",
2505 crate::spatial::ir::TensorSpace::Dram => "ddr",
2506 };
2507 let program_of = |name: &str| -> Option<&crate::spatial::ir::SpatialProgram> {
2508 match name {
2509 "embed" => model.embed.as_ref(),
2510 "head" => Some(&model.head),
2511 kind => model
2512 .kinds
2513 .iter()
2514 .find(|k| k.name == kind)
2515 .map(|k| &k.program),
2516 }
2517 };
2518 let role_name = |c: &crate::spatial::residency::StateClass| {
2519 let t = program_of(&c.program).and_then(|p| p.tensors.iter().find(|t| t.name == c.tensor));
2520 match t.map(|t| {
2521 (
2522 t.role,
2523 file_of(&c.tensor).is_some()
2524 || crate::spatial::passes::from_q8::stored_part(&c.tensor).is_some(),
2525 )
2526 }) {
2527 Some((
2528 crate::spatial::ir::TensorRole::Param | crate::spatial::ir::TensorRole::Input,
2529 true,
2530 )) => "weight",
2531 Some((r, _)) => match r {
2532 crate::spatial::ir::TensorRole::Input => "input",
2533 crate::spatial::ir::TensorRole::Output => "output",
2534 crate::spatial::ir::TensorRole::Param => "constant",
2535 crate::spatial::ir::TensorRole::Activation => "activation",
2536 crate::spatial::ir::TensorRole::State => "table",
2537 },
2538 None => "tensor",
2539 }
2540 };
2541 manifest["residency"] = serde_json::json!({
2542 "provenance": crate::spatial::fit::PROVENANCE_MODELED,
2543 "sram_bytes_per_chip": r.sram_bytes,
2544 "hbm_bytes_per_chip": r.hbm_bytes,
2545 "reserve_bytes": r.reserve.iter().map(|(c, b)| (c.to_string(), *b)).collect::<std::collections::BTreeMap<_, _>>(),
2546 "states": r.placed.iter().map(|(c, tier)| serde_json::json!({
2547 "program": c.program, "tensor": c.tensor, "chip": c.chip, "instances": c.instances,
2548 "bytes": c.bytes, "moved_per_step": c.moved, "tier": tier_name(tier),
2549 })).collect::<Vec<_>>(),
2550 "off_chip": r.off_chip.iter().map(|(c, tier)| serde_json::json!({
2551 "program": c.program, "tensor": c.tensor, "role": role_name(c), "chip": c.chip, "instances": c.instances,
2552 "bytes": c.bytes, "moved_per_step": c.moved, "tier": tier_name(tier),
2553 })).collect::<Vec<_>>(),
2554 });
2555 if let (
2558 Some(StepShape {
2559 ctx,
2560 batch,
2561 tp,
2562 prefill,
2563 }),
2564 Some(embed),
2565 ) = (decode, embed)
2566 {
2567 manifest["ctx"] = serde_json::json!(ctx);
2568 manifest["batch"] = serde_json::json!(batch);
2569 manifest["tensor_parallel"] = serde_json::json!(tp);
2570 manifest["handoff"] = crate::spatial::handoff::contract(spec, ctx).map_err(|e| e.to_string())?.to_json();
2572 if let Some(chunk) = prefill {
2574 manifest["form"] = serde_json::json!("prefill");
2575 manifest["chunk"] = serde_json::json!(chunk);
2576 }
2577 manifest["serving_plan"] = match crate::codegen_cuda::qwen38::Qwen38Cfg::from_spec(spec) {
2579 Ok(cfg) => match crate::spatial::fit::qwen38_serving_plan(&cfg, &facts, ctx) {
2580 Ok(p) => serde_json::to_value(p).expect("JSON"),
2581 Err(why) => serde_json::json!({ "refused": why }),
2582 },
2583 Err(_) => serde_json::json!({ "refused": format!("the serving plan sizes the Qwen3.5/3.8 hybrid, not {} (CHIP-5)", spec.arch) }),
2584 };
2585 manifest["runtime_inputs"] = match (prefill, batch) {
2587 (None, 1) => serde_json::json!(["tok", "pos"]),
2588 (Some(_), _) => serde_json::json!(["toks", "pos_s0"]),
2589 (None, rows) => serde_json::json!(std::iter::once("toks".to_string())
2590 .chain((0..rows).map(|b| format!("pos_s{b}")))
2591 .collect::<Vec<_>>()),
2592 };
2593 manifest["embed"] = embed;
2594 }
2595 let constants = match decode {
2596 None => Vec::new(),
2597 Some(StepShape { ctx, .. }) => {
2598 use crate::model::bind::{rope_tables, rotations, RotaryTable};
2599 use crate::model::spec::RopeScaling;
2600 let le = |v: Vec<f64>| v.into_iter().flat_map(|x| (x as f32).to_le_bytes()).collect::<Vec<u8>>();
2601 let mut constants = Vec::new();
2602 for (rotation, rope) in rotations(spec).into_iter().enumerate() {
2603 let factors = match rope.scaling {
2604 RopeScaling::Factors => Some(rdu.rope_factors.as_deref().ok_or_else(|| {
2605 format!("rdu backend: {}: rotation {rotation} reads the checkpoint's frequency factors, and none were given", rdu.name)
2606 })?),
2607 _ => None,
2608 };
2609 let (cos, sin) = rope_tables(rope, ctx, factors);
2610 for (is_cos, values) in [(true, cos), (false, sin)] {
2611 let name = RotaryTable { rotation, cached: true, cos: is_cos }.name();
2612 constants.push((format!("{weights_dir}/{name}.f"), le(values)));
2613 }
2614 }
2615 for table in crate::model::bind::computed_tables(spec) {
2617 let values = crate::model::bind::computed_values(spec, table, ctx).expect("a table the spec gives");
2618 constants.push((format!("{weights_dir}/{}.f", table.name()), le(values)));
2619 }
2620 constants
2621 }
2622 };
2623 Ok(RduBundle {
2624 manifest: format!(
2625 "{}\n",
2626 serde_json::to_string_pretty(&manifest).expect("JSON")
2627 ),
2628 constants,
2629 program: whole_text,
2630 })
2631}
2632
2633#[cfg(feature = "codegen")]
2641pub fn compile_to_rdu(
2642 source: &str,
2643 chip: crate::spatial::rdu_chip::RduChip,
2644) -> Result<RduArtifact, ParseError> {
2645 use crate::codegen_sva::plasticine_report::counted_loop_fabric;
2646 use crate::spatial::lower::rdu_lanes::{
2647 first_function, lane_of, lower_loop_lane, lower_whole_program_lane,
2648 };
2649 use crate::spatial::passes::SpatialReject;
2650 use crate::spatial::pipeline::compile_program_to_spatial;
2651 fn custom(msg: String) -> ParseError {
2652 ParseError {
2653 kind: crate::error::ParseErrorKind::Custom(msg),
2654 span: crate::token::Span::default(),
2655 }
2656 }
2657 refuse_exact(source, "RDU tier", "a dataflow fabric")?;
2658 let facts = chip.facts();
2659 let target = facts.spatial_target();
2660 match lane_of(source) {
2661 RduLane::Tensor => match compile_program_to_spatial(source, &target) {
2669 Ok(lowering) => match lowering.program.as_ref() {
2670 Some(program) => {
2671 let coverage = serde_json::json!({
2672 "whole_program": true,
2673 "statements_total": lowering.statements,
2674 "statements_lowered": lowering.lowered,
2675 "sections": lowering.sections,
2676 "state_tensors": lowering.state,
2677 });
2678 lower_rdu_spatial(program, chip, &facts, RduLane::Tensor, Some(coverage)).map_err(custom)
2679 }
2680 None => {
2681 let first: Vec<String> = lowering
2682 .missing
2683 .iter()
2684 .take(3)
2685 .map(|m| format!("stmt {} `{}` [{}]: {}", m.stmt_index, m.binder, m.kind, m.why))
2686 .collect();
2687 Err(custom(format!(
2688 "rdu backend: tensor lane: the {} cannot host {} of this program's {} tensor statements — REFUSING rather than reporting a fraction as the whole program ({} lowered into {} section(s)). Missing: {}",
2689 target.name,
2690 lowering.missing.len(),
2691 lowering.statements,
2692 lowering.lowered,
2693 lowering.sections,
2694 if first.is_empty() { "(none listed)".to_string() } else { first.join(" | ") },
2695 )))
2696 }
2697 },
2698 Err(SpatialReject::Parse(e)) => Err(custom(format!("rdu backend: tensor lane: the program does not parse: {e}"))),
2699 Err(SpatialReject::Unrecognized { matmul, elementwise, reduction }) => Err(custom(format!(
2700 "rdu backend: tensor lane: the program declares tensors but no recognizer of the whole-program walk lifts an op from it (matmul: {matmul:?}; elementwise: {elementwise:?}; reduction: {reduction:?})",
2701 ))),
2702 Err(other) => Err(custom(format!("rdu backend: tensor lane: the {} cannot host this tensor program: {other:?}", target.name))),
2703 },
2704 RduLane::Loop => {
2705 let art = lower_loop_lane(source, chip).map_err(|e| custom(format!("rdu backend: loop lane: {e}")))?;
2706 Ok(loop_lane_artifact(art, chip, &facts))
2707 }
2708 RduLane::WholeProgram => match lower_whole_program_lane(source, chip) {
2709 Ok(program) => lower_rdu_spatial(&program, chip, &facts, RduLane::WholeProgram, None).map_err(custom),
2710 Err(reject) => {
2711 let loop_verdict = match first_function(source) {
2712 Some((name, _)) => match counted_loop_fabric(source, &name) {
2713 Ok(_) => "a counted loop (would have taken the loop lane)".to_string(),
2714 Err(why) => format!("`{name}` is not a counted range loop ({why})"),
2715 },
2716 None => "no function to take (the loop lane's unit is a counted-loop function)".to_string(),
2717 };
2718 Err(custom(format!(
2719 "rdu backend: no lane hosts this program on the {} — lane by shape: whole-program; tensor lane: no tensor declared and no tensor op recognized; loop lane: {loop_verdict}; whole-program lane: {reject:?}",
2720 target.name
2721 )))
2722 }
2723 },
2724 }
2725}
2726
2727#[cfg(feature = "codegen")]
2732fn loop_lane_artifact(
2733 art: crate::spatial::lower::rdu_lanes::LoopLaneArtifact,
2734 chip: crate::spatial::rdu_chip::RduChip,
2735 facts: &crate::spatial::rdu_chip::RduChipFacts,
2736) -> RduArtifact {
2737 use crate::spatial::fit::{ChipBlock, HONESTY, PROVENANCE_MODELED};
2738 use crate::spatial::lower::rdu::{
2739 NeutralTarget, GATED_REASON, NEUTRAL_SCHEMA, NEUTRAL_VERSION,
2740 };
2741 let target = facts.spatial_target();
2742 let parse =
2743 |s: &str| serde_json::from_str::<serde_json::Value>(s).expect("the loop lane renders JSON");
2744 let pretty =
2745 |v: &serde_json::Value| format!("{}\n", serde_json::to_string_pretty(v).expect("JSON"));
2746 let (placement, row, certificate) = (
2747 parse(&art.placement_json),
2748 parse(&art.report_json),
2749 parse(&art.certificate_json),
2750 );
2751 let envelope = serde_json::json!({
2752 "schema": NEUTRAL_SCHEMA,
2753 "version": NEUTRAL_VERSION,
2754 "lane": RduLane::Loop,
2755 "target": NeutralTarget::of(&target, facts),
2756 "sections": [],
2757 "state": [],
2758 "gathers": [],
2759 "ii_report": {},
2760 "loop": {
2761 "function": art.plasticine.fn_name,
2762 "plasticine_target": art.plasticine.target,
2763 "placement": placement,
2764 "row": row,
2765 "spatial_source": art.spatial_source,
2766 },
2767 "certificate": certificate,
2768 });
2769 let report = serde_json::json!({
2770 "schema": RDU_EMIT_REPORT_SCHEMA,
2771 "version": 1,
2772 "provenance": PROVENANCE_MODELED,
2773 "no_speed_claim": true,
2774 "honesty": HONESTY,
2775 "lane": RduLane::Loop,
2776 "chip": chip.as_str(),
2777 "target": target.name,
2778 "gated": GATED_REASON,
2779 "program": { "name": art.plasticine.fn_name, "kind": "counted_loop", "plasticine_target": art.plasticine.target },
2780 "certificate": certificate,
2781 "plasticine_row": row,
2782 "spatial_source": true,
2783 "notes": [],
2784 "chip_facts": ChipBlock::of(facts),
2785 });
2786 RduArtifact {
2787 chip: chip.as_str(),
2788 lane: RduLane::Loop,
2789 neutral_json: serde_json::to_string(&envelope).expect("the loop envelope serializes"),
2790 placement_txt: art.pretty,
2791 certificate_json: art.certificate_json,
2792 report_json: pretty(&report),
2793 spatial_source: Some(art.spatial_source),
2794 neutral: None,
2795 notes: Vec::new(),
2796 }
2797}
2798
2799#[cfg(feature = "codegen")]
2802fn lower_rdu_spatial(
2803 program: &crate::spatial::ir::SpatialProgram,
2804 chip: crate::spatial::rdu_chip::RduChip,
2805 facts: &crate::spatial::rdu_chip::RduChipFacts,
2806 lane: RduLane,
2807 coverage: Option<serde_json::Value>,
2808) -> Result<RduArtifact, String> {
2809 use crate::spatial::fit::{
2810 CertificateSummary, ChipBlock, IiBlock, ProgramSummary, HONESTY, PROVENANCE_MODELED,
2811 };
2812 use crate::spatial::lower::rdu::RduSpatialBackend;
2813 use crate::spatial::lower::spatial_lang::emit_spatial_program;
2814 use crate::spatial::lower::{SpatialArtifact, SpatialBackend};
2815 use crate::spatial::rdu_chip::rdu_ii_report;
2816 let target = facts.spatial_target();
2817 let artifact = match RduSpatialBackend::with_facts(facts.clone()).lower(program) {
2818 Ok(SpatialArtifact::SdkGated(a)) => a,
2819 Ok(other) => {
2820 return Err(format!(
2821 "rdu backend: {} lane: the {} lane is SDK-gated, got {other:?}",
2822 lane.as_str(),
2823 target.name
2824 ))
2825 }
2826 Err(e) => {
2827 return Err(format!(
2828 "rdu backend: {} lane: the {} refused the verified program {}: {e:?}",
2829 lane.as_str(),
2830 target.name,
2831 program.name
2832 ))
2833 }
2834 };
2835 let summary = CertificateSummary::of(&artifact, program);
2843 let mut certificate = crate::spatial::lower::rdu::certificate_summary(&artifact.certificate);
2844 certificate["digest_hex"] = serde_json::json!(summary.digest_hex);
2845 certificate["rechecked"] = serde_json::json!(summary.rechecked);
2846 certificate["provenance"] = serde_json::json!(PROVENANCE_MODELED);
2847 let mut notes = Vec::new();
2848 let spatial_source = match emit_spatial_program(program, &target, None) {
2849 Ok(s) => Some(s),
2850 Err(e) => {
2851 notes.push(format!(
2852 "spatial: the Spatial emitter refused {}: {e:?}",
2853 program.name
2854 ));
2855 None
2856 }
2857 };
2858 let pretty =
2859 |v: &serde_json::Value| format!("{}\n", serde_json::to_string_pretty(v).expect("JSON"));
2860 let report = serde_json::json!({
2861 "schema": RDU_EMIT_REPORT_SCHEMA,
2862 "version": 1,
2863 "provenance": PROVENANCE_MODELED,
2864 "no_speed_claim": true,
2865 "honesty": HONESTY,
2866 "lane": lane,
2867 "chip": chip.as_str(),
2868 "target": target.name,
2869 "gated": artifact.reason,
2870 "program": ProgramSummary::of(program, &artifact.census),
2871 "certificate": summary,
2872 "ii_report": IiBlock::of(&rdu_ii_report(program, facts), format!("the emitted program {} on the {}", program.name, target.name)),
2873 "coverage": coverage.unwrap_or(serde_json::json!({ "whole_program": true, "statements_total": 1, "statements_lowered": 1, "sections": 1 })),
2876 "spatial_source": spatial_source.is_some(),
2877 "notes": notes,
2878 "chip_facts": ChipBlock::of(facts),
2879 });
2880 Ok(RduArtifact {
2881 chip: chip.as_str(),
2882 lane,
2883 neutral_json: artifact.json.clone(),
2884 placement_txt: artifact.pretty.clone(),
2885 certificate_json: pretty(&certificate),
2886 report_json: pretty(&report),
2887 spatial_source,
2888 neutral: Some(artifact),
2889 notes,
2890 })
2891}
2892
2893#[cfg(feature = "codegen")]
2901pub fn compile_to_cuda(source: &str) -> Result<crate::codegen_cuda::CudaArtifact, ParseError> {
2902 fn custom(msg: String) -> ParseError {
2903 ParseError {
2904 kind: crate::error::ParseErrorKind::Custom(msg),
2905 span: crate::token::Span::default(),
2906 }
2907 }
2908 refuse_exact(source, "CUDA tier", "a GPU thread")?;
2913 let oracle_c = compile_to_c_stepped(source)?;
2914 crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2915 let (stmts, types, _policies) = parsed?;
2916 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2917 let program = crate::vm::Compiler::compile_with_oracle_located(
2918 stmts,
2919 interner,
2920 Some(types),
2921 Some(oracle),
2922 )?;
2923 crate::codegen_cuda::codegen_program_cuda(&program, &oracle_c)
2924 .map_err(|e| custom(e.to_string()))
2925 })
2926}
2927
2928#[cfg(feature = "codegen")]
2933pub fn compile_to_cuda_gemm(
2934 m: usize,
2935 k: usize,
2936 n: usize,
2937) -> Result<crate::codegen_cuda::CudaGemmArtifact, ParseError> {
2938 fn custom(msg: String) -> ParseError {
2939 ParseError {
2940 kind: crate::error::ParseErrorKind::Custom(msg),
2941 span: crate::token::Span::default(),
2942 }
2943 }
2944 let (weights, acts) = crate::codegen_cuda::sample_gemm_data(m, k, n);
2945 crate::codegen_cuda::emit_int8_gemm(m, k, n, &weights, &acts).map_err(|e| custom(e.to_string()))
2946}
2947
2948pub fn compile_to_tenstorrent_matmul(
2954 source: &str,
2955) -> Result<(crate::codegen_tt::matmul_lower::MatmulSpec, String), String> {
2956 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
2957 let (stmts, _types, _policies) = parsed?;
2958 let spec = crate::tensor_recognize::recognize_matmul(stmts, interner)
2959 .map_err(|r| format!("not a tile-matmul the compiler can lower: {r:?}"))?;
2960 let target = crate::spatial::target::SpatialTarget::wormhole();
2965 let program = crate::spatial::pipeline::compile_to_spatial(source, &target)
2966 .map_err(|e| format!("not a tile-matmul the compiler can lower: {e:?}"))?;
2967 let kernel = crate::spatial::lower::tensix::TensixBackend::new(target)
2968 .compute_kernel_source(&program)
2969 .map_err(|e| format!("the Tensix printer refused the recognized matmul: {e:?}"))?;
2970 Ok((spec, kernel))
2971 })
2972}
2973
2974#[cfg(feature = "codegen")]
2981pub fn compile_to_cuda_matmul(
2982 source: &str,
2983) -> Result<(crate::codegen_tt::matmul_lower::MatmulSpec, String), String> {
2984 compile_to_cuda_matmul_with(source, &crate::codegen_cuda::knobs::CudaKnobs::default())
2985}
2986
2987#[cfg(feature = "codegen")]
2992pub fn compile_to_cuda_matmul_with(
2993 source: &str,
2994 knobs: &crate::codegen_cuda::knobs::CudaKnobs,
2995) -> Result<(crate::codegen_tt::matmul_lower::MatmulSpec, String), String> {
2996 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
2997 let (stmts, _types, _policies) = parsed?;
2998 let spec = crate::tensor_recognize::recognize_matmul(stmts, interner)
2999 .map_err(|r| format!("not a matmul the CUDA backend can lower: {r:?}"))?;
3000 let cu = crate::codegen_cuda::matrix::lower_matmul_to_cuda_with(&spec, knobs);
3001 Ok((spec, cu))
3002 })
3003}
3004
3005#[cfg(feature = "codegen")]
3010pub fn compile_to_cuda_tensor_op(source: &str) -> Result<String, String> {
3011 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3012 let (stmts, _types, _policies) = parsed?;
3013 if crate::codegen_cuda::qwen_emit::recognize_moe(stmts).is_some() {
3022 return Err("`moe` is a composite block — lower it with compile_to_cuda_forward_q8_moe*, not the single-op path".to_string());
3023 }
3024 if crate::codegen_cuda::qwen_emit::recognize_attention(stmts).is_some() {
3025 return Err("`attention` is a composite block — lower it through the forward path, not the single-op path".to_string());
3026 }
3027 if let Ok(spec) = crate::tensor_recognize::recognize_matmul(stmts, interner) {
3028 return Ok(crate::codegen_cuda::matrix::lower_matmul_to_cuda(&spec));
3029 }
3030 if let Ok(spec) = crate::tensor_recognize::recognize_elementwise(stmts, interner) {
3031 return Ok(crate::codegen_cuda::matrix::lower_elementwise_to_cuda(
3032 &spec,
3033 ));
3034 }
3035 if let Ok(spec) = crate::tensor_recognize::recognize_swiglu(stmts, interner) {
3036 return Ok(crate::codegen_cuda::fused_row::emit_swiglu(
3037 &spec,
3038 &crate::codegen_cuda::knobs::CudaKnobs::default(),
3039 ));
3040 }
3041 if let Ok(spec) = crate::tensor_recognize::recognize_fused_row(stmts, interner) {
3042 return Ok(crate::codegen_cuda::fused_row::emit_fused_row(
3043 &spec,
3044 &crate::codegen_cuda::knobs::CudaKnobs::default(),
3045 ));
3046 }
3047 Err("not a tensor op the CUDA backend can lower (matmul / elementwise / reduction / swiglu)".to_string())
3048 })
3049}
3050
3051#[cfg(feature = "codegen")]
3056pub fn compile_to_sol_solution(
3057 source: &str,
3058 definition: &str,
3059 inputs: &[&str],
3060 output: &str,
3061) -> Result<crate::codegen_cuda::SolSolution, String> {
3062 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3063 let (stmts, _types, _policies) = parsed?;
3064 let spec = crate::tensor_recognize::recognize_fused_row(stmts, interner)
3065 .map_err(|r| format!("not a fused-row op the SOL-ExecBench bridge can lower: {r:?}"))?;
3066 Ok(crate::codegen_cuda::emit_fused_row_solution(
3067 &spec,
3068 &crate::codegen_cuda::knobs::CudaKnobs::default(),
3069 definition,
3070 inputs,
3071 output,
3072 ))
3073 })
3074}
3075
3076#[cfg(feature = "codegen")]
3081pub fn compile_to_cuda_forward(source: &str) -> Result<String, String> {
3082 compile_to_cuda_forward_weighted(source, &std::collections::HashMap::new())
3083}
3084
3085#[cfg(feature = "codegen")]
3090pub fn compile_to_cuda_forward_weighted(
3091 source: &str,
3092 weights: &std::collections::HashMap<String, (String, usize)>,
3093) -> Result<String, String> {
3094 compile_to_cuda_forward_q8(source, weights, &std::collections::HashMap::new())
3095}
3096
3097#[cfg(feature = "codegen")]
3102pub fn compile_to_cuda_forward_q8(
3103 source: &str,
3104 weights: &std::collections::HashMap<String, (String, usize)>,
3105 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3106) -> Result<String, String> {
3107 compile_to_cuda_forward_q8_impl(
3108 source,
3109 weights,
3110 q8,
3111 &std::collections::HashMap::new(),
3112 crate::codegen_cuda::qwen_emit::Q8MatKind::Dequant,
3113 )
3114}
3115
3116#[cfg(feature = "codegen")]
3122pub fn compile_to_cuda_forward_q8_dp4a(
3123 source: &str,
3124 weights: &std::collections::HashMap<String, (String, usize)>,
3125 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3126) -> Result<String, String> {
3127 compile_to_cuda_forward_q8_impl(
3128 source,
3129 weights,
3130 q8,
3131 &std::collections::HashMap::new(),
3132 crate::codegen_cuda::qwen_emit::Q8MatKind::Int8Act,
3133 )
3134}
3135
3136#[cfg(feature = "codegen")]
3137fn compile_to_cuda_forward_q8_impl(
3138 source: &str,
3139 weights: &std::collections::HashMap<String, (String, usize)>,
3140 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3141 moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3142 kind: crate::codegen_cuda::qwen_emit::Q8MatKind,
3143) -> Result<String, String> {
3144 compile_to_cuda_forward_holding(source, weights, q8, moe, kind, &[])
3145}
3146
3147#[cfg(feature = "codegen")]
3150pub fn compile_to_cuda_forward_holding(
3151 source: &str,
3152 weights: &std::collections::HashMap<String, (String, usize)>,
3153 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3154 moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3155 kind: crate::codegen_cuda::qwen_emit::Q8MatKind,
3156 held: &[&str],
3157) -> Result<String, String> {
3158 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3159 let (stmts, _types, _policies) = parsed?;
3160 let graph = crate::codegen_cuda::qwen_emit::forward_graph_holding(stmts, interner, q8, moe, kind, held)
3161 .map_err(|e| e.to_string())?;
3162 let inits = crate::codegen_cuda::qwen_emit::collect_inits(stmts, interner);
3163 crate::codegen_cuda::qwen_emit::emit_forward(
3164 &graph, &inits, weights, q8, moe, kind, interner,
3165 )
3166 .map_err(|e| e.to_string())
3167 })
3168}
3169
3170#[cfg(feature = "codegen")]
3175pub fn compile_to_cuda_forward_q8_moe(
3176 source: &str,
3177 weights: &std::collections::HashMap<String, (String, usize)>,
3178 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3179 moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3180) -> Result<String, String> {
3181 compile_to_cuda_forward_q8_impl(
3182 source,
3183 weights,
3184 q8,
3185 moe,
3186 crate::codegen_cuda::qwen_emit::Q8MatKind::Dequant,
3187 )
3188}
3189
3190#[cfg(feature = "codegen")]
3198pub fn compile_to_cuda_forward_q8_moe_dp4a(
3199 source: &str,
3200 weights: &std::collections::HashMap<String, (String, usize)>,
3201 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3202 moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3203) -> Result<String, String> {
3204 compile_to_cuda_forward_q8_impl(
3205 source,
3206 weights,
3207 q8,
3208 moe,
3209 crate::codegen_cuda::qwen_emit::Q8MatKind::Int8Act,
3210 )
3211}
3212
3213#[cfg(feature = "codegen")]
3219pub fn compile_to_cuda_forward_q8_moe_exact(
3220 source: &str,
3221 weights: &std::collections::HashMap<String, (String, usize)>,
3222 q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3223 moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3224) -> Result<String, String> {
3225 compile_to_cuda_forward_q8_impl(
3226 source,
3227 weights,
3228 q8,
3229 moe,
3230 crate::codegen_cuda::qwen_emit::Q8MatKind::TwoPassInt8,
3231 )
3232}
3233
3234#[cfg(feature = "codegen")]
3237pub fn compile_to_tenstorrent_tensor_op(source: &str) -> Result<String, String> {
3238 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3239 let (stmts, _types, _policies) = parsed?;
3240 let _ = (stmts, interner);
3255 let target = crate::spatial::target::SpatialTarget::wormhole();
3256 let program = crate::spatial::pipeline::compile_to_spatial(source, &target).map_err(|e| {
3257 format!("not a tensor op the Tenstorrent backend can lower (matmul / elementwise / reduction / swiglu): {e:?}")
3258 })?;
3259 crate::spatial::lower::tensix::TensixBackend::new(target)
3262 .compute_kernel_source(&program)
3263 .map_err(|e| format!("the Tensix printer refused the recognized tensor op: {e:?}"))
3264 })
3265}
3266
3267#[cfg(feature = "codegen")]
3272fn mesh_program(values: &[i64]) -> Result<crate::spatial::ir::SpatialProgram, String> {
3273 let target = crate::spatial::target::SpatialTarget::wormhole();
3274 let tpl = crate::spatial::passes::from_tensor_op::from_pipe(values, &target)
3275 .map_err(|e| format!("the pattern's value stream does not lower: {e:?}"))?;
3276 crate::spatial::pipeline::run_passes(tpl, &target)
3277 .map_err(|e| format!("the lowered pattern did not survive the passes: {e:?}"))
3278}
3279
3280pub fn compile_to_tenstorrent_concurrency(
3285 source: &str,
3286) -> Result<
3287 crate::codegen_tt::concurrency_mesh::MeshLowering<
3288 crate::codegen_tt::concurrency_mesh::ConcurrencySpec,
3289 >,
3290 String,
3291> {
3292 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3293 let (stmts, _types, _policies) = parsed?;
3294 let spec =
3295 crate::codegen_tt::concurrency_mesh::recognize_producer_consumer(stmts, interner)
3296 .ok_or_else(|| {
3297 "not a producer/consumer pipe program the mesh tier can lower".to_string()
3298 })?;
3299 let program = Some(mesh_program(&spec.sends)?);
3300 Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3301 })
3302}
3303
3304pub fn compile_to_tenstorrent_fanout(
3309 source: &str,
3310) -> Result<
3311 crate::codegen_tt::concurrency_mesh::MeshLowering<
3312 crate::codegen_tt::concurrency_mesh::FanoutSpec,
3313 >,
3314 String,
3315> {
3316 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3317 let (stmts, _types, _policies) = parsed?;
3318 let spec = crate::codegen_tt::concurrency_mesh::recognize_fanout(stmts, interner)
3319 .ok_or_else(|| "not a fan-out program the mesh tier can lower".to_string())?;
3320 let program = Some(mesh_program(&spec.values)?);
3321 Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3322 })
3323}
3324
3325pub fn compile_to_tenstorrent_select(
3328 source: &str,
3329) -> Result<
3330 crate::codegen_tt::concurrency_mesh::MeshLowering<
3331 crate::codegen_tt::concurrency_mesh::SelectSpec,
3332 >,
3333 String,
3334> {
3335 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3336 let (stmts, _types, _policies) = parsed?;
3337 let spec = crate::codegen_tt::concurrency_mesh::recognize_select(stmts, interner)
3338 .ok_or_else(|| "not a select program the mesh tier can lower".to_string())?;
3339 let program = Some(mesh_program(&[spec.presend])?);
3343 Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3344 })
3345}
3346
3347pub fn compile_to_tenstorrent_racy_select(
3352 source: &str,
3353) -> Result<
3354 crate::codegen_tt::concurrency_mesh::MeshLowering<
3355 crate::codegen_tt::concurrency_mesh::RacySelectSpec,
3356 >,
3357 String,
3358> {
3359 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3360 let (stmts, _types, _policies) = parsed?;
3361 let spec = crate::codegen_tt::concurrency_mesh::recognize_racy_select(stmts, interner)
3362 .ok_or_else(|| "not a racy select program the mesh tier can lower".to_string())?;
3363 let program = if spec.send_vtime_ms < spec.timeout_ms {
3367 Some(mesh_program(&[spec.value])?)
3368 } else {
3369 None
3370 };
3371 Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3372 })
3373}
3374
3375pub fn compile_to_tenstorrent_dynamic(
3379 source: &str,
3380) -> Result<
3381 crate::codegen_tt::concurrency_mesh::MeshLowering<
3382 crate::codegen_tt::concurrency_mesh::DynamicSpec,
3383 >,
3384 String,
3385> {
3386 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3387 let (stmts, _types, _policies) = parsed?;
3388 let spec = crate::codegen_tt::concurrency_mesh::recognize_dynamic_producer(stmts, interner)
3389 .ok_or_else(|| "not a dynamic loop producer the mesh tier can lower".to_string())?;
3390 let program = Some(mesh_program(&spec.values)?);
3391 Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3392 })
3393}
3394
3395pub fn compile_to_tenstorrent_multi_racy(
3399 source: &str,
3400) -> Result<
3401 crate::codegen_tt::concurrency_mesh::MeshLowering<
3402 crate::codegen_tt::concurrency_mesh::RacyMultiSpec,
3403 >,
3404 String,
3405> {
3406 crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3407 let (stmts, _types, _policies) = parsed?;
3408 let spec = crate::codegen_tt::concurrency_mesh::recognize_multi_racy(stmts, interner)
3409 .ok_or_else(|| "not a multi-task racy select the mesh tier can lower".to_string())?;
3410 let winner = spec.tasks.iter().min_by_key(|(_, vt)| *vt).copied();
3414 let program = match winner {
3415 Some((value, vt)) if vt < spec.timeout_ms => Some(mesh_program(&[value])?),
3416 _ => None,
3417 };
3418 Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3419 })
3420}
3421
3422pub fn compile_to_wasm(source: &str) -> Result<Vec<u8>, ParseError> {
3423 compile_to_wasm_with(source, &crate::vm::reach::HostEntries::default())
3424}
3425
3426pub fn compile_to_wasm_with(
3430 source: &str,
3431 entries: &crate::vm::reach::HostEntries,
3432) -> Result<Vec<u8>, ParseError> {
3433 compile_to_wasm_module(source, entries, false)
3434}
3435
3436pub fn compile_to_wasm_checked(source: &str) -> Result<Vec<u8>, ParseError> {
3440 compile_to_wasm_module(source, &crate::vm::reach::HostEntries::default(), true)
3441}
3442
3443fn compile_to_wasm_module(
3444 source: &str,
3445 entries: &crate::vm::reach::HostEntries,
3446 checked: bool,
3447) -> Result<Vec<u8>, ParseError> {
3448 fn custom(msg: String) -> ParseError {
3449 ParseError {
3450 kind: crate::error::ParseErrorKind::Custom(msg),
3451 span: crate::token::Span::default(),
3452 }
3453 }
3454 let concrete = crate::monomorphize::Options {
3457 lower_option: false,
3458 };
3459 crate::ui_bridge::with_monomorphic_program_checked(source, concrete, |parsed, interner| {
3460 let (stmts, types, policies) = parsed?;
3461 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
3467 let mut program = crate::vm::Compiler::compile_with_oracle_located(
3469 stmts,
3470 interner,
3471 Some(types),
3472 Some(oracle),
3473 )?;
3474 crate::vm::peephole::peephole(&mut program);
3477 refuse_unlinkable_with(&program, interner, Backend::WebAssembly, entries)
3478 .map_err(custom)?;
3479 let assemble = if checked {
3480 crate::vm::wasm::assemble_program_checked
3481 } else {
3482 crate::vm::wasm::assemble_program_with
3483 };
3484 assemble(&program, &policies, interner, entries).map_err(|e| custom(e.to_string()))
3485 })
3486}
3487
3488pub fn compile_to_wasm_observed(
3496 source: &str,
3497) -> Result<(Vec<u8>, Vec<crate::vm::ObsSiteDesc>), ParseError> {
3498 fn custom(msg: String) -> ParseError {
3499 ParseError {
3500 kind: crate::error::ParseErrorKind::Custom(msg),
3501 span: crate::token::Span::default(),
3502 }
3503 }
3504 let concrete = crate::monomorphize::Options {
3505 lower_option: false,
3506 };
3507 crate::ui_bridge::with_monomorphic_program(source, concrete, |parsed, interner| {
3508 let (stmts, types, policies) = parsed.map_err(custom)?;
3509 let mut program =
3510 crate::vm::Compiler::compile_observed_located(stmts, interner, Some(types))?;
3511 let sites = program.observation_sites.clone();
3512 crate::vm::peephole::peephole(&mut program);
3515 refuse_unlinkable(&program, interner, Backend::WebAssembly).map_err(custom)?;
3516 let wasm = crate::vm::wasm::assemble_program(&program, &policies, interner)
3517 .map_err(|e| custom(e.to_string()))?;
3518 Ok((wasm, sites))
3519 })
3520}
3521
3522#[cfg(all(feature = "wasm-jit", not(target_arch = "wasm32")))]
3534pub fn compile_to_wasm_linked(source: &str) -> Result<Vec<u8>, ParseError> {
3535 let relocatable = compile_to_wasm_relocatable(source)?;
3536 crate::vm::wasm::link_relocatable_bigint(&relocatable).map_err(|e| ParseError {
3537 kind: crate::error::ParseErrorKind::Custom(e.to_string()),
3538 span: crate::token::Span::default(),
3539 })
3540}
3541
3542#[cfg(all(feature = "wasm-jit", not(target_arch = "wasm32")))]
3547pub fn compile_to_wasm_relocatable(source: &str) -> Result<Vec<u8>, ParseError> {
3548 fn custom(msg: String) -> ParseError {
3549 ParseError {
3550 kind: crate::error::ParseErrorKind::Custom(msg),
3551 span: crate::token::Span::default(),
3552 }
3553 }
3554 let concrete = crate::monomorphize::Options {
3555 lower_option: false,
3556 };
3557 crate::ui_bridge::with_monomorphic_program(
3558 source,
3559 concrete,
3560 |parsed, interner| -> Result<Vec<u8>, ParseError> {
3561 let (stmts, types, policies) = parsed.map_err(custom)?;
3562 let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
3563 let mut program = crate::vm::Compiler::compile_with_oracle_located(
3564 stmts,
3565 interner,
3566 Some(types),
3567 Some(oracle),
3568 )?;
3569 crate::vm::peephole::peephole(&mut program);
3571 refuse_unlinkable(&program, interner, Backend::WebAssembly).map_err(custom)?;
3572 let module = crate::vm::wasm::assemble_program_linked(&program, &policies, interner)
3573 .map_err(|e| custom(e.to_string()))?;
3574 crate::vm::wasm::module_to_relocatable(&module).map_err(|e| custom(e.to_string()))
3575 },
3576 )
3577}
3578
3579pub fn display_float_like_logos(f: f64) -> String {
3584 crate::interpreter::RuntimeValue::Float(f).to_display_string()
3585}
3586
3587pub fn classify_source(source: &str) -> Result<crate::concurrency::Determinacy, ParseError> {
3594 let mut interner = Interner::new();
3595 let mut lexer = Lexer::new(source, &mut interner);
3596 let tokens = lexer.tokenize();
3597
3598 let (type_registry, _policy_registry) = {
3599 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3600 let result = discovery.run_full();
3601 (result.types, result.policies)
3602 };
3603
3604 let mut world_state = WorldState::new();
3605 let expr_arena = Arena::new();
3606 let term_arena = Arena::new();
3607 let np_arena = Arena::new();
3608 let sym_arena = Arena::new();
3609 let role_arena = Arena::new();
3610 let pp_arena = Arena::new();
3611 let stmt_arena: Arena<Stmt> = Arena::new();
3612 let _compile_facts = crate::optimize::facts::scope();
3613 let imperative_expr_arena: Arena<Expr> = Arena::new();
3614 let type_expr_arena: Arena<TypeExpr> = Arena::new();
3615
3616 let ast_ctx = AstContext::with_types(
3617 &expr_arena,
3618 &term_arena,
3619 &np_arena,
3620 &sym_arena,
3621 &role_arena,
3622 &pp_arena,
3623 &stmt_arena,
3624 &imperative_expr_arena,
3625 &type_expr_arena,
3626 );
3627
3628 let mut parser = Parser::new(
3629 tokens,
3630 &mut world_state,
3631 &mut interner,
3632 ast_ctx,
3633 type_registry,
3634 );
3635 let stmts = parser.parse_program()?;
3636 Ok(crate::concurrency::classify_program(&stmts))
3637}
3638
3639pub fn first_parallel_block_independent(source: &str) -> Result<Option<bool>, ParseError> {
3643 let mut interner = Interner::new();
3644 let mut lexer = Lexer::new(source, &mut interner);
3645 let tokens = lexer.tokenize();
3646
3647 let (type_registry, _policy_registry) = {
3648 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3649 let result = discovery.run_full();
3650 (result.types, result.policies)
3651 };
3652
3653 let mut world_state = WorldState::new();
3654 let expr_arena = Arena::new();
3655 let term_arena = Arena::new();
3656 let np_arena = Arena::new();
3657 let sym_arena = Arena::new();
3658 let role_arena = Arena::new();
3659 let pp_arena = Arena::new();
3660 let stmt_arena: Arena<Stmt> = Arena::new();
3661 let _compile_facts = crate::optimize::facts::scope();
3662 let imperative_expr_arena: Arena<Expr> = Arena::new();
3663 let type_expr_arena: Arena<TypeExpr> = Arena::new();
3664
3665 let ast_ctx = AstContext::with_types(
3666 &expr_arena,
3667 &term_arena,
3668 &np_arena,
3669 &sym_arena,
3670 &role_arena,
3671 &pp_arena,
3672 &stmt_arena,
3673 &imperative_expr_arena,
3674 &type_expr_arena,
3675 );
3676
3677 let mut parser = Parser::new(
3678 tokens,
3679 &mut world_state,
3680 &mut interner,
3681 ast_ctx,
3682 type_registry,
3683 );
3684 let stmts = parser.parse_program()?;
3685 Ok(find_first_parallel_independence(&stmts))
3686}
3687
3688fn find_first_parallel_independence(stmts: &[Stmt]) -> Option<bool> {
3689 for s in stmts {
3690 match s {
3691 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
3692 return Some(crate::concurrency::branches_independent(tasks));
3693 }
3694 Stmt::FunctionDef { body, .. }
3695 | Stmt::While { body, .. }
3696 | Stmt::Repeat { body, .. }
3697 | Stmt::Zone { body, .. } => {
3698 if let Some(r) = find_first_parallel_independence(body) {
3699 return Some(r);
3700 }
3701 }
3702 Stmt::If {
3703 then_block,
3704 else_block,
3705 ..
3706 } => {
3707 if let Some(r) = find_first_parallel_independence(then_block) {
3708 return Some(r);
3709 }
3710 if let Some(eb) = else_block {
3711 if let Some(r) = find_first_parallel_independence(eb) {
3712 return Some(r);
3713 }
3714 }
3715 }
3716 _ => {}
3717 }
3718 }
3719 None
3720}
3721
3722pub fn send_check_source(
3727 source: &str,
3728) -> Result<Vec<crate::concurrency::SendDiagnostic>, ParseError> {
3729 let mut interner = Interner::new();
3730 let mut lexer = Lexer::new(source, &mut interner);
3731 let tokens = lexer.tokenize();
3732
3733 let (type_registry, _policy_registry) = {
3734 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3735 let result = discovery.run_full();
3736 (result.types, result.policies)
3737 };
3738
3739 let mut world_state = WorldState::new();
3740 let expr_arena = Arena::new();
3741 let term_arena = Arena::new();
3742 let np_arena = Arena::new();
3743 let sym_arena = Arena::new();
3744 let role_arena = Arena::new();
3745 let pp_arena = Arena::new();
3746 let stmt_arena: Arena<Stmt> = Arena::new();
3747 let _compile_facts = crate::optimize::facts::scope();
3748 let imperative_expr_arena: Arena<Expr> = Arena::new();
3749 let type_expr_arena: Arena<TypeExpr> = Arena::new();
3750
3751 let ast_ctx = AstContext::with_types(
3752 &expr_arena,
3753 &term_arena,
3754 &np_arena,
3755 &sym_arena,
3756 &role_arena,
3757 &pp_arena,
3758 &stmt_arena,
3759 &imperative_expr_arena,
3760 &type_expr_arena,
3761 );
3762
3763 let mut parser = Parser::new(
3764 tokens,
3765 &mut world_state,
3766 &mut interner,
3767 ast_ctx,
3768 type_registry,
3769 );
3770 let stmts = parser.parse_program()?;
3771 Ok(crate::concurrency::check_send_escape(&stmts))
3772}
3773
3774pub fn compile_program_full_deterministic(source: &str) -> Result<CompileOutput, ParseError> {
3779 crate::codegen::with_deterministic_replay(|| compile_program_full(source))
3780}
3781
3782fn refuse_undeclared_types(
3787 parsed: &[Stmt],
3788 spans: &[crate::token::Span],
3789 registry: &crate::analysis::TypeRegistry,
3790 interner: &Interner,
3791) -> Result<(), ParseError> {
3792 match crate::analysis::check::first_undeclared_type(parsed, registry, interner) {
3793 Some((index, name)) => Err(ParseError {
3794 kind: crate::error::ParseErrorKind::Custom(format!(
3795 "`{}` is not a type this program declares or imports",
3796 interner.resolve(name)
3797 )),
3798 span: index
3799 .and_then(|i| spans.get(i))
3800 .copied()
3801 .unwrap_or_default(),
3802 }),
3803 None => Ok(()),
3804 }
3805}
3806
3807pub fn compile_program_full(source: &str) -> Result<CompileOutput, ParseError> {
3812 let (imperative_src, math_src) = crate::ui_bridge::partition_mixed(source);
3816 let proven = match math_src.as_deref() {
3817 Some(math) => crate::ui_bridge::mixed_proven_module(math)?,
3818 None => None,
3819 };
3820 compile_program_full_with_proven(&imperative_src, proven.as_deref())
3821}
3822
3823pub fn compile_program_full_with_wire(source: &str) -> Result<CompileOutput, ParseError> {
3829 crate::codegen::types::with_wire_impls(true, || compile_program_full(source))
3830}
3831
3832pub fn compile_program_full_with_proven(
3838 source: &str,
3839 proven: Option<&str>,
3840) -> Result<CompileOutput, ParseError> {
3841 let prelude_src = crate::loader::apply_prelude(source);
3844 let pruned = crate::loader::prune_unreachable_prelude_from(source, prelude_src.as_ref());
3850 let source = pruned.as_str();
3851 let library = crate::loader::LibraryProvenance::of(source);
3852
3853 let mut interner = Interner::new();
3854 let mut lexer = Lexer::new(source, &mut interner);
3855 let tokens = lexer.tokenize();
3856
3857 let (type_registry, policy_registry) = {
3859 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3860 let result = discovery.run_full();
3861 (result.types, result.policies)
3862 };
3863 let codegen_policies = policy_registry.clone();
3864
3865 let mut world_state = WorldState::new();
3866 let expr_arena = Arena::new();
3867 let term_arena = Arena::new();
3868 let np_arena = Arena::new();
3869 let sym_arena = Arena::new();
3870 let role_arena = Arena::new();
3871 let pp_arena = Arena::new();
3872 let stmt_arena: Arena<Stmt> = Arena::new();
3873 let _compile_facts = crate::optimize::facts::scope();
3874 let imperative_expr_arena: Arena<Expr> = Arena::new();
3875 let type_expr_arena: Arena<TypeExpr> = Arena::new();
3876
3877 let ast_ctx = AstContext::with_types(
3878 &expr_arena,
3879 &term_arena,
3880 &np_arena,
3881 &sym_arena,
3882 &role_arena,
3883 &pp_arena,
3884 &stmt_arena,
3885 &imperative_expr_arena,
3886 &type_expr_arena,
3887 );
3888
3889 let mut parser = Parser::new(
3891 tokens,
3892 &mut world_state,
3893 &mut interner,
3894 ast_ctx,
3895 type_registry,
3896 );
3897 let stmts = parser.parse_program()?;
3900 let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
3901
3902 let stmts: Vec<Stmt> = if crate::codegen::observed_codegen_enabled() {
3910 stmts
3911 } else {
3912 match crate::elide_observation::elide_observation(&stmts, &stmt_arena) {
3913 Some(elided) => elided.to_vec(),
3914 None => stmts,
3915 }
3916 };
3917
3918 let (opt_config, gate) = crate::optimize::install_decorators(
3927 crate::optimization::OptimizationConfig::from_env(),
3928 &parser.program_opt_flags(),
3929 parser.required_optimizations(),
3930 );
3931 let codegen_registry = parser.into_type_registry();
3932 refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
3933
3934 check_as_written(&parsed, &interner, AsWritten::Escapes)?;
3936
3937 let resolved = crate::resolve_program::resolve_program(
3942 &stmts,
3943 crate::ast_map::Arenas {
3944 exprs: &imperative_expr_arena,
3945 stmts: &stmt_arena,
3946 types: &type_expr_arena,
3947 },
3948 &mut interner,
3949 opt_config.is_on(crate::optimization::Opt::Comptime),
3950 library.functions(),
3951 );
3952 let stmts: Vec<Stmt> = match resolved {
3953 Some(rw) => rw.to_vec(),
3954 None => stmts,
3955 };
3956 let (stmts, codegen_registry) = lift_program_bindings(
3957 stmts,
3958 codegen_registry,
3959 &mut interner,
3960 crate::ast_map::Arenas {
3961 exprs: &imperative_expr_arena,
3962 stmts: &stmt_arena,
3963 types: &type_expr_arena,
3964 },
3965 )?;
3966
3967 let stmts = crate::optimize::optimize_program(
3969 stmts,
3970 &imperative_expr_arena,
3971 &stmt_arena,
3972 &mut interner,
3973 &opt_config,
3974 );
3975
3976 let mut dependencies = extract_dependencies(&stmts, &interner)?;
3978
3979 let needs_wasm_bindgen = stmts.iter().any(|stmt| {
3981 if let Stmt::FunctionDef {
3982 is_exported: true,
3983 export_target: Some(target),
3984 ..
3985 } = stmt
3986 {
3987 interner.resolve(*target).eq_ignore_ascii_case("wasm")
3988 } else {
3989 false
3990 }
3991 });
3992 if needs_wasm_bindgen && !dependencies.iter().any(|d| d.name == "wasm-bindgen") {
3993 dependencies.push(CrateDependency {
3994 name: "wasm-bindgen".to_string(),
3995 version: "0.2".to_string(),
3996 features: vec![],
3997 });
3998 }
3999
4000 let proven_exports = proven
4007 .map(crate::analysis::proven_module_exports)
4008 .unwrap_or_default();
4009 crate::analysis::check_unknown_calls_with_exports(
4010 &stmts,
4011 &interner,
4012 &codegen_registry,
4013 &proven_exports,
4014 )
4015 .map_err(|e| ParseError {
4016 kind: e.to_parse_error_kind(&interner),
4017 span: crate::token::Span::default(),
4018 })?;
4019
4020 let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
4021 .map_err(|e| ParseError {
4022 kind: e.to_parse_error_kind(&interner, &stmts),
4023 span: crate::token::Span::default(),
4024 })?;
4025 let rust_code = crate::optimize::with_backend_lowering(|| {
4026 crate::codegen::codegen_program_with_proven(
4027 &stmts,
4028 &codegen_registry,
4029 &codegen_policies,
4030 &interner,
4031 &type_env,
4032 &opt_config,
4033 "proven",
4034 proven,
4035 )
4036 });
4037
4038 gate.verify().map_err(|m| ParseError {
4042 kind: crate::error::ParseErrorKind::Custom(m),
4043 span: crate::token::Span::default(),
4044 })?;
4045
4046 let has_c = stmts.iter().any(|stmt| {
4048 if let Stmt::FunctionDef {
4049 is_exported: true,
4050 export_target,
4051 ..
4052 } = stmt
4053 {
4054 match export_target {
4055 None => true,
4056 Some(t) => interner.resolve(*t).eq_ignore_ascii_case("c"),
4057 }
4058 } else {
4059 false
4060 }
4061 });
4062
4063 let c_header = if has_c {
4064 Some(generate_c_header(
4065 &stmts,
4066 "module",
4067 &interner,
4068 &codegen_registry,
4069 ))
4070 } else {
4071 None
4072 };
4073
4074 if has_c && !dependencies.iter().any(|d| d.name == "serde_json") {
4076 dependencies.push(CrateDependency {
4077 name: "serde_json".to_string(),
4078 version: "1".to_string(),
4079 features: vec![],
4080 });
4081 }
4082
4083 let python_bindings = if has_c {
4084 Some(generate_python_bindings(
4085 &stmts,
4086 "module",
4087 &interner,
4088 &codegen_registry,
4089 ))
4090 } else {
4091 None
4092 };
4093
4094 let (typescript_bindings, typescript_types) = if has_c {
4095 let (js, dts) =
4096 generate_typescript_bindings(&stmts, "module", &interner, &codegen_registry);
4097 (Some(js), Some(dts))
4098 } else {
4099 (None, None)
4100 };
4101
4102 Ok(CompileOutput {
4103 rust_code,
4104 dependencies,
4105 c_header,
4106 python_bindings,
4107 typescript_types,
4108 typescript_bindings,
4109 })
4110}
4111
4112pub fn compile_function_to_native_rust(
4123 source: &str,
4124 target: &str,
4125) -> Result<Option<AotModule>, ParseError> {
4126 let library = crate::loader::LibraryProvenance::of(source);
4127 let mut interner = Interner::new();
4128 let mut lexer = Lexer::new(source, &mut interner);
4129 let tokens = lexer.tokenize();
4130
4131 let (type_registry, policy_registry) = {
4132 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4133 let result = discovery.run_full();
4134 (result.types, result.policies)
4135 };
4136 let codegen_policies = policy_registry.clone();
4137
4138 let mut world_state = WorldState::new();
4139 let expr_arena = Arena::new();
4140 let term_arena = Arena::new();
4141 let np_arena = Arena::new();
4142 let sym_arena = Arena::new();
4143 let role_arena = Arena::new();
4144 let pp_arena = Arena::new();
4145 let stmt_arena: Arena<Stmt> = Arena::new();
4146 let _compile_facts = crate::optimize::facts::scope();
4147 let imperative_expr_arena: Arena<Expr> = Arena::new();
4148 let type_expr_arena: Arena<TypeExpr> = Arena::new();
4149 let ast_ctx = AstContext::with_types(
4150 &expr_arena,
4151 &term_arena,
4152 &np_arena,
4153 &sym_arena,
4154 &role_arena,
4155 &pp_arena,
4156 &stmt_arena,
4157 &imperative_expr_arena,
4158 &type_expr_arena,
4159 );
4160
4161 let mut parser = Parser::new(
4162 tokens,
4163 &mut world_state,
4164 &mut interner,
4165 ast_ctx,
4166 type_registry,
4167 );
4168 let stmts = parser.parse_program()?;
4169 let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
4170 let opt_config = {
4171 let mut c =
4172 crate::optimization::OptimizationConfig::from_env().merged(&parser.program_opt_flags());
4173 c.normalize();
4174 c
4175 };
4176 let codegen_registry = parser.into_type_registry();
4177 refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
4178 let resolved = crate::resolve_program::resolve_program(
4179 &stmts,
4180 crate::ast_map::Arenas {
4181 exprs: &imperative_expr_arena,
4182 stmts: &stmt_arena,
4183 types: &type_expr_arena,
4184 },
4185 &mut interner,
4186 opt_config.is_on(crate::optimization::Opt::Comptime),
4187 library.functions(),
4188 );
4189 let stmts: Vec<Stmt> = match resolved {
4190 Some(rw) => rw.to_vec(),
4191 None => stmts,
4192 };
4193 let stmts = crate::optimize::optimize_program(
4196 stmts,
4197 &imperative_expr_arena,
4198 &stmt_arena,
4199 &mut interner,
4200 &opt_config,
4201 );
4202
4203 let target_sig = stmts.iter().find_map(|s| match s {
4205 Stmt::FunctionDef {
4206 name,
4207 params,
4208 return_type,
4209 ..
4210 } if interner.resolve(*name) == target => {
4211 let ps: Vec<(crate::intern::Symbol, &TypeExpr)> =
4212 params.iter().map(|(s, t)| (*s, *t)).collect();
4213 Some((*name, ps, *return_type))
4214 }
4215 _ => None,
4216 });
4217 let Some((target_sym, params, return_type)) = target_sig else {
4218 return Ok(None);
4219 };
4220 if !crate::optimize::effects::EffectEnv::from_stmts(&stmts, &interner)
4224 .function_is_replayable(target)
4225 {
4226 return Ok(None);
4227 }
4228 let Some(shim) =
4230 crate::codegen::codegen_native_tier_export(target_sym, ¶ms, return_type, &interner)
4231 else {
4232 return Ok(None);
4233 };
4234
4235 let slice = crate::codegen::function_slice(&stmts, target_sym, &interner);
4236 let type_env = crate::analysis::check_program_located(&slice, &interner, &codegen_registry)
4237 .map_err(|e| ParseError {
4238 kind: e.to_parse_error_kind(&interner, &slice),
4239 span: crate::token::Span::default(),
4240 })?;
4241 let module = crate::codegen::codegen_program(
4242 &slice,
4243 &codegen_registry,
4244 &codegen_policies,
4245 &interner,
4246 &type_env,
4247 &opt_config,
4248 );
4249 let symbol = format!(
4250 "logos_native_{}",
4251 crate::analysis::types::RustNames::new(&interner).raw(target_sym)
4252 );
4253 Ok(Some(AotModule {
4254 rust: format!("{module}\n{shim}"),
4255 symbol,
4256 arity: params.len(),
4257 }))
4258}
4259
4260#[derive(Debug, Clone)]
4263pub struct AotModule {
4264 pub rust: String,
4265 pub symbol: String,
4266 pub arity: usize,
4267}
4268
4269#[cfg(not(target_arch = "wasm32"))]
4277pub fn build_native_wasm(
4278 rust_source: &str,
4279 crate_name: &str,
4280 work_dir: &std::path::Path,
4281) -> Result<std::path::PathBuf, String> {
4282 use std::process::Command;
4283 let proj = work_dir.join(crate_name);
4284 let _ = fs::remove_dir_all(&proj);
4285 fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
4286 fs::write(proj.join("src").join("lib.rs"), rust_source).map_err(|e| e.to_string())?;
4287
4288 let cargo_toml = format!(
4289 "[package]\nname = \"{crate_name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n\
4290 [lib]\ncrate-type = [\"cdylib\"]\n\n\
4291 [dependencies]\n\
4292 logicaffeine-data = {{ path = \"./crates/logicaffeine_data\" }}\n\
4293 logicaffeine-system = {{ path = \"./crates/logicaffeine_system\" }}\n\n\
4294 [profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\nstrip = true\n"
4295 );
4296 fs::write(proj.join("Cargo.toml"), &cargo_toml).map_err(|e| e.to_string())?;
4297
4298 copy_runtime_crates(&proj).map_err(|e| e.to_string())?;
4299
4300 let out = Command::new("cargo")
4303 .args([
4304 "build",
4305 "--release",
4306 "--lib",
4307 "--target",
4308 "wasm32-unknown-unknown",
4309 ])
4310 .arg("--target-dir")
4311 .arg(proj.join("target"))
4312 .current_dir(&proj)
4313 .output()
4314 .map_err(|e| format!("failed to run cargo: {e}"))?;
4315 if !out.status.success() {
4316 return Err(format!(
4317 "wasm bundle build failed:\n{}",
4318 String::from_utf8_lossy(&out.stderr)
4319 ));
4320 }
4321
4322 let wasm = proj
4323 .join("target")
4324 .join("wasm32-unknown-unknown")
4325 .join("release")
4326 .join(format!("{crate_name}.wasm"));
4327 if !wasm.exists() {
4328 return Err(format!("wasm module not found at {}", wasm.display()));
4329 }
4330 Ok(wasm)
4331}
4332
4333#[cfg(not(target_arch = "wasm32"))]
4341pub fn build_native_cdylib(
4342 rust_source: &str,
4343 crate_name: &str,
4344 work_dir: &std::path::Path,
4345) -> Result<std::path::PathBuf, String> {
4346 use std::process::Command;
4347 let proj = work_dir.join(crate_name);
4348 let _ = fs::remove_dir_all(&proj);
4349 fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
4350 fs::write(proj.join("src").join("lib.rs"), rust_source).map_err(|e| e.to_string())?;
4351
4352 let cargo_toml = format!(
4353 "[package]\nname = \"{crate_name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n\
4354 [lib]\ncrate-type = [\"cdylib\"]\n\n\
4355 [dependencies]\n\
4356 logicaffeine-data = {{ path = \"./crates/logicaffeine_data\" }}\n\
4357 logicaffeine-system = {{ path = \"./crates/logicaffeine_system\", features = [\"full\"] }}\n\
4358 tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}\n\n\
4359 [profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\nstrip = true\n"
4360 );
4361 fs::write(proj.join("Cargo.toml"), &cargo_toml).map_err(|e| e.to_string())?;
4362
4363 let cargo_cfg = proj.join(".cargo");
4364 fs::create_dir_all(&cargo_cfg).map_err(|e| e.to_string())?;
4365 fs::write(
4366 cargo_cfg.join("config.toml"),
4367 "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n",
4368 )
4369 .map_err(|e| e.to_string())?;
4370
4371 copy_runtime_crates(&proj).map_err(|e| e.to_string())?;
4372
4373 let out = Command::new("cargo")
4377 .args(["build", "--release", "--lib"])
4378 .arg("--target-dir")
4379 .arg(proj.join("target"))
4380 .current_dir(&proj)
4381 .output()
4382 .map_err(|e| format!("failed to run cargo: {e}"))?;
4383 if !out.status.success() {
4384 return Err(format!(
4385 "AOT cdylib build failed:\n{}",
4386 String::from_utf8_lossy(&out.stderr)
4387 ));
4388 }
4389
4390 let so = proj.join("target").join("release").join(format!(
4391 "{}{}{}",
4392 std::env::consts::DLL_PREFIX,
4393 crate_name,
4394 std::env::consts::DLL_SUFFIX
4395 ));
4396 if !so.exists() {
4397 return Err(format!("AOT cdylib not found at {}", so.display()));
4398 }
4399 Ok(so)
4400}
4401
4402#[cfg(not(target_arch = "wasm32"))]
4409pub fn aot_cache_key(rust_source: &str) -> String {
4410 let toolchain = std::process::Command::new("rustc")
4411 .arg("--version")
4412 .output()
4413 .ok()
4414 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
4415 .unwrap_or_default();
4416 let mut h: u64 = 0xcbf29ce4_84222325;
4417 for b in toolchain.bytes().chain(rust_source.bytes()) {
4418 h ^= b as u64;
4419 h = h.wrapping_mul(0x0000_0100_0000_01b3);
4420 }
4421 format!("{h:016x}")
4422}
4423
4424#[cfg(not(target_arch = "wasm32"))]
4429pub fn build_native_cdylib_cached(
4430 rust_source: &str,
4431 fn_name: &str,
4432 cache_dir: &std::path::Path,
4433) -> Result<std::path::PathBuf, String> {
4434 let key = aot_cache_key(rust_source);
4435 let crate_name = format!("aot_{fn_name}_{key}");
4436 let so = cache_dir
4437 .join(&crate_name)
4438 .join("target")
4439 .join("release")
4440 .join(format!(
4441 "{}{}{}",
4442 std::env::consts::DLL_PREFIX,
4443 crate_name,
4444 std::env::consts::DLL_SUFFIX
4445 ));
4446 if so.exists() {
4447 return Ok(so); }
4449 fs::create_dir_all(cache_dir).map_err(|e| e.to_string())?;
4450 build_native_cdylib(rust_source, &crate_name, cache_dir)
4451}
4452
4453#[cfg(not(target_arch = "wasm32"))]
4460pub fn aot_build_function(
4461 source: &str,
4462 fn_name: &str,
4463 cache_dir: &std::path::Path,
4464) -> Option<Box<dyn crate::vm::NativeFn>> {
4465 let module = compile_function_to_native_rust(source, fn_name)
4466 .ok()
4467 .flatten()?;
4468 let so = build_native_cdylib_cached(&module.rust, fn_name, cache_dir).ok()?;
4469 let (nf, _calls) = crate::vm::aot_tier::load_aot_native(&so, &module.symbol, module.arity)?;
4470 Some(nf)
4471}
4472
4473pub fn native_export_function_names(source: &str) -> Vec<String> {
4477 crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
4478 Ok((stmts, _types, _policies)) => stmts
4479 .iter()
4480 .filter_map(|s| match s {
4481 Stmt::FunctionDef {
4482 name,
4483 is_exported: true,
4484 export_target: Some(t),
4485 ..
4486 } if interner.resolve(*t).eq_ignore_ascii_case("native") => {
4487 Some(interner.resolve(*name).to_string())
4488 }
4489 _ => None,
4490 })
4491 .collect(),
4492 Err(_) => Vec::new(),
4493 })
4494}
4495
4496#[cfg(not(target_arch = "wasm32"))]
4503pub fn aot_load_bundle(
4504 source: &str,
4505 cache_dir: &std::path::Path,
4506) -> Vec<(String, Box<dyn crate::vm::NativeFn>)> {
4507 native_export_function_names(source)
4508 .into_iter()
4509 .filter_map(|name| aot_build_function(source, &name, cache_dir).map(|nf| (name, nf)))
4510 .collect()
4511}
4512
4513#[cfg(not(target_arch = "wasm32"))]
4519pub fn build_native_bundle(
4520 source: &str,
4521 bundle_dir: &std::path::Path,
4522) -> Result<Vec<(String, std::path::PathBuf)>, ParseError> {
4523 let mut manifest = Vec::new();
4524 for name in native_export_function_names(source) {
4525 let Some(module) = compile_function_to_native_rust(source, &name)? else {
4526 continue; };
4528 if let Ok(so) = build_native_cdylib_cached(&module.rust, &name, bundle_dir) {
4529 manifest.push((name, so));
4530 }
4531 }
4532 Ok(manifest)
4533}
4534
4535fn extract_dependencies(
4541 stmts: &[Stmt],
4542 interner: &Interner,
4543) -> Result<Vec<CrateDependency>, ParseError> {
4544 use std::collections::HashMap;
4545
4546 let mut seen: HashMap<String, String> = HashMap::new(); let mut deps: Vec<CrateDependency> = Vec::new();
4548
4549 for stmt in stmts {
4550 if let Stmt::Require {
4551 crate_name,
4552 version,
4553 features,
4554 span,
4555 } = stmt
4556 {
4557 let name = interner.resolve(*crate_name).to_string();
4558 let ver = interner.resolve(*version).to_string();
4559
4560 if let Some(existing_ver) = seen.get(&name) {
4561 if *existing_ver != ver {
4562 return Err(ParseError {
4563 kind: crate::error::ParseErrorKind::Custom(format!(
4564 "Conflicting versions for crate \"{}\": \"{}\" and \"{}\".",
4565 name, existing_ver, ver
4566 )),
4567 span: *span,
4568 });
4569 }
4570 } else {
4572 seen.insert(name.clone(), ver.clone());
4573 deps.push(CrateDependency {
4574 name,
4575 version: ver,
4576 features: features
4577 .iter()
4578 .map(|f| interner.resolve(*f).to_string())
4579 .collect(),
4580 });
4581 }
4582 }
4583 }
4584
4585 Ok(deps)
4586}
4587
4588#[derive(Clone, Copy, PartialEq, Eq)]
4590enum AsWritten {
4591 Escapes,
4593 EscapesAndOwnership,
4595}
4596
4597fn check_as_written(
4605 stmts: &[Stmt],
4606 interner: &Interner,
4607 checks: AsWritten,
4608) -> Result<(), ParseError> {
4609 fn refusal(message: String, span: crate::token::Span) -> ParseError {
4610 ParseError {
4611 kind: crate::error::ParseErrorKind::Custom(message),
4612 span,
4613 }
4614 }
4615 EscapeChecker::new(interner)
4616 .check_program(stmts)
4617 .map_err(|e| refusal(e.to_string(), e.span))?;
4618 if checks == AsWritten::EscapesAndOwnership {
4619 OwnershipChecker::new(interner)
4620 .check_program(stmts)
4621 .map_err(|e| refusal(e.to_string(), e.span))?;
4622 }
4623 Ok(())
4624}
4625
4626pub fn compile_to_rust_checked(source: &str) -> Result<String, ParseError> {
4664 let (imperative_src, _) = crate::ui_bridge::partition_mixed(source);
4667 let source = imperative_src.as_str();
4668 let library = crate::loader::LibraryProvenance::of(source);
4669 let mut interner = Interner::new();
4670 let mut lexer = Lexer::new(source, &mut interner);
4671 let tokens = lexer.tokenize();
4672
4673 let (type_registry, policy_registry) = {
4675 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4676 let result = discovery.run_full();
4677 (result.types, result.policies)
4678 };
4679 let codegen_policies = policy_registry.clone();
4680
4681 let mut world_state = WorldState::new();
4682 let expr_arena = Arena::new();
4683 let term_arena = Arena::new();
4684 let np_arena = Arena::new();
4685 let sym_arena = Arena::new();
4686 let role_arena = Arena::new();
4687 let pp_arena = Arena::new();
4688 let stmt_arena: Arena<Stmt> = Arena::new();
4689 let _compile_facts = crate::optimize::facts::scope();
4690 let imperative_expr_arena: Arena<Expr> = Arena::new();
4691 let type_expr_arena: Arena<TypeExpr> = Arena::new();
4692
4693 let ast_ctx = AstContext::with_types(
4694 &expr_arena,
4695 &term_arena,
4696 &np_arena,
4697 &sym_arena,
4698 &role_arena,
4699 &pp_arena,
4700 &stmt_arena,
4701 &imperative_expr_arena,
4702 &type_expr_arena,
4703 );
4704
4705 let mut parser = Parser::new(
4707 tokens,
4708 &mut world_state,
4709 &mut interner,
4710 ast_ctx,
4711 type_registry,
4712 );
4713 let stmts = parser.parse_program()?;
4714 let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
4715
4716 let (opt_config, gate) = crate::optimize::install_decorators(
4722 crate::optimization::OptimizationConfig::from_env(),
4723 &parser.program_opt_flags(),
4724 parser.required_optimizations(),
4725 );
4726 let codegen_registry = parser.into_type_registry();
4727 refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
4728
4729 check_as_written(&stmts, &interner, AsWritten::EscapesAndOwnership)?;
4732
4733 let resolved = crate::resolve_program::resolve_program(
4734 &stmts,
4735 crate::ast_map::Arenas {
4736 exprs: &imperative_expr_arena,
4737 stmts: &stmt_arena,
4738 types: &type_expr_arena,
4739 },
4740 &mut interner,
4741 opt_config.is_on(crate::optimization::Opt::Comptime),
4742 library.functions(),
4743 );
4744 let stmts: Vec<Stmt> = match resolved {
4745 Some(rw) => rw.to_vec(),
4746 None => stmts,
4747 };
4748 let (stmts, codegen_registry) = lift_program_bindings(
4749 stmts,
4750 codegen_registry,
4751 &mut interner,
4752 crate::ast_map::Arenas {
4753 exprs: &imperative_expr_arena,
4754 stmts: &stmt_arena,
4755 types: &type_expr_arena,
4756 },
4757 )?;
4758 let stmts = crate::optimize::optimize_program(
4759 stmts,
4760 &imperative_expr_arena,
4761 &stmt_arena,
4762 &mut interner,
4763 &opt_config,
4764 );
4765
4766 let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
4767 .map_err(|e| ParseError {
4768 kind: e.to_parse_error_kind(&interner, &stmts),
4769 span: crate::token::Span::default(),
4770 })?;
4771 let rust_code = codegen_program(
4772 &stmts,
4773 &codegen_registry,
4774 &codegen_policies,
4775 &interner,
4776 &type_env,
4777 &opt_config,
4778 );
4779
4780 gate.verify().map_err(|m| ParseError {
4781 kind: crate::error::ParseErrorKind::Custom(m),
4782 span: crate::token::Span::default(),
4783 })?;
4784
4785 Ok(rust_code)
4786}
4787
4788#[cfg(feature = "verification")]
4835pub fn compile_to_rust_verified(source: &str) -> Result<String, ParseError> {
4836 use crate::verification::VerificationPass;
4837 let library = crate::loader::LibraryProvenance::of(source);
4838
4839 let mut interner = Interner::new();
4840 let mut lexer = Lexer::new(source, &mut interner);
4841 let tokens = lexer.tokenize();
4842
4843 let (type_registry, policy_registry) = {
4845 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4846 let result = discovery.run_full();
4847 (result.types, result.policies)
4848 };
4849 let codegen_policies = policy_registry.clone();
4850
4851 let mut world_state = WorldState::new();
4852 let expr_arena = Arena::new();
4853 let term_arena = Arena::new();
4854 let np_arena = Arena::new();
4855 let sym_arena = Arena::new();
4856 let role_arena = Arena::new();
4857 let pp_arena = Arena::new();
4858 let stmt_arena: Arena<Stmt> = Arena::new();
4859 let _compile_facts = crate::optimize::facts::scope();
4860 let imperative_expr_arena: Arena<Expr> = Arena::new();
4861 let type_expr_arena: Arena<TypeExpr> = Arena::new();
4862
4863 let ast_ctx = AstContext::with_types(
4864 &expr_arena,
4865 &term_arena,
4866 &np_arena,
4867 &sym_arena,
4868 &role_arena,
4869 &pp_arena,
4870 &stmt_arena,
4871 &imperative_expr_arena,
4872 &type_expr_arena,
4873 );
4874
4875 let mut parser = Parser::new(
4877 tokens,
4878 &mut world_state,
4879 &mut interner,
4880 ast_ctx,
4881 type_registry,
4882 );
4883 let stmts = parser.parse_program()?;
4884 let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
4885
4886 let (opt_config, gate) = crate::optimize::install_decorators(
4892 crate::optimization::OptimizationConfig::from_env(),
4893 &parser.program_opt_flags(),
4894 parser.required_optimizations(),
4895 );
4896 let codegen_registry = parser.into_type_registry();
4897 refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
4898
4899 check_as_written(&stmts, &interner, AsWritten::Escapes)?;
4901
4902 let resolved = crate::resolve_program::resolve_program(
4903 &stmts,
4904 crate::ast_map::Arenas {
4905 exprs: &imperative_expr_arena,
4906 stmts: &stmt_arena,
4907 types: &type_expr_arena,
4908 },
4909 &mut interner,
4910 opt_config.is_on(crate::optimization::Opt::Comptime),
4911 library.functions(),
4912 );
4913 let stmts: Vec<Stmt> = match resolved {
4914 Some(rw) => rw.to_vec(),
4915 None => stmts,
4916 };
4917
4918 let mut verifier = VerificationPass::new(&interner);
4920 verifier.verify_program(&stmts).map_err(|e| ParseError {
4921 kind: crate::error::ParseErrorKind::Custom(format!("Verification Failed:\n\n{}", e)),
4922 span: crate::token::Span::default(),
4923 })?;
4924
4925 let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
4926 .map_err(|e| ParseError {
4927 kind: e.to_parse_error_kind(&interner, &stmts),
4928 span: crate::token::Span::default(),
4929 })?;
4930 let rust_code = codegen_program(
4931 &stmts,
4932 &codegen_registry,
4933 &codegen_policies,
4934 &interner,
4935 &type_env,
4936 &opt_config,
4937 );
4938
4939 gate.verify().map_err(|m| ParseError {
4940 kind: crate::error::ParseErrorKind::Custom(m),
4941 span: crate::token::Span::default(),
4942 })?;
4943
4944 Ok(rust_code)
4945}
4946
4947pub struct CheckArtifacts {
4982 pub rust_code: String,
4983 pub dependencies: Vec<CrateDependency>,
4984 pub source_map: crate::sourcemap::SourceMap,
4985 pub interner: Interner,
4986}
4987
4988pub fn prelude_user_offset(
4993 segments: &[crate::loader::PreludeSegment],
4994 pos: usize,
4995) -> Option<usize> {
4996 let mut at_end = None;
4997 for seg in segments {
4998 if pos >= seg.out_start && pos < seg.out_start + seg.len {
4999 return seg.user_start.map(|us| us + (pos - seg.out_start));
5000 }
5001 if pos == seg.out_start + seg.len {
5002 at_end = seg.user_start.map(|us| us + seg.len);
5003 }
5004 }
5005 at_end
5006}
5007
5008pub fn prelude_user_span(
5012 segments: &[crate::loader::PreludeSegment],
5013 span: crate::token::Span,
5014) -> Option<crate::token::Span> {
5015 match (
5016 prelude_user_offset(segments, span.start),
5017 prelude_user_offset(segments, span.end),
5018 ) {
5019 (Some(start), Some(end)) if start <= end => Some(crate::token::Span::new(start, end)),
5020 _ => None,
5021 }
5022}
5023
5024pub fn rustc_check_artifacts(source: &str) -> Result<CheckArtifacts, ParseError> {
5034 let user_source = source;
5035
5036 let (prelude_src, prelude_segments) = crate::loader::apply_prelude_mapped(user_source);
5041 let (pruned_src, kept_ranges) =
5047 crate::loader::prune_unreachable_prelude_mapped_from(user_source, prelude_src.as_ref());
5048 let to_pruned = |x: usize| -> usize {
5052 let mut kept = 0usize;
5053 for &(s, e) in &kept_ranges {
5054 if e <= x {
5055 kept += e - s;
5056 } else if s < x {
5057 kept += x - s;
5058 break;
5059 } else {
5060 break;
5061 }
5062 }
5063 kept
5064 };
5065 let prelude_segments: Vec<crate::loader::PreludeSegment> = prelude_segments
5070 .into_iter()
5071 .filter(|seg| seg.user_start.is_some())
5072 .map(|seg| crate::loader::PreludeSegment {
5073 out_start: to_pruned(seg.out_start),
5074 len: seg.len,
5075 user_start: seg.user_start,
5076 })
5077 .collect();
5078 let expanded: &str = pruned_src.as_str();
5079 let library = crate::loader::LibraryProvenance::of(expanded);
5080 for seg in &prelude_segments {
5081 if let Some(user_start) = seg.user_start {
5082 debug_assert_eq!(
5083 &expanded[seg.out_start..seg.out_start + seg.len],
5084 &user_source[user_start..user_start + seg.len],
5085 "prelude prune must keep user text byte-intact; span translation depends on it"
5086 );
5087 }
5088 }
5089
5090 let mut interner = Interner::new();
5091 let mut lexer = Lexer::new(expanded, &mut interner);
5092 let tokens = lexer.tokenize();
5093
5094 let (type_registry, policy_registry) = {
5095 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
5096 let result = discovery.run_full();
5097 (result.types, result.policies)
5098 };
5099 let codegen_policies = policy_registry.clone();
5100
5101 let mut world_state = WorldState::new();
5102 let expr_arena = Arena::new();
5103 let term_arena = Arena::new();
5104 let np_arena = Arena::new();
5105 let sym_arena = Arena::new();
5106 let role_arena = Arena::new();
5107 let pp_arena = Arena::new();
5108 let stmt_arena: Arena<Stmt> = Arena::new();
5109 let _compile_facts = crate::optimize::facts::scope();
5110 let imperative_expr_arena: Arena<Expr> = Arena::new();
5111 let type_expr_arena: Arena<TypeExpr> = Arena::new();
5112
5113 let ast_ctx = AstContext::with_types(
5114 &expr_arena,
5115 &term_arena,
5116 &np_arena,
5117 &sym_arena,
5118 &role_arena,
5119 &pp_arena,
5120 &stmt_arena,
5121 &imperative_expr_arena,
5122 &type_expr_arena,
5123 );
5124
5125 let mut parser = Parser::new(
5126 tokens,
5127 &mut world_state,
5128 &mut interner,
5129 ast_ctx,
5130 type_registry,
5131 );
5132 let stmts = parser.parse_program()?;
5133
5134 let stmt_spans: Vec<crate::token::Span> = parser
5137 .stmt_spans()
5138 .iter()
5139 .map(|span| prelude_user_span(&prelude_segments, *span).unwrap_or_default())
5140 .collect();
5141 let codegen_registry = parser.into_type_registry();
5142
5143 let resolved = crate::resolve_program::resolve_program(
5146 &stmts,
5147 crate::ast_map::Arenas {
5148 exprs: &imperative_expr_arena,
5149 stmts: &stmt_arena,
5150 types: &type_expr_arena,
5151 },
5152 &mut interner,
5153 false,
5154 library.functions(),
5155 );
5156 let stmts: Vec<Stmt> = match resolved {
5157 Some(rw) => rw.to_vec(),
5158 None => stmts,
5159 };
5160 let lifted_from = stmts.len();
5161 let (stmts, codegen_registry) = lift_program_bindings(
5162 stmts,
5163 codegen_registry,
5164 &mut interner,
5165 crate::ast_map::Arenas {
5166 exprs: &imperative_expr_arena,
5167 stmts: &stmt_arena,
5168 types: &type_expr_arena,
5169 },
5170 )?;
5171 let stmt_spans: Vec<crate::token::Span> =
5173 std::iter::repeat_n(crate::token::Span::default(), stmts.len() - lifted_from)
5174 .chain(stmt_spans)
5175 .collect();
5176
5177 let (type_env, _findings) =
5179 crate::analysis::check_program_collect(&stmts, &interner, &codegen_registry);
5180
5181 let dependencies = extract_dependencies(&stmts, &interner)?;
5182
5183 let (rust_code, source_map) = crate::codegen::codegen_program_mapped(
5184 &stmts,
5185 &codegen_registry,
5186 &codegen_policies,
5187 &interner,
5188 &type_env,
5189 &crate::optimization::OptimizationConfig::all_off(),
5190 &stmt_spans,
5191 user_source,
5192 );
5193
5194 Ok(CheckArtifacts {
5195 rust_code,
5196 dependencies,
5197 source_map,
5198 interner,
5199 })
5200}
5201
5202pub fn rustc_check(source: &str, cache_dir: &Path) -> Result<Vec<LogosError>, CompileError> {
5213 let artifacts = rustc_check_artifacts(source).map_err(CompileError::Parse)?;
5214 write_cargo_project(&artifacts.rust_code, &artifacts.dependencies, cache_dir)?;
5215
5216 let check_output = Command::new("cargo")
5220 .arg("check")
5221 .arg("--message-format=json")
5222 .current_dir(cache_dir)
5223 .env("CARGO_TARGET_DIR", cache_dir.join("target"))
5224 .output()
5225 .map_err(|e| CompileError::Io(e.to_string()))?;
5226
5227 let stdout = String::from_utf8_lossy(&check_output.stdout);
5228 let diagnostics = parse_rustc_json(&stdout);
5229 let findings = crate::diagnostic::translate_diagnostics_all(
5230 &diagnostics,
5231 &artifacts.source_map,
5232 &artifacts.interner,
5233 );
5234
5235 if !check_output.status.success() && findings.is_empty() {
5236 let stderr = String::from_utf8_lossy(&check_output.stderr);
5237 return Err(CompileError::Build(stderr.to_string()));
5238 }
5239
5240 Ok(findings)
5241}
5242
5243pub fn remap_project_errors(
5251 source: &str,
5252 cache_dir: &Path,
5253 file_map: Option<&crate::analysis::SourceMap>,
5254) -> Result<Vec<crate::diagnostic::RemappedError>, CompileError> {
5255 let artifacts = rustc_check_artifacts(source).map_err(CompileError::Parse)?;
5256 write_cargo_project(&artifacts.rust_code, &artifacts.dependencies, cache_dir)?;
5257
5258 let check_output = Command::new("cargo")
5262 .arg("check")
5263 .arg("--message-format=json")
5264 .current_dir(cache_dir)
5265 .env("CARGO_TARGET_DIR", cache_dir.join("target"))
5266 .output()
5267 .map_err(|e| CompileError::Io(e.to_string()))?;
5268
5269 let stdout = String::from_utf8_lossy(&check_output.stdout);
5270 let diagnostics = parse_rustc_json(&stdout);
5271
5272 let file_of = |offset: usize| -> Option<String> {
5275 file_map
5276 .and_then(|m| m.file_for(offset))
5277 .and_then(|p| p.file_name())
5278 .and_then(|s| s.to_str())
5279 .map(String::from)
5280 };
5281 Ok(crate::diagnostic::remap_rustc_diagnostics(
5282 &diagnostics,
5283 &artifacts.source_map,
5284 &file_of,
5285 ))
5286}
5287
5288pub fn compile_to_dir(source: &str, output_dir: &Path) -> Result<(), CompileError> {
5289 let output = compile_program_full(source).map_err(CompileError::Parse)?;
5290 write_cargo_project(&output.rust_code, &output.dependencies, output_dir)
5291}
5292
5293pub enum RuntimeCrateSource {
5301 Workspace,
5303 Registry { version: String },
5305}
5306
5307impl RuntimeCrateSource {
5308 pub fn detect() -> Self {
5311 match find_workspace_root() {
5312 Ok(_) => RuntimeCrateSource::Workspace,
5313 Err(_) => RuntimeCrateSource::Registry {
5314 version: env!("CARGO_PKG_VERSION").to_string(),
5315 },
5316 }
5317 }
5318
5319 pub fn is_workspace(&self) -> bool {
5322 matches!(self, RuntimeCrateSource::Workspace)
5323 }
5324
5325 pub fn data_dep(&self) -> String {
5327 match self {
5328 RuntimeCrateSource::Workspace => {
5329 "logicaffeine-data = { path = \"./crates/logicaffeine_data\" }".to_string()
5330 }
5331 RuntimeCrateSource::Registry { version } => {
5334 format!("logicaffeine-data = \"={version}\"")
5335 }
5336 }
5337 }
5338
5339 pub fn system_dep(&self, features: &[&str]) -> String {
5341 let feats = features
5342 .iter()
5343 .map(|f| format!("\"{f}\""))
5344 .collect::<Vec<_>>()
5345 .join(", ");
5346 match self {
5347 RuntimeCrateSource::Workspace => format!(
5348 "logicaffeine-system = {{ path = \"./crates/logicaffeine_system\", features = [{feats}] }}"
5349 ),
5350 RuntimeCrateSource::Registry { version } => {
5351 format!("logicaffeine-system = {{ version = \"={version}\", features = [{feats}] }}")
5352 }
5353 }
5354 }
5355
5356 pub fn linux_engine_section(&self) -> String {
5361 format!(
5362 "[target.'cfg(target_os = \"linux\")'.dependencies]\n{}\n",
5363 self.system_dep(&["full", "io-uring"])
5364 )
5365 }
5366}
5367
5368fn field_type_base_name<'i>(ty: &crate::analysis::FieldType, interner: &'i Interner) -> &'i str {
5370 use crate::analysis::FieldType;
5371 match ty {
5372 FieldType::Primitive(s) | FieldType::Named(s) | FieldType::TypeParam(s) => {
5373 interner.resolve(*s)
5374 }
5375 FieldType::Generic { base, .. } => interner.resolve(*base),
5376 FieldType::Tuple(_) => "Tuple",
5377 FieldType::Record(_) => "Record",
5378 }
5379}
5380
5381#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5386pub enum Backend {
5387 C,
5389 CFromAst,
5391 RiscV,
5392 WebAssembly,
5393 SoftCore,
5394}
5395
5396impl Backend {
5397 pub const ALL: [Backend; 5] = [
5398 Backend::C,
5399 Backend::CFromAst,
5400 Backend::RiscV,
5401 Backend::WebAssembly,
5402 Backend::SoftCore,
5403 ];
5404
5405 pub const fn name(self) -> &'static str {
5407 match self {
5408 Backend::C | Backend::CFromAst => "C",
5409 Backend::RiscV => "RISC-V",
5410 Backend::WebAssembly => "WebAssembly",
5411 Backend::SoftCore => "soft-core",
5412 }
5413 }
5414}
5415
5416pub fn refuse_unlinkable(
5423 program: &crate::vm::CompiledProgram,
5424 interner: &Interner,
5425 backend: Backend,
5426) -> Result<(), String> {
5427 refuse_unlinkable_with(
5428 program,
5429 interner,
5430 backend,
5431 &crate::vm::reach::HostEntries::default(),
5432 )
5433}
5434
5435pub fn refuse_unlinkable_with(
5438 program: &crate::vm::CompiledProgram,
5439 interner: &Interner,
5440 backend: Backend,
5441 entries: &crate::vm::reach::HostEntries,
5442) -> Result<(), String> {
5443 crate::semantics::native_kernels::refuse_kernel_calls_with(
5444 program,
5445 interner,
5446 backend.name(),
5447 entries,
5448 )?;
5449 for (_, op) in crate::vm::reach::running_ops_with(program, interner, entries) {
5450 if let crate::vm::Op::NewCrdt { kind, .. } = *op {
5451 if let Some(k) = crate::semantics::crdt::CrdtKind::from_new_crdt_code(kind) {
5452 if !k.lowered_by(backend) {
5453 return Err(k.refusal(backend.name()));
5454 }
5455 }
5456 }
5457 }
5458 Ok(())
5459}
5460
5461pub fn implied_crate_deps(rust_code: &str, requires: &[CrateDependency]) -> Vec<&'static str> {
5466 const IMPLIED: &[(&str, &str, &str)] = &[
5467 ("rayon", "rayon::", "rayon = \"1\""),
5469 ("memchr", "memchr::", "memchr = \"2\""),
5471 (
5473 "serde",
5474 "serde::",
5475 "serde = { version = \"1\", features = [\"derive\"] }",
5476 ),
5477 ];
5478 IMPLIED
5479 .iter()
5480 .filter(|(name, marker, _)| {
5481 rust_code.contains(marker) && !requires.iter().any(|d| d.name == *name)
5482 })
5483 .map(|(_, _, line)| *line)
5484 .collect()
5485}
5486
5487fn render_cargo_manifest(
5492 rust_code: &str,
5493 dependencies: &[CrateDependency],
5494 source: &RuntimeCrateSource,
5495) -> String {
5496 let data_dep = source.data_dep();
5497 let system_features: &[&str] = if rust_code.contains("logicaffeine_system::http::") {
5502 &["full", "http"]
5503 } else {
5504 &["full"]
5505 };
5506 let system_dep = source.system_dep(system_features);
5507
5508 let mut cargo_toml = format!(
5509 "[package]\n\
5510 name = \"logos_output\"\n\
5511 version = \"0.1.0\"\n\
5512 edition = \"2021\"\n\
5513 \n\
5514 [dependencies]\n\
5515 {data_dep}\n\
5516 {system_dep}\n\
5517 tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}\n"
5518 );
5519
5520 for dep in dependencies {
5523 if dep.features.is_empty() {
5524 let _ = writeln!(cargo_toml, "{} = \"{}\"", dep.name, dep.version);
5525 } else {
5526 let feats = dep
5527 .features
5528 .iter()
5529 .map(|f| format!("\"{}\"", f))
5530 .collect::<Vec<_>>()
5531 .join(", ");
5532 let _ = writeln!(
5533 cargo_toml,
5534 "{} = {{ version = \"{}\", features = [{}] }}",
5535 dep.name, dep.version, feats
5536 );
5537 }
5538 }
5539
5540 for line in implied_crate_deps(rust_code, dependencies) {
5541 let _ = writeln!(cargo_toml, "{line}");
5542 }
5543
5544 let _ = write!(cargo_toml, "\n{}", source.linux_engine_section());
5545
5546 let panic_strategy = crate::codegen::release_panic_strategy(rust_code);
5547 let _ = write!(cargo_toml, "\n[profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\npanic = \"{panic_strategy}\"\nstrip = true\n");
5548 cargo_toml
5549}
5550
5551pub fn write_cargo_project(
5556 rust_code: &str,
5557 dependencies: &[CrateDependency],
5558 output_dir: &Path,
5559) -> Result<(), CompileError> {
5560 let source = RuntimeCrateSource::detect();
5561
5562 let src_dir = output_dir.join("src");
5564 fs::create_dir_all(&src_dir).map_err(|e| CompileError::Io(e.to_string()))?;
5565
5566 let main_path = src_dir.join("main.rs");
5568 let mut file = fs::File::create(&main_path).map_err(|e| CompileError::Io(e.to_string()))?;
5569 file.write_all(rust_code.as_bytes())
5570 .map_err(|e| CompileError::Io(e.to_string()))?;
5571
5572 let cargo_toml = render_cargo_manifest(rust_code, dependencies, &source);
5574 let cargo_path = output_dir.join("Cargo.toml");
5575 let mut file = fs::File::create(&cargo_path).map_err(|e| CompileError::Io(e.to_string()))?;
5576 file.write_all(cargo_toml.as_bytes())
5577 .map_err(|e| CompileError::Io(e.to_string()))?;
5578
5579 let cargo_config_dir = output_dir.join(".cargo");
5582 fs::create_dir_all(&cargo_config_dir).map_err(|e| CompileError::Io(e.to_string()))?;
5583 let config_content = "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n";
5584 let config_path = cargo_config_dir.join("config.toml");
5585 fs::write(&config_path, config_content).map_err(|e| CompileError::Io(e.to_string()))?;
5586
5587 if source.is_workspace() {
5590 copy_runtime_crates(output_dir)?;
5591 }
5592
5593 Ok(())
5594}
5595
5596pub fn copy_runtime_crates(output_dir: &Path) -> Result<(), CompileError> {
5599 let crates_dir = output_dir.join("crates");
5600 fs::create_dir_all(&crates_dir).map_err(|e| CompileError::Io(e.to_string()))?;
5601
5602 let workspace_root = find_workspace_root()?;
5604 let workspace = WorkspacePackage::read(&workspace_root)?;
5605
5606 let data_src = workspace_root.join(CRATES_DATA_PATH);
5608 let data_dest = crates_dir.join("logicaffeine_data");
5609 copy_dir_recursive(&data_src, &data_dest)?;
5610 deworkspace_cargo_toml(&data_dest.join("Cargo.toml"), &workspace)?;
5611
5612 let system_src = workspace_root.join(CRATES_SYSTEM_PATH);
5614 let system_dest = crates_dir.join("logicaffeine_system");
5615 copy_dir_recursive(&system_src, &system_dest)?;
5616 deworkspace_cargo_toml(&system_dest.join("Cargo.toml"), &workspace)?;
5617
5618 let base_src = workspace_root.join("crates/logicaffeine_base");
5620 let base_dest = crates_dir.join("logicaffeine_base");
5621 copy_dir_recursive(&base_src, &base_dest)?;
5622 deworkspace_cargo_toml(&base_dest.join("Cargo.toml"), &workspace)?;
5623
5624 let lock_src = workspace_root.join("Cargo.lock");
5636 let lock_dest = output_dir.join("Cargo.lock");
5637 if lock_src.exists() && !lock_dest.exists() {
5638 fs::copy(&lock_src, &lock_dest).map_err(|e| CompileError::Io(e.to_string()))?;
5639 }
5640
5641 Ok(())
5642}
5643
5644struct WorkspacePackage {
5648 edition: String,
5649 rust_version: String,
5650}
5651
5652impl WorkspacePackage {
5653 fn read(workspace_root: &Path) -> Result<WorkspacePackage, CompileError> {
5654 let manifest = workspace_root.join("Cargo.toml");
5655 let text = fs::read_to_string(&manifest)
5656 .map_err(|e| CompileError::Io(format!("{}: {e}", manifest.display())))?;
5657 Self::parse(&text).ok_or_else(|| {
5658 CompileError::Io(format!(
5659 "{} declares no `edition` and `rust-version` under [workspace.package]",
5660 manifest.display()
5661 ))
5662 })
5663 }
5664
5665 fn parse(root_manifest: &str) -> Option<WorkspacePackage> {
5667 let mut in_table = false;
5668 let (mut edition, mut rust_version) = (None, None);
5669 for line in root_manifest.lines() {
5670 let t = line.trim();
5671 if t.starts_with('[') {
5672 in_table = t == "[workspace.package]";
5673 continue;
5674 }
5675 let Some((key, value)) = t.split_once('=').filter(|_| in_table) else {
5676 continue;
5677 };
5678 let Some(quoted) = value
5679 .trim()
5680 .strip_prefix('"')
5681 .and_then(|v| v.split_once('"'))
5682 .map(|(v, _)| v.to_string())
5683 else {
5684 continue;
5685 };
5686 match key.trim() {
5687 "edition" => edition = Some(quoted),
5688 "rust-version" => rust_version = Some(quoted),
5689 _ => {}
5690 }
5691 }
5692 Some(WorkspacePackage {
5693 edition: edition?,
5694 rust_version: rust_version?,
5695 })
5696 }
5697}
5698
5699fn deworkspace_cargo_toml(
5705 cargo_toml_path: &Path,
5706 workspace: &WorkspacePackage,
5707) -> Result<(), CompileError> {
5708 let content =
5709 fs::read_to_string(cargo_toml_path).map_err(|e| CompileError::Io(e.to_string()))?;
5710
5711 let mut result = String::with_capacity(content.len());
5712 for line in content.lines() {
5713 let trimmed = line.trim();
5714 if trimmed == "edition.workspace = true" {
5715 result.push_str(&format!("edition = \"{}\"", workspace.edition));
5716 } else if trimmed == "rust-version.workspace = true" {
5717 result.push_str(&format!("rust-version = \"{}\"", workspace.rust_version));
5718 } else if trimmed == "authors.workspace = true"
5719 || trimmed == "repository.workspace = true"
5720 || trimmed == "homepage.workspace = true"
5721 || trimmed == "documentation.workspace = true"
5722 || trimmed == "keywords.workspace = true"
5723 || trimmed == "categories.workspace = true"
5724 || trimmed == "license.workspace = true"
5725 {
5726 continue;
5728 } else if trimmed.contains(".workspace = true") {
5729 continue;
5731 } else if let Some(rewritten) = deworkspace_dep_line(trimmed)? {
5732 result.push_str(&rewritten);
5736 } else {
5737 result.push_str(line);
5738 }
5739 result.push('\n');
5740 }
5741
5742 fs::write(cargo_toml_path, result).map_err(|e| CompileError::Io(e.to_string()))?;
5743
5744 Ok(())
5745}
5746
5747fn deworkspace_dep_line(trimmed: &str) -> Result<Option<String>, CompileError> {
5755 let Some((name_part, rest)) = trimmed.split_once('=') else {
5756 return Ok(None);
5757 };
5758 let rest = rest.trim();
5759 if !rest.starts_with('{') || !rest.ends_with('}') || !rest.contains("workspace = true") {
5760 return Ok(None);
5761 }
5762 let name = name_part.trim();
5763 if !name
5764 .chars()
5765 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
5766 {
5767 return Ok(None);
5768 }
5769 let extra_keys: Vec<&str> = rest[1..rest.len() - 1]
5770 .split(',')
5771 .map(str::trim)
5772 .filter(|k| !k.is_empty() && *k != "workspace = true")
5773 .collect();
5774 if !name.starts_with("logicaffeine-") {
5775 return Err(CompileError::Io(format!(
5776 "staged crate inherits third-party dependency `{}` from the workspace — \
5777 declare a concrete version in the crate's Cargo.toml (the staged copy \
5778 has no workspace root to inherit from)",
5779 name
5780 )));
5781 }
5782 let dir = name.replace('-', "_");
5783 let mut entry = format!("{} = {{ path = \"../{}\"", name, dir);
5784 for key in extra_keys {
5785 entry.push_str(", ");
5786 entry.push_str(key);
5787 }
5788 entry.push_str(" }");
5789 Ok(Some(entry))
5790}
5791
5792pub(crate) fn find_workspace_root() -> Result<std::path::PathBuf, CompileError> {
5794 if let Ok(workspace) = std::env::var("LOGOS_WORKSPACE") {
5796 let path = Path::new(&workspace);
5797 if path.join("Cargo.toml").exists() && path.join("crates").exists() {
5798 return Ok(path.to_path_buf());
5799 }
5800 }
5801
5802 if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
5804 let path = Path::new(&manifest_dir);
5805 if let Some(parent) = path.parent().and_then(|p| p.parent()) {
5806 if parent.join("Cargo.toml").exists() {
5807 return Ok(parent.to_path_buf());
5808 }
5809 }
5810 }
5811
5812 if let Ok(exe) = std::env::current_exe() {
5815 if let Some(dir) = exe.parent() {
5816 let mut candidate = dir.to_path_buf();
5818 for _ in 0..5 {
5819 if candidate.join("Cargo.toml").exists() && candidate.join("crates").exists() {
5820 return Ok(candidate);
5821 }
5822 if !candidate.pop() {
5823 break;
5824 }
5825 }
5826 }
5827 }
5828
5829 let mut current = std::env::current_dir().map_err(|e| CompileError::Io(e.to_string()))?;
5831
5832 loop {
5833 if current.join("Cargo.toml").exists() && current.join("crates").exists() {
5834 return Ok(current);
5835 }
5836 if !current.pop() {
5837 return Err(CompileError::Io(
5838 "Could not find workspace root. Set LOGOS_WORKSPACE env var or run from within the workspace.".to_string()
5839 ));
5840 }
5841 }
5842}
5843
5844fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), CompileError> {
5847 fs::create_dir_all(dst).map_err(|e| CompileError::Io(e.to_string()))?;
5848
5849 for entry in fs::read_dir(src).map_err(|e| CompileError::Io(e.to_string()))? {
5850 let entry = entry.map_err(|e| CompileError::Io(e.to_string()))?;
5851 let src_path = entry.path();
5852 let file_name = entry.file_name();
5853 let dst_path = dst.join(&file_name);
5854
5855 if file_name == "target"
5857 || file_name == ".git"
5858 || file_name == "Cargo.lock"
5859 || file_name == ".DS_Store"
5860 {
5861 continue;
5862 }
5863
5864 if file_name.to_string_lossy().starts_with('.') {
5866 continue;
5867 }
5868
5869 if !src_path.exists() {
5871 continue;
5872 }
5873
5874 if src_path.is_dir() {
5875 copy_dir_recursive(&src_path, &dst_path)?;
5876 } else if file_name == "Cargo.toml" {
5877 match fs::read_to_string(&src_path) {
5880 Ok(content) => {
5881 let filtered: String = content
5882 .lines()
5883 .filter(|line| !line.trim().starts_with("[workspace]"))
5884 .collect::<Vec<_>>()
5885 .join("\n");
5886 fs::write(&dst_path, filtered).map_err(|e| CompileError::Io(e.to_string()))?;
5887 }
5888 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
5889 Err(e) => return Err(CompileError::Io(e.to_string())),
5890 }
5891 } else {
5892 match fs::copy(&src_path, &dst_path) {
5893 Ok(_) => {}
5894 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
5895 Err(e) => return Err(CompileError::Io(e.to_string())),
5896 }
5897 }
5898 }
5899
5900 Ok(())
5901}
5902
5903pub fn compile_and_run(source: &str, output_dir: &Path) -> Result<String, CompileError> {
5946 compile_to_rust_checked(source).map_err(CompileError::Parse)?;
5949
5950 compile_to_dir(source, output_dir)?;
5951
5952 let target_dir = output_dir.join("target");
5957
5958 let build_output = Command::new("cargo")
5960 .arg("build")
5961 .arg("--message-format=json")
5962 .current_dir(output_dir)
5963 .env("CARGO_TARGET_DIR", &target_dir)
5964 .output()
5965 .map_err(|e| CompileError::Io(e.to_string()))?;
5966
5967 if !build_output.status.success() {
5968 let stderr = String::from_utf8_lossy(&build_output.stderr);
5969 let stdout = String::from_utf8_lossy(&build_output.stdout);
5970
5971 let diagnostics = parse_rustc_json(&stdout);
5973
5974 if !diagnostics.is_empty() {
5975 let source_map = SourceMap::new(source.to_string());
5977 let interner = Interner::new();
5978
5979 if let Some(logos_error) = translate_diagnostics(&diagnostics, &source_map, &interner) {
5980 return Err(CompileError::Ownership(logos_error));
5981 }
5982 }
5983
5984 return Err(CompileError::Build(stderr.to_string()));
5986 }
5987
5988 let run_output = Command::new("cargo")
5990 .arg("run")
5991 .arg("--quiet")
5992 .current_dir(output_dir)
5993 .env("CARGO_TARGET_DIR", &target_dir)
5994 .output()
5995 .map_err(|e| CompileError::Io(e.to_string()))?;
5996
5997 if !run_output.status.success() {
5998 let stderr = String::from_utf8_lossy(&run_output.stderr);
5999 return Err(CompileError::Runtime(stderr.to_string()));
6000 }
6001
6002 let stdout = String::from_utf8_lossy(&run_output.stdout);
6003 Ok(stdout.to_string())
6004}
6005
6006pub fn compile_file(path: &Path) -> Result<String, CompileError> {
6009 let source = fs::read_to_string(path).map_err(|e| CompileError::Io(e.to_string()))?;
6010 compile_to_rust(&source).map_err(CompileError::Parse)
6011}
6012
6013pub fn compile_project(entry_file: &Path) -> Result<CompileOutput, CompileError> {
6031 compile_project_with_deps(entry_file, Vec::new())
6032}
6033
6034pub fn compile_project_with_deps(
6038 entry_file: &Path,
6039 dep_roots: Vec<crate::loader::DepRoot>,
6040) -> Result<CompileOutput, CompileError> {
6041 use crate::analysis::{assemble_project_with_deps, discover_with_imports};
6042 use crate::loader::Loader;
6043
6044 let root_path = entry_file.parent().unwrap_or(Path::new(".")).to_path_buf();
6045 let mut loader = Loader::with_dep_roots(root_path, dep_roots.clone());
6046 let mut interner = Interner::new();
6047
6048 let assembled = assemble_project_with_deps(entry_file, dep_roots).map_err(CompileError::Io)?;
6054
6055 let source = crate::loader::prune_unreachable_prelude_from(
6064 &assembled.source,
6065 crate::loader::apply_prelude(&assembled.source).as_ref(),
6066 );
6067
6068 let type_registry = discover_with_imports(entry_file, &source, &mut loader, &mut interner)
6070 .map_err(|e| CompileError::Io(e))?;
6071
6072 compile_to_rust_with_registry_full(
6076 &source,
6077 type_registry,
6078 &mut interner,
6079 Some(&assembled.scope),
6080 )
6081 .map_err(|pe| attribute_parse_error(pe, &assembled, &source))
6082}
6083
6084fn attribute_parse_error(
6094 pe: ParseError,
6095 assembled: &crate::analysis::AssembledProgram,
6096 final_source: &str,
6097) -> CompileError {
6098 let prelude_len = final_source.len().saturating_sub(assembled.source.len());
6099 let insert_at = if assembled.source.starts_with("##") {
6100 0
6101 } else {
6102 assembled.source.find("\n##").map(|i| i + 1).unwrap_or(0)
6103 };
6104 let to_assembled = |at: usize| -> Option<usize> {
6105 if prelude_len == 0 || at <= insert_at {
6106 Some(at)
6107 } else if at >= insert_at + prelude_len {
6108 Some(at - prelude_len)
6109 } else {
6110 None
6111 }
6112 };
6113 let span = match (to_assembled(pe.span.start), to_assembled(pe.span.end)) {
6114 (Some(start), Some(end)) if start <= end => crate::token::Span::new(start, end),
6115 _ => crate::token::Span::default(),
6116 };
6117 let pe = ParseError { span, ..pe };
6118 if matches!(pe.kind, crate::error::ParseErrorKind::Custom(_)) {
6121 return CompileError::Parse(pe);
6122 }
6123
6124 if let Some(file) = assembled.source_map.file_for(pe.span.start) {
6128 if file != assembled.scope.entry() {
6129 if let Some(name) = file.file_name().and_then(|s| s.to_str()) {
6130 return CompileError::Parse(ParseError {
6131 kind: crate::error::ParseErrorKind::Custom(format!(
6132 "in `{name}`: {}",
6133 describe_parse_error(&pe)
6134 )),
6135 span: pe.span,
6136 });
6137 }
6138 }
6139 }
6140 CompileError::Parse(pe)
6141}
6142
6143pub(crate) fn describe_parse_error(pe: &ParseError) -> String {
6147 crate::error::socratic_explanation(pe, &Interner::new())
6148}
6149
6150pub fn enforce_project_scope(entry_file: &Path) -> Result<(), String> {
6156 enforce_project_scope_with_deps(entry_file, Vec::new()).map_err(|e| e.to_string())
6157}
6158
6159#[derive(Debug)]
6161pub enum ProjectScopeError {
6162 Parse(ParseError),
6165 Refused(String),
6167}
6168
6169impl std::fmt::Display for ProjectScopeError {
6170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6171 match self {
6172 ProjectScopeError::Parse(pe) => f.write_str(&describe_parse_error(pe)),
6173 ProjectScopeError::Refused(why) => f.write_str(why),
6174 }
6175 }
6176}
6177
6178impl std::error::Error for ProjectScopeError {}
6179
6180pub fn enforce_project_scope_with_deps(
6183 entry_file: &Path,
6184 dep_roots: Vec<crate::loader::DepRoot>,
6185) -> Result<(), ProjectScopeError> {
6186 use crate::analysis::{assemble_project_with_deps, check_scopes, discover_with_imports};
6187 use crate::loader::Loader;
6188
6189 let root_path = entry_file.parent().unwrap_or(Path::new(".")).to_path_buf();
6190 let mut loader = Loader::with_dep_roots(root_path, dep_roots.clone());
6191 let mut interner = Interner::new();
6192
6193 let assembled =
6194 assemble_project_with_deps(entry_file, dep_roots).map_err(ProjectScopeError::Refused)?;
6195 let source = crate::loader::apply_prelude(&assembled.source).into_owned();
6196 let type_registry = discover_with_imports(entry_file, &source, &mut loader, &mut interner)
6197 .map_err(ProjectScopeError::Refused)?;
6198
6199 let mut lexer = Lexer::new(&source, &mut interner);
6200 let mut tokens = lexer.tokenize();
6201 let functions = crate::analysis::assemble::defined_function_names(&source);
6202 crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
6203
6204 let mut world_state = WorldState::new();
6205 let expr_arena = Arena::new();
6206 let term_arena = Arena::new();
6207 let np_arena = Arena::new();
6208 let sym_arena = Arena::new();
6209 let role_arena = Arena::new();
6210 let pp_arena = Arena::new();
6211 let stmt_arena: Arena<Stmt> = Arena::new();
6212 let _compile_facts = crate::optimize::facts::scope();
6213 let imperative_expr_arena: Arena<Expr> = Arena::new();
6214 let type_expr_arena: Arena<TypeExpr> = Arena::new();
6215 let ast_ctx = AstContext::with_types(
6216 &expr_arena,
6217 &term_arena,
6218 &np_arena,
6219 &sym_arena,
6220 &role_arena,
6221 &pp_arena,
6222 &stmt_arena,
6223 &imperative_expr_arena,
6224 &type_expr_arena,
6225 );
6226
6227 let mut parser = Parser::new(
6228 tokens,
6229 &mut world_state,
6230 &mut interner,
6231 ast_ctx,
6232 type_registry,
6233 );
6234 let stmts = parser.parse_program().map_err(ProjectScopeError::Parse)?;
6235
6236 check_scopes(&stmts, &assembled.scope, &interner).map_err(ProjectScopeError::Refused)
6237}
6238
6239fn compile_to_rust_with_registry_full(
6244 source: &str,
6245 type_registry: crate::analysis::TypeRegistry,
6246 interner: &mut Interner,
6247 scope: Option<&crate::analysis::ScopeInfo>,
6248) -> Result<CompileOutput, ParseError> {
6249 let library = crate::loader::LibraryProvenance::of(source);
6250 let mut lexer = Lexer::new(source, interner);
6251 let mut tokens = lexer.tokenize();
6252
6253 let functions = crate::analysis::assemble::defined_function_names(source);
6257 crate::analysis::assemble::resolve_qualified_names(&mut tokens, interner, &functions);
6258
6259 let policy_registry = {
6261 let mut discovery = DiscoveryPass::new(&tokens, interner);
6262 discovery.run_full().policies
6263 };
6264
6265 let codegen_policies = policy_registry.clone();
6266
6267 let mut world_state = WorldState::new();
6268 let expr_arena = Arena::new();
6269 let term_arena = Arena::new();
6270 let np_arena = Arena::new();
6271 let sym_arena = Arena::new();
6272 let role_arena = Arena::new();
6273 let pp_arena = Arena::new();
6274 let stmt_arena: Arena<Stmt> = Arena::new();
6275 let _compile_facts = crate::optimize::facts::scope();
6276 let imperative_expr_arena: Arena<Expr> = Arena::new();
6277 let type_expr_arena: Arena<TypeExpr> = Arena::new();
6278
6279 let ast_ctx = AstContext::with_types(
6280 &expr_arena,
6281 &term_arena,
6282 &np_arena,
6283 &sym_arena,
6284 &role_arena,
6285 &pp_arena,
6286 &stmt_arena,
6287 &imperative_expr_arena,
6288 &type_expr_arena,
6289 );
6290
6291 let mut parser = Parser::new(tokens, &mut world_state, interner, ast_ctx, type_registry);
6292 let stmts = parser.parse_program()?;
6293 let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
6294
6295 let (opt_config, gate) = crate::optimize::install_decorators(
6302 crate::optimization::OptimizationConfig::from_env(),
6303 &parser.program_opt_flags(),
6304 parser.required_optimizations(),
6305 );
6306 let codegen_registry = parser.into_type_registry();
6307 refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, interner)?;
6308
6309 if let Some(scope) = scope {
6313 crate::analysis::check_scopes(&stmts, scope, interner).map_err(|msg| ParseError {
6314 kind: crate::error::ParseErrorKind::Custom(msg),
6315 span: crate::token::Span::default(),
6316 })?;
6317 }
6318 check_as_written(&stmts, interner, AsWritten::Escapes)?;
6319
6320 let resolved = crate::resolve_program::resolve_program(
6321 &stmts,
6322 crate::ast_map::Arenas {
6323 exprs: &imperative_expr_arena,
6324 stmts: &stmt_arena,
6325 types: &type_expr_arena,
6326 },
6327 interner,
6328 opt_config.is_on(crate::optimization::Opt::Comptime),
6329 library.functions(),
6330 );
6331 let stmts: Vec<Stmt> = match resolved {
6332 Some(rw) => rw.to_vec(),
6333 None => stmts,
6334 };
6335
6336 let (stmts, codegen_registry) = lift_program_bindings(
6345 stmts,
6346 codegen_registry,
6347 interner,
6348 crate::ast_map::Arenas {
6349 exprs: &imperative_expr_arena,
6350 stmts: &stmt_arena,
6351 types: &type_expr_arena,
6352 },
6353 )?;
6354 let stmts = crate::optimize::optimize_program(
6355 stmts,
6356 &imperative_expr_arena,
6357 &stmt_arena,
6358 interner,
6359 &opt_config,
6360 );
6361
6362 let mut dependencies = extract_dependencies(&stmts, interner)?;
6364
6365 let needs_wasm_bindgen = stmts.iter().any(|stmt| {
6367 if let Stmt::FunctionDef {
6368 is_exported: true,
6369 export_target: Some(target),
6370 ..
6371 } = stmt
6372 {
6373 interner.resolve(*target).eq_ignore_ascii_case("wasm")
6374 } else {
6375 false
6376 }
6377 });
6378 if needs_wasm_bindgen && !dependencies.iter().any(|d| d.name == "wasm-bindgen") {
6379 dependencies.push(CrateDependency {
6380 name: "wasm-bindgen".to_string(),
6381 version: "0.2".to_string(),
6382 features: vec![],
6383 });
6384 }
6385
6386 crate::analysis::check_unknown_calls(&stmts, interner, &codegen_registry).map_err(|e| {
6390 ParseError {
6391 kind: e.to_parse_error_kind(interner),
6392 span: crate::token::Span::default(),
6393 }
6394 })?;
6395
6396 let type_env = crate::analysis::check_program_located(&stmts, interner, &codegen_registry)
6397 .map_err(|e| ParseError {
6398 kind: e.to_parse_error_kind(interner, &stmts),
6399 span: crate::token::Span::default(),
6400 })?;
6401 let rust_code = codegen_program(
6402 &stmts,
6403 &codegen_registry,
6404 &codegen_policies,
6405 interner,
6406 &type_env,
6407 &opt_config,
6408 );
6409
6410 gate.verify().map_err(|m| ParseError {
6413 kind: crate::error::ParseErrorKind::Custom(m),
6414 span: crate::token::Span::default(),
6415 })?;
6416
6417 let has_c = stmts.iter().any(|stmt| {
6419 if let Stmt::FunctionDef {
6420 is_exported: true,
6421 export_target,
6422 ..
6423 } = stmt
6424 {
6425 match export_target {
6426 None => true,
6427 Some(t) => interner.resolve(*t).eq_ignore_ascii_case("c"),
6428 }
6429 } else {
6430 false
6431 }
6432 });
6433
6434 let c_header = if has_c {
6435 Some(generate_c_header(
6436 &stmts,
6437 "module",
6438 interner,
6439 &codegen_registry,
6440 ))
6441 } else {
6442 None
6443 };
6444
6445 if has_c && !dependencies.iter().any(|d| d.name == "serde_json") {
6446 dependencies.push(CrateDependency {
6447 name: "serde_json".to_string(),
6448 version: "1".to_string(),
6449 features: vec![],
6450 });
6451 }
6452
6453 let python_bindings = if has_c {
6454 Some(generate_python_bindings(
6455 &stmts,
6456 "module",
6457 interner,
6458 &codegen_registry,
6459 ))
6460 } else {
6461 None
6462 };
6463
6464 let (typescript_bindings, typescript_types) = if has_c {
6465 let (js, dts) = generate_typescript_bindings(&stmts, "module", interner, &codegen_registry);
6466 (Some(js), Some(dts))
6467 } else {
6468 (None, None)
6469 };
6470
6471 Ok(CompileOutput {
6472 rust_code,
6473 dependencies,
6474 c_header,
6475 python_bindings,
6476 typescript_types,
6477 typescript_bindings,
6478 })
6479}
6480
6481#[derive(Debug)]
6503pub enum CompileError {
6504 Parse(ParseError),
6509
6510 Io(String),
6514
6515 Build(String),
6520
6521 Runtime(String),
6525
6526 Ownership(LogosError),
6532}
6533
6534impl std::fmt::Display for CompileError {
6535 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6536 match self {
6537 CompileError::Parse(e) => write!(f, "Parse error: {}", describe_parse_error(e)),
6538 CompileError::Io(e) => write!(f, "IO error: {}", e),
6539 CompileError::Build(e) => write!(f, "Build error: {}", e),
6540 CompileError::Runtime(e) => write!(f, "Runtime error: {}", e),
6541 CompileError::Ownership(e) => write!(f, "{}", e),
6542 }
6543 }
6544}
6545
6546impl std::error::Error for CompileError {}
6547
6548pub fn encode_program_source(source: &str) -> Result<String, ParseError> {
6558 let full_source = if source.contains("## Main") || source.contains("## To ") {
6559 source.to_string()
6560 } else {
6561 format!("## Main\n{}", source)
6562 };
6563
6564 let mut interner = Interner::new();
6565 let mut lexer = Lexer::new(&full_source, &mut interner);
6566 let tokens = lexer.tokenize();
6567
6568 let type_registry = {
6569 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
6570 let result = discovery.run_full();
6571 result.types
6572 };
6573
6574 let mut variant_constructors: HashMap<String, Vec<String>> = HashMap::new();
6576 for (_type_name, type_def) in type_registry.iter_types() {
6577 if let crate::analysis::TypeDef::Enum { variants, .. } = type_def {
6578 for variant in variants {
6579 let vname = interner.resolve(variant.name).to_string();
6580 let field_names: Vec<String> = variant
6581 .fields
6582 .iter()
6583 .map(|f| interner.resolve(f.name).to_string())
6584 .collect();
6585 variant_constructors.insert(vname, field_names);
6586 }
6587 }
6588 }
6589
6590 let mut world_state = WorldState::new();
6591 let expr_arena = Arena::new();
6592 let term_arena = Arena::new();
6593 let np_arena = Arena::new();
6594 let sym_arena = Arena::new();
6595 let role_arena = Arena::new();
6596 let pp_arena = Arena::new();
6597 let stmt_arena: Arena<Stmt> = Arena::new();
6598 let _compile_facts = crate::optimize::facts::scope();
6599 let imperative_expr_arena: Arena<Expr> = Arena::new();
6600 let type_expr_arena: Arena<TypeExpr> = Arena::new();
6601
6602 let ast_ctx = AstContext::with_types(
6603 &expr_arena,
6604 &term_arena,
6605 &np_arena,
6606 &sym_arena,
6607 &role_arena,
6608 &pp_arena,
6609 &stmt_arena,
6610 &imperative_expr_arena,
6611 &type_expr_arena,
6612 );
6613
6614 let mut parser = crate::parser::Parser::new(
6615 tokens,
6616 &mut world_state,
6617 &mut interner,
6618 ast_ctx,
6619 type_registry,
6620 );
6621 let stmts = parser.parse_program()?;
6622
6623 let mut functions: Vec<(String, Vec<String>, Vec<String>, String, Vec<&Stmt>)> = Vec::new();
6624 let mut main_stmts: Vec<&Stmt> = Vec::new();
6625
6626 for stmt in &stmts {
6627 if let Stmt::FunctionDef {
6628 name,
6629 params,
6630 body,
6631 return_type,
6632 is_native,
6633 ..
6634 } = stmt
6635 {
6636 if *is_native {
6637 continue; }
6639 let fn_name = interner.resolve(*name).to_string();
6640 let param_names: Vec<String> = params
6641 .iter()
6642 .map(|(name, _)| interner.resolve(*name).to_string())
6643 .collect();
6644 let param_types: Vec<String> = params
6645 .iter()
6646 .map(|(_, ty)| decompile_type_expr(ty, &interner))
6647 .collect();
6648 let ret_type = return_type
6649 .map(|rt| decompile_type_expr(rt, &interner))
6650 .unwrap_or_else(|| "Nothing".to_string());
6651 let body_stmts: Vec<&Stmt> = body.iter().collect();
6652 functions.push((fn_name, param_names, param_types, ret_type, body_stmts));
6653 } else {
6654 main_stmts.push(stmt);
6655 }
6656 }
6657
6658 let mut counter = 0usize;
6659 let mut output = String::new();
6660 reset_inspect_otherwise_idx(); output.push_str("Let encodedFuncMap be a new Map of Text to CFunc.\n");
6666 output.push_str("Let encodedFuncSeq be a new Seq of CFunc.\n");
6667
6668 for (fn_name, params, param_types, ret_type, body) in &functions {
6669 let body_var = encode_stmt_list_src(
6670 body,
6671 &mut counter,
6672 &mut output,
6673 &interner,
6674 &variant_constructors,
6675 );
6676
6677 let params_var = format!("params_{}", counter);
6678 counter += 1;
6679 output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
6680 for p in params {
6681 output.push_str(&format!("Push \"{}\" to {}.\n", p, params_var));
6682 }
6683
6684 let param_types_var = format!("paramTypes_{}", counter);
6685 counter += 1;
6686 output.push_str(&format!("Let {} be a new Seq of Text.\n", param_types_var));
6687 for pt in param_types {
6688 output.push_str(&format!("Push \"{}\" to {}.\n", pt, param_types_var));
6689 }
6690
6691 let func_var = format!("func_{}", counter);
6692 counter += 1;
6693 output.push_str(&format!(
6694 "Let {} be a new CFuncDef with name \"{}\" and params {} and paramTypes {} and returnType \"{}\" and body {}.\n",
6695 func_var, fn_name, params_var, param_types_var, ret_type, body_var
6696 ));
6697 output.push_str(&format!("Push copy of {} to encodedFuncSeq.\n", func_var));
6702 output.push_str(&format!(
6703 "Set item \"{}\" of encodedFuncMap to {}.\n",
6704 fn_name, func_var
6705 ));
6706 }
6707
6708 let main_var = encode_stmt_list_src(
6710 &main_stmts,
6711 &mut counter,
6712 &mut output,
6713 &interner,
6714 &variant_constructors,
6715 );
6716 output.push_str(&format!("Let encodedMain be {}.\n", main_var));
6717
6718 Ok(output)
6719}
6720
6721pub fn encode_program_source_compact(source: &str) -> Result<String, ParseError> {
6725 let full_source = if source.contains("## Main") || source.contains("## To ") {
6726 source.to_string()
6727 } else {
6728 format!("## Main\n{}", source)
6729 };
6730
6731 let mut interner = Interner::new();
6732 let mut lexer = Lexer::new(&full_source, &mut interner);
6733 let tokens = lexer.tokenize();
6734
6735 let type_registry = {
6736 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
6737 let result = discovery.run_full();
6738 result.types
6739 };
6740
6741 let mut variant_constructors: HashMap<String, Vec<String>> = HashMap::new();
6742 for (_type_name, type_def) in type_registry.iter_types() {
6743 if let crate::analysis::TypeDef::Enum { variants, .. } = type_def {
6744 for variant in variants {
6745 let vname = interner.resolve(variant.name).to_string();
6746 let field_names: Vec<String> = variant
6747 .fields
6748 .iter()
6749 .map(|f| interner.resolve(f.name).to_string())
6750 .collect();
6751 variant_constructors.insert(vname, field_names);
6752 }
6753 }
6754 }
6755
6756 let mut world_state = WorldState::new();
6757 let expr_arena = Arena::new();
6758 let term_arena = Arena::new();
6759 let np_arena = Arena::new();
6760 let sym_arena = Arena::new();
6761 let role_arena = Arena::new();
6762 let pp_arena = Arena::new();
6763 let stmt_arena: Arena<Stmt> = Arena::new();
6764 let _compile_facts = crate::optimize::facts::scope();
6765 let imperative_expr_arena: Arena<Expr> = Arena::new();
6766 let type_expr_arena: Arena<TypeExpr> = Arena::new();
6767
6768 let ast_ctx = AstContext::with_types(
6769 &expr_arena,
6770 &term_arena,
6771 &np_arena,
6772 &sym_arena,
6773 &role_arena,
6774 &pp_arena,
6775 &stmt_arena,
6776 &imperative_expr_arena,
6777 &type_expr_arena,
6778 );
6779
6780 let mut parser = crate::parser::Parser::new(
6781 tokens,
6782 &mut world_state,
6783 &mut interner,
6784 ast_ctx,
6785 type_registry,
6786 );
6787 let stmts = parser.parse_program()?;
6788
6789 let mut functions: Vec<(String, Vec<String>, Vec<String>, String, Vec<&Stmt>)> = Vec::new();
6790 let mut main_stmts: Vec<&Stmt> = Vec::new();
6791
6792 for stmt in &stmts {
6793 if let Stmt::FunctionDef {
6794 name,
6795 params,
6796 body,
6797 return_type,
6798 is_native,
6799 ..
6800 } = stmt
6801 {
6802 if *is_native {
6803 continue;
6804 }
6805 let fn_name = interner.resolve(*name).to_string();
6806 let param_names: Vec<String> = params
6807 .iter()
6808 .map(|(name, _)| interner.resolve(*name).to_string())
6809 .collect();
6810 let param_types: Vec<String> = params
6811 .iter()
6812 .map(|(_, ty)| decompile_type_expr(ty, &interner))
6813 .collect();
6814 let ret_type = return_type
6815 .map(|rt| decompile_type_expr(rt, &interner))
6816 .unwrap_or_else(|| "Nothing".to_string());
6817 let body_stmts: Vec<&Stmt> = body.iter().collect();
6818 functions.push((fn_name, param_names, param_types, ret_type, body_stmts));
6819 } else {
6820 main_stmts.push(stmt);
6821 }
6822 }
6823
6824 let mut counter = 0usize;
6825 let mut output = String::new();
6826
6827 output.push_str("Let encodedFuncMap be a new Map of Text to CFunc.\n");
6828
6829 for (fn_name, params, param_types, ret_type, body) in &functions {
6830 let body_var = encode_stmt_list_compact(
6831 body,
6832 &mut counter,
6833 &mut output,
6834 &interner,
6835 &variant_constructors,
6836 );
6837
6838 let params_var = format!("params_{}", counter);
6839 counter += 1;
6840 output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
6841 for p in params {
6842 output.push_str(&format!("Push \"{}\" to {}.\n", p, params_var));
6843 }
6844
6845 let param_types_var = format!("paramTypes_{}", counter);
6846 counter += 1;
6847 output.push_str(&format!("Let {} be a new Seq of Text.\n", param_types_var));
6848 for pt in param_types {
6849 output.push_str(&format!("Push \"{}\" to {}.\n", pt, param_types_var));
6850 }
6851
6852 let func_var = format!("func_{}", counter);
6853 counter += 1;
6854 output.push_str(&format!(
6855 "Let {} be a new CFuncDef with name \"{}\" and params {} and paramTypes {} and returnType \"{}\" and body {}.\n",
6856 func_var, fn_name, params_var, param_types_var, ret_type, body_var
6857 ));
6858 output.push_str(&format!(
6859 "Set item \"{}\" of encodedFuncMap to {}.\n",
6860 fn_name, func_var
6861 ));
6862 }
6863
6864 let main_var = encode_stmt_list_compact(
6865 &main_stmts,
6866 &mut counter,
6867 &mut output,
6868 &interner,
6869 &variant_constructors,
6870 );
6871 output.push_str(&format!("Let encodedMain be {}.\n", main_var));
6872
6873 Ok(output)
6874}
6875
6876fn try_inline_expr(expr: &Expr, interner: &Interner) -> Option<String> {
6879 match expr {
6880 Expr::Literal(lit) => match lit {
6881 Literal::Number(n) => Some(format!("(a new CInt with value {})", n)),
6882 Literal::Boolean(b) => Some(format!("(a new CBool with value {})", b)),
6883 Literal::Text(s) => {
6884 let text = interner.resolve(*s);
6885 Some(format!("(a new CText with value \"{}\")", text))
6886 }
6887 Literal::Float(f) => {
6888 let fs = format!("{}", f);
6889 let fs = if fs.contains('.') {
6890 fs
6891 } else {
6892 format!("{}.0", fs)
6893 };
6894 Some(format!("(a new CFloat with value {})", fs))
6895 }
6896 Literal::Nothing => Some("(a new CText with value \"nothing\")".to_string()),
6897 _ => None,
6898 },
6899 Expr::Identifier(sym) => {
6900 let name = interner.resolve(*sym);
6901 Some(format!("(a new CVar with name \"{}\")", name))
6902 }
6903 Expr::Not { operand } => {
6904 if let Some(inner) = try_inline_expr(operand, interner) {
6905 Some(format!("(a new CNot with inner {})", inner))
6906 } else {
6907 None
6908 }
6909 }
6910 Expr::OptionNone => Some("(a new COptionNone)".to_string()),
6911 _ => None,
6912 }
6913}
6914
6915fn encode_expr_compact(
6916 expr: &Expr,
6917 counter: &mut usize,
6918 output: &mut String,
6919 interner: &Interner,
6920 variants: &HashMap<String, Vec<String>>,
6921) -> String {
6922 if let Some(inline) = try_inline_expr(expr, interner) {
6924 return inline;
6925 }
6926
6927 let var = format!("e_{}", *counter);
6929 *counter += 1;
6930
6931 match expr {
6932 Expr::BinaryOp { op, left, right } => {
6933 let left_var = encode_expr_compact(left, counter, output, interner, variants);
6934 let right_var = encode_expr_compact(right, counter, output, interner, variants);
6935 let op_str = match op {
6936 BinaryOpKind::Add => "+",
6937 BinaryOpKind::Subtract => "-",
6938 BinaryOpKind::Multiply => "*",
6939 BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
6940 BinaryOpKind::FloorDivide => "//",
6941 BinaryOpKind::Modulo => "%",
6942 BinaryOpKind::Eq => "==",
6943 BinaryOpKind::NotEq => "!=",
6944 BinaryOpKind::Lt => "<",
6945 BinaryOpKind::Gt => ">",
6946 BinaryOpKind::LtEq => "<=",
6947 BinaryOpKind::GtEq => ">=",
6948 BinaryOpKind::And => "&&",
6949 BinaryOpKind::Or => "||",
6950 BinaryOpKind::Concat => "+",
6951 BinaryOpKind::SeqConcat => "followed by",
6952 BinaryOpKind::ApproxEq => "is approximately",
6953 BinaryOpKind::Pow => "**",
6954 BinaryOpKind::BitXor => "^",
6955 BinaryOpKind::BitAnd => "&",
6956 BinaryOpKind::BitOr => "|",
6957 BinaryOpKind::Shl => "<<",
6958 BinaryOpKind::Shr => ">>",
6959 };
6960 output.push_str(&format!(
6961 "Let {} be a new CBinOp with op \"{}\" and left {} and right {}.\n",
6962 var, op_str, left_var, right_var
6963 ));
6964 }
6965 Expr::Call { function, args } => {
6966 let fn_name = interner.resolve(*function);
6967 if let Some(field_names) = variants.get(fn_name) {
6968 let names_var = format!("nvNames_{}", *counter);
6969 *counter += 1;
6970 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
6971 let vals_var = format!("nvVals_{}", *counter);
6972 *counter += 1;
6973 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
6974 for (i, arg) in args.iter().enumerate() {
6975 let fname = field_names.get(i).map(|s| s.as_str()).unwrap_or("value");
6976 output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
6977 let arg_var = encode_expr_compact(arg, counter, output, interner, variants);
6978 output.push_str(&format!("Push {} to {}.\n", arg_var, vals_var));
6979 }
6980 output.push_str(&format!(
6981 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
6982 var, fn_name, names_var, vals_var
6983 ));
6984 } else {
6985 let args_var = format!("callArgs_{}", *counter);
6986 *counter += 1;
6987 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
6988 for arg in args {
6989 let arg_var = encode_expr_compact(arg, counter, output, interner, variants);
6990 output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
6991 }
6992 output.push_str(&format!(
6993 "Let {} be a new CCall with name \"{}\" and args {}.\n",
6994 var, fn_name, args_var
6995 ));
6996 }
6997 }
6998 Expr::Index { collection, index } => {
6999 let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7000 let idx_var = encode_expr_compact(index, counter, output, interner, variants);
7001 output.push_str(&format!(
7002 "Let {} be a new CIndex with coll {} and idx {}.\n",
7003 var, coll_var, idx_var
7004 ));
7005 }
7006 Expr::Length { collection } => {
7007 let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7008 output.push_str(&format!(
7009 "Let {} be a new CLen with target {}.\n",
7010 var, coll_var
7011 ));
7012 }
7013 Expr::FieldAccess { object, field } => {
7014 let obj_var = encode_expr_compact(object, counter, output, interner, variants);
7015 let field_name = interner.resolve(*field);
7016 output.push_str(&format!(
7017 "Let {} be a new CMapGet with target {} and key (a new CText with value \"{}\").\n",
7018 var, obj_var, field_name
7019 ));
7020 }
7021 Expr::NewVariant {
7022 variant, fields, ..
7023 } => {
7024 let variant_name = interner.resolve(*variant);
7025 let names_var = format!("nvNames_{}", *counter);
7026 *counter += 1;
7027 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7028 let vals_var = format!("nvVals_{}", *counter);
7029 *counter += 1;
7030 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7031 for (field_name, field_expr) in fields {
7032 let fname = interner.resolve(*field_name);
7033 output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7034 let field_var =
7035 encode_expr_compact(field_expr, counter, output, interner, variants);
7036 output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7037 }
7038 output.push_str(&format!(
7039 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7040 var, variant_name, names_var, vals_var
7041 ));
7042 }
7043 Expr::New {
7044 type_name,
7045 init_fields,
7046 ..
7047 } => {
7048 let tn = interner.resolve(*type_name);
7049 if tn == "Seq" || tn == "List" {
7050 output.push_str(&format!("Let {} be a new CNewSeq.\n", var));
7051 } else if tn == "Set" {
7052 output.push_str(&format!("Let {} be a new CNewSet.\n", var));
7053 } else {
7054 let names_var = format!("nvNames_{}", *counter);
7055 *counter += 1;
7056 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7057 let vals_var = format!("nvVals_{}", *counter);
7058 *counter += 1;
7059 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7060 for (field_name, field_expr) in init_fields {
7061 let fname = interner.resolve(*field_name);
7062 output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7063 let field_var =
7064 encode_expr_compact(field_expr, counter, output, interner, variants);
7065 output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7066 }
7067 output.push_str(&format!(
7068 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7069 var, tn, names_var, vals_var
7070 ));
7071 }
7072 }
7073 Expr::InterpolatedString(parts) => {
7074 if parts.is_empty() {
7075 output.push_str(&format!("Let {} be (a new CText with value \"\").\n", var));
7076 } else {
7077 let parts_var = format!("isparts_{}", *counter);
7080 *counter += 1;
7081 output.push_str(&format!("Let {} be a new Seq of CStringPart.\n", parts_var));
7082 for part in parts {
7083 match part {
7084 StringPart::Literal(sym) => {
7085 let text = interner.resolve(*sym);
7086 output.push_str(&format!(
7087 "Push a new CLiteralPart with value \"{}\" to {}.\n",
7088 text, parts_var
7089 ));
7090 }
7091 StringPart::Expr { value, .. } => {
7092 let pv =
7093 encode_expr_compact(value, counter, output, interner, variants);
7094 output.push_str(&format!(
7095 "Push a new CExprPart with expr {} to {}.\n",
7096 pv, parts_var
7097 ));
7098 }
7099 }
7100 }
7101 output.push_str(&format!(
7102 "Let {} be a new CInterpolatedString with parts {}.\n",
7103 var, parts_var
7104 ));
7105 }
7106 }
7107 Expr::Range { start, end } => {
7108 let start_var = encode_expr_compact(start, counter, output, interner, variants);
7109 let end_var = encode_expr_compact(end, counter, output, interner, variants);
7110 output.push_str(&format!(
7111 "Let {} be a new CRange with start {} and end {}.\n",
7112 var, start_var, end_var
7113 ));
7114 }
7115 Expr::Copy { expr } => {
7116 let inner_var = encode_expr_compact(expr, counter, output, interner, variants);
7117 output.push_str(&format!(
7118 "Let {} be a new CCopy with target {}.\n",
7119 var, inner_var
7120 ));
7121 }
7122 Expr::Contains { collection, value } => {
7123 let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7124 let val_var = encode_expr_compact(value, counter, output, interner, variants);
7125 output.push_str(&format!(
7126 "Let {} be a new CContains with coll {} and elem {}.\n",
7127 var, coll_var, val_var
7128 ));
7129 }
7130 Expr::OptionSome { value } => {
7131 let inner_var = encode_expr_compact(value, counter, output, interner, variants);
7132 output.push_str(&format!(
7133 "Let {} be a new COptionSome with inner {}.\n",
7134 var, inner_var
7135 ));
7136 }
7137 Expr::Tuple(elems) => {
7138 let items_var = format!("tupItems_{}", *counter);
7139 *counter += 1;
7140 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
7141 for elem in elems {
7142 let elem_var = encode_expr_compact(elem, counter, output, interner, variants);
7143 output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
7144 }
7145 output.push_str(&format!(
7146 "Let {} be a new CTuple with items {}.\n",
7147 var, items_var
7148 ));
7149 }
7150 Expr::Closure { params, body, .. } => {
7151 let params_var = format!("clp_{}", *counter);
7152 *counter += 1;
7153 output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
7154 let mut param_names = HashSet::new();
7155 for (sym, _) in params {
7156 let name = interner.resolve(*sym);
7157 param_names.insert(name.to_string());
7158 output.push_str(&format!("Push \"{}\" to {}.\n", name, params_var));
7159 }
7160 let body_var = format!("clb_{}", *counter);
7161 *counter += 1;
7162 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
7163 match body {
7164 ClosureBody::Expression(e) => {
7165 let ret_expr = encode_expr_compact(e, counter, output, interner, variants);
7166 let ret_var = format!("s_{}", *counter);
7167 *counter += 1;
7168 output.push_str(&format!(
7169 "Let {} be a new CReturn with expr {}.\n",
7170 ret_var, ret_expr
7171 ));
7172 output.push_str(&format!("Push {} to {}.\n", ret_var, body_var));
7173 }
7174 ClosureBody::Block(stmts) => {
7175 for s in stmts.iter() {
7176 let sv = encode_stmt_compact(s, counter, output, interner, variants);
7177 output.push_str(&format!("Push {} to {}.\n", sv, body_var));
7178 }
7179 }
7180 }
7181 let bound: HashSet<String> = param_names;
7182 let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound)
7187 .into_iter()
7188 .collect();
7189 free.sort();
7190 let cap_var = format!("clc_{}", *counter);
7191 *counter += 1;
7192 output.push_str(&format!("Let {} be a new Seq of Text.\n", cap_var));
7193 for fv in &free {
7194 output.push_str(&format!("Push \"{}\" to {}.\n", fv, cap_var));
7195 }
7196 output.push_str(&format!(
7197 "Let {} be a new CClosure with params {} and body {} and captured {}.\n",
7198 var, params_var, body_var, cap_var
7199 ));
7200 }
7201 Expr::CallExpr { callee, args } => {
7202 let callee_var = encode_expr_compact(callee, counter, output, interner, variants);
7203 let args_var = format!("cea_{}", *counter);
7204 *counter += 1;
7205 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
7206 for a in args {
7207 let av = encode_expr_compact(a, counter, output, interner, variants);
7208 output.push_str(&format!("Push {} to {}.\n", av, args_var));
7209 }
7210 output.push_str(&format!(
7211 "Let {} be a new CCallExpr with target {} and args {}.\n",
7212 var, callee_var, args_var
7213 ));
7214 }
7215 Expr::Slice {
7216 collection,
7217 start,
7218 end,
7219 } => {
7220 let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7221 let start_var = encode_expr_compact(start, counter, output, interner, variants);
7222 let end_var = encode_expr_compact(end, counter, output, interner, variants);
7223 output.push_str(&format!(
7224 "Let {} be a new CSlice with coll {} and startIdx {} and endIdx {}.\n",
7225 var, coll_var, start_var, end_var
7226 ));
7227 }
7228 Expr::Union { left, right } => {
7229 let left_var = encode_expr_compact(left, counter, output, interner, variants);
7230 let right_var = encode_expr_compact(right, counter, output, interner, variants);
7231 output.push_str(&format!(
7232 "Let {} be a new CUnion with left {} and right {}.\n",
7233 var, left_var, right_var
7234 ));
7235 }
7236 Expr::Intersection { left, right } => {
7237 let left_var = encode_expr_compact(left, counter, output, interner, variants);
7238 let right_var = encode_expr_compact(right, counter, output, interner, variants);
7239 output.push_str(&format!(
7240 "Let {} be a new CIntersection with left {} and right {}.\n",
7241 var, left_var, right_var
7242 ));
7243 }
7244 Expr::Give { value } => {
7245 let inner_var = encode_expr_compact(value, counter, output, interner, variants);
7246 output.push_str(&format!("Let {} be {}.\n", var, inner_var));
7247 }
7248 Expr::Escape { code, .. } => {
7249 let code_str = interner.resolve(*code);
7250 output.push_str(&format!(
7251 "Let {} be a new CEscExpr with code \"{}\".\n",
7252 var,
7253 code_str.replace('\"', "\\\"")
7254 ));
7255 }
7256 _ => {
7257 output.push_str(&format!(
7259 "Let {} be (a new CText with value \"unsupported\").\n",
7260 var
7261 ));
7262 }
7263 }
7264
7265 var
7266}
7267
7268fn encode_stmt_compact(
7269 stmt: &Stmt,
7270 counter: &mut usize,
7271 output: &mut String,
7272 interner: &Interner,
7273 variants: &HashMap<String, Vec<String>>,
7274) -> String {
7275 let var = format!("s_{}", *counter);
7276 *counter += 1;
7277
7278 match stmt {
7279 Stmt::Let {
7280 var: name, value, ..
7281 } => {
7282 let name_str = interner.resolve(*name);
7283 let expr_var = encode_expr_compact(value, counter, output, interner, variants);
7284 output.push_str(&format!(
7285 "Let {} be a new CLet with name \"{}\" and expr {}.\n",
7286 var, name_str, expr_var
7287 ));
7288 }
7289 Stmt::Set { target, value } => {
7290 let name_str = interner.resolve(*target);
7291 let expr_var = encode_expr_compact(value, counter, output, interner, variants);
7292 output.push_str(&format!(
7293 "Let {} be a new CSet with name \"{}\" and expr {}.\n",
7294 var, name_str, expr_var
7295 ));
7296 }
7297 Stmt::If {
7298 cond,
7299 then_block,
7300 else_block,
7301 } => {
7302 let cond_var = encode_expr_compact(cond, counter, output, interner, variants);
7303 let then_stmts: Vec<&Stmt> = then_block.iter().collect();
7304 let then_var =
7305 encode_stmt_list_compact(&then_stmts, counter, output, interner, variants);
7306 let else_var = if let Some(els) = else_block {
7307 let else_stmts: Vec<&Stmt> = els.iter().collect();
7308 encode_stmt_list_compact(&else_stmts, counter, output, interner, variants)
7309 } else {
7310 let empty_var = format!("emptyBlock_{}", *counter);
7311 *counter += 1;
7312 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
7313 empty_var
7314 };
7315 output.push_str(&format!(
7316 "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
7317 var, cond_var, then_var, else_var
7318 ));
7319 }
7320 Stmt::While { cond, body, .. } => {
7321 let cond_var = encode_expr_compact(cond, counter, output, interner, variants);
7322 let body_stmts: Vec<&Stmt> = body.iter().collect();
7323 let body_var =
7324 encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7325 output.push_str(&format!(
7326 "Let {} be a new CWhile with cond {} and body {}.\n",
7327 var, cond_var, body_var
7328 ));
7329 }
7330 Stmt::Return { value } => {
7331 if let Some(val) = value {
7332 let expr_var = encode_expr_compact(val, counter, output, interner, variants);
7333 output.push_str(&format!(
7334 "Let {} be a new CReturn with expr {}.\n",
7335 var, expr_var
7336 ));
7337 } else {
7338 output.push_str(&format!(
7339 "Let {} be a new CReturn with expr (a new CText with value \"nothing\").\n",
7340 var
7341 ));
7342 }
7343 }
7344 Stmt::Show { object, .. } => {
7345 let expr_var = encode_expr_compact(object, counter, output, interner, variants);
7346 output.push_str(&format!(
7347 "Let {} be a new CShow with expr {}.\n",
7348 var, expr_var
7349 ));
7350 }
7351 Stmt::Repeat {
7352 pattern,
7353 iterable,
7354 body,
7355 } => {
7356 let var_str = match pattern {
7357 Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
7358 Pattern::Tuple(syms) => {
7359 if let Some(s) = syms.first() {
7360 interner.resolve(*s).to_string()
7361 } else {
7362 "item".to_string()
7363 }
7364 }
7365 };
7366 let coll_var = encode_expr_compact(iterable, counter, output, interner, variants);
7367 let body_stmts: Vec<&Stmt> = body.iter().collect();
7368 let body_var =
7369 encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7370 output.push_str(&format!(
7371 "Let {} be a new CRepeat with var \"{}\" and coll {} and body {}.\n",
7372 var, var_str, coll_var, body_var
7373 ));
7374 }
7375 Stmt::Push { value, collection } => {
7376 let coll_name = extract_ident_name(collection, interner);
7377 let expr_var = encode_expr_compact(value, counter, output, interner, variants);
7378 output.push_str(&format!(
7379 "Let {} be a new CPush with expr {} and target \"{}\".\n",
7380 var, expr_var, coll_name
7381 ));
7382 }
7383 Stmt::SetIndex {
7384 collection,
7385 index,
7386 value,
7387 } => {
7388 let target_str = extract_ident_name(collection, interner);
7389 let idx_var = encode_expr_compact(index, counter, output, interner, variants);
7390 let val_var = encode_expr_compact(value, counter, output, interner, variants);
7391 output.push_str(&format!(
7392 "Let {} be a new CSetIdx with target \"{}\" and idx {} and val {}.\n",
7393 var, target_str, idx_var, val_var
7394 ));
7395 }
7396 Stmt::SetField {
7397 object,
7398 field,
7399 value,
7400 } => {
7401 let target_str = extract_ident_name(object, interner);
7402 let field_str = interner.resolve(*field);
7403 let val_var = encode_expr_compact(value, counter, output, interner, variants);
7404 output.push_str(&format!(
7405 "Let {} be a new CSetField with target \"{}\" and field \"{}\" and val {}.\n",
7406 var, target_str, field_str, val_var
7407 ));
7408 }
7409 Stmt::Break => {
7410 output.push_str(&format!("Let {} be a new CBreak.\n", var));
7411 }
7412 Stmt::Inspect { target, arms, .. } => {
7413 let target_var = encode_expr_compact(target, counter, output, interner, variants);
7414 let arms_var = format!("arms_{}", *counter);
7415 *counter += 1;
7416 output.push_str(&format!("Let {} be a new Seq of CMatchArm.\n", arms_var));
7417 for arm in arms {
7418 if let Some(variant_sym) = arm.variant {
7419 let vname = interner.resolve(variant_sym);
7420 let bindings_var = format!("bindings_{}", *counter);
7421 *counter += 1;
7422 output.push_str(&format!("Let {} be a new Seq of Text.\n", bindings_var));
7423 for (_, binding_name) in &arm.bindings {
7424 let bn = interner.resolve(*binding_name);
7425 output.push_str(&format!("Push \"{}\" to {}.\n", bn, bindings_var));
7426 }
7427 let body_stmts: Vec<&Stmt> = arm.body.iter().collect();
7428 let body_var =
7429 encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7430 let arm_var = format!("arm_{}", *counter);
7431 *counter += 1;
7432 output.push_str(&format!(
7433 "Let {} be a new CWhen with variantName \"{}\" and bindings {} and body {}.\n",
7434 arm_var, vname, bindings_var, body_var
7435 ));
7436 output.push_str(&format!("Push {} to {}.\n", arm_var, arms_var));
7437 } else {
7438 let body_stmts: Vec<&Stmt> = arm.body.iter().collect();
7439 let body_var =
7440 encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7441 let arm_var = format!("arm_{}", *counter);
7442 *counter += 1;
7443 output.push_str(&format!(
7444 "Let {} be a new COtherwise with body {}.\n",
7445 arm_var, body_var
7446 ));
7447 output.push_str(&format!("Push {} to {}.\n", arm_var, arms_var));
7448 }
7449 }
7450 output.push_str(&format!(
7451 "Let {} be a new CInspect with target {} and arms {}.\n",
7452 var, target_var, arms_var
7453 ));
7454 }
7455 _ => {
7456 return encode_stmt_src(stmt, counter, output, interner, variants);
7458 }
7459 }
7460
7461 var
7462}
7463
7464fn encode_stmt_list_compact(
7465 stmts: &[&Stmt],
7466 counter: &mut usize,
7467 output: &mut String,
7468 interner: &Interner,
7469 variants: &HashMap<String, Vec<String>>,
7470) -> String {
7471 let list_var = format!("stmts_{}", *counter);
7472 *counter += 1;
7473 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", list_var));
7474 for s in stmts {
7475 let sv = encode_stmt_compact(s, counter, output, interner, variants);
7476 output.push_str(&format!("Push {} to {}.\n", sv, list_var));
7477 }
7478 list_var
7479}
7480
7481fn collect_free_vars_expr<'a>(
7482 expr: &'a Expr,
7483 interner: &Interner,
7484 bound: &HashSet<String>,
7485) -> HashSet<String> {
7486 let mut free = HashSet::new();
7487 match expr {
7488 Expr::Identifier(sym) => {
7489 let name = interner.resolve(*sym).to_string();
7490 if !bound.contains(&name) {
7491 free.insert(name);
7492 }
7493 }
7494 Expr::BinaryOp { left, right, .. } => {
7495 free.extend(collect_free_vars_expr(left, interner, bound));
7496 free.extend(collect_free_vars_expr(right, interner, bound));
7497 }
7498 Expr::Not { operand } => {
7499 free.extend(collect_free_vars_expr(operand, interner, bound));
7500 }
7501 Expr::Copy { expr: inner } => {
7502 free.extend(collect_free_vars_expr(inner, interner, bound));
7503 }
7504 Expr::CallExpr { callee, args } => {
7505 free.extend(collect_free_vars_expr(callee, interner, bound));
7506 for a in args {
7507 free.extend(collect_free_vars_expr(a, interner, bound));
7508 }
7509 }
7510 Expr::Index { collection, index } => {
7511 free.extend(collect_free_vars_expr(collection, interner, bound));
7512 free.extend(collect_free_vars_expr(index, interner, bound));
7513 }
7514 Expr::InterpolatedString(parts) => {
7515 for part in parts {
7516 if let StringPart::Expr { value, .. } = part {
7517 free.extend(collect_free_vars_expr(value, interner, bound));
7518 }
7519 }
7520 }
7521 Expr::Closure { params, body, .. } => {
7522 let mut inner_bound = bound.clone();
7523 for (sym, _) in params {
7524 inner_bound.insert(interner.resolve(*sym).to_string());
7525 }
7526 match body {
7527 ClosureBody::Expression(e) => {
7528 free.extend(collect_free_vars_expr(e, interner, &inner_bound));
7529 }
7530 ClosureBody::Block(stmts) => {
7531 for s in stmts.iter() {
7532 free.extend(collect_free_vars_stmt(s, interner, &inner_bound));
7533 }
7534 }
7535 }
7536 }
7537 _ => {}
7538 }
7539 free
7540}
7541
7542fn collect_free_vars_stmt<'a>(
7543 stmt: &'a Stmt,
7544 interner: &Interner,
7545 bound: &HashSet<String>,
7546) -> HashSet<String> {
7547 let mut free = HashSet::new();
7548 match stmt {
7549 Stmt::Let { var, value, .. } => {
7550 free.extend(collect_free_vars_expr(value, interner, bound));
7551 }
7552 Stmt::Set { target, value, .. } => {
7553 let n = interner.resolve(*target).to_string();
7554 if !bound.contains(&n) {
7555 free.insert(n);
7556 }
7557 free.extend(collect_free_vars_expr(value, interner, bound));
7558 }
7559 Stmt::Show { object, .. } => {
7560 free.extend(collect_free_vars_expr(object, interner, bound));
7561 }
7562 Stmt::Return { value } => {
7563 if let Some(v) = value {
7564 free.extend(collect_free_vars_expr(v, interner, bound));
7565 }
7566 }
7567 _ => {}
7568 }
7569 free
7570}
7571
7572fn encode_expr_src(
7573 expr: &Expr,
7574 counter: &mut usize,
7575 output: &mut String,
7576 interner: &Interner,
7577 variants: &HashMap<String, Vec<String>>,
7578) -> String {
7579 let var = format!("e_{}", *counter);
7580 *counter += 1;
7581
7582 match expr {
7583 Expr::Literal(lit) => match lit {
7584 Literal::Number(n) => {
7585 output.push_str(&format!("Let {} be a new CInt with value {}.\n", var, n));
7586 }
7587 Literal::Boolean(b) => {
7588 output.push_str(&format!("Let {} be a new CBool with value {}.\n", var, b));
7589 }
7590 Literal::Text(s) => {
7591 let text = interner.resolve(*s);
7592 output.push_str(&format!(
7593 "Let {} be a new CText with value \"{}\".\n",
7594 var, text
7595 ));
7596 }
7597 Literal::Float(f) => {
7598 let fs = format!("{}", f);
7602 let fs = if fs.contains('.') || fs.contains('e') || fs.contains('E') {
7603 fs
7604 } else {
7605 format!("{}.0", fs)
7606 };
7607 output.push_str(&format!("Let {} be a new CFloat with value {}.\n", var, fs));
7608 }
7609 Literal::Duration(nanos) => {
7610 let millis = nanos / 1_000_000;
7611 let amount_var = format!("e_{}", *counter);
7612 *counter += 1;
7613 output.push_str(&format!(
7614 "Let {} be a new CInt with value {}.\n",
7615 amount_var, millis
7616 ));
7617 output.push_str(&format!(
7618 "Let {} be a new CDuration with amount {} and unit \"milliseconds\".\n",
7619 var, amount_var
7620 ));
7621 }
7622 Literal::Nothing => {
7623 output.push_str(&format!(
7624 "Let {} be a new CText with value \"nothing\".\n",
7625 var
7626 ));
7627 }
7628 _ => {
7629 output.push_str(&format!(
7630 "Let {} be a new CText with value \"unsupported\".\n",
7631 var
7632 ));
7633 }
7634 },
7635 Expr::Identifier(sym) => {
7636 let name = interner.resolve(*sym);
7637 output.push_str(&format!(
7638 "Let {} be a new CVar with name \"{}\".\n",
7639 var, name
7640 ));
7641 }
7642 Expr::BinaryOp { op, left, right } => {
7643 let left_var = encode_expr_src(left, counter, output, interner, variants);
7644 let right_var = encode_expr_src(right, counter, output, interner, variants);
7645 let op_str = match op {
7646 BinaryOpKind::Add => "+",
7647 BinaryOpKind::Subtract => "-",
7648 BinaryOpKind::Multiply => "*",
7649 BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
7650 BinaryOpKind::FloorDivide => "//",
7651 BinaryOpKind::Modulo => "%",
7652 BinaryOpKind::Eq => "==",
7653 BinaryOpKind::NotEq => "!=",
7654 BinaryOpKind::Lt => "<",
7655 BinaryOpKind::Gt => ">",
7656 BinaryOpKind::LtEq => "<=",
7657 BinaryOpKind::GtEq => ">=",
7658 BinaryOpKind::And => "&&",
7659 BinaryOpKind::Or => "||",
7660 BinaryOpKind::Concat => "+",
7661 BinaryOpKind::SeqConcat => "followed by",
7662 BinaryOpKind::ApproxEq => "is approximately",
7663 BinaryOpKind::Pow => "**",
7664 BinaryOpKind::BitXor => "^",
7665 BinaryOpKind::BitAnd => "&",
7666 BinaryOpKind::BitOr => "|",
7667 BinaryOpKind::Shl => "<<",
7668 BinaryOpKind::Shr => ">>",
7669 };
7670 output.push_str(&format!(
7671 "Let {} be a new CBinOp with op \"{}\" and left {} and right {}.\n",
7672 var, op_str, left_var, right_var
7673 ));
7674 }
7675 Expr::Not { operand } => {
7676 let inner_var = encode_expr_src(operand, counter, output, interner, variants);
7677 output.push_str(&format!(
7678 "Let {} be a new CNot with inner {}.\n",
7679 var, inner_var
7680 ));
7681 }
7682 Expr::Call { function, args } => {
7683 let fn_name = interner.resolve(*function);
7684 if let Some(field_names) = variants.get(fn_name) {
7685 let names_var = format!("nvNames_{}", *counter);
7687 *counter += 1;
7688 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7689 let vals_var = format!("nvVals_{}", *counter);
7690 *counter += 1;
7691 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7692 for (i, arg) in args.iter().enumerate() {
7693 let fname = field_names.get(i).map(|s| s.as_str()).unwrap_or("value");
7694 output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7695 let arg_var = encode_expr_src(arg, counter, output, interner, variants);
7696 output.push_str(&format!("Push {} to {}.\n", arg_var, vals_var));
7697 }
7698 output.push_str(&format!(
7699 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7700 var, fn_name, names_var, vals_var
7701 ));
7702 } else {
7703 let args_var = format!("callArgs_{}", *counter);
7704 *counter += 1;
7705 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
7706 for arg in args {
7707 let arg_var = encode_expr_src(arg, counter, output, interner, variants);
7708 output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
7709 }
7710 output.push_str(&format!(
7711 "Let {} be a new CCall with name \"{}\" and args {}.\n",
7712 var, fn_name, args_var
7713 ));
7714 }
7715 }
7716 Expr::Index { collection, index } => {
7717 let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7718 let idx_var = encode_expr_src(index, counter, output, interner, variants);
7719 output.push_str(&format!(
7720 "Let {} be a new CIndex with coll {} and idx {}.\n",
7721 var, coll_var, idx_var
7722 ));
7723 }
7724 Expr::Length { collection } => {
7725 let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7726 output.push_str(&format!(
7727 "Let {} be a new CLen with target {}.\n",
7728 var, coll_var
7729 ));
7730 }
7731 Expr::FieldAccess { object, field } => {
7732 let obj_var = encode_expr_src(object, counter, output, interner, variants);
7733 let field_name = interner.resolve(*field);
7734 let key_var = format!("e_{}", *counter);
7735 *counter += 1;
7736 output.push_str(&format!(
7737 "Let {} be a new CText with value \"{}\".\n",
7738 key_var, field_name
7739 ));
7740 output.push_str(&format!(
7741 "Let {} be a new CMapGet with target {} and key {}.\n",
7742 var, obj_var, key_var
7743 ));
7744 }
7745 Expr::NewVariant {
7746 variant, fields, ..
7747 } => {
7748 let variant_name = interner.resolve(*variant);
7749 let names_var = format!("nvNames_{}", *counter);
7750 *counter += 1;
7751 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7752 let vals_var = format!("nvVals_{}", *counter);
7753 *counter += 1;
7754 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7755 for (field_name, field_expr) in fields {
7756 let fname = interner.resolve(*field_name);
7757 output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7758 let field_var = encode_expr_src(field_expr, counter, output, interner, variants);
7759 output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7760 }
7761 output.push_str(&format!(
7762 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7763 var, variant_name, names_var, vals_var
7764 ));
7765 }
7766 Expr::New {
7767 type_name,
7768 init_fields,
7769 ..
7770 } => {
7771 let tn = interner.resolve(*type_name);
7772 if tn == "Seq" || tn == "List" {
7773 output.push_str(&format!("Let {} be a new CNewSeq.\n", var));
7774 } else if tn == "Set" {
7775 output.push_str(&format!("Let {} be a new CNewSet.\n", var));
7776 } else if tn == "Map" || tn.starts_with("Map ") {
7777 let names_var = format!("nvNames_{}", *counter);
7779 *counter += 1;
7780 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7781 let vals_var = format!("nvVals_{}", *counter);
7782 *counter += 1;
7783 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7784 output.push_str(&format!(
7785 "Let {} be a new CNew with typeName \"Map\" and fieldNames {} and fields {}.\n",
7786 var, names_var, vals_var
7787 ));
7788 } else if init_fields.is_empty() {
7789 let names_var = format!("nvNames_{}", *counter);
7790 *counter += 1;
7791 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7792 let vals_var = format!("nvVals_{}", *counter);
7793 *counter += 1;
7794 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7795 output.push_str(&format!(
7796 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7797 var, tn, names_var, vals_var
7798 ));
7799 } else {
7800 let names_var = format!("nvNames_{}", *counter);
7801 *counter += 1;
7802 output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7803 let vals_var = format!("nvVals_{}", *counter);
7804 *counter += 1;
7805 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7806 for (field_name, field_expr) in init_fields {
7807 let fname = interner.resolve(*field_name);
7808 output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7809 let field_var =
7810 encode_expr_src(field_expr, counter, output, interner, variants);
7811 output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7812 }
7813 output.push_str(&format!(
7814 "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7815 var, tn, names_var, vals_var
7816 ));
7817 }
7818 }
7819 Expr::InterpolatedString(parts) => {
7820 if parts.is_empty() {
7821 output.push_str(&format!("Let {} be a new CText with value \"\".\n", var));
7822 } else {
7823 let parts_var = format!("isparts_{}", *counter);
7829 *counter += 1;
7830 output.push_str(&format!("Let {} be a new Seq of CStringPart.\n", parts_var));
7831 for part in parts {
7832 match part {
7833 StringPart::Literal(sym) => {
7834 let text = interner.resolve(*sym);
7835 output.push_str(&format!(
7836 "Push a new CLiteralPart with value \"{}\" to {}.\n",
7837 text, parts_var
7838 ));
7839 }
7840 StringPart::Expr { value, .. } => {
7841 let pv = encode_expr_src(value, counter, output, interner, variants);
7842 output.push_str(&format!(
7843 "Push a new CExprPart with expr {} to {}.\n",
7844 pv, parts_var
7845 ));
7846 }
7847 }
7848 }
7849 output.push_str(&format!(
7850 "Let {} be a new CInterpolatedString with parts {}.\n",
7851 var, parts_var
7852 ));
7853 }
7854 }
7855 Expr::Range { start, end } => {
7856 let start_var = encode_expr_src(start, counter, output, interner, variants);
7857 let end_var = encode_expr_src(end, counter, output, interner, variants);
7858 output.push_str(&format!(
7859 "Let {} be a new CRange with start {} and end {}.\n",
7860 var, start_var, end_var
7861 ));
7862 }
7863 Expr::Slice {
7864 collection,
7865 start,
7866 end,
7867 } => {
7868 let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7869 let start_var = encode_expr_src(start, counter, output, interner, variants);
7870 let end_var = encode_expr_src(end, counter, output, interner, variants);
7871 output.push_str(&format!(
7872 "Let {} be a new CSlice with coll {} and startIdx {} and endIdx {}.\n",
7873 var, coll_var, start_var, end_var
7874 ));
7875 }
7876 Expr::Copy { expr } => {
7877 let inner_var = encode_expr_src(expr, counter, output, interner, variants);
7878 output.push_str(&format!(
7879 "Let {} be a new CCopy with target {}.\n",
7880 var, inner_var
7881 ));
7882 }
7883 Expr::Contains { collection, value } => {
7884 let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7885 let val_var = encode_expr_src(value, counter, output, interner, variants);
7886 output.push_str(&format!(
7887 "Let {} be a new CContains with coll {} and elem {}.\n",
7888 var, coll_var, val_var
7889 ));
7890 }
7891 Expr::Union { left, right } => {
7892 let left_var = encode_expr_src(left, counter, output, interner, variants);
7893 let right_var = encode_expr_src(right, counter, output, interner, variants);
7894 output.push_str(&format!(
7895 "Let {} be a new CUnion with left {} and right {}.\n",
7896 var, left_var, right_var
7897 ));
7898 }
7899 Expr::Intersection { left, right } => {
7900 let left_var = encode_expr_src(left, counter, output, interner, variants);
7901 let right_var = encode_expr_src(right, counter, output, interner, variants);
7902 output.push_str(&format!(
7903 "Let {} be a new CIntersection with left {} and right {}.\n",
7904 var, left_var, right_var
7905 ));
7906 }
7907 Expr::OptionSome { value } => {
7908 let inner_var = encode_expr_src(value, counter, output, interner, variants);
7909 output.push_str(&format!(
7910 "Let {} be a new COptionSome with inner {}.\n",
7911 var, inner_var
7912 ));
7913 }
7914 Expr::OptionNone => {
7915 output.push_str(&format!("Let {} be a new COptionNone.\n", var));
7916 }
7917 Expr::Tuple(elems) => {
7918 let items_var = format!("tupItems_{}", *counter);
7919 *counter += 1;
7920 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
7921 for elem in elems {
7922 let elem_var = encode_expr_src(elem, counter, output, interner, variants);
7923 output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
7924 }
7925 output.push_str(&format!(
7926 "Let {} be a new CTuple with items {}.\n",
7927 var, items_var
7928 ));
7929 }
7930 Expr::Closure { params, body, .. } => {
7931 let params_var = format!("clp_{}", *counter);
7932 *counter += 1;
7933 output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
7934 let mut param_names = HashSet::new();
7935 for (sym, _) in params {
7936 let name = interner.resolve(*sym);
7937 param_names.insert(name.to_string());
7938 output.push_str(&format!("Push \"{}\" to {}.\n", name, params_var));
7939 }
7940 let body_var = format!("clb_{}", *counter);
7941 *counter += 1;
7942 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
7943 match body {
7944 ClosureBody::Expression(e) => {
7945 let ret_expr = encode_expr_src(e, counter, output, interner, variants);
7946 let ret_var = format!("s_{}", *counter);
7947 *counter += 1;
7948 output.push_str(&format!(
7949 "Let {} be a new CReturn with expr {}.\n",
7950 ret_var, ret_expr
7951 ));
7952 output.push_str(&format!("Push {} to {}.\n", ret_var, body_var));
7953 }
7954 ClosureBody::Block(stmts) => {
7955 for s in stmts.iter() {
7956 let sv = encode_stmt_src(s, counter, output, interner, variants);
7957 output.push_str(&format!("Push {} to {}.\n", sv, body_var));
7958 }
7959 }
7960 }
7961 let bound: HashSet<String> = param_names;
7962 let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound)
7967 .into_iter()
7968 .collect();
7969 free.sort();
7970 let cap_var = format!("clc_{}", *counter);
7971 *counter += 1;
7972 output.push_str(&format!("Let {} be a new Seq of Text.\n", cap_var));
7973 for fv in &free {
7974 output.push_str(&format!("Push \"{}\" to {}.\n", fv, cap_var));
7975 }
7976 output.push_str(&format!(
7977 "Let {} be a new CClosure with params {} and body {} and captured {}.\n",
7978 var, params_var, body_var, cap_var
7979 ));
7980 }
7981 Expr::CallExpr { callee, args } => {
7982 let callee_var = encode_expr_src(callee, counter, output, interner, variants);
7983 let args_var = format!("cea_{}", *counter);
7984 *counter += 1;
7985 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
7986 for a in args {
7987 let av = encode_expr_src(a, counter, output, interner, variants);
7988 output.push_str(&format!("Push {} to {}.\n", av, args_var));
7989 }
7990 output.push_str(&format!(
7991 "Let {} be a new CCallExpr with target {} and args {}.\n",
7992 var, callee_var, args_var
7993 ));
7994 }
7995 Expr::Give { value } => {
7996 let inner_var = encode_expr_src(value, counter, output, interner, variants);
7997 output.push_str(&format!("Let {} be {}.\n", var, inner_var));
7998 }
7999 Expr::Escape { code, .. } => {
8000 let code_str = interner.resolve(*code);
8001 output.push_str(&format!(
8002 "Let {} be a new CEscExpr with code \"{}\".\n",
8003 var,
8004 code_str.replace('\"', "\\\"")
8005 ));
8006 }
8007 Expr::List(elems) => {
8008 let items_var = format!("litems_{}", *counter);
8009 *counter += 1;
8010 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
8011 for elem in elems {
8012 let elem_var = encode_expr_src(elem, counter, output, interner, variants);
8013 output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
8014 }
8015 output.push_str(&format!(
8016 "Let {} be a new CList with items {}.\n",
8017 var, items_var
8018 ));
8019 }
8020 Expr::ManifestOf { zone } => {
8021 let zone_var = encode_expr_src(zone, counter, output, interner, variants);
8022 output.push_str(&format!(
8023 "Let {} be a new CManifestOf with zn {}.\n",
8024 var, zone_var
8025 ));
8026 }
8027 Expr::ChunkAt { index, zone } => {
8028 let idx_var = encode_expr_src(index, counter, output, interner, variants);
8029 let zone_var = encode_expr_src(zone, counter, output, interner, variants);
8030 output.push_str(&format!(
8031 "Let {} be a new CChunkAt with idx {} and zn {}.\n",
8032 var, idx_var, zone_var
8033 ));
8034 }
8035 Expr::WithCapacity { value, .. } => {
8036 return encode_expr_src(value, counter, output, interner, variants);
8040 }
8041 _ => {
8042 output.push_str(&format!(
8043 "Let {} be a new CText with value \"unsupported\".\n",
8044 var
8045 ));
8046 }
8047 }
8048
8049 var
8050}
8051
8052fn encode_stmt_src(
8053 stmt: &Stmt,
8054 counter: &mut usize,
8055 output: &mut String,
8056 interner: &Interner,
8057 variants: &HashMap<String, Vec<String>>,
8058) -> String {
8059 let var = format!("s_{}", *counter);
8060 *counter += 1;
8061
8062 match stmt {
8063 Stmt::Let { var: name, value, .. } => {
8064 let name_str = interner.resolve(*name);
8065 let expr_var = encode_expr_src(value, counter, output, interner, variants);
8066 output.push_str(&format!(
8067 "Let {} be a new CLet with name \"{}\" and expr {}.\n",
8068 var, name_str, expr_var
8069 ));
8070 }
8071 Stmt::Set { target, value } => {
8072 let name_str = interner.resolve(*target);
8073 let expr_var = encode_expr_src(value, counter, output, interner, variants);
8074 output.push_str(&format!(
8075 "Let {} be a new CSet with name \"{}\" and expr {}.\n",
8076 var, name_str, expr_var
8077 ));
8078 }
8079 Stmt::Swap { a, b } => {
8080 let (an, bn) = (interner.resolve(*a), interner.resolve(*b));
8084 output.push_str(&format!("Let swapBlock_{var} be a new Seq of CStmt.\n"));
8085 output.push_str(&format!("Let swapVarA_{var} be a new CVar with name \"{an}\".\n"));
8086 output.push_str(&format!("Let swapS1_{var} be a new CLet with name \"swaptmp_{var}\" and expr swapVarA_{var}.\n"));
8087 output.push_str(&format!("Push swapS1_{var} to swapBlock_{var}.\n"));
8088 output.push_str(&format!("Let swapVarB_{var} be a new CVar with name \"{bn}\".\n"));
8089 output.push_str(&format!("Let swapS2_{var} be a new CSet with name \"{an}\" and expr swapVarB_{var}.\n"));
8090 output.push_str(&format!("Push swapS2_{var} to swapBlock_{var}.\n"));
8091 output.push_str(&format!("Let swapVarT_{var} be a new CVar with name \"swaptmp_{var}\".\n"));
8092 output.push_str(&format!("Let swapS3_{var} be a new CSet with name \"{bn}\" and expr swapVarT_{var}.\n"));
8093 output.push_str(&format!("Push swapS3_{var} to swapBlock_{var}.\n"));
8094 output.push_str(&format!("Let swapCond_{var} be a new CBool with value true.\n"));
8095 output.push_str(&format!("Let swapEmpty_{var} be a new Seq of CStmt.\n"));
8096 output.push_str(&format!(
8097 "Let {var} be a new CIf with cond swapCond_{var} and thenBlock swapBlock_{var} and elseBlock swapEmpty_{var}.\n"
8098 ));
8099 }
8100 Stmt::If { cond, then_block, else_block } => {
8101 let cond_var = encode_expr_src(cond, counter, output, interner, variants);
8102 let then_stmts: Vec<&Stmt> = then_block.iter().collect();
8103 let then_var = encode_stmt_list_src(&then_stmts, counter, output, interner, variants);
8104 let else_var = if let Some(els) = else_block {
8105 let else_stmts: Vec<&Stmt> = els.iter().collect();
8106 encode_stmt_list_src(&else_stmts, counter, output, interner, variants)
8107 } else {
8108 let empty_var = format!("emptyBlock_{}", *counter);
8109 *counter += 1;
8110 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
8111 empty_var
8112 };
8113 output.push_str(&format!(
8114 "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8115 var, cond_var, then_var, else_var
8116 ));
8117 }
8118 Stmt::While { cond, body, .. } => {
8119 let cond_var = encode_expr_src(cond, counter, output, interner, variants);
8120 let body_stmts: Vec<&Stmt> = body.iter().collect();
8121 let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
8122 output.push_str(&format!(
8123 "Let {} be a new CWhile with cond {} and body {}.\n",
8124 var, cond_var, body_var
8125 ));
8126 }
8127 Stmt::Splice { body } | Stmt::Reversibly { body } => {
8128 let cond_var = format!("splice_cond_{}", *counter);
8133 *counter += 1;
8134 output.push_str(&format!("Let {} be a new CBool with value true.\n", cond_var));
8135 let body_stmts: Vec<&Stmt> = body.iter().collect();
8136 let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
8137 let empty_var = format!("emptyBlock_{}", *counter);
8138 *counter += 1;
8139 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
8140 output.push_str(&format!(
8141 "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8142 var, cond_var, body_var, empty_var
8143 ));
8144 }
8145 Stmt::Return { value } => {
8146 if let Some(expr) = value {
8147 let expr_var = encode_expr_src(expr, counter, output, interner, variants);
8148 output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, expr_var));
8149 } else {
8150 let nothing_var = format!("e_{}", *counter);
8151 *counter += 1;
8152 output.push_str(&format!("Let {} be a new CInt with value 0.\n", nothing_var));
8153 output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, nothing_var));
8154 }
8155 }
8156 Stmt::Show { object, .. } => {
8157 let expr_var = encode_expr_src(object, counter, output, interner, variants);
8158 output.push_str(&format!("Let {} be a new CShow with expr {}.\n", var, expr_var));
8159 }
8160 Stmt::Call { function, args } => {
8161 let fn_name = interner.resolve(*function);
8162 let args_var = format!("callSArgs_{}", *counter);
8163 *counter += 1;
8164 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
8165 for arg in args {
8166 let arg_var = encode_expr_src(arg, counter, output, interner, variants);
8167 output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
8168 }
8169 output.push_str(&format!(
8170 "Let {} be a new CCallS with name \"{}\" and args {}.\n",
8171 var, fn_name, args_var
8172 ));
8173 }
8174 Stmt::Push { value, collection } => {
8175 let val_var = encode_expr_src(value, counter, output, interner, variants);
8176 let coll_name = extract_ident_name(collection, interner);
8177 output.push_str(&format!(
8178 "Let {} be a new CPush with expr {} and target \"{}\".\n",
8179 var, val_var, coll_name
8180 ));
8181 }
8182 Stmt::SetIndex { collection, index, value } => {
8183 let coll_name = extract_ident_name(collection, interner);
8184 let idx_var = encode_expr_src(index, counter, output, interner, variants);
8185 let val_var = encode_expr_src(value, counter, output, interner, variants);
8186 output.push_str(&format!(
8187 "Let {} be a new CSetIdx with target \"{}\" and idx {} and val {}.\n",
8188 var, coll_name, idx_var, val_var
8189 ));
8190 }
8191 Stmt::SetField { object, field, value } => {
8192 let map_name = extract_ident_name(object, interner);
8193 let field_name = interner.resolve(*field);
8194 let key_var = format!("e_{}", *counter);
8195 *counter += 1;
8196 output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", key_var, field_name));
8197 let val_var = encode_expr_src(value, counter, output, interner, variants);
8198 output.push_str(&format!(
8199 "Let {} be a new CMapSet with target \"{}\" and key {} and val {}.\n",
8200 var, map_name, key_var, val_var
8201 ));
8202 }
8203 Stmt::Pop { collection, .. } => {
8204 let coll_name = extract_ident_name(collection, interner);
8205 output.push_str(&format!(
8206 "Let {} be a new CPop with target \"{}\".\n",
8207 var, coll_name
8208 ));
8209 }
8210 Stmt::Add { value, collection } => {
8211 let val_var = encode_expr_src(value, counter, output, interner, variants);
8212 let coll_name = extract_ident_name(collection, interner);
8213 output.push_str(&format!(
8214 "Let {} be a new CAdd with elem {} and target \"{}\".\n",
8215 var, val_var, coll_name
8216 ));
8217 }
8218 Stmt::Remove { value, collection } => {
8219 let val_var = encode_expr_src(value, counter, output, interner, variants);
8220 let coll_name = extract_ident_name(collection, interner);
8221 output.push_str(&format!(
8222 "Let {} be a new CRemove with elem {} and target \"{}\".\n",
8223 var, val_var, coll_name
8224 ));
8225 }
8226 Stmt::Inspect { .. } => {
8227 return String::new(); }
8229 Stmt::Repeat { .. } => {
8230 return String::new(); }
8232 Stmt::Break => {
8233 output.push_str(&format!("Let {} be a new CBreak.\n", var));
8234 }
8235 Stmt::RuntimeAssert { condition, hard, dim: _, reason } => {
8236 let cond_var = encode_expr_src(condition, counter, output, interner, variants);
8237 let msg_var = match reason {
8238 Some(r) => encode_expr_src(r, counter, output, interner, variants),
8239 None => {
8240 let msg_var = format!("e_{}", *counter);
8241 *counter += 1;
8242 output.push_str(&format!("Let {} be a new CText with value \"assertion failed\".\n", msg_var));
8243 msg_var
8244 }
8245 };
8246 let variant = if *hard { "CHardAssert" } else { "CRuntimeAssert" };
8250 output.push_str(&format!(
8251 "Let {} be a new {} with cond {} and msg {}.\n",
8252 var, variant, cond_var, msg_var
8253 ));
8254 }
8255 Stmt::Fail { reason } => {
8257 let cond_var = format!("e_{}", *counter);
8258 *counter += 1;
8259 output.push_str(&format!("Let {} be a new CBool with value false.\n", cond_var));
8260 let msg_var = encode_expr_src(reason, counter, output, interner, variants);
8261 output.push_str(&format!("Let {} be a new CHardAssert with cond {} and msg {}.\n", var, cond_var, msg_var));
8262 }
8263 Stmt::Give { object, recipient } => {
8264 let expr_var = encode_expr_src(object, counter, output, interner, variants);
8265 let target_name = extract_ident_name(recipient, interner);
8266 output.push_str(&format!(
8267 "Let {} be a new CGive with expr {} and target \"{}\".\n",
8268 var, expr_var, target_name
8269 ));
8270 }
8271 Stmt::Escape { code, .. } => {
8272 let code_str = interner.resolve(*code);
8273 output.push_str(&format!(
8274 "Let {} be a new CEscStmt with code \"{}\".\n",
8275 var, code_str.replace('\"', "\\\"")
8276 ));
8277 }
8278 Stmt::Sleep { milliseconds } => {
8279 let dur_var = encode_expr_src(milliseconds, counter, output, interner, variants);
8280 output.push_str(&format!(
8281 "Let {} be a new CSleep with duration {}.\n",
8282 var, dur_var
8283 ));
8284 }
8285 Stmt::ReadFrom { var: read_var, source } => {
8286 let var_name = interner.resolve(*read_var);
8287 match source {
8288 ReadSource::Console => {
8289 output.push_str(&format!(
8290 "Let {} be a new CReadConsole with target \"{}\".\n",
8291 var, var_name
8292 ));
8293 }
8294 ReadSource::File(path_expr) => {
8295 let path_var = encode_expr_src(path_expr, counter, output, interner, variants);
8296 output.push_str(&format!(
8297 "Let {} be a new CReadFile with path {} and target \"{}\".\n",
8298 var, path_var, var_name
8299 ));
8300 }
8301 }
8302 }
8303 Stmt::WriteFile { content, path } => {
8304 let path_var = encode_expr_src(path, counter, output, interner, variants);
8305 let content_var = encode_expr_src(content, counter, output, interner, variants);
8306 output.push_str(&format!(
8307 "Let {} be a new CWriteFile with path {} and content {}.\n",
8308 var, path_var, content_var
8309 ));
8310 }
8311 Stmt::Check { source_text, .. } => {
8312 let pred_var = format!("e_{}", *counter);
8313 *counter += 1;
8314 output.push_str(&format!("Let {} be a new CBool with value true.\n", pred_var));
8315 let msg_var = format!("e_{}", *counter);
8316 *counter += 1;
8317 output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", msg_var, source_text.replace('\"', "\\\"")));
8318 output.push_str(&format!(
8319 "Let {} be a new CCheck with predicate {} and msg {}.\n",
8320 var, pred_var, msg_var
8321 ));
8322 }
8323 Stmt::Assert { .. } => {
8324 let prop_var = format!("e_{}", *counter);
8325 *counter += 1;
8326 output.push_str(&format!("Let {} be a new CBool with value true.\n", prop_var));
8327 output.push_str(&format!(
8328 "Let {} be a new CAssert with proposition {}.\n",
8329 var, prop_var
8330 ));
8331 }
8332 Stmt::Trust { justification, .. } => {
8333 let prop_var = format!("e_{}", *counter);
8334 *counter += 1;
8335 output.push_str(&format!("Let {} be a new CBool with value true.\n", prop_var));
8336 let just_str = interner.resolve(*justification);
8337 output.push_str(&format!(
8338 "Let {} be a new CTrust with proposition {} and justification \"{}\".\n",
8339 var, prop_var, just_str
8340 ));
8341 }
8342 Stmt::Require { crate_name, .. } => {
8343 let dep_name = interner.resolve(*crate_name);
8344 output.push_str(&format!(
8345 "Let {} be a new CRequire with dependency \"{}\".\n",
8346 var, dep_name
8347 ));
8348 }
8349 Stmt::MergeCrdt { source, target } => {
8350 let source_var = encode_expr_src(source, counter, output, interner, variants);
8351 let target_name = extract_ident_name(target, interner);
8354 output.push_str(&format!(
8355 "Let {} be a new CMerge with target \"{}\" and other {}.\n",
8356 var, target_name, source_var
8357 ));
8358 }
8359 Stmt::JoinCrdt { source, target } => {
8362 let source_var = encode_expr_src(source, counter, output, interner, variants);
8363 let target_name = extract_ident_name(target, interner);
8364 output.push_str(&format!(
8365 "Let {} be a new CJoin with target \"{}\" and other {}.\n",
8366 var, target_name, source_var
8367 ));
8368 }
8369 Stmt::IncreaseCrdt { object, field, amount } => {
8370 let amount_var = encode_expr_src(amount, counter, output, interner, variants);
8371 let target_name =
8374 format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
8375 output.push_str(&format!(
8376 "Let {} be a new CIncrease with target \"{}\" and amount {}.\n",
8377 var, target_name, amount_var
8378 ));
8379 }
8380 Stmt::DecreaseCrdt { object, field, amount } => {
8381 let amount_var = encode_expr_src(amount, counter, output, interner, variants);
8382 let target_name =
8383 format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
8384 output.push_str(&format!(
8385 "Let {} be a new CDecrease with target \"{}\" and amount {}.\n",
8386 var, target_name, amount_var
8387 ));
8388 }
8389 Stmt::AppendToSequence { sequence, value } => {
8390 let value_var = encode_expr_src(value, counter, output, interner, variants);
8391 let target_name = extract_ident_name(sequence, interner);
8392 output.push_str(&format!(
8393 "Let {} be a new CAppendToSeq with target \"{}\" and value {}.\n",
8394 var, target_name, value_var
8395 ));
8396 }
8397 Stmt::ResolveConflict { object, field, .. } => {
8398 let target_name =
8399 format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
8400 output.push_str(&format!(
8401 "Let {} be a new CResolve with target \"{}\".\n",
8402 var, target_name
8403 ));
8404 }
8405 Stmt::Sync { var: sync_var, topic } => {
8406 let topic_var = encode_expr_src(topic, counter, output, interner, variants);
8407 let var_name = interner.resolve(*sync_var);
8408 output.push_str(&format!(
8409 "Let {} be a new CSync with target \"{}\" and channel {}.\n",
8410 var, var_name, topic_var
8411 ));
8412 }
8413 Stmt::Mount { var: mount_var, path } => {
8414 let path_var = encode_expr_src(path, counter, output, interner, variants);
8415 let var_name = interner.resolve(*mount_var);
8416 output.push_str(&format!(
8417 "Let {} be a new CMount with target \"{}\" and path {}.\n",
8418 var, var_name, path_var
8419 ));
8420 }
8421 Stmt::Concurrent { tasks } => {
8422 let branches_var = format!("e_{}", *counter);
8423 *counter += 1;
8424 output.push_str(&format!("Let {} be a new Seq of Seq of CStmt.\n", branches_var));
8425 for stmt in tasks.iter() {
8428 let branch_var = format!("e_{}", *counter);
8429 *counter += 1;
8430 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", branch_var));
8431 let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8432 if !sv.is_empty() {
8433 output.push_str(&format!("Push {} to {}.\n", sv, branch_var));
8434 }
8435 output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8436 }
8437 output.push_str(&format!(
8438 "Let {} be a new CConcurrent with branches {}.\n",
8439 var, branches_var
8440 ));
8441 }
8442 Stmt::Parallel { tasks } => {
8443 let branches_var = format!("e_{}", *counter);
8444 *counter += 1;
8445 output.push_str(&format!("Let {} be a new Seq of Seq of CStmt.\n", branches_var));
8446 for stmt in tasks.iter() {
8448 let branch_var = format!("e_{}", *counter);
8449 *counter += 1;
8450 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", branch_var));
8451 let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8452 if !sv.is_empty() {
8453 output.push_str(&format!("Push {} to {}.\n", sv, branch_var));
8454 }
8455 output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8456 }
8457 output.push_str(&format!(
8458 "Let {} be a new CParallel with branches {}.\n",
8459 var, branches_var
8460 ));
8461 }
8462 Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
8463 let func_name = interner.resolve(*function);
8464 let args_var = format!("e_{}", *counter);
8465 *counter += 1;
8466 output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
8467 for arg in args {
8468 let av = encode_expr_src(arg, counter, output, interner, variants);
8469 output.push_str(&format!("Push {} to {}.\n", av, args_var));
8470 }
8471 let body_var = format!("e_{}", *counter);
8472 *counter += 1;
8473 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8474 let call_var = format!("e_{}", *counter);
8475 *counter += 1;
8476 output.push_str(&format!(
8477 "Let {} be a new CCallS with name \"{}\" and args {}.\n",
8478 call_var, func_name, args_var
8479 ));
8480 output.push_str(&format!("Push {} to {}.\n", call_var, body_var));
8481 let handle_name = if let Stmt::LaunchTaskWithHandle { handle, .. } = stmt {
8482 interner.resolve(*handle).to_string()
8483 } else {
8484 "_task".to_string()
8485 };
8486 output.push_str(&format!(
8487 "Let {} be a new CLaunchTask with body {} and handle \"{}\".\n",
8488 var, body_var, handle_name
8489 ));
8490 }
8491 Stmt::StopTask { handle } => {
8492 let handle_var = encode_expr_src(handle, counter, output, interner, variants);
8493 output.push_str(&format!(
8494 "Let {} be a new CStopTask with handle {}.\n",
8495 var, handle_var
8496 ));
8497 }
8498 Stmt::CloseChannel { channel } => {
8507 let chan_var = encode_expr_src(channel, counter, output, interner, variants);
8508 output.push_str(&format!(
8509 "Let {} be a new CStopTask with handle {}.\n",
8510 var, chan_var
8511 ));
8512 }
8513 Stmt::AwaitTask { handle, result } => {
8514 let chan_name = match handle {
8515 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8516 _ => "task".to_string(),
8517 };
8518 let target_name = result.map(|r| interner.resolve(r).to_string()).unwrap_or_else(|| "_await".to_string());
8519 output.push_str(&format!(
8520 "Let {} be a new CReceivePipe with chan \"{}\" and target \"{}\".\n",
8521 var, chan_name, target_name
8522 ));
8523 }
8524 Stmt::CreatePipe { var: pipe_var, capacity, .. } => {
8525 let cap = capacity.unwrap_or(32);
8526 let cap_var = format!("e_{}", *counter);
8527 *counter += 1;
8528 output.push_str(&format!("Let {} be a new CInt with value {}.\n", cap_var, cap));
8529 let pipe_name = interner.resolve(*pipe_var);
8530 output.push_str(&format!(
8531 "Let {} be a new CCreatePipe with name \"{}\" and capacity {}.\n",
8532 var, pipe_name, cap_var
8533 ));
8534 }
8535 Stmt::SendPipe { value, pipe } => {
8536 let val_var = encode_expr_src(value, counter, output, interner, variants);
8537 let pipe_name = match pipe {
8538 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8539 _ => "pipe".to_string(),
8540 };
8541 output.push_str(&format!(
8542 "Let {} be a new CSendPipe with chan \"{}\" and value {}.\n",
8543 var, pipe_name, val_var
8544 ));
8545 }
8546 Stmt::ReceivePipe { var: recv_var, pipe } => {
8547 let recv_name = interner.resolve(*recv_var);
8548 let pipe_name = match pipe {
8549 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8550 _ => "pipe".to_string(),
8551 };
8552 output.push_str(&format!(
8553 "Let {} be a new CReceivePipe with chan \"{}\" and target \"{}\".\n",
8554 var, pipe_name, recv_name
8555 ));
8556 }
8557 Stmt::TrySendPipe { value, pipe, .. } => {
8558 let val_var = encode_expr_src(value, counter, output, interner, variants);
8559 let pipe_name = match pipe {
8560 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8561 _ => "pipe".to_string(),
8562 };
8563 output.push_str(&format!(
8564 "Let {} be a new CTrySendPipe with chan \"{}\" and value {}.\n",
8565 var, pipe_name, val_var
8566 ));
8567 }
8568 Stmt::TryReceivePipe { var: recv_var, pipe } => {
8569 let recv_name = interner.resolve(*recv_var);
8570 let pipe_name = match pipe {
8571 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8572 _ => "pipe".to_string(),
8573 };
8574 output.push_str(&format!(
8575 "Let {} be a new CTryReceivePipe with chan \"{}\" and target \"{}\".\n",
8576 var, pipe_name, recv_name
8577 ));
8578 }
8579 Stmt::Select { branches } => {
8580 let branches_var = format!("e_{}", *counter);
8581 *counter += 1;
8582 output.push_str(&format!("Let {} be a new Seq of CSelectBranch.\n", branches_var));
8583 for branch in branches {
8584 match branch {
8585 SelectBranch::Receive { var: recv_var, pipe, body } => {
8586 let recv_name = interner.resolve(*recv_var);
8587 let pipe_name = match pipe {
8588 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8589 _ => "pipe".to_string(),
8590 };
8591 let body_var = format!("e_{}", *counter);
8592 *counter += 1;
8593 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8594 for stmt in body.iter() {
8595 let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8596 if !sv.is_empty() {
8597 output.push_str(&format!("Push {} to {}.\n", sv, body_var));
8598 }
8599 }
8600 let branch_var = format!("e_{}", *counter);
8601 *counter += 1;
8602 output.push_str(&format!(
8603 "Let {} be a new CSelectRecv with chan \"{}\" and var \"{}\" and body {}.\n",
8604 branch_var, pipe_name, recv_name, body_var
8605 ));
8606 output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8607 }
8608 SelectBranch::Timeout { milliseconds, body } => {
8609 let dur_var = encode_expr_src(milliseconds, counter, output, interner, variants);
8610 let body_var = format!("e_{}", *counter);
8611 *counter += 1;
8612 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8613 for stmt in body.iter() {
8614 let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8615 if !sv.is_empty() {
8616 output.push_str(&format!("Push {} to {}.\n", sv, body_var));
8617 }
8618 }
8619 let branch_var = format!("e_{}", *counter);
8620 *counter += 1;
8621 output.push_str(&format!(
8622 "Let {} be a new CSelectTimeout with duration {} and body {}.\n",
8623 branch_var, dur_var, body_var
8624 ));
8625 output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8626 }
8627 }
8628 }
8629 output.push_str(&format!(
8630 "Let {} be a new CSelect with branches {}.\n",
8631 var, branches_var
8632 ));
8633 }
8634 Stmt::Spawn { agent_type, name } => {
8635 let agent_name = interner.resolve(*agent_type);
8636 let target_name = interner.resolve(*name);
8637 output.push_str(&format!(
8638 "Let {} be a new CSpawn with agentType \"{}\" and target \"{}\".\n",
8639 var, agent_name, target_name
8640 ));
8641 }
8642 Stmt::SendMessage { message, destination, .. } => {
8643 let target_var = encode_expr_src(destination, counter, output, interner, variants);
8644 let msg_var = encode_expr_src(message, counter, output, interner, variants);
8645 output.push_str(&format!(
8646 "Let {} be a new CSendMessage with target {} and msg {}.\n",
8647 var, target_var, msg_var
8648 ));
8649 }
8650 Stmt::StreamMessage { values, destination } => {
8654 let target_var = encode_expr_src(destination, counter, output, interner, variants);
8655 let vals_var = encode_expr_src(values, counter, output, interner, variants);
8656 output.push_str(&format!(
8657 "Let {} be a new CStreamMessage with target {} and values {}.\n",
8658 var, target_var, vals_var
8659 ));
8660 }
8661 Stmt::AwaitMessage { into, .. } => {
8662 let await_name = interner.resolve(*into);
8663 output.push_str(&format!(
8664 "Let {} be a new CAwaitMessage with target \"{}\".\n",
8665 var, await_name
8666 ));
8667 }
8668 Stmt::Listen { address, secure: _ } => {
8671 let addr_var = encode_expr_src(address, counter, output, interner, variants);
8672 output.push_str(&format!(
8673 "Let {} be a new CListen with addr {} and handler \"default\".\n",
8674 var, addr_var
8675 ));
8676 }
8677 Stmt::Serve { port, handler: _ } => {
8680 let addr_var = encode_expr_src(port, counter, output, interner, variants);
8681 output.push_str(&format!(
8682 "Let {} be a new CListen with addr {} and handler \"default\".\n",
8683 var, addr_var
8684 ));
8685 }
8686 Stmt::ConnectTo { address, secure: _ } => {
8687 let addr_var = encode_expr_src(address, counter, output, interner, variants);
8688 output.push_str(&format!(
8689 "Let {} be a new CConnectTo with addr {} and target \"conn\".\n",
8690 var, addr_var
8691 ));
8692 }
8693 Stmt::Zone { name, body, .. } => {
8694 let zone_name = interner.resolve(*name);
8695 let body_var = format!("e_{}", *counter);
8696 *counter += 1;
8697 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8698 for stmt in body.iter() {
8699 let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8700 if !sv.is_empty() {
8701 output.push_str(&format!("Push {} to {}.\n", sv, body_var));
8702 }
8703 }
8704 output.push_str(&format!(
8705 "Let {} be a new CZone with name \"{}\" and kind \"heap\" and body {}.\n",
8706 var, zone_name, body_var
8707 ));
8708 }
8709 Stmt::LetPeerAgent { var: pa_var, address } => {
8710 let addr_var = encode_expr_src(address, counter, output, interner, variants);
8711 let pa_name = interner.resolve(*pa_var);
8712 output.push_str(&format!(
8713 "Let {} be a new CConnectTo with addr {} and target \"{}\".\n",
8714 var, addr_var, pa_name
8715 ));
8716 }
8717 Stmt::FunctionDef { .. }
8730 | Stmt::StructDef { .. }
8731 | Stmt::Ui(_)
8732 | Stmt::Fetch { .. }
8733 | Stmt::GivenFetch { .. }
8734 | Stmt::ServeFetches
8735 | Stmt::Replay { .. }
8736 | Stmt::ComponentDef(_)
8737 | Stmt::DirectiveDef { .. }
8738 | Stmt::RouteDef { .. }
8739 | Stmt::MiddlewareDef { .. }
8740 | Stmt::RedirectDef { .. }
8741 | Stmt::Theorem(_)
8742 | Stmt::Definition(_)
8743 | Stmt::Axiom(_)
8744 | Stmt::Theory(_)
8745 | Stmt::Site(_) => {
8750 return String::new();
8751 }
8752 Stmt::TestDef { .. }
8756 | Stmt::Expect { .. }
8757 | Stmt::ExpectFail { .. }
8758 | Stmt::ExpectOutput { .. }
8759 | Stmt::AdvanceTime { .. }
8760 | Stmt::GivenFile { .. }
8761 | Stmt::Observe { .. }
8765 | Stmt::During { .. }
8766 | Stmt::ForAll { .. } => {
8767 return String::new();
8768 }
8769 }
8770
8771 var
8772}
8773
8774fn encode_stmts_src(
8775 stmt: &Stmt,
8776 counter: &mut usize,
8777 output: &mut String,
8778 interner: &Interner,
8779 variants: &HashMap<String, Vec<String>>,
8780) -> Vec<String> {
8781 match stmt {
8782 Stmt::Inspect { target, arms, .. } => {
8783 let mut otherwise_stmts: Vec<&Stmt> = Vec::new();
8784 let mut variant_arms: Vec<(&MatchArm, Vec<&Stmt>)> = Vec::new();
8785
8786 for arm in arms {
8787 if arm.variant.is_none() {
8788 otherwise_stmts = arm.body.iter().collect();
8789 } else {
8790 let body_refs: Vec<&Stmt> = arm.body.iter().collect();
8791 variant_arms.push((arm, body_refs));
8792 }
8793 }
8794
8795 if variant_arms.is_empty() {
8796 let mut result = Vec::new();
8797 for s in &otherwise_stmts {
8798 for v in encode_stmts_src(s, counter, output, interner, variants) {
8799 result.push(v);
8800 }
8801 }
8802 return result;
8803 }
8804
8805 let has_otherwise = !otherwise_stmts.is_empty();
8810 let mut result = Vec::new();
8811
8812 let matched_var_name = if has_otherwise {
8814 let name = format!("__inspectMatched_{}", next_inspect_otherwise_idx());
8819 *counter += 1;
8820 let false_expr = format!("e_{}", *counter);
8821 *counter += 1;
8822 output.push_str(&format!(
8823 "Let {} be a new CBool with value false.\n",
8824 false_expr
8825 ));
8826 let let_stmt = format!("s_{}", *counter);
8827 *counter += 1;
8828 output.push_str(&format!(
8829 "Let {} be a new CLet with name \"{}\" and expr {}.\n",
8830 let_stmt, name, false_expr
8831 ));
8832 result.push(let_stmt);
8833 Some(name)
8834 } else {
8835 None
8836 };
8837
8838 for (arm, body_stmts) in &variant_arms {
8840 let variant_name = interner.resolve(arm.variant.unwrap());
8841
8842 let tag_target = encode_expr_src(target, counter, output, interner, variants);
8844 let tag_key = format!("e_{}", *counter);
8845 *counter += 1;
8846 output.push_str(&format!(
8847 "Let {} be a new CText with value \"__tag\".\n",
8848 tag_key
8849 ));
8850 let tag_get = format!("e_{}", *counter);
8851 *counter += 1;
8852 output.push_str(&format!(
8853 "Let {} be a new CMapGet with target {} and key {}.\n",
8854 tag_get, tag_target, tag_key
8855 ));
8856 let variant_text = format!("e_{}", *counter);
8857 *counter += 1;
8858 output.push_str(&format!(
8859 "Let {} be a new CText with value \"{}\".\n",
8860 variant_text, variant_name
8861 ));
8862 let cond_var = format!("e_{}", *counter);
8863 *counter += 1;
8864 output.push_str(&format!(
8865 "Let {} be a new CBinOp with op \"==\" and left {} and right {}.\n",
8866 cond_var, tag_get, variant_text
8867 ));
8868
8869 let then_list = format!("stmtList_{}", *counter);
8871 *counter += 1;
8872 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", then_list));
8873
8874 if let Some(ref mname) = matched_var_name {
8876 let true_expr = format!("e_{}", *counter);
8877 *counter += 1;
8878 output.push_str(&format!(
8879 "Let {} be a new CBool with value true.\n",
8880 true_expr
8881 ));
8882 let set_stmt = format!("s_{}", *counter);
8883 *counter += 1;
8884 output.push_str(&format!(
8885 "Let {} be a new CSet with name \"{}\" and expr {}.\n",
8886 set_stmt, mname, true_expr
8887 ));
8888 output.push_str(&format!("Push {} to {}.\n", set_stmt, then_list));
8889 }
8890
8891 for (field_name, binding_name) in &arm.bindings {
8893 let field_str = interner.resolve(*field_name);
8894 let bind_str = interner.resolve(*binding_name);
8895 let bind_target = encode_expr_src(target, counter, output, interner, variants);
8896 let fkey = format!("e_{}", *counter);
8897 *counter += 1;
8898 output.push_str(&format!(
8899 "Let {} be a new CText with value \"{}\".\n",
8900 fkey, field_str
8901 ));
8902 let fget = format!("e_{}", *counter);
8903 *counter += 1;
8904 output.push_str(&format!(
8905 "Let {} be a new CMapGet with target {} and key {}.\n",
8906 fget, bind_target, fkey
8907 ));
8908 let bind_let = format!("s_{}", *counter);
8909 *counter += 1;
8910 output.push_str(&format!(
8911 "Let {} be a new CLet with name \"{}\" and expr {}.\n",
8912 bind_let, bind_str, fget
8913 ));
8914 output.push_str(&format!("Push {} to {}.\n", bind_let, then_list));
8915 }
8916
8917 for body_stmt in body_stmts {
8919 match body_stmt {
8920 Stmt::Inspect { .. } | Stmt::Repeat { .. } => {
8921 let vars =
8922 encode_stmts_src(body_stmt, counter, output, interner, variants);
8923 for v in vars {
8924 output.push_str(&format!("Push {} to {}.\n", v, then_list));
8925 }
8926 }
8927 _ => {
8928 let bvar =
8929 encode_stmt_src(body_stmt, counter, output, interner, variants);
8930 if !bvar.is_empty() {
8931 output.push_str(&format!("Push {} to {}.\n", bvar, then_list));
8932 }
8933 }
8934 }
8935 }
8936
8937 let empty_else = format!("stmtList_{}", *counter);
8939 *counter += 1;
8940 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_else));
8941
8942 let if_var = format!("s_{}", *counter);
8944 *counter += 1;
8945 output.push_str(&format!(
8946 "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8947 if_var, cond_var, then_list, empty_else
8948 ));
8949
8950 result.push(if_var);
8951 }
8952
8953 if let Some(ref mname) = matched_var_name {
8955 let matched_ref = format!("e_{}", *counter);
8956 *counter += 1;
8957 output.push_str(&format!(
8958 "Let {} be a new CVar with name \"{}\".\n",
8959 matched_ref, mname
8960 ));
8961 let not_matched = format!("e_{}", *counter);
8962 *counter += 1;
8963 output.push_str(&format!(
8964 "Let {} be a new CNot with inner {}.\n",
8965 not_matched, matched_ref
8966 ));
8967
8968 let otherwise_block =
8969 encode_stmt_list_src(&otherwise_stmts, counter, output, interner, variants);
8970 let empty_else = format!("stmtList_{}", *counter);
8971 *counter += 1;
8972 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_else));
8973
8974 let otherwise_if = format!("s_{}", *counter);
8975 *counter += 1;
8976 output.push_str(&format!(
8977 "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8978 otherwise_if, not_matched, otherwise_block, empty_else
8979 ));
8980 result.push(otherwise_if);
8981 }
8982
8983 result
8984 }
8985 Stmt::Repeat {
8986 pattern,
8987 iterable,
8988 body,
8989 ..
8990 } => {
8991 let loop_var_name = match pattern {
8992 Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
8993 Pattern::Tuple(syms) => {
8994 if let Some(s) = syms.first() {
8995 interner.resolve(*s).to_string()
8996 } else {
8997 "item".to_string()
8998 }
8999 }
9000 };
9001
9002 if let Expr::Range { start, end } = iterable {
9004 let start_var = encode_expr_src(start, counter, output, interner, variants);
9005 let end_var = encode_expr_src(end, counter, output, interner, variants);
9006 let body_stmts: Vec<&Stmt> = body.iter().collect();
9007 let body_var =
9008 encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
9009 let rr = format!("s_{}", *counter);
9010 *counter += 1;
9011 output.push_str(&format!(
9012 "Let {} be a new CRepeatRange with var \"{}\" and start {} and end {} and body {}.\n",
9013 rr, loop_var_name, start_var, end_var, body_var
9014 ));
9015 return vec![rr];
9016 }
9017
9018 let coll_var = encode_expr_src(iterable, counter, output, interner, variants);
9020 let body_stmts: Vec<&Stmt> = body.iter().collect();
9021 let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
9022 let rep = format!("s_{}", *counter);
9023 *counter += 1;
9024 output.push_str(&format!(
9025 "Let {} be a new CRepeat with var \"{}\" and coll {} and body {}.\n",
9026 rep, loop_var_name, coll_var, body_var
9027 ));
9028 vec![rep]
9029 }
9030 Stmt::Add { collection, .. }
9034 | Stmt::Remove { collection, .. }
9035 | Stmt::AppendToSequence {
9036 sequence: collection,
9037 ..
9038 } => {
9039 let mut result = Vec::new();
9040 if let Some(fd) = emit_force_dynamic(collection, counter, output, interner) {
9041 result.push(fd);
9042 }
9043 let v = encode_stmt_src(stmt, counter, output, interner, variants);
9044 if !v.is_empty() {
9045 result.push(v);
9046 }
9047 result
9048 }
9049 Stmt::IncreaseCrdt { object, .. }
9053 | Stmt::DecreaseCrdt { object, .. }
9054 | Stmt::ResolveConflict { object, .. }
9055 | Stmt::MergeCrdt { target: object, .. }
9056 | Stmt::JoinCrdt { target: object, .. } => {
9057 let mut result = Vec::new();
9058 if let Some(fd) = emit_force_dynamic_struct(object, counter, output, interner) {
9059 result.push(fd);
9060 }
9061 let v = encode_stmt_src(stmt, counter, output, interner, variants);
9062 if !v.is_empty() {
9063 result.push(v);
9064 }
9065 result
9066 }
9067 _ => {
9068 let v = encode_stmt_src(stmt, counter, output, interner, variants);
9069 if v.is_empty() {
9070 vec![]
9071 } else {
9072 vec![v]
9073 }
9074 }
9075 }
9076}
9077
9078fn encode_stmt_list_src(
9079 stmts: &[&Stmt],
9080 counter: &mut usize,
9081 output: &mut String,
9082 interner: &Interner,
9083 variants: &HashMap<String, Vec<String>>,
9084) -> String {
9085 let list_var = format!("stmtList_{}", *counter);
9086 *counter += 1;
9087 output.push_str(&format!("Let {} be a new Seq of CStmt.\n", list_var));
9088
9089 for stmt in stmts {
9090 for stmt_var in encode_stmts_src(stmt, counter, output, interner, variants) {
9091 output.push_str(&format!("Push {} to {}.\n", stmt_var, list_var));
9092 }
9093 }
9094
9095 list_var
9096}
9097
9098fn extract_ident_name(expr: &Expr, interner: &Interner) -> String {
9099 match expr {
9100 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
9101 Expr::FieldAccess { object, field } => {
9106 format!(
9107 "{}'s {}",
9108 extract_ident_name(object, interner),
9109 interner.resolve(*field)
9110 )
9111 }
9112 _ => "unknown".to_string(),
9113 }
9114}
9115
9116fn crdt_base_var(expr: &Expr, interner: &Interner) -> Option<String> {
9122 match expr {
9123 Expr::FieldAccess { object, .. } => Some(crdt_base_var_root(object, interner)),
9124 _ => None,
9125 }
9126}
9127
9128fn crdt_base_var_root(expr: &Expr, interner: &Interner) -> String {
9129 match expr {
9130 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
9131 Expr::FieldAccess { object, .. } => crdt_base_var_root(object, interner),
9132 _ => "unknown".to_string(),
9133 }
9134}
9135
9136fn emit_force_dynamic_named(base: &str, counter: &mut usize, output: &mut String) -> String {
9139 let v = format!("s_{}", *counter);
9140 *counter += 1;
9141 output.push_str(&format!(
9142 "Let {} be a new CForceDynamic with name \"{}\".\n",
9143 v, base
9144 ));
9145 v
9146}
9147
9148fn emit_force_dynamic(
9151 collection: &Expr,
9152 counter: &mut usize,
9153 output: &mut String,
9154 interner: &Interner,
9155) -> Option<String> {
9156 let base = crdt_base_var(collection, interner)?;
9157 Some(emit_force_dynamic_named(&base, counter, output))
9158}
9159
9160fn emit_force_dynamic_struct(
9163 object: &Expr,
9164 counter: &mut usize,
9165 output: &mut String,
9166 interner: &Interner,
9167) -> Option<String> {
9168 match object {
9169 Expr::Identifier(_) | Expr::FieldAccess { .. } => Some(emit_force_dynamic_named(
9170 &crdt_base_var_root(object, interner),
9171 counter,
9172 output,
9173 )),
9174 _ => None,
9175 }
9176}
9177
9178pub fn projection1_source(
9191 _core_types: &str,
9192 _interpreter: &str,
9193 program: &str,
9194) -> Result<String, String> {
9195 let full_source = if program.contains("## Main") || program.contains("## To ") {
9196 program.to_string()
9197 } else {
9198 format!("## Main\n{}", program)
9199 };
9200
9201 let mut interner = Interner::new();
9202 let mut lexer = Lexer::new(&full_source, &mut interner);
9203 let tokens = lexer.tokenize();
9204
9205 let type_registry = {
9206 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
9207 let result = discovery.run_full();
9208 result.types
9209 };
9210
9211 let mut world_state = WorldState::new();
9212 let expr_arena = Arena::new();
9213 let term_arena = Arena::new();
9214 let np_arena = Arena::new();
9215 let sym_arena = Arena::new();
9216 let role_arena = Arena::new();
9217 let pp_arena = Arena::new();
9218 let stmt_arena: Arena<Stmt> = Arena::new();
9219 let _compile_facts = crate::optimize::facts::scope();
9220 let imperative_expr_arena: Arena<Expr> = Arena::new();
9221 let type_expr_arena: Arena<TypeExpr> = Arena::new();
9222
9223 let ast_ctx = AstContext::with_types(
9224 &expr_arena,
9225 &term_arena,
9226 &np_arena,
9227 &sym_arena,
9228 &role_arena,
9229 &pp_arena,
9230 &stmt_arena,
9231 &imperative_expr_arena,
9232 &type_expr_arena,
9233 );
9234
9235 let mut parser = crate::parser::Parser::new(
9236 tokens,
9237 &mut world_state,
9238 &mut interner,
9239 ast_ctx,
9240 type_registry,
9241 );
9242 let stmts = parser
9243 .parse_program()
9244 .map_err(|e| format!("Parse error: {}", describe_parse_error(&e)))?;
9245
9246 let opt_config = {
9249 let mut c =
9250 crate::optimization::OptimizationConfig::from_env().merged(&parser.program_opt_flags());
9251 c.normalize();
9252 c
9253 };
9254 let resolved = crate::resolve_program::resolve_program(
9255 &stmts,
9256 crate::ast_map::Arenas {
9257 exprs: &imperative_expr_arena,
9258 stmts: &stmt_arena,
9259 types: &type_expr_arena,
9260 },
9261 &mut interner,
9262 opt_config.is_on(crate::optimization::Opt::Comptime),
9263 &crate::loader::library_owned_functions(&full_source),
9264 );
9265 let stmts: Vec<Stmt> = match resolved {
9266 Some(rw) => rw.to_vec(),
9267 None => stmts,
9268 };
9269
9270 let optimized = crate::optimize::optimize_for_projection(
9275 stmts,
9276 &imperative_expr_arena,
9277 &stmt_arena,
9278 &mut interner,
9279 &opt_config,
9280 );
9281
9282 let mut output = String::new();
9283
9284 for stmt in &optimized {
9285 if matches!(stmt, Stmt::FunctionDef { .. }) {
9286 decompile_stmt(stmt, &interner, &mut output, 0);
9287 output.push('\n');
9288 }
9289 }
9290
9291 output.push_str("## Main\n");
9292 for stmt in &optimized {
9293 if !matches!(stmt, Stmt::FunctionDef { .. }) {
9294 decompile_stmt(stmt, &interner, &mut output, 0);
9295 }
9296 }
9297
9298 Ok(prepend_type_definitions(&full_source, output))
9303}
9304
9305fn decompile_stmt(stmt: &Stmt, interner: &Interner, out: &mut String, indent: usize) {
9306 let pad = " ".repeat(indent);
9307 match stmt {
9308 Stmt::ComponentDef(def) => decompile_component(def, interner, out),
9309 Stmt::DirectiveDef {
9310 name,
9311 params,
9312 body,
9313 removed,
9314 } => {
9315 out.push_str(&format!(
9316 "## Directive {} {}:\n",
9317 interner.resolve(*name),
9318 decompile_params(params, interner)
9319 ));
9320 for inner in body.iter() {
9321 decompile_stmt(inner, interner, out, 1);
9322 }
9323 if let Some(r) = removed {
9324 out.push_str(" When removed:\n");
9325 for inner in r.iter() {
9326 decompile_stmt(inner, interner, out, 2);
9327 }
9328 }
9329 }
9330 Stmt::RouteDef {
9331 method,
9332 path,
9333 params,
9334 return_type,
9335 body,
9336 ..
9337 } => {
9338 let ret = return_type
9339 .map(|t| format!(" -> {}", decompile_type_expr(t, interner)))
9340 .unwrap_or_default();
9341 let ps = decompile_params(params, interner);
9342 out.push_str(&format!(
9343 "## Route {} {}{}{}:\n",
9344 interner.resolve(*method),
9345 interner.resolve(*path),
9346 if ps.is_empty() {
9347 String::new()
9348 } else {
9349 format!(" {ps}")
9350 },
9351 ret
9352 ));
9353 match &**body {
9354 logicaffeine_language::ast::component::RouteBody::Statements(b) => {
9355 for inner in b.iter() {
9356 decompile_stmt(inner, interner, out, 1);
9357 }
9358 }
9359 logicaffeine_language::ast::component::RouteBody::View(view) => {
9360 for line in decompile_view(view, interner).lines() {
9361 out.push_str(&format!(" {line}\n"));
9362 }
9363 }
9364 }
9365 }
9366 Stmt::MiddlewareDef { param, body } => {
9367 out.push_str(&format!(
9368 "## Before each request ({}: {}) -> Option of Response:\n",
9369 interner.resolve(param.0),
9370 decompile_type_expr(param.1, interner)
9371 ));
9372 for inner in body.iter() {
9373 decompile_stmt(inner, interner, out, 1);
9374 }
9375 }
9376 Stmt::RedirectDef { from, to } => {
9377 out.push_str(&format!(
9378 "## Redirect {} -> {}.\n",
9379 interner.resolve(*from),
9380 interner.resolve(*to)
9381 ));
9382 }
9383 Stmt::FunctionDef {
9384 name,
9385 params,
9386 body,
9387 return_type,
9388 ..
9389 } => {
9390 let fn_name = interner.resolve(*name);
9391 let param_strs: Vec<String> = params
9392 .iter()
9393 .map(|(name, ty)| {
9394 let pname = interner.resolve(*name);
9395 format!("{}: {}", pname, decompile_type_expr(ty, interner))
9396 })
9397 .collect();
9398 let ret_str = if let Some(rt) = return_type {
9399 format!(" -> {}", decompile_type_expr(rt, interner))
9400 } else {
9401 String::new()
9402 };
9403 out.push_str(&format!(
9404 "{}## To {} ({}){}:\n",
9405 pad,
9406 fn_name,
9407 param_strs.join(", "),
9408 ret_str
9409 ));
9410 for s in body.iter() {
9411 decompile_stmt(s, interner, out, indent + 1);
9412 }
9413 }
9414 Stmt::Let {
9415 var,
9416 ty,
9417 value,
9418 mutable,
9419 } => {
9420 let name = interner.resolve(*var);
9421 let declared = ty
9422 .map(|t| format!(": {}", decompile_type_expr(t, interner)))
9423 .unwrap_or_default();
9424 let expr_str = decompile_expr(value, interner);
9425 let mutable = if *mutable { "mutable " } else { "" };
9426 out.push_str(&format!("{pad}Let {mutable}{name}{declared} be {expr_str}.\n"));
9427 }
9428 Stmt::Set { target, value } => {
9429 let name = interner.resolve(*target);
9430 let expr_str = decompile_expr(value, interner);
9431 out.push_str(&format!("{}Set {} to {}.\n", pad, name, expr_str));
9432 }
9433 Stmt::Show { object, .. } => {
9434 let expr_str = decompile_expr(object, interner);
9435 out.push_str(&format!("{}Show {}.\n", pad, expr_str));
9436 }
9437 Stmt::Return { value } => {
9438 if let Some(expr) = value {
9439 let expr_str = decompile_expr(expr, interner);
9440 out.push_str(&format!("{}Return {}.\n", pad, expr_str));
9441 } else {
9442 out.push_str(&format!("{}Return.\n", pad));
9443 }
9444 }
9445 Stmt::If {
9446 cond,
9447 then_block,
9448 else_block,
9449 } => {
9450 let cond_str = decompile_expr(cond, interner);
9451 out.push_str(&format!("{}If {}:\n", pad, cond_str));
9452 for s in then_block.iter() {
9453 decompile_stmt(s, interner, out, indent + 1);
9454 }
9455 if let Some(els) = else_block {
9456 out.push_str(&format!("{}Otherwise:\n", pad));
9457 for s in els.iter() {
9458 decompile_stmt(s, interner, out, indent + 1);
9459 }
9460 }
9461 }
9462 Stmt::While { cond, body, .. } => {
9463 let cond_str = decompile_expr(cond, interner);
9464 out.push_str(&format!("{}While {}:\n", pad, cond_str));
9465 for s in body.iter() {
9466 decompile_stmt(s, interner, out, indent + 1);
9467 }
9468 }
9469 Stmt::Call { function, args } => {
9470 let fn_name = interner.resolve(*function);
9471 let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
9472 if arg_strs.is_empty() {
9473 out.push_str(&format!("{}{}().\n", pad, fn_name));
9474 } else {
9475 out.push_str(&format!("{}{}({}).\n", pad, fn_name, arg_strs.join(", ")));
9476 }
9477 }
9478 Stmt::Push { value, collection } => {
9479 let val_str = decompile_expr(value, interner);
9480 let coll_str = decompile_expr(collection, interner);
9481 out.push_str(&format!("{}Push {} to {}.\n", pad, val_str, coll_str));
9482 }
9483 Stmt::SetIndex {
9484 collection,
9485 index,
9486 value,
9487 } => {
9488 let coll_str = decompile_expr(collection, interner);
9489 let idx_str = decompile_expr(index, interner);
9490 let val_str = decompile_expr(value, interner);
9491 out.push_str(&format!(
9492 "{}Set item {} of {} to {}.\n",
9493 pad, idx_str, coll_str, val_str
9494 ));
9495 }
9496 Stmt::SetField {
9497 object,
9498 field,
9499 value,
9500 } => {
9501 let obj_str = decompile_expr(object, interner);
9502 let field_name = interner.resolve(*field);
9503 let val_str = decompile_expr(value, interner);
9504 out.push_str(&format!(
9505 "{}Set {} of {} to {}.\n",
9506 pad, field_name, obj_str, val_str
9507 ));
9508 }
9509 Stmt::Repeat {
9510 pattern,
9511 iterable,
9512 body,
9513 ..
9514 } => {
9515 let var_name = match pattern {
9516 Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
9517 Pattern::Tuple(syms) => syms
9518 .iter()
9519 .map(|s| interner.resolve(*s).to_string())
9520 .collect::<Vec<_>>()
9521 .join(", "),
9522 };
9523 let iter_str = decompile_expr(iterable, interner);
9524 out.push_str(&format!(
9525 "{}Repeat for {} in {}:\n",
9526 pad, var_name, iter_str
9527 ));
9528 for s in body.iter() {
9529 decompile_stmt(s, interner, out, indent + 1);
9530 }
9531 }
9532 Stmt::Inspect { target, arms, .. } => {
9533 let target_str = decompile_expr(target, interner);
9534 out.push_str(&format!("{}Inspect {}:\n", pad, target_str));
9535 for arm in arms {
9536 if let Some(variant) = arm.variant {
9537 let variant_name = interner.resolve(variant);
9538 let bindings: Vec<String> = arm
9539 .bindings
9540 .iter()
9541 .map(|(_, b)| interner.resolve(*b).to_string())
9542 .collect();
9543 if bindings.is_empty() {
9544 out.push_str(&format!("{} When {}:\n", pad, variant_name));
9545 } else {
9546 out.push_str(&format!(
9547 "{} When {}({}):\n",
9548 pad,
9549 variant_name,
9550 bindings.join(", ")
9551 ));
9552 }
9553 } else {
9554 out.push_str(&format!("{} Otherwise:\n", pad));
9555 }
9556 for s in arm.body.iter() {
9557 decompile_stmt(s, interner, out, indent + 2);
9558 }
9559 }
9560 }
9561 Stmt::Pop { collection, into } => {
9562 let coll_str = decompile_expr(collection, interner);
9563 if let Some(target) = into {
9564 let target_name = interner.resolve(*target);
9565 out.push_str(&format!(
9566 "{}Pop from {} into {}.\n",
9567 pad, coll_str, target_name
9568 ));
9569 } else {
9570 out.push_str(&format!("{}Pop from {}.\n", pad, coll_str));
9571 }
9572 }
9573 Stmt::Break => {
9574 out.push_str(&format!("{}Break.\n", pad));
9575 }
9576 Stmt::RuntimeAssert {
9577 condition,
9578 hard,
9579 dim: _,
9580 reason,
9581 } => {
9582 let cond_str = decompile_expr(condition, interner);
9583 let kw = if *hard { "Require that" } else { "Assert that" };
9586 match reason {
9587 Some(r) => out.push_str(&format!(
9588 "{}{} {}, otherwise {}.\n",
9589 pad,
9590 kw,
9591 cond_str,
9592 decompile_expr(r, interner)
9593 )),
9594 None => out.push_str(&format!("{}{} {}.\n", pad, kw, cond_str)),
9595 }
9596 }
9597 Stmt::Fail { reason } => {
9598 out.push_str(&format!(
9599 "{}Fail with {}.\n",
9600 pad,
9601 decompile_expr(reason, interner)
9602 ));
9603 }
9604 Stmt::Add { value, collection } => {
9605 let val_str = decompile_expr(value, interner);
9606 let coll_str = decompile_expr(collection, interner);
9607 out.push_str(&format!("{}Add {} to {}.\n", pad, val_str, coll_str));
9608 }
9609 Stmt::Remove { value, collection } => {
9610 let val_str = decompile_expr(value, interner);
9611 let coll_str = decompile_expr(collection, interner);
9612 out.push_str(&format!("{}Remove {} from {}.\n", pad, val_str, coll_str));
9613 }
9614 Stmt::Zone { name, body, .. } => {
9615 let zone_name = interner.resolve(*name);
9616 out.push_str(&format!(
9617 "{}Inside a new zone called \"{}\":\n",
9618 pad, zone_name
9619 ));
9620 for s in body.iter() {
9621 decompile_stmt(s, interner, out, indent + 1);
9622 }
9623 }
9624 Stmt::ReadFrom { var, .. } => {
9625 let var_name = interner.resolve(*var);
9626 out.push_str(&format!("{}Read {} from the console.\n", pad, var_name));
9627 }
9628 Stmt::WriteFile { content, path } => {
9629 let content_str = decompile_expr(content, interner);
9630 let path_str = decompile_expr(path, interner);
9631 out.push_str(&format!(
9632 "{}Write {} to file {}.\n",
9633 pad, content_str, path_str
9634 ));
9635 }
9636 Stmt::Sleep { milliseconds } => {
9637 let ms = decompile_expr(milliseconds, interner);
9638 out.push_str(&format!("{}Sleep {}.\n", pad, ms));
9639 }
9640 Stmt::IncreaseCrdt {
9644 object,
9645 field,
9646 amount,
9647 } => {
9648 let obj = decompile_expr(object, interner);
9649 let fld = interner.resolve(*field);
9650 let amt = decompile_expr(amount, interner);
9651 out.push_str(&format!("{}Increase {}'s {} by {}.\n", pad, obj, fld, amt));
9652 }
9653 Stmt::DecreaseCrdt {
9654 object,
9655 field,
9656 amount,
9657 } => {
9658 let obj = decompile_expr(object, interner);
9659 let fld = interner.resolve(*field);
9660 let amt = decompile_expr(amount, interner);
9661 out.push_str(&format!("{}Decrease {}'s {} by {}.\n", pad, obj, fld, amt));
9662 }
9663 Stmt::MergeCrdt { source, target } => {
9664 let src = decompile_expr(source, interner);
9665 let tgt = decompile_expr(target, interner);
9666 out.push_str(&format!("{}Merge {} into {}.\n", pad, src, tgt));
9667 }
9668 Stmt::JoinCrdt { source, target } => {
9669 let src = decompile_expr(source, interner);
9670 let tgt = decompile_expr(target, interner);
9671 out.push_str(&format!("{}Converge {} into {}.\n", pad, src, tgt));
9672 }
9673 Stmt::AppendToSequence { sequence, value } => {
9674 let seq = decompile_expr(sequence, interner);
9675 let val = decompile_expr(value, interner);
9676 out.push_str(&format!("{}Append {} to {}.\n", pad, val, seq));
9677 }
9678 Stmt::ResolveConflict {
9679 object,
9680 field,
9681 value,
9682 } => {
9683 let obj = decompile_expr(object, interner);
9684 let fld = interner.resolve(*field);
9685 let val = decompile_expr(value, interner);
9686 out.push_str(&format!("{}Resolve {}'s {} to {}.\n", pad, obj, fld, val));
9687 }
9688 _ => {
9689 }
9692 }
9693}
9694
9695fn decompile_expr(expr: &Expr, interner: &Interner) -> String {
9696 match expr {
9697 Expr::Dom(q) => match q.selector() {
9698 Some(sel) => format!("the {} of {}", q.noun(), decompile_expr(sel, interner)),
9699 None => format!("the {}", q.noun()),
9700 },
9701 Expr::View(v) => decompile_view(v, interner),
9702 Expr::Literal(lit) => match lit {
9703 Literal::Number(n) => n.to_string(),
9704 Literal::Float(f) => format!("{}", f),
9705 Literal::Boolean(b) => {
9706 if *b {
9707 "true".to_string()
9708 } else {
9709 "false".to_string()
9710 }
9711 }
9712 Literal::Text(s) => format!("\"{}\"", interner.resolve(*s)),
9713 Literal::Nothing => "nothing".to_string(),
9714 Literal::Char(c) => format!("'{}'", c),
9715 Literal::Duration(ns) => format!("{}", ns),
9716 Literal::Date(days) => format!("{}", days),
9717 Literal::Moment(ns) => format!("{}", ns),
9718 Literal::Span { months, days } => format!("{} months {} days", months, days),
9719 Literal::Time(ns) => format!("{}", ns),
9720 },
9721 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
9722 Expr::BinaryOp { op, left, right } => {
9723 let l = if matches!(left, Expr::BinaryOp { .. }) {
9724 format!("({})", decompile_expr(left, interner))
9725 } else {
9726 decompile_expr(left, interner)
9727 };
9728 let r = if matches!(right, Expr::BinaryOp { .. }) {
9729 format!("({})", decompile_expr(right, interner))
9730 } else {
9731 decompile_expr(right, interner)
9732 };
9733 if matches!(op, BinaryOpKind::Shl) {
9736 if let Expr::Literal(Literal::Number(k)) = right {
9738 let multiplier = 1i64 << k;
9739 return format!("{} * {}", l, multiplier);
9740 }
9741 }
9742 if matches!(op, BinaryOpKind::Shr) {
9743 if let Expr::Literal(Literal::Number(k)) = right {
9745 let divisor = 1i64 << k;
9746 return format!("{} / {}", l, divisor);
9747 }
9748 }
9749 let op_str = match op {
9750 BinaryOpKind::Add => "+",
9751 BinaryOpKind::Subtract => "-",
9752 BinaryOpKind::Multiply => "*",
9753 BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
9754 BinaryOpKind::FloorDivide => "//",
9755 BinaryOpKind::Modulo => "%",
9756 BinaryOpKind::Eq => "equals",
9757 BinaryOpKind::NotEq => "is not",
9758 BinaryOpKind::Lt => "is less than",
9759 BinaryOpKind::Gt => "is greater than",
9760 BinaryOpKind::LtEq => "is at most",
9761 BinaryOpKind::GtEq => "is at least",
9762 BinaryOpKind::And => "and",
9763 BinaryOpKind::Or => "or",
9764 BinaryOpKind::Concat => "+",
9765 BinaryOpKind::SeqConcat => "followed by",
9766 BinaryOpKind::ApproxEq => "is approximately",
9767 BinaryOpKind::Pow => "**",
9768 BinaryOpKind::BitXor => "+",
9769 BinaryOpKind::BitAnd => "&",
9770 BinaryOpKind::BitOr => "|",
9771 BinaryOpKind::Shl => "*",
9772 BinaryOpKind::Shr => "/",
9773 };
9774 format!("{} {} {}", l, op_str, r)
9775 }
9776 Expr::Not { operand } => {
9777 let inner = decompile_expr(operand, interner);
9781 format!("not ({})", inner)
9782 }
9783 Expr::Call { function, args } => {
9784 let fn_name = interner.resolve(*function);
9785 let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
9786 if arg_strs.is_empty() {
9787 format!("{}()", fn_name)
9788 } else {
9789 format!("{}({})", fn_name, arg_strs.join(", "))
9790 }
9791 }
9792 Expr::Index { collection, index } => {
9793 let coll = decompile_expr(collection, interner);
9794 let idx = decompile_expr(index, interner);
9795 format!("item {} of {}", idx, coll)
9796 }
9797 Expr::Length { collection } => {
9798 let coll = decompile_expr(collection, interner);
9799 format!("length of {}", coll)
9800 }
9801 Expr::FieldAccess { object, field } => {
9802 let obj = decompile_expr(object, interner);
9803 let field_name = interner.resolve(*field);
9804 format!("{}'s {}", obj, field_name)
9808 }
9809 Expr::New {
9810 type_name,
9811 type_args,
9812 init_fields,
9813 } => {
9814 let name = interner.resolve(*type_name);
9815 let mut out = format!("a new {name}");
9816 if !type_args.is_empty() {
9817 let args: Vec<String> = type_args
9818 .iter()
9819 .map(|t| decompile_type_expr(t, interner))
9820 .collect();
9821 out.push_str(&format!(" of {}", args.join(generic_separator(name))));
9822 }
9823 if !init_fields.is_empty() {
9824 let fields: Vec<String> = init_fields
9825 .iter()
9826 .map(|(name, value)| {
9827 format!("{} {}", interner.resolve(*name), decompile_expr(value, interner))
9828 })
9829 .collect();
9830 out.push_str(&format!(" with {}", fields.join(" and ")));
9831 }
9832 out
9833 }
9834 Expr::NewVariant {
9835 variant, fields, ..
9836 } => {
9837 let vn = interner.resolve(*variant);
9838 if fields.is_empty() {
9839 format!("a new {}", vn)
9840 } else {
9841 let parts: Vec<String> = fields
9842 .iter()
9843 .map(|(name, val)| {
9844 let n = interner.resolve(*name);
9845 let v = decompile_expr(val, interner);
9846 format!("{} {}", n, v)
9847 })
9848 .collect();
9849 format!("a new {} with {}", vn, parts.join(" and "))
9850 }
9851 }
9852 Expr::InterpolatedString(parts) => {
9853 let mut result = String::new();
9854 for part in parts {
9855 match part {
9856 StringPart::Literal(sym) => {
9857 result.push_str(&interner.resolve(*sym));
9858 }
9859 StringPart::Expr { value, debug, .. } => {
9860 let expr_str = decompile_expr(value, interner);
9861 if *debug {
9862 result.push_str(&format!("{{{}=}}", expr_str));
9863 } else {
9864 result.push_str(&format!("{{{}}}", expr_str));
9865 }
9866 }
9867 }
9868 }
9869 format!("\"{}\"", result)
9870 }
9871 Expr::Slice {
9872 collection,
9873 start,
9874 end,
9875 } => {
9876 let coll = decompile_expr(collection, interner);
9877 let s = decompile_expr(start, interner);
9878 let e = decompile_expr(end, interner);
9879 format!("{} {} through {}", coll, s, e)
9880 }
9881 Expr::Copy { expr } => {
9882 let inner = decompile_expr(expr, interner);
9883 format!("copy of {}", inner)
9884 }
9885 Expr::Give { value } => {
9886 let inner = decompile_expr(value, interner);
9887 format!("Give {}", inner)
9888 }
9889 Expr::Contains { collection, value } => {
9890 let coll = decompile_expr(collection, interner);
9891 let val = decompile_expr(value, interner);
9892 format!("{} contains {}", coll, val)
9893 }
9894 Expr::Union { left, right } => {
9895 let l = decompile_expr(left, interner);
9896 let r = decompile_expr(right, interner);
9897 format!("{} union {}", l, r)
9898 }
9899 Expr::Intersection { left, right } => {
9900 let l = decompile_expr(left, interner);
9901 let r = decompile_expr(right, interner);
9902 format!("{} intersection {}", l, r)
9903 }
9904 Expr::List(elems) => {
9905 let parts: Vec<String> = elems.iter().map(|e| decompile_expr(e, interner)).collect();
9906 format!("[{}]", parts.join(", "))
9907 }
9908 Expr::Tuple(elems) => {
9909 let parts: Vec<String> = elems.iter().map(|e| decompile_expr(e, interner)).collect();
9910 format!("({})", parts.join(", "))
9911 }
9912 Expr::Range { start, end } => {
9913 let s = decompile_expr(start, interner);
9914 let e = decompile_expr(end, interner);
9915 format!("{} to {}", s, e)
9916 }
9917 Expr::OptionSome { value } => {
9918 let inner = decompile_expr(value, interner);
9919 format!("some {}", inner)
9920 }
9921 Expr::OptionNone => "none".to_string(),
9922 Expr::WithCapacity { value, capacity } => {
9923 let val = decompile_expr(value, interner);
9924 let cap = decompile_expr(capacity, interner);
9925 format!("{} with capacity {}", val, cap)
9926 }
9927 Expr::Escape { language, code } => {
9928 let lang = interner.resolve(*language);
9929 let src = interner.resolve(*code);
9930 format!("Escape to {}:\n{}", lang, src)
9931 }
9932 Expr::ManifestOf { zone } => {
9933 let z = decompile_expr(zone, interner);
9934 format!("the manifest of {}", z)
9935 }
9936 Expr::ChunkAt { index, zone } => {
9937 let idx = decompile_expr(index, interner);
9938 let z = decompile_expr(zone, interner);
9939 format!("the chunk at {} in {}", idx, z)
9940 }
9941 Expr::Closure {
9942 params,
9943 body,
9944 return_type,
9945 } => {
9946 let param_strs: Vec<String> = params
9947 .iter()
9948 .map(|(name, ty)| {
9949 let n = interner.resolve(*name);
9950 let t = decompile_type_expr(ty, interner);
9951 format!("{}: {}", n, t)
9952 })
9953 .collect();
9954 let ret = if let Some(rt) = return_type {
9955 format!(" -> {}", decompile_type_expr(rt, interner))
9956 } else {
9957 String::new()
9958 };
9959 match body {
9960 ClosureBody::Expression(expr) => {
9961 let e = decompile_expr(expr, interner);
9962 format!("({}){} -> {}", param_strs.join(", "), ret, e)
9963 }
9964 ClosureBody::Block(_) => {
9965 format!("({}){} -> [block]", param_strs.join(", "), ret)
9966 }
9967 }
9968 }
9969 Expr::CallExpr { callee, args } => {
9970 let c = decompile_expr(callee, interner);
9971 let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
9972 format!("{}({})", c, arg_strs.join(", "))
9973 }
9974 }
9975}
9976
9977fn generic_separator(base: &str) -> &'static str {
9980 match base {
9981 "Map" | "HashMap" | "SharedMap" | "ORMap" => " to ",
9982 _ => " and ",
9983 }
9984}
9985
9986fn decompile_type_expr(ty: &TypeExpr, interner: &Interner) -> String {
9987 match ty {
9988 TypeExpr::Primitive(sym) => interner.resolve(*sym).to_string(),
9989 TypeExpr::Named(sym) => interner.resolve(*sym).to_string(),
9990 TypeExpr::Generic { base, params } => {
9991 let base_str = interner.resolve(*base);
9992 let param_strs: Vec<String> = params
9993 .iter()
9994 .map(|p| decompile_type_expr(p, interner))
9995 .collect();
9996 format!("{} of {}", base_str, param_strs.join(generic_separator(base_str)))
9997 }
9998 TypeExpr::Tuple(params) => {
9999 let elems: Vec<String> = params
10000 .iter()
10001 .map(|p| decompile_type_expr(p, interner))
10002 .collect();
10003 format!("({})", elems.join(", "))
10004 }
10005 TypeExpr::Record {
10006 field_names,
10007 field_types,
10008 } => {
10009 let elems: Vec<String> = field_names
10010 .iter()
10011 .zip(field_types.iter())
10012 .map(|(n, t)| {
10013 format!(
10014 "{}: {}",
10015 interner.resolve(*n),
10016 decompile_type_expr(t, interner)
10017 )
10018 })
10019 .collect();
10020 format!("({})", elems.join(", "))
10021 }
10022 TypeExpr::Function { inputs, output } => {
10023 let in_strs: Vec<String> = inputs
10024 .iter()
10025 .map(|t| decompile_type_expr(t, interner))
10026 .collect();
10027 let out_str = decompile_type_expr(output, interner);
10028 format!("fn({}) -> {}", in_strs.join(", "), out_str)
10029 }
10030 TypeExpr::Refinement { base, .. } => decompile_type_expr(base, interner),
10031 TypeExpr::Persistent { inner } => {
10032 format!("Persistent {}", decompile_type_expr(inner, interner))
10033 }
10034 TypeExpr::Mutable { inner } => {
10035 format!("mutable {}", decompile_type_expr(inner, interner))
10036 }
10037 }
10038}
10039
10040pub fn verify_no_overhead_source(source: &str) -> Result<(), String> {
10047 let mut interner = Interner::new();
10048 let mut lexer = Lexer::new(source, &mut interner);
10049 let tokens = lexer.tokenize();
10050
10051 let type_registry = {
10052 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
10053 let result = discovery.run_full();
10054 result.types
10055 };
10056
10057 let mut world_state = WorldState::new();
10058 let expr_arena = Arena::new();
10059 let term_arena = Arena::new();
10060 let np_arena = Arena::new();
10061 let sym_arena = Arena::new();
10062 let role_arena = Arena::new();
10063 let pp_arena = Arena::new();
10064 let stmt_arena: Arena<Stmt> = Arena::new();
10065 let _compile_facts = crate::optimize::facts::scope();
10066 let imperative_expr_arena: Arena<Expr> = Arena::new();
10067 let type_expr_arena: Arena<TypeExpr> = Arena::new();
10068
10069 let ast_ctx = AstContext::with_types(
10070 &expr_arena,
10071 &term_arena,
10072 &np_arena,
10073 &sym_arena,
10074 &role_arena,
10075 &pp_arena,
10076 &stmt_arena,
10077 &imperative_expr_arena,
10078 &type_expr_arena,
10079 );
10080
10081 let mut parser = crate::parser::Parser::new(
10082 tokens,
10083 &mut world_state,
10084 &mut interner,
10085 ast_ctx,
10086 type_registry,
10087 );
10088 let stmts = parser
10089 .parse_program()
10090 .map_err(|e| format!("Parse error: {}", describe_parse_error(&e)))?;
10091
10092 verify_no_overhead_stmts(&stmts, &interner)
10093}
10094
10095const CORE_VARIANT_NAMES: &[&str] = &[
10096 "CInt",
10097 "CBool",
10098 "CText",
10099 "CVar",
10100 "CBinOp",
10101 "CNot",
10102 "CCall",
10103 "CIndex",
10104 "CLen",
10105 "CMapGet",
10106 "CLet",
10107 "CSet",
10108 "CIf",
10109 "CWhile",
10110 "CReturn",
10111 "CShow",
10112 "CCallS",
10113 "CPush",
10114 "CSetIdx",
10115 "CMapSet",
10116 "CFuncDef",
10117 "CProg",
10118 "CManifestOf",
10119 "CChunkAt",
10120 "VInt",
10121 "VBool",
10122 "VText",
10123 "VSeq",
10124 "VMap",
10125 "VError",
10126 "VNothing",
10127];
10128
10129const CORE_TYPE_NAMES: &[&str] = &[
10134 "CVal",
10135 "CExpr",
10136 "CStmt",
10137 "CFunc",
10138 "CFuncDef",
10139 "CProgram",
10140 "CProg",
10141 "CoreOut",
10142 "CoreOutR",
10143 "PEState",
10144 "PEStateR",
10145 "PEMiniState",
10146 "PEMiniR",
10147];
10148
10149fn verify_no_overhead_stmts(stmts: &[Stmt], interner: &Interner) -> Result<(), String> {
10150 for stmt in stmts {
10151 check_stmt_overhead(stmt, interner)?;
10152 }
10153 Ok(())
10154}
10155
10156fn check_stmt_overhead(stmt: &Stmt, interner: &Interner) -> Result<(), String> {
10157 match stmt {
10158 Stmt::Inspect { arms, .. } => {
10159 for arm in arms {
10160 if let Some(variant) = arm.variant {
10161 let variant_name = interner.resolve(variant);
10162 if CORE_VARIANT_NAMES.contains(&variant_name) {
10163 return Err(format!(
10164 "Interpretive overhead: Inspect dispatches on Core variant '{}'",
10165 variant_name
10166 ));
10167 }
10168 }
10169 for s in arm.body.iter() {
10170 check_stmt_overhead(s, interner)?;
10171 }
10172 }
10173 }
10174 Stmt::If {
10175 cond,
10176 then_block,
10177 else_block,
10178 } => {
10179 check_expr_overhead(cond, interner)?;
10180 for s in then_block.iter() {
10181 check_stmt_overhead(s, interner)?;
10182 }
10183 if let Some(els) = else_block {
10184 for s in els.iter() {
10185 check_stmt_overhead(s, interner)?;
10186 }
10187 }
10188 }
10189 Stmt::While { cond, body, .. } => {
10190 check_expr_overhead(cond, interner)?;
10191 for s in body.iter() {
10192 check_stmt_overhead(s, interner)?;
10193 }
10194 }
10195 Stmt::FunctionDef { body, .. } => {
10196 for s in body.iter() {
10197 check_stmt_overhead(s, interner)?;
10198 }
10199 }
10200 Stmt::Repeat { body, .. } => {
10201 for s in body.iter() {
10202 check_stmt_overhead(s, interner)?;
10203 }
10204 }
10205 Stmt::Let { value, .. } | Stmt::Set { value, .. } | Stmt::Show { object: value, .. } => {
10206 check_expr_overhead(value, interner)?;
10207 }
10208 Stmt::Return { value } => {
10209 if let Some(v) = value {
10210 check_expr_overhead(v, interner)?;
10211 }
10212 }
10213 _ => {}
10214 }
10215 Ok(())
10216}
10217
10218fn check_expr_overhead(expr: &Expr, interner: &Interner) -> Result<(), String> {
10219 match expr {
10220 Expr::Index { collection, index } => {
10221 if let Expr::Identifier(coll_sym) = collection {
10223 let coll_name = interner.resolve(*coll_sym);
10224 if coll_name == "env" {
10225 if let Expr::Literal(Literal::Text(_)) = index {
10226 return Err(
10227 "Interpretive overhead: environment lookup 'item ... of env' on literal key".to_string()
10228 );
10229 }
10230 }
10231 }
10232 check_expr_overhead(collection, interner)?;
10233 check_expr_overhead(index, interner)?;
10234 }
10235 Expr::New { type_name, .. } => {
10236 let tn = interner.resolve(*type_name);
10237 if CORE_VARIANT_NAMES.contains(&tn) {
10238 return Err(format!(
10239 "Interpretive overhead: Core type constructor 'new {}'",
10240 tn
10241 ));
10242 }
10243 }
10244 Expr::NewVariant { variant, .. } => {
10245 let vn = interner.resolve(*variant);
10246 if CORE_VARIANT_NAMES.contains(&vn) {
10247 return Err(format!(
10248 "Interpretive overhead: Core variant constructor '{}'",
10249 vn
10250 ));
10251 }
10252 }
10253 Expr::Call { function, args } => {
10254 let fn_name = interner.resolve(*function);
10255 if CORE_VARIANT_NAMES.contains(&fn_name) {
10256 return Err(format!(
10257 "Interpretive overhead: Core variant call '{}'",
10258 fn_name
10259 ));
10260 }
10261 for a in args {
10262 check_expr_overhead(a, interner)?;
10263 }
10264 }
10265 Expr::BinaryOp { left, right, .. } => {
10266 check_expr_overhead(left, interner)?;
10267 check_expr_overhead(right, interner)?;
10268 }
10269 Expr::Not { operand } => {
10270 check_expr_overhead(operand, interner)?;
10271 }
10272 Expr::Length { collection } => {
10273 check_expr_overhead(collection, interner)?;
10274 }
10275 Expr::FieldAccess { object, .. } => {
10276 check_expr_overhead(object, interner)?;
10277 }
10278 _ => {}
10279 }
10280 Ok(())
10281}
10282
10283const DISPATCH_FN_NAMES: &[&str] = &[
10287 "peExpr",
10288 "peBlock",
10289 "coreEval",
10290 "coreExecBlock",
10291 "applyBinOp",
10292];
10293
10294pub fn count_dispatch(source: &str) -> usize {
10307 let mut interner = Interner::new();
10308 let mut lexer = Lexer::new(source, &mut interner);
10309 let tokens = lexer.tokenize();
10310
10311 let type_registry = {
10312 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
10313 let result = discovery.run_full();
10314 result.types
10315 };
10316
10317 let mut world_state = WorldState::new();
10318 let expr_arena = Arena::new();
10319 let term_arena = Arena::new();
10320 let np_arena = Arena::new();
10321 let sym_arena = Arena::new();
10322 let role_arena = Arena::new();
10323 let pp_arena = Arena::new();
10324 let stmt_arena: Arena<Stmt> = Arena::new();
10325 let _compile_facts = crate::optimize::facts::scope();
10326 let imperative_expr_arena: Arena<Expr> = Arena::new();
10327 let type_expr_arena: Arena<TypeExpr> = Arena::new();
10328
10329 let ast_ctx = AstContext::with_types(
10330 &expr_arena,
10331 &term_arena,
10332 &np_arena,
10333 &sym_arena,
10334 &role_arena,
10335 &pp_arena,
10336 &stmt_arena,
10337 &imperative_expr_arena,
10338 &type_expr_arena,
10339 );
10340
10341 let mut parser = crate::parser::Parser::new(
10342 tokens,
10343 &mut world_state,
10344 &mut interner,
10345 ast_ctx,
10346 type_registry,
10347 );
10348 let stmts = match parser.parse_program() {
10349 Ok(s) => s,
10350 Err(_) => return usize::MAX,
10353 };
10354
10355 let mut count = 0usize;
10356 for stmt in &stmts {
10357 count_stmt_dispatch(stmt, &interner, &mut count);
10358 }
10359 count
10360}
10361
10362fn count_block_dispatch(block: &[Stmt], interner: &Interner, count: &mut usize) {
10363 for s in block {
10364 count_stmt_dispatch(s, interner, count);
10365 }
10366}
10367
10368fn decompile_params(
10372 params: &[(logicaffeine_base::Symbol, &TypeExpr)],
10373 interner: &Interner,
10374) -> String {
10375 params
10376 .iter()
10377 .map(|(n, t)| {
10378 format!(
10379 "({}: {})",
10380 interner.resolve(*n),
10381 decompile_type_expr(t, interner)
10382 )
10383 })
10384 .collect::<Vec<_>>()
10385 .join(" and ")
10386}
10387
10388fn decompile_component(
10393 def: &logicaffeine_language::ast::component::ComponentDef,
10394 interner: &Interner,
10395 out: &mut String,
10396) {
10397 use logicaffeine_language::ast::component::{ComponentKind, StoreMode, Trigger};
10398 let props = decompile_params(&def.props, interner);
10399 match &def.kind {
10400 ComponentKind::Component => out.push_str(&format!(
10401 "## Component {}{}\n",
10402 interner.resolve(def.name),
10403 if props.is_empty() {
10404 String::new()
10405 } else {
10406 format!(" {props}")
10407 }
10408 )),
10409 ComponentKind::Page { path, params } => {
10410 let ps = decompile_params(params, interner);
10411 out.push_str(&format!(
10412 "## Page {}{}\n",
10413 interner.resolve(*path),
10414 if ps.is_empty() {
10415 String::new()
10416 } else {
10417 format!(" {ps}")
10418 }
10419 ));
10420 }
10421 ComponentKind::Store { mode } => {
10422 let tail = match mode {
10423 StoreMode::Local => String::new(),
10424 StoreMode::Persisted { key } => {
10425 format!(" persisted as {}", decompile_expr(key, interner))
10426 }
10427 StoreMode::Shared { topic } => {
10428 format!(" shared on {}", decompile_expr(topic, interner))
10429 }
10430 StoreMode::Preserved => " preserved across reloads".to_string(),
10431 };
10432 out.push_str(&format!(
10433 "## Store {}{}\n",
10434 interner.resolve(def.name),
10435 tail
10436 ));
10437 }
10438 ComponentKind::ErrorPage { status } => out.push_str(&format!("## Error page {status}\n")),
10439 }
10440 for u in &def.uses {
10441 out.push_str(&format!("Use {}.\n", interner.resolve(*u)));
10442 }
10443 if !def.state.is_empty() {
10444 out.push_str("State:\n");
10445 for f in &def.state {
10446 let ty =
10447 f.ty.map(|t| format!(": {}", decompile_type_expr(t, interner)))
10448 .unwrap_or_default();
10449 let verb = if f.derived { "always be" } else { "be" };
10450 out.push_str(&format!(
10451 " Let {}{} {} {}.\n",
10452 interner.resolve(f.name),
10453 ty,
10454 verb,
10455 decompile_expr(f.init, interner)
10456 ));
10457 }
10458 }
10459 if !def.events.is_empty() || !def.actions.is_empty() {
10460 out.push_str("Actions:\n");
10461 for ev in &def.events {
10462 let head = match &ev.trigger {
10463 Trigger::PageLoads => "When the page loads".to_string(),
10464 Trigger::Appears => "When this component appears".to_string(),
10465 Trigger::Disappears => "When this component disappears".to_string(),
10466 Trigger::RouteChanges => "When the route changes".to_string(),
10467 Trigger::Online => "When the app comes back online".to_string(),
10468 Trigger::Offline => "When the app goes offline".to_string(),
10469 Trigger::Selector {
10470 selector,
10471 event,
10472 key: None,
10473 } => format!(
10474 "When {} is {}",
10475 decompile_expr(selector, interner),
10476 interner.resolve(*event)
10477 ),
10478 Trigger::Selector {
10479 selector,
10480 event: _,
10481 key: Some(k),
10482 } => format!(
10483 "When the user presses {} in {}",
10484 interner.resolve(*k),
10485 decompile_expr(selector, interner)
10486 ),
10487 Trigger::Key { key } => format!("When the user presses {}", interner.resolve(*key)),
10488 Trigger::FieldChanges { store: None, field } => {
10489 format!("When {} changes", interner.resolve(*field))
10490 }
10491 Trigger::FieldChanges {
10492 store: Some(st),
10493 field,
10494 } => format!(
10495 "When {}'s {} changes",
10496 interner.resolve(*st),
10497 interner.resolve(*field)
10498 ),
10499 Trigger::Every {
10500 seconds,
10501 name: None,
10502 } => format!("Every {} seconds", decompile_expr(seconds, interner)),
10503 Trigger::Every {
10504 seconds,
10505 name: Some(n),
10506 } => format!(
10507 "Every {} seconds as {}",
10508 decompile_expr(seconds, interner),
10509 interner.resolve(*n)
10510 ),
10511 Trigger::After {
10512 seconds,
10513 name: None,
10514 } => format!("After {} seconds", decompile_expr(seconds, interner)),
10515 Trigger::After {
10516 seconds,
10517 name: Some(n),
10518 } => format!(
10519 "After {} seconds as {}",
10520 decompile_expr(seconds, interner),
10521 interner.resolve(*n)
10522 ),
10523 Trigger::Message { topic, param } => format!(
10524 "When a message arrives on {} ({}: {})",
10525 decompile_expr(topic, interner),
10526 interner.resolve(param.0),
10527 decompile_type_expr(param.1, interner)
10528 ),
10529 Trigger::ActionFails { param } => {
10530 format!("When an action fails ({}: Text)", interner.resolve(*param))
10531 }
10532 Trigger::FetchFails { url, error } => format!(
10533 "When a fetch fails ({}: Text) and ({}: Text)",
10534 interner.resolve(*url),
10535 interner.resolve(*error)
10536 ),
10537 Trigger::WindowResizes => "When the window resizes".to_string(),
10538 Trigger::ScrollsToBottom { selector: None } => {
10539 "When the user scrolls to the bottom".to_string()
10540 }
10541 Trigger::ScrollsToBottom {
10542 selector: Some(sel),
10543 } => format!(
10544 "When the user scrolls to the bottom of {}",
10545 decompile_expr(sel, interner)
10546 ),
10547 Trigger::FileDropped { selector, param } => format!(
10548 "When a file is dropped on {} ({}: {})",
10549 decompile_expr(selector, interner),
10550 interner.resolve(param.0),
10551 decompile_type_expr(param.1, interner)
10552 ),
10553 };
10554 out.push_str(&format!(" {head}:\n"));
10555 for inner in ev.body.iter() {
10556 decompile_stmt(inner, interner, out, 2);
10557 }
10558 }
10559 for a in &def.actions {
10560 let ps = decompile_params(&a.params, interner);
10561 out.push_str(&format!(
10562 " To {}{}:\n",
10563 interner.resolve(a.name),
10564 if ps.is_empty() {
10565 String::new()
10566 } else {
10567 format!(" {ps}")
10568 }
10569 ));
10570 for inner in a.body.iter() {
10571 decompile_stmt(inner, interner, out, 2);
10572 }
10573 }
10574 }
10575 if let Some(view) = &def.view {
10576 out.push_str("View:\n");
10577 for line in decompile_view(view, interner).lines() {
10578 out.push_str(&format!(" {line}\n"));
10579 }
10580 }
10581 if let Some(style) = &def.style {
10582 out.push_str("Style:\n");
10583 for line in interner.resolve(style.css).lines() {
10584 out.push_str(&format!(" {line}\n"));
10585 }
10586 }
10587}
10588
10589fn decompile_view(view: &logicaffeine_language::ast::view::ViewDef, interner: &Interner) -> String {
10591 use logicaffeine_language::ast::view::{Attr, ViewNode};
10592 fn esc(s: &str, out: &mut String) {
10593 for c in s.chars() {
10594 match c {
10595 '&' => out.push_str("&"),
10596 '<' => out.push_str("<"),
10597 '>' => out.push_str(">"),
10598 '{' => out.push_str("{"),
10599 '}' => out.push_str("}"),
10600 _ => out.push(c),
10601 }
10602 }
10603 }
10604 fn go(nodes: &[ViewNode], interner: &Interner, out: &mut String) {
10605 for n in nodes {
10606 match n {
10607 ViewNode::Element {
10608 tag,
10609 attrs,
10610 children,
10611 ..
10612 } => {
10613 out.push('<');
10614 out.push_str(interner.resolve(*tag));
10615 for a in attrs {
10616 match a {
10617 Attr::Plain { name, value } => {
10618 out.push(' ');
10619 out.push_str(interner.resolve(*name));
10620 out.push_str("={");
10621 out.push_str(&decompile_expr(value, interner));
10622 out.push('}');
10623 }
10624 Attr::Bind { field } => {
10625 out.push_str(" bind={");
10626 out.push_str(interner.resolve(*field));
10627 out.push('}');
10628 }
10629 Attr::Class { name, cond } => {
10630 out.push_str(&format!(
10631 " class:{}={{{}}}",
10632 interner.resolve(*name),
10633 decompile_expr(cond, interner)
10634 ));
10635 }
10636 Attr::Directive { name, value } => {
10637 out.push_str(&format!(
10638 " {}={{{}}}",
10639 interner.resolve(*name),
10640 decompile_expr(value, interner)
10641 ));
10642 }
10643 }
10644 }
10645 out.push('>');
10646 if logicaffeine_language::lgx::html::is_void(interner.resolve(*tag)) {
10647 continue;
10648 }
10649 go(children, interner, out);
10650 out.push_str("</");
10651 out.push_str(interner.resolve(*tag));
10652 out.push('>');
10653 }
10654 ViewNode::Text { text, .. } => {
10655 out.push('{');
10656 out.push_str(&decompile_expr(text, interner));
10657 out.push('}');
10658 }
10659 ViewNode::Component {
10660 name,
10661 props,
10662 children,
10663 ..
10664 } => {
10665 out.push('<');
10666 out.push_str(interner.resolve(*name));
10667 for (k, v) in props {
10668 out.push(' ');
10669 out.push_str(interner.resolve(*k));
10670 out.push_str("={");
10671 out.push_str(&decompile_expr(v, interner));
10672 out.push('}');
10673 }
10674 if children.is_empty() {
10675 out.push_str("/>");
10676 } else {
10677 out.push('>');
10678 go(children, interner, out);
10679 out.push_str("</");
10680 out.push_str(interner.resolve(*name));
10681 out.push('>');
10682 }
10683 }
10684 ViewNode::Each {
10685 pattern,
10686 iterable,
10687 key,
10688 index,
10689 body,
10690 empty,
10691 ..
10692 } => {
10693 let pat = match pattern {
10694 logicaffeine_language::ast::stmt::Pattern::Identifier(s) => {
10695 interner.resolve(*s).to_string()
10696 }
10697 logicaffeine_language::ast::stmt::Pattern::Tuple(items) => format!(
10698 "({})",
10699 items
10700 .iter()
10701 .map(|s| interner.resolve(*s))
10702 .collect::<Vec<_>>()
10703 .join(", ")
10704 ),
10705 };
10706 out.push_str(&format!(
10707 "{{for each {pat} in {}",
10708 decompile_expr(iterable, interner)
10709 ));
10710 if let Some(k) = key {
10711 out.push_str(&format!(", keyed by {}", decompile_expr(k, interner)));
10712 }
10713 if let Some(i) = index {
10714 out.push_str(&format!(", at index {}", interner.resolve(*i)));
10715 }
10716 out.push_str(":}");
10717 go(body, interner, out);
10718 if !empty.is_empty() {
10719 out.push_str("{else:}");
10720 go(empty, interner, out);
10721 }
10722 out.push_str("{end}");
10723 }
10724 ViewNode::If {
10725 arms, otherwise, ..
10726 } => {
10727 for (i, (c, b)) in arms.iter().enumerate() {
10728 out.push_str(if i == 0 { "{if " } else { "{else if " });
10729 out.push_str(&decompile_expr(c, interner));
10730 out.push_str(":}");
10731 go(b, interner, out);
10732 }
10733 if let Some(o) = otherwise {
10734 out.push_str("{else:}");
10735 go(o, interner, out);
10736 }
10737 out.push_str("{end}");
10738 }
10739 ViewNode::Handler {
10740 event,
10741 modifiers,
10742 body,
10743 ..
10744 } => {
10745 let _ = modifiers;
10746 out.push_str(&format!(
10749 "{{# on {}: {} statement(s) #}}",
10750 interner.resolve(*event),
10751 body.len()
10752 ));
10753 }
10754 ViewNode::Raw { html, .. } => {
10755 out.push_str("{raw ");
10756 out.push_str(&decompile_expr(html, interner));
10757 out.push('}');
10758 }
10759 ViewNode::Inspect {
10760 scrutinee, arms, ..
10761 } => {
10762 out.push_str(&format!(
10763 "{{inspect {}:}}",
10764 decompile_expr(scrutinee, interner)
10765 ));
10766 for arm in arms {
10767 let head = match arm.variant {
10768 None => "Otherwise".to_string(),
10769 Some(v) => {
10770 let bs: Vec<&str> = arm
10771 .bindings
10772 .iter()
10773 .map(|(_, b)| interner.resolve(*b))
10774 .collect();
10775 if bs.is_empty() {
10776 interner.resolve(v).to_string()
10777 } else {
10778 format!("{} ({})", interner.resolve(v), bs.join(", "))
10779 }
10780 }
10781 };
10782 out.push_str(&format!("{{when {head}:}}"));
10783 go(&arm.body, interner, out);
10784 }
10785 out.push_str("{end}");
10786 }
10787 ViewNode::Let { var, value, .. } => {
10788 out.push_str(&format!(
10789 "{{let {} be {}}}",
10790 interner.resolve(*var),
10791 decompile_expr(value, interner)
10792 ));
10793 }
10794 ViewNode::Extends { layout, .. } => {
10795 out.push_str(&format!("{{extends {}}}", interner.resolve(*layout)));
10796 }
10797 ViewNode::Block { name, default, .. } => match default {
10798 None => out.push_str(&format!("{{block {}}}", interner.resolve(*name))),
10799 Some(d) => {
10800 out.push_str(&format!("{{block {}:}}", interner.resolve(*name)));
10801 go(d, interner, out);
10802 out.push_str("{end}");
10803 }
10804 },
10805 ViewNode::Children { .. } => out.push_str("{children}"),
10806 }
10807 }
10808 }
10809 let mut out = String::new();
10810 go(&view.nodes, interner, &mut out);
10811 out
10812}
10813
10814fn type_expr_mentions_core(t: &TypeExpr, interner: &Interner) -> bool {
10815 let is_core = |s| {
10816 let n = interner.resolve(s);
10817 CORE_TYPE_NAMES.contains(&n) || CORE_VARIANT_NAMES.contains(&n)
10818 };
10819 match t {
10820 TypeExpr::Primitive(s) | TypeExpr::Named(s) => is_core(*s),
10821 TypeExpr::Generic { base, params } => {
10822 is_core(*base) || params.iter().any(|p| type_expr_mentions_core(p, interner))
10823 }
10824 TypeExpr::Tuple(params) => params.iter().any(|p| type_expr_mentions_core(p, interner)),
10825 TypeExpr::Record { field_types, .. } => field_types
10826 .iter()
10827 .any(|p| type_expr_mentions_core(p, interner)),
10828 TypeExpr::Function { inputs, output } => {
10829 inputs.iter().any(|p| type_expr_mentions_core(p, interner))
10830 || type_expr_mentions_core(output, interner)
10831 }
10832 TypeExpr::Refinement { base, .. } => type_expr_mentions_core(base, interner),
10833 TypeExpr::Persistent { inner } | TypeExpr::Mutable { inner } => {
10834 type_expr_mentions_core(inner, interner)
10835 }
10836 }
10837}
10838
10839fn count_escape_code_dispatch(text: &str, count: &mut usize) {
10843 for word in text.split(|c: char| !c.is_alphanumeric() && c != '_') {
10844 if !word.is_empty()
10845 && (CORE_VARIANT_NAMES.contains(&word) || DISPATCH_FN_NAMES.contains(&word))
10846 {
10847 *count += 1;
10848 }
10849 }
10850}
10851
10852fn count_stmt_dispatch(stmt: &Stmt, interner: &Interner, count: &mut usize) {
10856 match stmt {
10857 Stmt::ComponentDef(def) => {
10858 for f in &def.state {
10859 count_expr_dispatch(f.init, interner, count);
10860 }
10861 for ev in &def.events {
10862 for inner in ev.body.iter() {
10863 count_stmt_dispatch(inner, interner, count);
10864 }
10865 }
10866 for a in &def.actions {
10867 for inner in a.body.iter() {
10868 count_stmt_dispatch(inner, interner, count);
10869 }
10870 }
10871 if let Some(view) = &def.view {
10872 let (view_exprs, view_blocks) = view.exprs_and_blocks();
10873 for e in view_exprs {
10874 count_expr_dispatch(e, interner, count);
10875 }
10876 for b in view_blocks {
10877 for inner in b.iter() {
10878 count_stmt_dispatch(inner, interner, count);
10879 }
10880 }
10881 }
10882 }
10883 Stmt::DirectiveDef { body, removed, .. } => {
10884 for inner in body.iter() {
10885 count_stmt_dispatch(inner, interner, count);
10886 }
10887 if let Some(r) = removed {
10888 for inner in r.iter() {
10889 count_stmt_dispatch(inner, interner, count);
10890 }
10891 }
10892 }
10893 Stmt::RouteDef { body, .. } => match &**body {
10894 logicaffeine_language::ast::component::RouteBody::Statements(b) => {
10895 for inner in b.iter() {
10896 count_stmt_dispatch(inner, interner, count);
10897 }
10898 }
10899 logicaffeine_language::ast::component::RouteBody::View(view) => {
10900 let (view_exprs, view_blocks) = view.exprs_and_blocks();
10901 for e in view_exprs {
10902 count_expr_dispatch(e, interner, count);
10903 }
10904 for b in view_blocks {
10905 for inner in b.iter() {
10906 count_stmt_dispatch(inner, interner, count);
10907 }
10908 }
10909 }
10910 },
10911 Stmt::MiddlewareDef { body, .. } => {
10912 for inner in body.iter() {
10913 count_stmt_dispatch(inner, interner, count);
10914 }
10915 }
10916 Stmt::RedirectDef { .. } => {}
10917 Stmt::ServeFetches | Stmt::Replay { .. } => {}
10918 Stmt::GivenFetch { url, status, body, .. } => {
10919 count_expr_dispatch(url, interner, count);
10920 count_expr_dispatch(status, interner, count);
10921 count_expr_dispatch(body, interner, count);
10922 }
10923 Stmt::Fetch { url, body, .. } => {
10924 count_expr_dispatch(url, interner, count);
10925 if let Some(b) = body {
10926 count_expr_dispatch(b, interner, count);
10927 }
10928 }
10929 Stmt::Ui(u) => {
10930 for x in u.exprs() {
10931 count_expr_dispatch(x, interner, count);
10932 }
10933 }
10934 Stmt::Splice { body } | Stmt::Reversibly { body } => {
10935 for inner in body.iter() {
10936 count_stmt_dispatch(inner, interner, count);
10937 }
10938 }
10939 Stmt::Let { value, ty, .. } => {
10940 if let Some(t) = ty {
10941 if type_expr_mentions_core(t, interner) {
10942 *count += 1;
10943 }
10944 }
10945 count_expr_dispatch(value, interner, count);
10946 }
10947 Stmt::Set { value, .. } => count_expr_dispatch(value, interner, count),
10948 Stmt::Swap { .. } => {}
10950 Stmt::Call { function, args } => {
10951 let fn_name = interner.resolve(*function);
10952 if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
10953 *count += 1;
10954 }
10955 for a in args {
10956 count_expr_dispatch(a, interner, count);
10957 }
10958 }
10959 Stmt::If { cond, then_block, else_block } => {
10960 count_expr_dispatch(cond, interner, count);
10961 count_block_dispatch(then_block, interner, count);
10962 if let Some(els) = else_block {
10963 count_block_dispatch(els, interner, count);
10964 }
10965 }
10966 Stmt::While { cond, body, decreasing } => {
10967 count_expr_dispatch(cond, interner, count);
10968 count_block_dispatch(body, interner, count);
10969 if let Some(d) = decreasing {
10970 count_expr_dispatch(d, interner, count);
10971 }
10972 }
10973 Stmt::Repeat { iterable, body, .. } => {
10974 count_expr_dispatch(iterable, interner, count);
10975 count_block_dispatch(body, interner, count);
10976 }
10977 Stmt::Return { value } => {
10978 if let Some(v) = value {
10979 count_expr_dispatch(v, interner, count);
10980 }
10981 }
10982 Stmt::RuntimeAssert { condition, reason, .. } => {
10983 count_expr_dispatch(condition, interner, count);
10984 if let Some(r) = reason {
10985 count_expr_dispatch(r, interner, count);
10986 }
10987 }
10988 Stmt::Fail { reason } => count_expr_dispatch(reason, interner, count),
10989 Stmt::Give { object, recipient } | Stmt::Show { object, recipient } => {
10990 count_expr_dispatch(object, interner, count);
10991 count_expr_dispatch(recipient, interner, count);
10992 }
10993 Stmt::SetField { object, value, .. } => {
10994 count_expr_dispatch(object, interner, count);
10995 count_expr_dispatch(value, interner, count);
10996 }
10997 Stmt::FunctionDef { body, .. } => count_block_dispatch(body, interner, count),
10998 Stmt::TestDef { body, .. } => count_block_dispatch(body, interner, count),
10999 Stmt::During { body, .. } => count_block_dispatch(body, interner, count),
11000 Stmt::ForAll { body, constraint, .. } => {
11001 if let Some(c) = constraint {
11002 count_expr_dispatch(c, interner, count);
11003 }
11004 count_block_dispatch(body, interner, count);
11005 }
11006 Stmt::Observe { payloads, .. } => {
11007 for (_, e) in payloads {
11008 count_expr_dispatch(e, interner, count);
11009 }
11010 }
11011 Stmt::Expect { condition } => count_expr_dispatch(condition, interner, count),
11012 Stmt::ExpectFail { body, .. } => count_block_dispatch(body, interner, count),
11013 Stmt::ExpectOutput { .. } | Stmt::GivenFile { .. } => {}
11014 Stmt::AdvanceTime { millis } => count_expr_dispatch(millis, interner, count),
11015 Stmt::Inspect { target, arms, .. } => {
11016 count_expr_dispatch(target, interner, count);
11017 for arm in arms {
11018 if let Some(variant) = arm.variant {
11019 if CORE_VARIANT_NAMES.contains(&interner.resolve(variant)) {
11020 *count += 1;
11021 }
11022 }
11023 count_block_dispatch(arm.body, interner, count);
11024 }
11025 }
11026 Stmt::Push { value, collection }
11027 | Stmt::Add { value, collection }
11028 | Stmt::Remove { value, collection } => {
11029 count_expr_dispatch(value, interner, count);
11030 count_expr_dispatch(collection, interner, count);
11031 }
11032 Stmt::Pop { collection, .. } => count_expr_dispatch(collection, interner, count),
11033 Stmt::SetIndex { collection, index, value } => {
11034 count_expr_dispatch(collection, interner, count);
11035 count_expr_dispatch(index, interner, count);
11036 count_expr_dispatch(value, interner, count);
11037 }
11038 Stmt::Zone { body, .. } => count_block_dispatch(body, interner, count),
11039 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
11040 count_block_dispatch(tasks, interner, count)
11041 }
11042 Stmt::ReadFrom { source, .. } => {
11043 if let ReadSource::File(path) = source {
11044 count_expr_dispatch(path, interner, count);
11045 }
11046 }
11047 Stmt::WriteFile { content, path } => {
11048 count_expr_dispatch(content, interner, count);
11049 count_expr_dispatch(path, interner, count);
11050 }
11051 Stmt::SendMessage { message, destination, .. } => {
11052 count_expr_dispatch(message, interner, count);
11053 count_expr_dispatch(destination, interner, count);
11054 }
11055 Stmt::AwaitMessage { source, .. } => count_expr_dispatch(source, interner, count),
11056 Stmt::StreamMessage { values, destination } => {
11057 count_expr_dispatch(values, interner, count);
11058 count_expr_dispatch(destination, interner, count);
11059 }
11060 Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
11061 count_expr_dispatch(source, interner, count);
11062 count_expr_dispatch(target, interner, count);
11063 }
11064 Stmt::IncreaseCrdt { object, amount, .. } | Stmt::DecreaseCrdt { object, amount, .. } => {
11065 count_expr_dispatch(object, interner, count);
11066 count_expr_dispatch(amount, interner, count);
11067 }
11068 Stmt::AppendToSequence { sequence, value } => {
11069 count_expr_dispatch(sequence, interner, count);
11070 count_expr_dispatch(value, interner, count);
11071 }
11072 Stmt::ResolveConflict { object, value, .. } => {
11073 count_expr_dispatch(object, interner, count);
11074 count_expr_dispatch(value, interner, count);
11075 }
11076 Stmt::Listen { address, .. } | Stmt::ConnectTo { address, .. } | Stmt::LetPeerAgent { address, .. } => {
11077 count_expr_dispatch(address, interner, count)
11078 }
11079 Stmt::Serve { port, handler } => {
11080 count_expr_dispatch(port, interner, count);
11081 count_expr_dispatch(handler, interner, count);
11082 }
11083 Stmt::Sleep { milliseconds } => count_expr_dispatch(milliseconds, interner, count),
11084 Stmt::Sync { topic, .. } => count_expr_dispatch(topic, interner, count),
11085 Stmt::Mount { path, .. } => count_expr_dispatch(path, interner, count),
11086 Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
11087 let fn_name = interner.resolve(*function);
11088 if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
11089 *count += 1;
11090 }
11091 for a in args {
11092 count_expr_dispatch(a, interner, count);
11093 }
11094 }
11095 Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
11096 count_expr_dispatch(value, interner, count);
11097 count_expr_dispatch(pipe, interner, count);
11098 }
11099 Stmt::ReceivePipe { pipe, .. } | Stmt::TryReceivePipe { pipe, .. } => {
11100 count_expr_dispatch(pipe, interner, count)
11101 }
11102 Stmt::StopTask { handle } => count_expr_dispatch(handle, interner, count),
11103 Stmt::CloseChannel { channel } => count_expr_dispatch(channel, interner, count),
11104 Stmt::AwaitTask { handle, .. } => count_expr_dispatch(handle, interner, count),
11105 Stmt::Select { branches } => {
11106 for b in branches {
11107 match b {
11108 SelectBranch::Receive { pipe, body, .. } => {
11109 count_expr_dispatch(pipe, interner, count);
11110 count_block_dispatch(body, interner, count);
11111 }
11112 SelectBranch::Timeout { milliseconds, body } => {
11113 count_expr_dispatch(milliseconds, interner, count);
11114 count_block_dispatch(body, interner, count);
11115 }
11116 }
11117 }
11118 }
11119 Stmt::Escape { code, .. } => count_escape_code_dispatch(interner.resolve(*code), count),
11120 Stmt::Break
11123 | Stmt::Assert { .. }
11124 | Stmt::Trust { .. }
11125 | Stmt::StructDef { .. }
11126 | Stmt::Spawn { .. }
11127 | Stmt::Check { .. }
11128 | Stmt::CreatePipe { .. }
11129 | Stmt::Theorem(_)
11130 | Stmt::Definition(_)
11131 | Stmt::Axiom(_)
11132 | Stmt::Theory(_)
11133 | Stmt::Require { .. }
11134 | Stmt::Site(_) => {}
11137 }
11138}
11139
11140fn count_expr_dispatch(expr: &Expr, interner: &Interner, count: &mut usize) {
11144 match expr {
11145 Expr::Dom(q) => {
11146 if let Some(sel) = q.selector() {
11147 count_expr_dispatch(sel, interner, count);
11148 }
11149 }
11150 Expr::View(v) => {
11151 let (view_exprs, view_blocks) = v.exprs_and_blocks();
11152 for e in view_exprs {
11153 count_expr_dispatch(e, interner, count);
11154 }
11155 for b in view_blocks {
11156 for inner in b.iter() {
11157 count_stmt_dispatch(inner, interner, count);
11158 }
11159 }
11160 }
11161 Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone => {}
11162 Expr::BinaryOp { left, right, .. }
11163 | Expr::Union { left, right }
11164 | Expr::Intersection { left, right } => {
11165 count_expr_dispatch(left, interner, count);
11166 count_expr_dispatch(right, interner, count);
11167 }
11168 Expr::Not { operand } => count_expr_dispatch(operand, interner, count),
11169 Expr::Call { function, args } => {
11170 let fn_name = interner.resolve(*function);
11171 if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
11172 *count += 1;
11173 }
11174 for a in args {
11175 count_expr_dispatch(a, interner, count);
11176 }
11177 }
11178 Expr::Index { collection, index } => {
11179 if let Expr::Identifier(coll_sym) = collection {
11182 let coll_name = interner.resolve(*coll_sym);
11183 if coll_name == "env" || coll_name == "funcs" {
11184 *count += 1;
11185 }
11186 }
11187 count_expr_dispatch(collection, interner, count);
11188 count_expr_dispatch(index, interner, count);
11189 }
11190 Expr::Slice {
11191 collection,
11192 start,
11193 end,
11194 } => {
11195 count_expr_dispatch(collection, interner, count);
11196 count_expr_dispatch(start, interner, count);
11197 count_expr_dispatch(end, interner, count);
11198 }
11199 Expr::Copy { expr: inner } => count_expr_dispatch(inner, interner, count),
11200 Expr::Give { value } => count_expr_dispatch(value, interner, count),
11201 Expr::Length { collection } => count_expr_dispatch(collection, interner, count),
11202 Expr::Contains { collection, value } => {
11203 count_expr_dispatch(collection, interner, count);
11204 count_expr_dispatch(value, interner, count);
11205 }
11206 Expr::ManifestOf { zone } => count_expr_dispatch(zone, interner, count),
11207 Expr::ChunkAt { index, zone } => {
11208 count_expr_dispatch(index, interner, count);
11209 count_expr_dispatch(zone, interner, count);
11210 }
11211 Expr::List(items) | Expr::Tuple(items) => {
11212 for e in items {
11213 count_expr_dispatch(e, interner, count);
11214 }
11215 }
11216 Expr::Range { start, end } => {
11217 count_expr_dispatch(start, interner, count);
11218 count_expr_dispatch(end, interner, count);
11219 }
11220 Expr::FieldAccess { object, .. } => count_expr_dispatch(object, interner, count),
11221 Expr::New {
11222 type_name,
11223 type_args,
11224 init_fields,
11225 } => {
11226 let tn = interner.resolve(*type_name);
11227 if CORE_VARIANT_NAMES.contains(&tn) || CORE_TYPE_NAMES.contains(&tn) {
11228 *count += 1;
11229 }
11230 for ta in type_args {
11233 if type_expr_mentions_core(ta, interner) {
11234 *count += 1;
11235 }
11236 }
11237 for (_, v) in init_fields {
11238 count_expr_dispatch(v, interner, count);
11239 }
11240 }
11241 Expr::NewVariant {
11242 variant, fields, ..
11243 } => {
11244 if CORE_VARIANT_NAMES.contains(&interner.resolve(*variant)) {
11245 *count += 1;
11246 }
11247 for (_, v) in fields {
11248 count_expr_dispatch(v, interner, count);
11249 }
11250 }
11251 Expr::Escape { code, .. } => count_escape_code_dispatch(interner.resolve(*code), count),
11252 Expr::OptionSome { value } => count_expr_dispatch(value, interner, count),
11253 Expr::WithCapacity { value, capacity } => {
11254 count_expr_dispatch(value, interner, count);
11255 count_expr_dispatch(capacity, interner, count);
11256 }
11257 Expr::Closure { body, .. } => match body {
11258 ClosureBody::Expression(e) => count_expr_dispatch(e, interner, count),
11259 ClosureBody::Block(b) => count_block_dispatch(b, interner, count),
11260 },
11261 Expr::CallExpr { callee, args } => {
11262 count_expr_dispatch(callee, interner, count);
11263 for a in args {
11264 count_expr_dispatch(a, interner, count);
11265 }
11266 }
11267 Expr::InterpolatedString(parts) => {
11268 for p in parts {
11269 if let StringPart::Expr { value, .. } = p {
11270 count_expr_dispatch(value, interner, count);
11271 }
11272 }
11273 }
11274 }
11275}
11276
11277pub fn pe_source_text() -> &'static str {
11283 include_str!("optimize/pe_source.logos")
11284}
11285
11286pub fn decompile_source_text() -> &'static str {
11287 include_str!("optimize/decompile_source.logos")
11288}
11289
11290pub fn pe_bti_source_text() -> &'static str {
11291 include_str!("optimize/pe_bti_source.logos")
11292}
11293
11294pub fn pe_mini_source_text() -> &'static str {
11295 include_str!("optimize/pe_mini_source.logos")
11296}
11297
11298pub fn core_types_for_pe_source() -> &'static str {
11305 CORE_TYPES_FOR_PE
11306}
11307
11308const CORE_TYPES_FOR_PE: &str = r#"
11309## A CExpr is one of:
11310 A CInt with value Int.
11311 A CFloat with value Real.
11312 A CBool with value Bool.
11313 A CText with value Text.
11314 A CVar with name Text.
11315 A CBinOp with op Text and left CExpr and right CExpr.
11316 A CNot with inner CExpr.
11317 A CCall with name Text and args Seq of CExpr.
11318 A CIndex with coll CExpr and idx CExpr.
11319 A CLen with target CExpr.
11320 A CMapGet with target CExpr and key CExpr.
11321 A CNewSeq.
11322 A CNewVariant with tag Text and fnames Seq of Text and fvals Seq of CExpr.
11323 A CList with items Seq of CExpr.
11324 A CRange with start CExpr and end CExpr.
11325 A CSlice with coll CExpr and startIdx CExpr and endIdx CExpr.
11326 A CCopy with target CExpr.
11327 A CNewSet.
11328 A CContains with coll CExpr and elem CExpr.
11329 A CUnion with left CExpr and right CExpr.
11330 A CIntersection with left CExpr and right CExpr.
11331 A COptionSome with inner CExpr.
11332 A COptionNone.
11333 A CTuple with items Seq of CExpr.
11334 A CNew with typeName Text and fieldNames Seq of Text and fields Seq of CExpr.
11335 A CFieldAccess with target CExpr and field Text.
11336 A CClosure with params Seq of Text and body Seq of CStmt and captured Seq of Text.
11337 A CCallExpr with target CExpr and args Seq of CExpr.
11338 A CInterpolatedString with parts Seq of CStringPart.
11339 A CDuration with amount CExpr and unit Text.
11340 A CTimeNow.
11341 A CDateToday.
11342 A CEscExpr with code Text.
11343 A CManifestOf with zn CExpr.
11344 A CChunkAt with idx CExpr and zn CExpr.
11345
11346## A CStringPart is one of:
11347 A CLiteralPart with value Text.
11348 A CExprPart with expr CExpr.
11349
11350## A CStmt is one of:
11351 A CLet with name Text and expr CExpr.
11352 A CSet with name Text and expr CExpr.
11353 A CIf with cond CExpr and thenBlock Seq of CStmt and elseBlock Seq of CStmt.
11354 A CWhile with cond CExpr and body Seq of CStmt.
11355 A CReturn with expr CExpr.
11356 A CShow with expr CExpr.
11357 A CCallS with name Text and args Seq of CExpr.
11358 A CPush with expr CExpr and target Text.
11359 A CSetIdx with target Text and idx CExpr and val CExpr.
11360 A CMapSet with target Text and key CExpr and val CExpr.
11361 A CPop with target Text.
11362 A CRepeat with var Text and coll CExpr and body Seq of CStmt.
11363 A CRepeatRange with var Text and start CExpr and end CExpr and body Seq of CStmt.
11364 A CBreak.
11365 A CAdd with elem CExpr and target Text.
11366 A CRemove with elem CExpr and target Text.
11367 A CForceDynamic with name Text.
11368 A CSetField with target Text and field Text and val CExpr.
11369 A CStructDef with name Text and fieldNames Seq of Text.
11370 A CInspect with target CExpr and arms Seq of CMatchArm.
11371 A CEnumDef with name Text and variants Seq of Text.
11372 A CRuntimeAssert with cond CExpr and msg CExpr.
11373 A CHardAssert with cond CExpr and msg CExpr.
11374 A CGive with expr CExpr and target Text.
11375 A CEscStmt with code Text.
11376 A CSleep with duration CExpr.
11377 A CReadConsole with target Text.
11378 A CReadFile with path CExpr and target Text.
11379 A CWriteFile with path CExpr and content CExpr.
11380 A CCheck with predicate CExpr and msg CExpr.
11381 A CAssert with proposition CExpr.
11382 A CTrust with proposition CExpr and justification Text.
11383 A CRequire with dependency Text.
11384 A CMerge with target Text and other CExpr.
11385 A CJoin with target Text and other CExpr.
11386 A CIncrease with target Text and amount CExpr.
11387 A CDecrease with target Text and amount CExpr.
11388 A CAppendToSeq with target Text and value CExpr.
11389 A CResolve with target Text.
11390 A CSync with target Text and channel CExpr.
11391 A CMount with target Text and path CExpr.
11392 A CConcurrent with branches Seq of Seq of CStmt.
11393 A CParallel with branches Seq of Seq of CStmt.
11394 A CLaunchTask with body Seq of CStmt and handle Text.
11395 A CStopTask with handle CExpr.
11396 A CSelect with branches Seq of CSelectBranch.
11397 A CCreatePipe with name Text and capacity CExpr.
11398 A CSendPipe with chan Text and value CExpr.
11399 A CReceivePipe with chan Text and target Text.
11400 A CTrySendPipe with chan Text and value CExpr.
11401 A CTryReceivePipe with chan Text and target Text.
11402 A CSpawn with agentType Text and target Text.
11403 A CSendMessage with target CExpr and msg CExpr.
11404 A CStreamMessage with target CExpr and values CExpr.
11405 A CAwaitMessage with target Text.
11406 A CListen with addr CExpr and handler Text.
11407 A CConnectTo with addr CExpr and target Text.
11408 A CZone with name Text and kind Text and body Seq of CStmt.
11409
11410## A CSelectBranch is one of:
11411 A CSelectRecv with chan Text and var Text and body Seq of CStmt.
11412 A CSelectTimeout with duration CExpr and body Seq of CStmt.
11413
11414## A CMatchArm is one of:
11415 A CWhen with variantName Text and bindings Seq of Text and body Seq of CStmt.
11416 A COtherwise with body Seq of CStmt.
11417
11418## A CFunc is one of:
11419 A CFuncDef with name Text and params Seq of Text and paramTypes Seq of Text and returnType Text and body Seq of CStmt.
11420
11421## A CProgram is one of:
11422 A CProg with funcs Seq of CFunc and main Seq of CStmt.
11423
11424## A PEState is one of:
11425 A PEStateR with env Map of Text to CVal and funcs Map of Text to CFunc and depth Int and staticEnv Map of Text to CExpr and specResults Map of Text to CExpr and onStack Seq of Text.
11426
11427## A CVal is one of:
11428 A VInt with value Int.
11429 A VFloat with value Real.
11430 A VBool with value Bool.
11431 A VText with value Text.
11432 A VSeq with items Seq of CVal.
11433 A VMap with entries Map of Text to CVal.
11434 A VError with msg Text.
11435 A VNothing.
11436 A VSet with items Seq of CVal.
11437 A VOption with inner CVal and present Bool.
11438 A VTuple with items Seq of CVal.
11439 A VStruct with typeName Text and fields Map of Text to CVal.
11440 A VVariant with typeName Text and variantName Text and fields Seq of CVal.
11441 A VClosure with params Seq of Text and body Seq of CStmt and capturedEnv Map of Text to CVal.
11442 A VDuration with millis Int.
11443 A VDate with year Int and month Int and day Int.
11444 A VMoment with millis Int.
11445 A VSpan with startMillis Int and endMillis Int.
11446 A VTime with hour Int and minute Int and second Int.
11447 A VCrdt with kind Text and state Map of Text to CVal.
11448"#;
11449
11450pub fn quote_pe_source() -> Result<String, String> {
11458 let pe_source = pe_source_text();
11459 let full_source = format!("{}\n{}", CORE_TYPES_FOR_PE, pe_source);
11460 let encoded = encode_program_source(&full_source)
11461 .map_err(|e| format!("Failed to encode PE: {}", describe_parse_error(&e)))?;
11462 Ok(format!("{}\n{}", pe_source, encoded))
11463}
11464
11465pub fn projection2_source() -> Result<String, String> {
11484 let pe_source = pe_source_text();
11485
11486 let compiler_source = replace_word(
11487 &replace_word(&pe_source, "peExpr", "compileExpr"),
11488 "peBlock",
11489 "compileBlock",
11490 );
11491
11492 Ok(format!("{}\n{}", CORE_TYPES_FOR_PE, compiler_source))
11493}
11494
11495pub fn projection3_source() -> Result<String, String> {
11514 let pe_source = pe_source_text();
11515
11516 let cogen_source = replace_word(
11517 &replace_word(&pe_source, "peExpr", "cogenExpr"),
11518 "peBlock",
11519 "cogenBlock",
11520 );
11521
11522 Ok(format!("{}\n{}", CORE_TYPES_FOR_PE, cogen_source))
11523}
11524
11525pub fn run_logos_source(source: &str) -> Result<String, String> {
11530 let compile_output = compile_program_full(source)
11531 .map_err(|e| format!("Compilation failed: {}", describe_parse_error(&e)))?;
11532
11533 let temp_base = std::env::temp_dir().join("logos_run_source");
11535 std::fs::create_dir_all(&temp_base).map_err(|e| format!("mkdir failed: {}", e))?;
11536
11537 let pkg_name = format!(
11538 "logos_run_{}_{}",
11539 std::process::id(),
11540 std::time::SystemTime::now()
11541 .duration_since(std::time::UNIX_EPOCH)
11542 .unwrap()
11543 .as_nanos()
11544 );
11545 let project_dir = temp_base.join(&pkg_name);
11546
11547 let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
11549 let workspace_root = manifest_dir.parent().unwrap().parent().unwrap();
11550
11551 let cargo_toml = format!(
11552 r#"[package]
11553name = "{}"
11554version = "0.1.0"
11555edition = "2021"
11556
11557[dependencies]
11558logicaffeine-data = {{ path = "{}/crates/logicaffeine_data" }}
11559logicaffeine-system = {{ path = "{}/crates/logicaffeine_system", features = ["full"] }}
11560tokio = {{ version = "1", features = ["rt-multi-thread", "macros"] }}
11561serde = {{ version = "1", features = ["derive"] }}
11562rayon = "1"
11563"#,
11564 pkg_name,
11565 workspace_root.display(),
11566 workspace_root.display(),
11567 );
11568
11569 std::fs::create_dir_all(project_dir.join("src")).map_err(|e| format!("mkdir failed: {}", e))?;
11570 std::fs::write(project_dir.join("Cargo.toml"), cargo_toml)
11571 .map_err(|e| format!("Write Cargo.toml failed: {}", e))?;
11572 std::fs::write(project_dir.join("src/main.rs"), &compile_output.rust_code)
11573 .map_err(|e| format!("Write main.rs failed: {}", e))?;
11574 std::fs::copy(
11578 workspace_root.join("Cargo.lock"),
11579 project_dir.join("Cargo.lock"),
11580 )
11581 .map_err(|e| format!("Seed Cargo.lock failed: {}", e))?;
11582
11583 let shard = std::env::var("NEXTEST_TEST_GROUP_SLOT")
11587 .ok()
11588 .and_then(|s| s.parse::<u64>().ok())
11589 .or_else(|| {
11590 std::env::var("NEXTEST_TEST_GLOBAL_SLOT")
11591 .ok()
11592 .and_then(|s| s.parse::<u64>().ok())
11593 .map(|n| n % 12)
11594 });
11595 let target_dir = match shard {
11596 Some(s) => std::env::temp_dir().join(format!("logos_e2e_cache_{s}")),
11597 None => std::env::temp_dir().join("logos_e2e_cache"),
11598 };
11599 std::fs::create_dir_all(&target_dir).map_err(|e| format!("mkdir target failed: {}", e))?;
11600
11601 let mut run_cmd = std::process::Command::new("cargo");
11602 run_cmd
11603 .args(["run", "--quiet"])
11604 .current_dir(&project_dir)
11605 .env("CARGO_TARGET_DIR", &target_dir)
11606 .env("RUST_MIN_STACK", "268435456");
11607 if crate::semantics::collections::reference_scope_active() {
11612 run_cmd.env("LOGOS_VALUE_SEMANTICS", "0");
11613 }
11614 let output = run_cmd
11615 .output()
11616 .map_err(|e| format!("cargo run failed: {}", e))?;
11617
11618 let _ = std::fs::remove_dir_all(&project_dir);
11623 {
11624 let stem = pkg_name.replace('-', "_");
11625 let debug = target_dir.join("debug");
11626 let _ = std::fs::remove_file(debug.join(&pkg_name));
11627 let _ = std::fs::remove_file(debug.join(format!("{pkg_name}.d")));
11628 for sub in ["deps", "incremental", ".fingerprint", "build"] {
11629 if let Ok(rd) = std::fs::read_dir(debug.join(sub)) {
11630 for e in rd.flatten() {
11631 let name = e.file_name();
11632 let n = name.to_string_lossy();
11633 if n.starts_with(&format!("{stem}-")) || n.starts_with(&format!("lib{stem}-")) {
11634 let path = e.path();
11635 let _ = if path.is_dir() {
11636 std::fs::remove_dir_all(&path)
11637 } else {
11638 std::fs::remove_file(&path)
11639 };
11640 }
11641 }
11642 }
11643 }
11644 }
11645
11646 if !output.status.success() {
11647 return Err(format!(
11648 "Execution failed (status={:?} code={:?}):\nstderr: {}\nstdout: {}",
11649 output.status,
11650 output.status.code(),
11651 String::from_utf8_lossy(&output.stderr),
11652 String::from_utf8_lossy(&output.stdout),
11653 ));
11654 }
11655
11656 Ok(String::from_utf8_lossy(&output.stdout).to_string())
11657}
11658
11659pub struct GenuineProjectionResult {
11662 pub source: String,
11665 pub block_entry: String,
11668 pub expr_entry: Option<String>,
11670}
11671
11672fn discover_entry_points(
11675 residual: &str,
11676 block_prefix: &str,
11677 expr_prefix: &str,
11678) -> (String, Option<String>) {
11679 let mut block_entry = String::new();
11680 let mut expr_entry = None;
11681 for line in residual.lines() {
11682 let trimmed = line.trim();
11683 if let Some(rest) = trimmed.strip_prefix("## To ") {
11684 let name = rest.split(" (").next().unwrap_or("").trim();
11686 if name.starts_with(block_prefix) && block_entry.is_empty() {
11687 block_entry = name.to_string();
11688 } else if name.starts_with(expr_prefix) && expr_entry.is_none() {
11689 expr_entry = Some(name.to_string());
11690 }
11691 }
11692 }
11693 (block_entry, expr_entry)
11694}
11695
11696pub fn projection1_source_real(
11701 core_types: &str,
11702 _interpreter: &str,
11703 program: &str,
11704) -> Result<String, String> {
11705 let full_source = if program.contains("## Main") || program.contains("## To ") {
11706 program.to_string()
11707 } else {
11708 format!("## Main\n{}", program)
11709 };
11710
11711 let encoded = encode_program_source(&full_source)
11713 .map_err(|e| format!("Failed to encode program: {}", describe_parse_error(&e)))?;
11714
11715 let pe_source = pe_source_text();
11717 let decompile_source = decompile_source_text();
11718
11719 let actual_core_types = if core_types.is_empty() {
11721 CORE_TYPES_FOR_PE
11722 } else {
11723 core_types
11724 };
11725
11726 let driver = r#"
11727 Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
11728 Let residual be peBlock(encodedMain, state).
11729 Let source be decompileBlock(residual, 0).
11730 Show source.
11731"#;
11732
11733 let combined = format!(
11734 "{}\n{}\n{}\n## Main\n{}\n{}",
11735 actual_core_types, pe_source, decompile_source, encoded, driver,
11736 );
11737
11738 let raw_residual = with_reference_semantics(|| run_logos_source(&combined))?;
11740 let trimmed = raw_residual.trim();
11741
11742 if trimmed.is_empty() {
11744 return Ok("## Main\n".to_string());
11745 }
11746
11747 if trimmed.contains("## To ") || trimmed.starts_with("## Main") {
11749 Ok(trimmed.to_string())
11750 } else {
11751 Ok(format!("## Main\n{}", trimmed))
11752 }
11753}
11754
11755pub fn projection1_source_real_fast(
11762 core_types: &str,
11763 _interpreter: &str,
11764 program: &str,
11765) -> Result<String, String> {
11766 let combined = pe_combined_source(core_types, program)?;
11767
11768 let raw_residual = interpret_bootstrap(&combined)
11769 .map_err(|e| format!("PE execution failed: {}", describe_parse_error(&e)))?;
11770 let residual = finish_projection1_residual(raw_residual)?;
11771 Ok(prepend_type_definitions(program, residual))
11776}
11777
11778pub use crate::concurrency::marshal::{decode_value_raw, encode_value_raw};
11779
11780pub fn core_interp_source() -> &'static str {
11785 include_str!("optimize/core_interp.logos")
11786}
11787
11788const PE_DRIVER_CORE: &str = r#"Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
11801Let residual be peBlock(encodedMain, state).
11802Let nl be chr(10).
11803Let mutable output be "".
11804Let specFuncs be peFuncs(state).
11805Let mutable allNames be collectCallNames(residual).
11806Let mutable emitted be a new Map of Text to Bool.
11807Let mutable changed be true.
11808While changed:
11809 Set changed to false.
11810 Let mutable toAdd be a new Seq of Text.
11811 Repeat for fnKey in allNames:
11812 Let fkStr be "{fnKey}".
11813 If emitted contains fkStr:
11814 Let skipE be true.
11815 Otherwise:
11816 Set item fkStr of emitted to true.
11817 Let fkStr2 be "{fnKey}".
11818 If specFuncs contains fkStr2:
11819 Let fdef be item fkStr2 of specFuncs.
11820 Inspect fdef:
11821 When CFuncDef (fn0, ps0, pt0, rt0, body0):
11822 Let children be collectCallNames(body0).
11823 Repeat for child in children:
11824 Let childStr be "{child}".
11825 If not emitted contains childStr:
11826 Push child to toAdd.
11827 Set changed to true.
11828 Otherwise:
11829 Let skipF be true.
11830 Repeat for ta in toAdd:
11831 Push ta to allNames.
11832Repeat for fnKey in allNames:
11833 Let fkStr be "{fnKey}".
11834 If specFuncs contains fkStr:
11835 Let fdef be item fkStr of specFuncs.
11836 Let funcSrc be decompileFunc(fdef).
11837 If the length of funcSrc is greater than 0:
11838 Set output to "{output}{funcSrc}{nl}".
11839Let mainSrc be decompileBlock(residual, 0).
11840Set output to "{output}## Main{nl}{mainSrc}"."#;
11841
11842fn pe_driver_body(last: &str) -> String {
11845 format!("{PE_DRIVER_CORE}\n{last}")
11846}
11847
11848pub fn pe_native_source() -> String {
11849 let core = CORE_TYPES_FOR_PE;
11850 let pe = pe_source_text();
11851 let decompile = decompile_source_text();
11852 let driver_body = pe_driver_body("Let __wrn be writeWireResidual(output).");
11857 let indented: String = driver_body
11862 .lines()
11863 .map(|l| {
11864 if l.is_empty() {
11865 String::new()
11866 } else {
11867 format!(" {l}")
11868 }
11869 })
11870 .collect::<Vec<_>>()
11871 .join("\n");
11872 let main = format!(
11873 " While true:\n Let __prog be readWireProgram().\n Inspect __prog:\n When CProg (encFuncs, encMain):\n Let encodedMain be encMain.\n Let mutable encodedFuncMap be a new Map of Text to CFunc.\n Repeat for __f in encFuncs:\n Inspect __f:\n When CFuncDef (__nm, __ps, __pt, __rt, __bd):\n Set item __nm of encodedFuncMap to __f.\n Otherwise:\n Let __skip be true.\n{indented}\n Otherwise:\n Let __wrn be writeWireResidual(\"\").\n"
11874 );
11875 format!("{}\n{}\n{}\n## Main\n{}", core, pe, decompile, main)
11876}
11877
11878pub fn pe_cdylib_source() -> String {
11887 let core = CORE_TYPES_FOR_PE;
11888 let pe = pe_source_text();
11889 let decompile = decompile_source_text();
11890 let driver_body = pe_driver_body("Return output.");
11894 let indented: String = driver_body
11895 .lines()
11896 .map(|l| {
11897 if l.is_empty() {
11898 String::new()
11899 } else {
11900 format!(" {l}")
11901 }
11902 })
11903 .collect::<Vec<_>>()
11904 .join("\n");
11905 let func = format!(
11906 "## To peSpecializeOnce (__prog: CProgram) -> Text is exported for native:\n Inspect __prog:\n When CProg (encFuncs, encMain):\n Let encodedMain be encMain.\n Let mutable encodedFuncMap be a new Map of Text to CFunc.\n Repeat for __f in encFuncs:\n Inspect __f:\n When CFuncDef (__nm, __ps, __pt, __rt, __bd):\n Set item __nm of encodedFuncMap to __f.\n Otherwise:\n Let __skip be true.\n{indented}\n Otherwise:\n Return \"\".\n"
11907 );
11908 format!(
11909 "{}\n{}\n{}\n{}\n## Main\n Let __x be 0.\n",
11910 core, pe, decompile, func
11911 )
11912}
11913
11914use crate::interpreter::RuntimeValue;
11915
11916fn cv_enum(ctor: &str) -> &'static str {
11930 match ctor {
11931 "CProg" => "CProgram",
11932 "CFuncDef" => "CFunc",
11933 "CLiteralPart" | "CExprPart" => "CStringPart",
11934 "CInt"
11935 | "CBool"
11936 | "CText"
11937 | "CFloat"
11938 | "CVar"
11939 | "CBinOp"
11940 | "CNot"
11941 | "CCall"
11942 | "CIndex"
11943 | "CLen"
11944 | "CMapGet"
11945 | "CList"
11946 | "CTuple"
11947 | "CRange"
11948 | "CSlice"
11949 | "CCopy"
11950 | "CContains"
11951 | "CUnion"
11952 | "CIntersection"
11953 | "COptionSome"
11954 | "COptionNone"
11955 | "CNewSeq"
11956 | "CNewSet"
11957 | "CNew"
11958 | "CNewVariant"
11959 | "CInterpolatedString"
11960 | "CClosure"
11961 | "CDuration"
11962 | "CCallExpr"
11963 | "CChunkAt"
11964 | "CEscExpr"
11965 | "CManifestOf" => "CExpr",
11966 "CSelectRecv" | "CSelectTimeout" => "CSelectBranch",
11967 _ => "CStmt",
11968 }
11969}
11970
11971fn cv_ind(ctor: &str, args: Vec<RuntimeValue>) -> RuntimeValue {
11972 RuntimeValue::Inductive(std::rc::Rc::new(crate::interpreter::InductiveValue {
11973 inductive_type: cv_enum(ctor).to_string(),
11974 constructor: ctor.to_string(),
11975 args,
11976 }))
11977}
11978fn cv_text(s: &str) -> RuntimeValue {
11979 RuntimeValue::Text(std::rc::Rc::new(s.to_string()))
11980}
11981fn cv_list(items: Vec<RuntimeValue>) -> RuntimeValue {
11982 RuntimeValue::List(std::rc::Rc::new(std::cell::RefCell::new(
11983 crate::interpreter::ListRepr::from_values(items),
11984 )))
11985}
11986
11987fn cv_binop_str(op: BinaryOpKind) -> &'static str {
11989 match op {
11990 BinaryOpKind::Add => "+",
11991 BinaryOpKind::Subtract => "-",
11992 BinaryOpKind::Multiply => "*",
11993 BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
11994 BinaryOpKind::FloorDivide => "//",
11995 BinaryOpKind::Modulo => "%",
11996 BinaryOpKind::Eq => "==",
11997 BinaryOpKind::NotEq => "!=",
11998 BinaryOpKind::Lt => "<",
11999 BinaryOpKind::Gt => ">",
12000 BinaryOpKind::LtEq => "<=",
12001 BinaryOpKind::GtEq => ">=",
12002 BinaryOpKind::And => "&&",
12003 BinaryOpKind::Or => "||",
12004 BinaryOpKind::Concat => "+",
12005 BinaryOpKind::SeqConcat => "followed by",
12006 BinaryOpKind::ApproxEq => "is approximately",
12007 BinaryOpKind::Pow => "**",
12008 BinaryOpKind::BitXor => "^",
12009 BinaryOpKind::BitAnd => "&",
12010 BinaryOpKind::BitOr => "|",
12011 BinaryOpKind::Shl => "<<",
12012 BinaryOpKind::Shr => ">>",
12013 }
12014}
12015
12016type VCtors = std::collections::HashMap<String, Vec<String>>;
12017
12018trait CoreSink {
12025 type Val;
12026 fn int(n: i64) -> Self::Val;
12027 fn boolean(b: bool) -> Self::Val;
12028 fn float(f: f64) -> Self::Val;
12029 fn text(s: &str) -> Self::Val;
12030 fn list(items: Vec<Self::Val>) -> Self::Val;
12031 fn inductive(ctor: &str, args: Vec<Self::Val>) -> Self::Val;
12032}
12033
12034struct TreeSink;
12036impl CoreSink for TreeSink {
12037 type Val = RuntimeValue;
12038 fn int(n: i64) -> RuntimeValue {
12039 RuntimeValue::Int(n)
12040 }
12041 fn boolean(b: bool) -> RuntimeValue {
12042 RuntimeValue::Bool(b)
12043 }
12044 fn float(f: f64) -> RuntimeValue {
12045 RuntimeValue::Float(f)
12046 }
12047 fn text(s: &str) -> RuntimeValue {
12048 cv_text(s)
12049 }
12050 fn list(items: Vec<RuntimeValue>) -> RuntimeValue {
12051 cv_list(items)
12052 }
12053 fn inductive(ctor: &str, args: Vec<RuntimeValue>) -> RuntimeValue {
12054 cv_ind(ctor, args)
12055 }
12056}
12057
12058struct WireSink;
12064impl CoreSink for WireSink {
12065 type Val = Vec<u8>;
12066 fn int(n: i64) -> Vec<u8> {
12067 let mut v = Vec::with_capacity(4);
12068 v.push(logicaffeine_data::wire::T_INT);
12069 logicaffeine_data::wire::write_uvarint(logicaffeine_data::wire::zigzag(n), &mut v);
12070 v
12071 }
12072 fn boolean(b: bool) -> Vec<u8> {
12073 vec![if b {
12074 logicaffeine_data::wire::T_TRUE
12075 } else {
12076 logicaffeine_data::wire::T_FALSE
12077 }]
12078 }
12079 fn float(f: f64) -> Vec<u8> {
12080 let mut v = Vec::with_capacity(9);
12081 v.push(logicaffeine_data::wire::T_FLOAT);
12082 v.extend_from_slice(&f.to_le_bytes());
12083 v
12084 }
12085 fn text(s: &str) -> Vec<u8> {
12086 let mut v = Vec::with_capacity(2 + s.len());
12087 v.push(logicaffeine_data::wire::T_TEXT);
12088 logicaffeine_data::wire::write_str(s, &mut v);
12089 v
12090 }
12091 fn list(items: Vec<Vec<u8>>) -> Vec<u8> {
12092 let mut v = Vec::new();
12093 v.push(logicaffeine_data::wire::T_LIST);
12094 logicaffeine_data::wire::write_uvarint(items.len() as u64, &mut v);
12095 for it in &items {
12096 v.extend_from_slice(it);
12097 }
12098 v
12099 }
12100 fn inductive(ctor: &str, args: Vec<Vec<u8>>) -> Vec<u8> {
12101 let mut v = Vec::new();
12102 logicaffeine_data::wire::write_inductive_header(
12103 &mut v,
12104 cv_enum(ctor),
12105 ctor,
12106 args.len() as u64,
12107 );
12108 for a in &args {
12109 v.extend_from_slice(a);
12110 }
12111 v
12112 }
12113}
12114
12115fn exprs_to_core<S: CoreSink>(
12116 args: &[&Expr],
12117 interner: &Interner,
12118 vctors: &VCtors,
12119) -> Option<Vec<S::Val>> {
12120 let mut out = Vec::with_capacity(args.len());
12121 for a in args {
12122 out.push(expr_to_core::<S>(a, interner, vctors)?);
12123 }
12124 Some(out)
12125}
12126
12127fn expr_to_core<S: CoreSink>(expr: &Expr, interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
12128 Some(match expr {
12129 Expr::Literal(Literal::Number(n)) => S::inductive("CInt", vec![S::int(*n)]),
12130 Expr::Literal(Literal::Boolean(b)) => S::inductive("CBool", vec![S::boolean(*b)]),
12131 Expr::Literal(Literal::Text(s)) => {
12132 S::inductive("CText", vec![S::text(interner.resolve(*s))])
12133 }
12134 Expr::Literal(Literal::Float(f)) => S::inductive("CFloat", vec![S::float(*f)]),
12135 Expr::Literal(Literal::Duration(nanos)) => S::inductive(
12139 "CDuration",
12140 vec![
12141 S::inductive("CInt", vec![S::int(nanos / 1_000_000)]),
12142 S::text("milliseconds"),
12143 ],
12144 ),
12145 Expr::Literal(Literal::Nothing) => S::inductive("CText", vec![S::text("nothing")]),
12146 Expr::Identifier(sym) => S::inductive("CVar", vec![S::text(interner.resolve(*sym))]),
12147 Expr::BinaryOp { op, left, right } => S::inductive(
12148 "CBinOp",
12149 vec![
12150 S::text(cv_binop_str(*op)),
12151 expr_to_core::<S>(left, interner, vctors)?,
12152 expr_to_core::<S>(right, interner, vctors)?,
12153 ],
12154 ),
12155 Expr::Not { operand } => {
12156 S::inductive("CNot", vec![expr_to_core::<S>(operand, interner, vctors)?])
12157 }
12158 Expr::Call { function, args } => {
12159 let fn_name = interner.resolve(*function);
12160 if let Some(field_names) = vctors.get(fn_name) {
12161 let mut fnames: Vec<S::Val> = Vec::with_capacity(args.len());
12163 let mut fvals: Vec<S::Val> = Vec::with_capacity(args.len());
12164 for (i, a) in args.iter().enumerate() {
12165 fnames.push(S::text(
12166 field_names.get(i).map(|s| s.as_str()).unwrap_or("value"),
12167 ));
12168 fvals.push(expr_to_core::<S>(a, interner, vctors)?);
12169 }
12170 S::inductive(
12171 "CNewVariant",
12172 vec![S::text(fn_name), S::list(fnames), S::list(fvals)],
12173 )
12174 } else {
12175 let avals = exprs_to_core::<S>(args, interner, vctors)?;
12176 S::inductive("CCall", vec![S::text(fn_name), S::list(avals)])
12177 }
12178 }
12179 Expr::Index { collection, index } => S::inductive(
12180 "CIndex",
12181 vec![
12182 expr_to_core::<S>(collection, interner, vctors)?,
12183 expr_to_core::<S>(index, interner, vctors)?,
12184 ],
12185 ),
12186 Expr::Length { collection } => S::inductive(
12187 "CLen",
12188 vec![expr_to_core::<S>(collection, interner, vctors)?],
12189 ),
12190 Expr::FieldAccess { object, field } => S::inductive(
12191 "CMapGet",
12192 vec![
12193 expr_to_core::<S>(object, interner, vctors)?,
12194 S::inductive("CText", vec![S::text(interner.resolve(*field))]),
12195 ],
12196 ),
12197 Expr::List(elems) => {
12198 let mut items: Vec<S::Val> = Vec::with_capacity(elems.len());
12199 for e in elems.iter() {
12200 items.push(expr_to_core::<S>(e, interner, vctors)?);
12201 }
12202 S::inductive("CList", vec![S::list(items)])
12203 }
12204 Expr::Tuple(elems) => {
12205 let mut items: Vec<S::Val> = Vec::with_capacity(elems.len());
12206 for e in elems.iter() {
12207 items.push(expr_to_core::<S>(e, interner, vctors)?);
12208 }
12209 S::inductive("CTuple", vec![S::list(items)])
12210 }
12211 Expr::Range { start, end } => S::inductive(
12212 "CRange",
12213 vec![
12214 expr_to_core::<S>(start, interner, vctors)?,
12215 expr_to_core::<S>(end, interner, vctors)?,
12216 ],
12217 ),
12218 Expr::Slice {
12219 collection,
12220 start,
12221 end,
12222 } => S::inductive(
12223 "CSlice",
12224 vec![
12225 expr_to_core::<S>(collection, interner, vctors)?,
12226 expr_to_core::<S>(start, interner, vctors)?,
12227 expr_to_core::<S>(end, interner, vctors)?,
12228 ],
12229 ),
12230 Expr::Copy { expr } => {
12231 S::inductive("CCopy", vec![expr_to_core::<S>(expr, interner, vctors)?])
12232 }
12233 Expr::Contains { collection, value } => S::inductive(
12234 "CContains",
12235 vec![
12236 expr_to_core::<S>(collection, interner, vctors)?,
12237 expr_to_core::<S>(value, interner, vctors)?,
12238 ],
12239 ),
12240 Expr::Union { left, right } => S::inductive(
12241 "CUnion",
12242 vec![
12243 expr_to_core::<S>(left, interner, vctors)?,
12244 expr_to_core::<S>(right, interner, vctors)?,
12245 ],
12246 ),
12247 Expr::Intersection { left, right } => S::inductive(
12248 "CIntersection",
12249 vec![
12250 expr_to_core::<S>(left, interner, vctors)?,
12251 expr_to_core::<S>(right, interner, vctors)?,
12252 ],
12253 ),
12254 Expr::OptionSome { value } => S::inductive(
12255 "COptionSome",
12256 vec![expr_to_core::<S>(value, interner, vctors)?],
12257 ),
12258 Expr::OptionNone => S::inductive("COptionNone", vec![]),
12259 Expr::InterpolatedString(parts) => {
12260 if parts.is_empty() {
12261 S::inductive("CText", vec![S::text("")])
12262 } else {
12263 let mut pvals: Vec<S::Val> = Vec::with_capacity(parts.len());
12264 for part in parts {
12265 pvals.push(match part {
12266 StringPart::Literal(sym) => {
12267 S::inductive("CLiteralPart", vec![S::text(interner.resolve(*sym))])
12268 }
12269 StringPart::Expr { value, .. } => S::inductive(
12270 "CExprPart",
12271 vec![expr_to_core::<S>(value, interner, vctors)?],
12272 ),
12273 });
12274 }
12275 S::inductive("CInterpolatedString", vec![S::list(pvals)])
12276 }
12277 }
12278 Expr::NewVariant {
12279 variant, fields, ..
12280 } => {
12281 let mut fnames: Vec<S::Val> = Vec::with_capacity(fields.len());
12282 let mut fvals: Vec<S::Val> = Vec::with_capacity(fields.len());
12283 for (fname, fexpr) in fields {
12284 fnames.push(S::text(interner.resolve(*fname)));
12285 fvals.push(expr_to_core::<S>(fexpr, interner, vctors)?);
12286 }
12287 S::inductive(
12288 "CNewVariant",
12289 vec![
12290 S::text(interner.resolve(*variant)),
12291 S::list(fnames),
12292 S::list(fvals),
12293 ],
12294 )
12295 }
12296 Expr::New {
12297 type_name,
12298 init_fields,
12299 ..
12300 } => {
12301 let tn = interner.resolve(*type_name);
12302 if tn == "Seq" || tn == "List" {
12303 S::inductive("CNewSeq", vec![])
12304 } else if tn == "Set" {
12305 S::inductive("CNewSet", vec![])
12306 } else if tn == "Map" || tn.starts_with("Map ") {
12307 S::inductive(
12308 "CNew",
12309 vec![S::text("Map"), S::list(vec![]), S::list(vec![])],
12310 )
12311 } else if init_fields.is_empty() {
12312 S::inductive(
12313 "CNewVariant",
12314 vec![S::text(tn), S::list(vec![]), S::list(vec![])],
12315 )
12316 } else {
12317 let mut fnames: Vec<S::Val> = Vec::with_capacity(init_fields.len());
12318 let mut fvals: Vec<S::Val> = Vec::with_capacity(init_fields.len());
12319 for (fname, fexpr) in init_fields {
12320 fnames.push(S::text(interner.resolve(*fname)));
12321 fvals.push(expr_to_core::<S>(fexpr, interner, vctors)?);
12322 }
12323 S::inductive("CNew", vec![S::text(tn), S::list(fnames), S::list(fvals)])
12324 }
12325 }
12326 Expr::Closure { params, body, .. } => {
12329 let mut bound: std::collections::HashSet<String> = std::collections::HashSet::new();
12330 let mut param_vals: Vec<S::Val> = Vec::with_capacity(params.len());
12331 for (sym, _) in params {
12332 let name = interner.resolve(*sym);
12333 bound.insert(name.to_string());
12334 param_vals.push(S::text(name));
12335 }
12336 let body_vals: Vec<S::Val> = match body {
12337 ClosureBody::Expression(e) => {
12338 vec![S::inductive(
12339 "CReturn",
12340 vec![expr_to_core::<S>(e, interner, vctors)?],
12341 )]
12342 }
12343 ClosureBody::Block(stmts) => {
12344 let mut bv: Vec<S::Val> = Vec::with_capacity(stmts.len());
12345 for s in stmts.iter() {
12346 if matches!(s, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12349 return None;
12350 }
12351 bv.push(stmt_to_core::<S>(s, interner, vctors)?);
12352 }
12353 bv
12354 }
12355 };
12356 let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound)
12357 .into_iter()
12358 .collect();
12359 free.sort();
12360 let cap_vals: Vec<S::Val> = free.iter().map(|fv| S::text(fv)).collect();
12361 S::inductive(
12362 "CClosure",
12363 vec![S::list(param_vals), S::list(body_vals), S::list(cap_vals)],
12364 )
12365 }
12366 Expr::CallExpr { callee, args } => {
12368 let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
12369 for a in args.iter() {
12370 avals.push(expr_to_core::<S>(a, interner, vctors)?);
12371 }
12372 S::inductive(
12373 "CCallExpr",
12374 vec![expr_to_core::<S>(callee, interner, vctors)?, S::list(avals)],
12375 )
12376 }
12377 Expr::ChunkAt { index, zone } => S::inductive(
12378 "CChunkAt",
12379 vec![
12380 expr_to_core::<S>(index, interner, vctors)?,
12381 expr_to_core::<S>(zone, interner, vctors)?,
12382 ],
12383 ),
12384 Expr::ManifestOf { zone } => S::inductive(
12385 "CManifestOf",
12386 vec![expr_to_core::<S>(zone, interner, vctors)?],
12387 ),
12388 Expr::Escape { code, .. } => {
12389 S::inductive("CEscExpr", vec![S::text(interner.resolve(*code))])
12390 }
12391 Expr::Give { value } => expr_to_core::<S>(value, interner, vctors)?,
12394 Expr::WithCapacity { value, .. } => expr_to_core::<S>(value, interner, vctors)?,
12395 _ => return None,
12396 })
12397}
12398
12399fn stmt_to_core<S: CoreSink>(stmt: &Stmt, interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
12400 Some(match stmt {
12401 Stmt::Let { var, value, .. } => S::inductive(
12402 "CLet",
12403 vec![
12404 S::text(interner.resolve(*var)),
12405 expr_to_core::<S>(value, interner, vctors)?,
12406 ],
12407 ),
12408 Stmt::Set { target, value } => S::inductive(
12409 "CSet",
12410 vec![
12411 S::text(interner.resolve(*target)),
12412 expr_to_core::<S>(value, interner, vctors)?,
12413 ],
12414 ),
12415 Stmt::Show { object, .. } => {
12416 S::inductive("CShow", vec![expr_to_core::<S>(object, interner, vctors)?])
12417 }
12418 Stmt::SetIndex {
12419 collection,
12420 index,
12421 value,
12422 } => S::inductive(
12423 "CSetIdx",
12424 vec![
12425 S::text(&extract_ident_name(collection, interner)),
12426 expr_to_core::<S>(index, interner, vctors)?,
12427 expr_to_core::<S>(value, interner, vctors)?,
12428 ],
12429 ),
12430 Stmt::SetField {
12431 object,
12432 field,
12433 value,
12434 } => S::inductive(
12435 "CMapSet",
12436 vec![
12437 S::text(&extract_ident_name(object, interner)),
12438 S::inductive("CText", vec![S::text(interner.resolve(*field))]),
12439 expr_to_core::<S>(value, interner, vctors)?,
12440 ],
12441 ),
12442 Stmt::Pop { collection, .. } => S::inductive(
12443 "CPop",
12444 vec![S::text(&extract_ident_name(collection, interner))],
12445 ),
12446 Stmt::Give { object, recipient } => S::inductive(
12447 "CGive",
12448 vec![
12449 expr_to_core::<S>(object, interner, vctors)?,
12450 S::text(&extract_ident_name(recipient, interner)),
12451 ],
12452 ),
12453 Stmt::Sleep { milliseconds } => S::inductive(
12454 "CSleep",
12455 vec![expr_to_core::<S>(milliseconds, interner, vctors)?],
12456 ),
12457 Stmt::RuntimeAssert {
12458 condition,
12459 hard,
12460 dim: _,
12461 reason,
12462 } => S::inductive(
12463 if *hard {
12464 "CHardAssert"
12465 } else {
12466 "CRuntimeAssert"
12467 },
12468 vec![
12469 expr_to_core::<S>(condition, interner, vctors)?,
12470 match reason {
12471 Some(r) => expr_to_core::<S>(r, interner, vctors)?,
12472 None => S::inductive("CText", vec![S::text("assertion failed")]),
12473 },
12474 ],
12475 ),
12476 Stmt::Fail { reason } => S::inductive(
12477 "CHardAssert",
12478 vec![
12479 S::inductive("CBool", vec![S::boolean(false)]),
12480 expr_to_core::<S>(reason, interner, vctors)?,
12481 ],
12482 ),
12483 Stmt::Return { value } => {
12484 let e = match value {
12485 Some(v) => expr_to_core::<S>(v, interner, vctors)?,
12486 None => S::inductive("CInt", vec![S::int(0)]),
12487 };
12488 S::inductive("CReturn", vec![e])
12489 }
12490 Stmt::Break => S::inductive("CBreak", vec![]),
12491 Stmt::If {
12492 cond,
12493 then_block,
12494 else_block,
12495 } => {
12496 let cond_v = expr_to_core::<S>(cond, interner, vctors)?;
12497 let then_s: Vec<&Stmt> = then_block.iter().collect();
12498 let then_v = stmt_list_to_core::<S>(&then_s, interner, vctors)?;
12499 let else_v = match else_block {
12500 Some(els) => {
12501 let else_s: Vec<&Stmt> = els.iter().collect();
12502 stmt_list_to_core::<S>(&else_s, interner, vctors)?
12503 }
12504 None => S::list(vec![]),
12505 };
12506 S::inductive("CIf", vec![cond_v, then_v, else_v])
12507 }
12508 Stmt::While { cond, body, .. } => {
12509 let cond_v = expr_to_core::<S>(cond, interner, vctors)?;
12510 let body_s: Vec<&Stmt> = body.iter().collect();
12511 S::inductive(
12512 "CWhile",
12513 vec![cond_v, stmt_list_to_core::<S>(&body_s, interner, vctors)?],
12514 )
12515 }
12516 Stmt::Call { function, args } => {
12517 let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
12518 for a in args {
12519 avals.push(expr_to_core::<S>(a, interner, vctors)?);
12520 }
12521 S::inductive(
12522 "CCallS",
12523 vec![S::text(interner.resolve(*function)), S::list(avals)],
12524 )
12525 }
12526 Stmt::Push { value, collection } => S::inductive(
12527 "CPush",
12528 vec![
12529 expr_to_core::<S>(value, interner, vctors)?,
12530 S::text(&extract_ident_name(collection, interner)),
12531 ],
12532 ),
12533 Stmt::Repeat {
12534 pattern,
12535 iterable,
12536 body,
12537 ..
12538 } => {
12539 let loop_var = match pattern {
12540 Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
12541 Pattern::Tuple(syms) => syms
12542 .first()
12543 .map(|s| interner.resolve(*s).to_string())
12544 .unwrap_or_else(|| "item".to_string()),
12545 };
12546 let body_s: Vec<&Stmt> = body.iter().collect();
12547 let body_v = stmt_list_to_core::<S>(&body_s, interner, vctors)?;
12548 if let Expr::Range { start, end } = iterable {
12549 S::inductive(
12550 "CRepeatRange",
12551 vec![
12552 S::text(&loop_var),
12553 expr_to_core::<S>(start, interner, vctors)?,
12554 expr_to_core::<S>(end, interner, vctors)?,
12555 body_v,
12556 ],
12557 )
12558 } else {
12559 S::inductive(
12560 "CRepeat",
12561 vec![
12562 S::text(&loop_var),
12563 expr_to_core::<S>(iterable, interner, vctors)?,
12564 body_v,
12565 ],
12566 )
12567 }
12568 }
12569 Stmt::Add { value, collection } => S::inductive(
12571 "CAdd",
12572 vec![
12573 expr_to_core::<S>(value, interner, vctors)?,
12574 S::text(&extract_ident_name(collection, interner)),
12575 ],
12576 ),
12577 Stmt::Remove { value, collection } => S::inductive(
12578 "CRemove",
12579 vec![
12580 expr_to_core::<S>(value, interner, vctors)?,
12581 S::text(&extract_ident_name(collection, interner)),
12582 ],
12583 ),
12584 Stmt::MergeCrdt { source, target } => S::inductive(
12585 "CMerge",
12586 vec![
12587 S::text(&extract_ident_name(target, interner)),
12588 expr_to_core::<S>(source, interner, vctors)?,
12589 ],
12590 ),
12591 Stmt::JoinCrdt { source, target } => S::inductive(
12593 "CJoin",
12594 vec![
12595 S::text(&extract_ident_name(target, interner)),
12596 expr_to_core::<S>(source, interner, vctors)?,
12597 ],
12598 ),
12599 Stmt::IncreaseCrdt {
12600 object,
12601 field,
12602 amount,
12603 } => S::inductive(
12604 "CIncrease",
12605 vec![
12606 S::text(&format!(
12607 "{}'s {}",
12608 extract_ident_name(object, interner),
12609 interner.resolve(*field)
12610 )),
12611 expr_to_core::<S>(amount, interner, vctors)?,
12612 ],
12613 ),
12614 Stmt::DecreaseCrdt {
12615 object,
12616 field,
12617 amount,
12618 } => S::inductive(
12619 "CDecrease",
12620 vec![
12621 S::text(&format!(
12622 "{}'s {}",
12623 extract_ident_name(object, interner),
12624 interner.resolve(*field)
12625 )),
12626 expr_to_core::<S>(amount, interner, vctors)?,
12627 ],
12628 ),
12629 Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
12631 let func_name = interner.resolve(*function);
12632 let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
12633 for a in args {
12634 avals.push(expr_to_core::<S>(a, interner, vctors)?);
12635 }
12636 let call = S::inductive("CCallS", vec![S::text(func_name), S::list(avals)]);
12637 let body = S::list(vec![call]);
12638 let handle_name = if let Stmt::LaunchTaskWithHandle { handle, .. } = stmt {
12639 interner.resolve(*handle).to_string()
12640 } else {
12641 "_task".to_string()
12642 };
12643 S::inductive("CLaunchTask", vec![body, S::text(&handle_name)])
12644 }
12645 Stmt::Concurrent { tasks } => {
12649 let mut branches: Vec<S::Val> = Vec::with_capacity(tasks.len());
12650 for task in tasks.iter() {
12651 if matches!(task, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12652 return None;
12653 }
12654 branches.push(S::list(vec![stmt_to_core::<S>(task, interner, vctors)?]));
12655 }
12656 S::inductive("CConcurrent", vec![S::list(branches)])
12657 }
12658 Stmt::Parallel { tasks } => {
12659 let mut branches: Vec<S::Val> = Vec::with_capacity(tasks.len());
12660 for task in tasks.iter() {
12661 if matches!(task, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12662 return None;
12663 }
12664 branches.push(S::list(vec![stmt_to_core::<S>(task, interner, vctors)?]));
12665 }
12666 S::inductive("CParallel", vec![S::list(branches)])
12667 }
12668 Stmt::AppendToSequence { sequence, value } => S::inductive(
12671 "CAppendToSeq",
12672 vec![
12673 S::text(&extract_ident_name(sequence, interner)),
12674 expr_to_core::<S>(value, interner, vctors)?,
12675 ],
12676 ),
12677 Stmt::CreatePipe {
12679 var: pipe_var,
12680 capacity,
12681 ..
12682 } => {
12683 let cap = capacity.unwrap_or(32);
12684 S::inductive(
12685 "CCreatePipe",
12686 vec![
12687 S::text(interner.resolve(*pipe_var)),
12688 S::inductive("CInt", vec![S::int(cap as i64)]),
12689 ],
12690 )
12691 }
12692 Stmt::SendPipe { value, pipe } => S::inductive(
12693 "CSendPipe",
12694 vec![
12695 S::text(&pipe_ident_name(pipe, interner)),
12696 expr_to_core::<S>(value, interner, vctors)?,
12697 ],
12698 ),
12699 Stmt::ReceivePipe {
12700 var: recv_var,
12701 pipe,
12702 } => S::inductive(
12703 "CReceivePipe",
12704 vec![
12705 S::text(&pipe_ident_name(pipe, interner)),
12706 S::text(interner.resolve(*recv_var)),
12707 ],
12708 ),
12709 Stmt::TrySendPipe { value, pipe, .. } => S::inductive(
12710 "CTrySendPipe",
12711 vec![
12712 S::text(&pipe_ident_name(pipe, interner)),
12713 expr_to_core::<S>(value, interner, vctors)?,
12714 ],
12715 ),
12716 Stmt::TryReceivePipe {
12717 var: recv_var,
12718 pipe,
12719 } => S::inductive(
12720 "CTryReceivePipe",
12721 vec![
12722 S::text(&pipe_ident_name(pipe, interner)),
12723 S::text(interner.resolve(*recv_var)),
12724 ],
12725 ),
12726 Stmt::Select { branches } => {
12729 let mut bvals: Vec<S::Val> = Vec::with_capacity(branches.len());
12730 for branch in branches.iter() {
12731 match branch {
12732 SelectBranch::Receive {
12733 var: recv_var,
12734 pipe,
12735 body,
12736 } => bvals.push(S::inductive(
12737 "CSelectRecv",
12738 vec![
12739 S::text(&pipe_ident_name(pipe, interner)),
12740 S::text(interner.resolve(*recv_var)),
12741 select_body_to_core::<S>(body, interner, vctors)?,
12742 ],
12743 )),
12744 SelectBranch::Timeout { milliseconds, body } => bvals.push(S::inductive(
12745 "CSelectTimeout",
12746 vec![
12747 expr_to_core::<S>(milliseconds, interner, vctors)?,
12748 select_body_to_core::<S>(body, interner, vctors)?,
12749 ],
12750 )),
12751 }
12752 }
12753 S::inductive("CSelect", vec![S::list(bvals)])
12754 }
12755 Stmt::Assert { .. } => S::inductive(
12758 "CAssert",
12759 vec![S::inductive("CBool", vec![S::boolean(true)])],
12760 ),
12761 Stmt::Check { source_text, .. } => S::inductive(
12762 "CCheck",
12763 vec![
12764 S::inductive("CBool", vec![S::boolean(true)]),
12765 S::inductive("CText", vec![S::text(source_text)]),
12766 ],
12767 ),
12768 Stmt::Trust { justification, .. } => S::inductive(
12769 "CTrust",
12770 vec![
12771 S::inductive("CBool", vec![S::boolean(true)]),
12772 S::text(interner.resolve(*justification)),
12773 ],
12774 ),
12775 Stmt::Require { crate_name, .. } => {
12776 S::inductive("CRequire", vec![S::text(interner.resolve(*crate_name))])
12777 }
12778 Stmt::Escape { code, .. } => {
12780 S::inductive("CEscStmt", vec![S::text(interner.resolve(*code))])
12781 }
12782 Stmt::Splice { body } => {
12784 let body_refs: Vec<&Stmt> = body.iter().collect();
12785 S::inductive(
12786 "CIf",
12787 vec![
12788 S::inductive("CBool", vec![S::boolean(true)]),
12789 stmt_list_to_core::<S>(&body_refs, interner, vctors)?,
12790 S::list(vec![]),
12791 ],
12792 )
12793 }
12794 Stmt::StopTask { handle } => S::inductive(
12796 "CStopTask",
12797 vec![expr_to_core::<S>(handle, interner, vctors)?],
12798 ),
12799 Stmt::Spawn { agent_type, name } => S::inductive(
12800 "CSpawn",
12801 vec![
12802 S::text(interner.resolve(*agent_type)),
12803 S::text(interner.resolve(*name)),
12804 ],
12805 ),
12806 Stmt::Zone { name, body, .. } => S::inductive(
12808 "CZone",
12809 vec![
12810 S::text(interner.resolve(*name)),
12811 S::text("heap"),
12812 select_body_to_core::<S>(body, interner, vctors)?,
12813 ],
12814 ),
12815 Stmt::ResolveConflict { object, field, .. } => S::inductive(
12817 "CResolve",
12818 vec![S::text(&format!(
12819 "{}'s {}",
12820 extract_ident_name(object, interner),
12821 interner.resolve(*field)
12822 ))],
12823 ),
12824 Stmt::Sync {
12826 var: sync_var,
12827 topic,
12828 } => S::inductive(
12829 "CSync",
12830 vec![
12831 S::text(interner.resolve(*sync_var)),
12832 expr_to_core::<S>(topic, interner, vctors)?,
12833 ],
12834 ),
12835 Stmt::Mount {
12836 var: mount_var,
12837 path,
12838 } => S::inductive(
12839 "CMount",
12840 vec![
12841 S::text(interner.resolve(*mount_var)),
12842 expr_to_core::<S>(path, interner, vctors)?,
12843 ],
12844 ),
12845 Stmt::ReadFrom {
12847 var: read_var,
12848 source,
12849 } => {
12850 let var_name = interner.resolve(*read_var);
12851 match source {
12852 ReadSource::Console => S::inductive("CReadConsole", vec![S::text(var_name)]),
12853 ReadSource::File(path_expr) => S::inductive(
12854 "CReadFile",
12855 vec![
12856 expr_to_core::<S>(path_expr, interner, vctors)?,
12857 S::text(var_name),
12858 ],
12859 ),
12860 }
12861 }
12862 Stmt::WriteFile { content, path } => S::inductive(
12863 "CWriteFile",
12864 vec![
12865 expr_to_core::<S>(path, interner, vctors)?,
12866 expr_to_core::<S>(content, interner, vctors)?,
12867 ],
12868 ),
12869 Stmt::ConnectTo { address, .. } => S::inductive(
12871 "CConnectTo",
12872 vec![
12873 expr_to_core::<S>(address, interner, vctors)?,
12874 S::text("conn"),
12875 ],
12876 ),
12877 Stmt::Listen { address, .. } => S::inductive(
12878 "CListen",
12879 vec![
12880 expr_to_core::<S>(address, interner, vctors)?,
12881 S::text("default"),
12882 ],
12883 ),
12884 Stmt::SendMessage {
12885 message,
12886 destination,
12887 ..
12888 } => S::inductive(
12889 "CSendMessage",
12890 vec![
12891 expr_to_core::<S>(destination, interner, vctors)?,
12892 expr_to_core::<S>(message, interner, vctors)?,
12893 ],
12894 ),
12895 Stmt::AwaitMessage { into, .. } => {
12896 S::inductive("CAwaitMessage", vec![S::text(interner.resolve(*into))])
12897 }
12898 Stmt::StreamMessage {
12899 values,
12900 destination,
12901 } => S::inductive(
12902 "CStreamMessage",
12903 vec![
12904 expr_to_core::<S>(destination, interner, vctors)?,
12905 expr_to_core::<S>(values, interner, vctors)?,
12906 ],
12907 ),
12908 Stmt::LetPeerAgent {
12909 var: pa_var,
12910 address,
12911 } => S::inductive(
12912 "CConnectTo",
12913 vec![
12914 expr_to_core::<S>(address, interner, vctors)?,
12915 S::text(interner.resolve(*pa_var)),
12916 ],
12917 ),
12918 _ => return None,
12919 })
12920}
12921
12922fn pipe_ident_name(pipe: &Expr, interner: &Interner) -> String {
12924 match pipe {
12925 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
12926 _ => "pipe".to_string(),
12927 }
12928}
12929
12930fn select_body_to_core<S: CoreSink>(
12933 body: &[Stmt],
12934 interner: &Interner,
12935 vctors: &VCtors,
12936) -> Option<S::Val> {
12937 let mut items: Vec<S::Val> = Vec::with_capacity(body.len());
12938 for s in body.iter() {
12939 if matches!(s, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12940 return None;
12941 }
12942 items.push(stmt_to_core::<S>(s, interner, vctors)?);
12943 }
12944 Some(S::list(items))
12945}
12946
12947fn stmt_list_to_core<S: CoreSink>(
12948 stmts: &[&Stmt],
12949 interner: &Interner,
12950 vctors: &VCtors,
12951) -> Option<S::Val> {
12952 Some(S::list(stmt_list_to_vec::<S>(stmts, interner, vctors)?))
12953}
12954
12955fn stmt_list_to_vec<S: CoreSink>(
12959 stmts: &[&Stmt],
12960 interner: &Interner,
12961 vctors: &VCtors,
12962) -> Option<Vec<S::Val>> {
12963 let mut out: Vec<S::Val> = Vec::with_capacity(stmts.len());
12964 for s in stmts {
12965 match s {
12966 Stmt::Inspect { .. } => inspect_to_cif::<S>(s, &mut out, interner, vctors)?,
12967 Stmt::Add { collection, .. } | Stmt::Remove { collection, .. } => {
12972 if let Some(base) = crdt_base_var(collection, interner) {
12973 out.push(S::inductive("CForceDynamic", vec![S::text(&base)]));
12974 }
12975 out.push(stmt_to_core::<S>(s, interner, vctors)?);
12976 }
12977 Stmt::AppendToSequence { sequence, .. } => {
12978 if let Some(base) = crdt_base_var(sequence, interner) {
12979 out.push(S::inductive("CForceDynamic", vec![S::text(&base)]));
12980 }
12981 out.push(stmt_to_core::<S>(s, interner, vctors)?);
12982 }
12983 Stmt::IncreaseCrdt { object, .. }
12984 | Stmt::DecreaseCrdt { object, .. }
12985 | Stmt::ResolveConflict { object, .. } => {
12986 if matches!(object, Expr::Identifier(_) | Expr::FieldAccess { .. }) {
12987 out.push(S::inductive(
12988 "CForceDynamic",
12989 vec![S::text(&crdt_base_var_root(object, interner))],
12990 ));
12991 }
12992 out.push(stmt_to_core::<S>(s, interner, vctors)?);
12993 }
12994 Stmt::MergeCrdt { target, .. } | Stmt::JoinCrdt { target, .. } => {
12995 if matches!(target, Expr::Identifier(_) | Expr::FieldAccess { .. }) {
12996 out.push(S::inductive(
12997 "CForceDynamic",
12998 vec![S::text(&crdt_base_var_root(target, interner))],
12999 ));
13000 }
13001 out.push(stmt_to_core::<S>(s, interner, vctors)?);
13002 }
13003 _ => out.push(stmt_to_core::<S>(s, interner, vctors)?),
13004 }
13005 }
13006 Some(out)
13007}
13008
13009thread_local! {
13010 static INSPECT_OTHERWISE_IDX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
13018}
13019
13020fn reset_inspect_otherwise_idx() {
13021 INSPECT_OTHERWISE_IDX.with(|c| c.set(0));
13022}
13023
13024pub fn next_inspect_otherwise_idx() -> usize {
13028 INSPECT_OTHERWISE_IDX.with(|c| {
13029 let v = c.get();
13030 c.set(v + 1);
13031 v
13032 })
13033}
13034
13035fn inspect_to_cif<S: CoreSink>(
13043 stmt: &Stmt,
13044 out: &mut Vec<S::Val>,
13045 interner: &Interner,
13046 vctors: &VCtors,
13047) -> Option<()> {
13048 let Stmt::Inspect { target, arms, .. } = stmt else {
13049 return None;
13050 };
13051 let has_otherwise = arms.iter().any(|a| a.variant.is_none());
13052 let has_variant = arms.iter().any(|a| a.variant.is_some());
13053
13054 if !has_variant {
13056 for arm in arms {
13057 if arm.variant.is_none() {
13058 let body_refs: Vec<&Stmt> = arm.body.iter().collect();
13059 out.extend(stmt_list_to_vec::<S>(&body_refs, interner, vctors)?);
13060 }
13061 }
13062 return Some(());
13063 }
13064
13065 let matched_name = if has_otherwise {
13068 let name = format!("__inspectMatched_{}", next_inspect_otherwise_idx());
13069 out.push(S::inductive(
13070 "CLet",
13071 vec![
13072 S::text(&name),
13073 S::inductive("CBool", vec![S::boolean(false)]),
13074 ],
13075 ));
13076 Some(name)
13077 } else {
13078 None
13079 };
13080
13081 for arm in arms {
13082 if arm.variant.is_none() {
13083 continue;
13084 }
13085 let variant_name = interner.resolve(arm.variant.unwrap());
13086 let tag_get = S::inductive(
13087 "CMapGet",
13088 vec![
13089 expr_to_core::<S>(target, interner, vctors)?,
13090 S::inductive("CText", vec![S::text("__tag")]),
13091 ],
13092 );
13093 let cond = S::inductive(
13094 "CBinOp",
13095 vec![
13096 S::text("=="),
13097 tag_get,
13098 S::inductive("CText", vec![S::text(variant_name)]),
13099 ],
13100 );
13101 let mut then_items: Vec<S::Val> = Vec::new();
13102 if let Some(ref mname) = matched_name {
13103 then_items.push(S::inductive(
13104 "CSet",
13105 vec![
13106 S::text(mname),
13107 S::inductive("CBool", vec![S::boolean(true)]),
13108 ],
13109 ));
13110 }
13111 for (field_name, binding_name) in &arm.bindings {
13112 let field_str = interner.resolve(*field_name);
13113 let bind_str = interner.resolve(*binding_name);
13114 let fget = S::inductive(
13115 "CMapGet",
13116 vec![
13117 expr_to_core::<S>(target, interner, vctors)?,
13118 S::inductive("CText", vec![S::text(field_str)]),
13119 ],
13120 );
13121 then_items.push(S::inductive("CLet", vec![S::text(bind_str), fget]));
13122 }
13123 let body_refs: Vec<&Stmt> = arm.body.iter().collect();
13124 then_items.extend(stmt_list_to_vec::<S>(&body_refs, interner, vctors)?);
13125 out.push(S::inductive(
13126 "CIf",
13127 vec![cond, S::list(then_items), S::list(vec![])],
13128 ));
13129 }
13130
13131 if let Some(ref mname) = matched_name {
13133 let not_matched = S::inductive("CNot", vec![S::inductive("CVar", vec![S::text(mname)])]);
13134 let mut otherwise_body: Vec<&Stmt> = Vec::new();
13135 for arm in arms {
13136 if arm.variant.is_none() {
13137 otherwise_body = arm.body.iter().collect();
13138 }
13139 }
13140 let ow = stmt_list_to_core::<S>(&otherwise_body, interner, vctors)?;
13141 out.push(S::inductive("CIf", vec![not_matched, ow, S::list(vec![])]));
13142 }
13143 Some(())
13144}
13145
13146pub fn program_covered_by_native_builder(program: &str) -> bool {
13149 program_to_core_value(program).is_some()
13150}
13151
13152fn program_to_core_value(program: &str) -> Option<RuntimeValue> {
13155 program_to_core::<TreeSink>(program)
13156}
13157
13158fn program_to_core<S: CoreSink>(program: &str) -> Option<S::Val> {
13164 reset_inspect_otherwise_idx(); let full_source = if program.contains("## Main") || program.contains("## To ") {
13166 program.to_string()
13167 } else {
13168 format!("## Main\n{}", program)
13169 };
13170 let mut interner = Interner::new();
13171 let mut lexer = Lexer::new(&full_source, &mut interner);
13172 let tokens = lexer.tokenize();
13173 let type_registry = {
13174 let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
13175 discovery.run_full().types
13176 };
13177 let mut vctors: VCtors = std::collections::HashMap::new();
13178 for (_t, def) in type_registry.iter_types() {
13179 if let crate::analysis::TypeDef::Enum { variants, .. } = def {
13180 for v in variants {
13181 let fnames: Vec<String> = v
13182 .fields
13183 .iter()
13184 .map(|f| interner.resolve(f.name).to_string())
13185 .collect();
13186 vctors.insert(interner.resolve(v.name).to_string(), fnames);
13187 }
13188 }
13189 }
13190 let mut world_state = WorldState::new();
13191 let expr_arena = Arena::new();
13192 let term_arena = Arena::new();
13193 let np_arena = Arena::new();
13194 let sym_arena = Arena::new();
13195 let role_arena = Arena::new();
13196 let pp_arena = Arena::new();
13197 let stmt_arena: Arena<Stmt> = Arena::new();
13198 let _compile_facts = crate::optimize::facts::scope();
13199 let imperative_expr_arena: Arena<Expr> = Arena::new();
13200 let type_expr_arena: Arena<TypeExpr> = Arena::new();
13201 let ast_ctx = AstContext::with_types(
13202 &expr_arena,
13203 &term_arena,
13204 &np_arena,
13205 &sym_arena,
13206 &role_arena,
13207 &pp_arena,
13208 &stmt_arena,
13209 &imperative_expr_arena,
13210 &type_expr_arena,
13211 );
13212 let mut parser = crate::parser::Parser::new(
13213 tokens,
13214 &mut world_state,
13215 &mut interner,
13216 ast_ctx,
13217 type_registry,
13218 );
13219 let stmts = parser.parse_program().ok()?;
13220 build_core::<S>(&stmts, &interner, &vctors)
13221}
13222
13223fn build_core<S: CoreSink>(stmts: &[Stmt], interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
13229 let mut funcs: Vec<S::Val> = Vec::new();
13230 let mut main_stmts: Vec<&Stmt> = Vec::new();
13231 for stmt in stmts {
13232 if let Stmt::FunctionDef {
13233 name,
13234 params,
13235 body,
13236 return_type,
13237 is_native,
13238 ..
13239 } = stmt
13240 {
13241 if *is_native {
13242 continue;
13243 }
13244 let fname = interner.resolve(*name).to_string();
13245 let pnames: Vec<S::Val> = params
13246 .iter()
13247 .map(|(n, _)| S::text(interner.resolve(*n)))
13248 .collect();
13249 let ptypes: Vec<S::Val> = params
13250 .iter()
13251 .map(|(_, ty)| S::text(&decompile_type_expr(ty, interner)))
13252 .collect();
13253 let ret = return_type
13254 .map(|rt| decompile_type_expr(rt, interner))
13255 .unwrap_or_else(|| "Nothing".to_string());
13256 let body_s: Vec<&Stmt> = body.iter().collect();
13257 let body_v = stmt_list_to_core::<S>(&body_s, interner, vctors)?;
13258 funcs.push(S::inductive(
13259 "CFuncDef",
13260 vec![
13261 S::text(&fname),
13262 S::list(pnames),
13263 S::list(ptypes),
13264 S::text(&ret),
13265 body_v,
13266 ],
13267 ));
13268 } else if matches!(
13269 stmt,
13270 Stmt::StructDef { .. }
13271 | Stmt::Theorem(_)
13272 | Stmt::Definition(_)
13273 | Stmt::Axiom(_)
13274 | Stmt::Theory(_)
13275 ) {
13276 } else {
13282 main_stmts.push(stmt);
13283 }
13284 }
13285 let main_v = stmt_list_to_core::<S>(&main_stmts, interner, vctors)?;
13286 Some(S::inductive("CProg", vec![S::list(funcs), main_v]))
13287}
13288
13289pub fn program_to_core_wire_bytes(program: &str) -> Result<Vec<u8>, String> {
13297 if let Some(bytes) = program_to_core::<WireSink>(program) {
13298 return Ok(bytes);
13299 }
13300 program_to_core_wire_bytes_via_interpreter(program)
13301}
13302
13303pub fn stmts_to_core_wire_bytes(
13311 stmts: &[Stmt],
13312 interner: &Interner,
13313 variant_fields: &std::collections::HashMap<String, Vec<String>>,
13314) -> Option<Vec<u8>> {
13315 build_core::<WireSink>(stmts, interner, variant_fields)
13316}
13317
13318pub fn program_to_core_wire_bytes_two_pass(program: &str) -> Option<Vec<u8>> {
13324 program_to_core::<TreeSink>(program).and_then(|v| encode_value_raw(&v).ok())
13325}
13326
13327pub fn program_to_core_wire_bytes_via_interpreter(program: &str) -> Result<Vec<u8>, String> {
13332 let full_source = if program.contains("## Main") || program.contains("## To ") {
13333 program.to_string()
13334 } else {
13335 format!("## Main\n{}", program)
13336 };
13337 let encoded = encode_program_source(&full_source)
13338 .map_err(|e| format!("Failed to encode program: {}", describe_parse_error(&e)))?;
13339 let driver = " Let prog be a new CProg with funcs encodedFuncSeq and main encodedMain.\n Let wb be wireBytes(prog).\n Repeat for b in wb:\n Show \"{b}\".\n";
13340 let combined = format!("{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, encoded, driver);
13341 let out = interpret_bootstrap(&combined)
13342 .map_err(|e| format!("wire-encode run failed: {}", describe_parse_error(&e)))?;
13343 let mut bytes = Vec::new();
13344 for line in out.lines() {
13345 let t = line.trim();
13346 if t.is_empty() {
13347 continue;
13348 }
13349 let n: u16 = t
13350 .parse()
13351 .map_err(|_| format!("wireBytes emitted a non-byte line: {:?}", t))?;
13352 bytes.push(n as u8);
13353 }
13354 Ok(bytes)
13355}
13356
13357#[cfg(not(target_arch = "wasm32"))]
13358thread_local! {
13359 static NATIVE_PE_BIN: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
13364}
13365
13366#[cfg(not(target_arch = "wasm32"))]
13372const BOOTSTRAP_SEMANTICS: &str = "collections: reference";
13373
13374#[cfg(not(target_arch = "wasm32"))]
13379pub fn build_native_pe_binary() -> Result<std::path::PathBuf, String> {
13380 if let Some(p) = NATIVE_PE_BIN.with(|c| c.borrow().clone()) {
13383 if p.exists() {
13384 return Ok(p);
13385 }
13386 }
13387 let src = pe_native_source();
13388 let key = aot_cache_key(&format!("{src}\n{BOOTSTRAP_SEMANTICS}"));
13392 let base = std::env::temp_dir().join("logos_native_pe");
13393 std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
13394 let proj = base.join(format!("pe_{key}"));
13395 let bin = proj.join("target").join("release").join("logos_native_pe");
13396 if bin.exists() {
13397 NATIVE_PE_BIN.with(|c| *c.borrow_mut() = Some(bin.clone()));
13398 return Ok(bin);
13399 }
13400 let rust = with_reference_semantics(|| compile_program_full_with_wire(&src))
13401 .map_err(|e| format!("native PE compile: {}", describe_parse_error(&e)))?
13402 .rust_code;
13403 std::fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
13404 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
13405 let root = manifest.parent().unwrap().parent().unwrap();
13406 std::fs::write(
13407 proj.join("Cargo.toml"),
13408 format!(
13409 "[package]\nname=\"logos_native_pe\"\nversion=\"0.1.0\"\nedition=\"2021\"\n[dependencies]\nlogicaffeine-data={{path=\"{r}/crates/logicaffeine_data\"}}\nlogicaffeine-system={{path=\"{r}/crates/logicaffeine_system\",features=[\"full\"]}}\ntokio={{version=\"1\",features=[\"rt-multi-thread\",\"macros\"]}}\nserde={{version=\"1\",features=[\"derive\"]}}\nrayon=\"1\"\n[profile.release]\nopt-level=3\n",
13410 r = root.display()
13411 ),
13412 )
13413 .map_err(|e| e.to_string())?;
13414 std::fs::write(proj.join("src/main.rs"), &rust).map_err(|e| e.to_string())?;
13415 std::fs::copy(root.join("Cargo.lock"), proj.join("Cargo.lock")).map_err(|e| e.to_string())?;
13416 let out = std::process::Command::new("cargo")
13417 .args(["build", "--release", "--quiet"])
13418 .current_dir(&proj)
13419 .env("CARGO_TARGET_DIR", proj.join("target"))
13420 .env("RUST_MIN_STACK", "268435456")
13421 .output()
13422 .map_err(|e| e.to_string())?;
13423 if !out.status.success() {
13424 return Err(format!(
13425 "native PE build failed:\n{}",
13426 String::from_utf8_lossy(&out.stderr)
13427 ));
13428 }
13429 if bin.exists() {
13430 NATIVE_PE_BIN.with(|c| *c.borrow_mut() = Some(bin.clone()));
13431 Ok(bin)
13432 } else {
13433 Err("native PE binary missing after a successful build".into())
13434 }
13435}
13436
13437#[cfg(not(target_arch = "wasm32"))]
13447struct PeServer {
13448 child: std::process::Child,
13449 stdin: std::process::ChildStdin,
13450 stdout: std::io::BufReader<std::process::ChildStdout>,
13451}
13452
13453#[cfg(not(target_arch = "wasm32"))]
13454impl Drop for PeServer {
13455 fn drop(&mut self) {
13456 let _ = self.child.kill();
13458 let _ = self.child.wait();
13459 }
13460}
13461
13462#[cfg(not(target_arch = "wasm32"))]
13463thread_local! {
13464 static PE_SERVER: std::cell::RefCell<Option<PeServer>> = const { std::cell::RefCell::new(None) };
13465}
13466
13467#[cfg(not(target_arch = "wasm32"))]
13468pub fn run_native_pe_server(program: &str) -> Result<String, String> {
13469 use std::io::{Read, Write};
13470 let bytes = program_to_core_wire_bytes(program)?;
13471 let raw = PE_SERVER.with(|cell| -> Result<String, String> {
13472 let attempt = |slot: &mut Option<PeServer>| -> Result<String, String> {
13475 if slot.is_none() {
13476 let bin = build_native_pe_binary()?;
13477 let mut child = std::process::Command::new(&bin)
13478 .stdin(std::process::Stdio::piped())
13479 .stdout(std::process::Stdio::piped())
13480 .stderr(std::process::Stdio::null())
13481 .env("RUST_MIN_STACK", "268435456")
13482 .spawn()
13483 .map_err(|e| format!("native PE server spawn: {e}"))?;
13484 let stdin = child.stdin.take().unwrap();
13485 let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
13486 *slot = Some(PeServer {
13487 child,
13488 stdin,
13489 stdout,
13490 });
13491 }
13492 let srv = slot.as_mut().unwrap();
13493 srv.stdin
13494 .write_all(&(bytes.len() as u32).to_le_bytes())
13495 .and_then(|_| srv.stdin.write_all(&bytes))
13496 .and_then(|_| srv.stdin.flush())
13497 .map_err(|e| format!("native PE server write: {e}"))?;
13498 let mut len = [0u8; 4];
13499 srv.stdout
13500 .read_exact(&mut len)
13501 .map_err(|e| format!("native PE server read length: {e}"))?;
13502 let n = u32::from_le_bytes(len) as usize;
13503 let mut buf = vec![0u8; n];
13504 srv.stdout
13505 .read_exact(&mut buf)
13506 .map_err(|e| format!("native PE server read residual: {e}"))?;
13507 String::from_utf8(buf).map_err(|e| format!("native PE residual not UTF-8: {e}"))
13508 };
13509 let mut slot = cell.borrow_mut();
13510 match attempt(&mut slot) {
13511 Ok(v) => Ok(v),
13512 Err(e) => {
13513 *slot = None; Err(e)
13515 }
13516 }
13517 })?;
13518 let residual = finish_projection1_residual(raw)?;
13519 Ok(prepend_type_definitions(program, residual))
13520}
13521
13522#[cfg(not(target_arch = "wasm32"))]
13523thread_local! {
13524 static NATIVE_PE_CDYLIB: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
13526}
13527
13528#[cfg(not(target_arch = "wasm32"))]
13534const PE_CDYLIB_SHIM: &str = r#"
13535
13536// ── in-process FFI entry (appended by build_native_pe_cdylib) ───────────────────────────────
13537#[no_mangle]
13538pub extern "C" fn logos_pe_specialize(ptr: *const u8, len: usize, out_len: *mut usize) -> *mut u8 {
13539 let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
13540 let prog = <CProgram as logicaffeine_data::wire::WireDecode>::wire_decode(bytes, &mut 0usize)
13541 .expect("logos_pe_specialize: decode CProgram");
13542 let out: String = peSpecializeOnce(prog);
13543 let boxed: Box<[u8]> = out.into_bytes().into_boxed_slice();
13544 let n = boxed.len();
13545 unsafe { *out_len = n; }
13546 Box::into_raw(boxed) as *mut u8
13547}
13548
13549#[no_mangle]
13550pub extern "C" fn logos_pe_free(ptr: *mut u8, len: usize) {
13551 if !ptr.is_null() {
13552 unsafe { drop(Box::from_raw(std::slice::from_raw_parts_mut(ptr, len) as *mut [u8])); }
13553 }
13554}
13555"#;
13556
13557#[cfg(not(target_arch = "wasm32"))]
13560pub fn native_pe_cdylib_lib_rs() -> Result<String, String> {
13561 let generated = with_reference_semantics(|| compile_program_full_with_wire(&pe_cdylib_source()))
13562 .map_err(|e| format!("native PE cdylib compile: {}", describe_parse_error(&e)))?
13563 .rust_code;
13564 Ok(format!("{generated}\n{PE_CDYLIB_SHIM}"))
13565}
13566
13567#[cfg(not(target_arch = "wasm32"))]
13574pub fn build_native_pe_cdylib() -> Result<std::path::PathBuf, String> {
13575 if let Some(p) = NATIVE_PE_CDYLIB.with(|c| c.borrow().clone()) {
13576 if p.exists() {
13577 return Ok(p);
13578 }
13579 }
13580 let src = pe_cdylib_source();
13581 let key = aot_cache_key(&format!("{src}\n{PE_CDYLIB_SHIM}\n{BOOTSTRAP_SEMANTICS}"));
13584 let base = std::env::temp_dir().join("logos_native_pe_cdylib");
13585 std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
13586 let proj = base.join(format!("pe_{key}"));
13587 let so = proj.join("target").join("release").join(format!(
13588 "{}logos_native_pe_lib{}",
13589 std::env::consts::DLL_PREFIX,
13590 std::env::consts::DLL_SUFFIX
13591 ));
13592 if so.exists() {
13593 NATIVE_PE_CDYLIB.with(|c| *c.borrow_mut() = Some(so.clone()));
13594 return Ok(so);
13595 }
13596 let lib_rs = native_pe_cdylib_lib_rs()?;
13597 std::fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
13598 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
13599 let root = manifest.parent().unwrap().parent().unwrap();
13600 std::fs::write(
13601 proj.join("Cargo.toml"),
13602 format!(
13603 "[package]\nname=\"logos_native_pe_lib\"\nversion=\"0.1.0\"\nedition=\"2021\"\n[lib]\ncrate-type=[\"cdylib\"]\npath=\"src/lib.rs\"\n[dependencies]\nlogicaffeine-data={{path=\"{r}/crates/logicaffeine_data\"}}\nlogicaffeine-system={{path=\"{r}/crates/logicaffeine_system\",features=[\"full\"]}}\ntokio={{version=\"1\",features=[\"rt-multi-thread\",\"macros\"]}}\nserde={{version=\"1\",features=[\"derive\"]}}\nrayon=\"1\"\n[profile.release]\nopt-level=3\n",
13604 r = root.display()
13605 ),
13606 )
13607 .map_err(|e| e.to_string())?;
13608 std::fs::write(proj.join("src/lib.rs"), &lib_rs).map_err(|e| e.to_string())?;
13609 std::fs::copy(root.join("Cargo.lock"), proj.join("Cargo.lock")).map_err(|e| e.to_string())?;
13610 let out = std::process::Command::new("cargo")
13611 .args(["build", "--release", "--quiet"])
13612 .current_dir(&proj)
13613 .env("CARGO_TARGET_DIR", proj.join("target"))
13614 .env("RUST_MIN_STACK", "268435456")
13615 .output()
13616 .map_err(|e| e.to_string())?;
13617 if !out.status.success() {
13618 return Err(format!(
13619 "native PE cdylib build failed:\n{}",
13620 String::from_utf8_lossy(&out.stderr)
13621 ));
13622 }
13623 if so.exists() {
13624 NATIVE_PE_CDYLIB.with(|c| *c.borrow_mut() = Some(so.clone()));
13625 Ok(so)
13626 } else {
13627 Err("native PE cdylib missing after a successful build".into())
13628 }
13629}
13630
13631#[cfg(not(target_arch = "wasm32"))]
13635struct PeLib {
13636 _lib: libloading::Library,
13637 specialize: unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8,
13638 free: unsafe extern "C" fn(*mut u8, usize),
13639}
13640
13641#[cfg(not(target_arch = "wasm32"))]
13642thread_local! {
13643 static PE_LIB: std::cell::RefCell<Option<PeLib>> = const { std::cell::RefCell::new(None) };
13644}
13645
13646#[cfg(not(target_arch = "wasm32"))]
13653pub fn run_native_pe_inprocess(program: &str) -> Result<String, String> {
13654 let bytes = program_to_core_wire_bytes(program)?;
13655 let raw = PE_LIB.with(|cell| -> Result<String, String> {
13656 let mut slot = cell.borrow_mut();
13657 if slot.is_none() {
13658 let so = build_native_pe_cdylib()?;
13659 unsafe {
13663 let lib = libloading::Library::new(&so)
13664 .map_err(|e| format!("native PE cdylib load: {e}"))?;
13665 let specialize: libloading::Symbol<
13666 unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8,
13667 > = lib
13668 .get(b"logos_pe_specialize")
13669 .map_err(|e| format!("dlsym logos_pe_specialize: {e}"))?;
13670 let free: libloading::Symbol<unsafe extern "C" fn(*mut u8, usize)> = lib
13671 .get(b"logos_pe_free")
13672 .map_err(|e| format!("dlsym logos_pe_free: {e}"))?;
13673 let specialize = *specialize;
13674 let free = *free;
13675 *slot = Some(PeLib {
13676 _lib: lib,
13677 specialize,
13678 free,
13679 });
13680 }
13681 }
13682 let pl = slot.as_ref().unwrap();
13683 let mut out_len: usize = 0;
13684 let p = unsafe { (pl.specialize)(bytes.as_ptr(), bytes.len(), &mut out_len as *mut usize) };
13687 if p.is_null() {
13688 return Err("native PE cdylib returned a null residual".into());
13689 }
13690 let residual_bytes = unsafe { std::slice::from_raw_parts(p, out_len).to_vec() };
13691 unsafe { (pl.free)(p, out_len) };
13692 String::from_utf8(residual_bytes).map_err(|e| format!("native PE residual not UTF-8: {e}"))
13693 })?;
13694 let residual = finish_projection1_residual(raw)?;
13695 Ok(prepend_type_definitions(program, residual))
13696}
13697
13698#[cfg(not(target_arch = "wasm32"))]
13704pub fn run_native_pe(program: &str) -> Result<String, String> {
13705 match run_native_pe_inprocess(program) {
13706 Ok(v) => Ok(v),
13707 Err(_) => run_native_pe_server(program),
13708 }
13709}
13710
13711pub fn projection1_source_real_fast_on_vm(
13719 core_types: &str,
13720 _interpreter: &str,
13721 program: &str,
13722) -> Result<String, String> {
13723 let combined = pe_combined_source(core_types, program)?;
13724
13725 let raw_residual = with_reference_semantics(|| vm_run_source(&combined))
13726 .map_err(|e| format!("PE VM execution failed: {e}"))?;
13727 let residual = finish_projection1_residual(raw_residual)?;
13728 Ok(prepend_type_definitions(program, residual))
13729}
13730
13731fn prepend_type_definitions(program: &str, residual: String) -> String {
13735 let mut defs = String::new();
13736 let mut keep = false;
13737 for line in program.lines() {
13738 if let Some(header) = line.strip_prefix("## ") {
13739 keep = header != "Main" && !header.starts_with("To ");
13740 }
13741 if keep {
13742 defs.push_str(line);
13743 defs.push('\n');
13744 }
13745 }
13746 if defs.trim().is_empty() {
13747 residual
13748 } else {
13749 format!("{}{}", defs, residual)
13750 }
13751}
13752
13753pub fn pe_combined_source(core_types: &str, program: &str) -> Result<String, String> {
13757 let full_source = if program.contains("## Main") || program.contains("## To ") {
13758 program.to_string()
13759 } else {
13760 format!("## Main\n{}", program)
13761 };
13762
13763 let encoded = encode_program_source(&full_source)
13764 .map_err(|e| format!("Failed to encode program: {}", describe_parse_error(&e)))?;
13765
13766 let pe_source = pe_source_text();
13767 let decompile_source = decompile_source_text();
13768
13769 let actual_core_types = if core_types.is_empty() {
13770 CORE_TYPES_FOR_PE
13771 } else {
13772 core_types
13773 };
13774
13775 let driver = r#"
13779 Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
13780 Let residual be peBlock(encodedMain, state).
13781 Let nl be chr(10).
13782 Let mutable output be "".
13783 Let specFuncs be peFuncs(state).
13784 Let mutable allNames be collectCallNames(residual).
13785 Let mutable emitted be a new Map of Text to Bool.
13786 Let mutable changed be true.
13787 While changed:
13788 Set changed to false.
13789 Let mutable toAdd be a new Seq of Text.
13790 Repeat for fnKey in allNames:
13791 Let fkStr be "{fnKey}".
13792 If emitted contains fkStr:
13793 Let skipE be true.
13794 Otherwise:
13795 Set item fkStr of emitted to true.
13796 Let fkStr2 be "{fnKey}".
13797 If specFuncs contains fkStr2:
13798 Let fdef be item fkStr2 of specFuncs.
13799 Inspect fdef:
13800 When CFuncDef (fn0, ps0, pt0, rt0, body0):
13801 Let children be collectCallNames(body0).
13802 Repeat for child in children:
13803 Let childStr be "{child}".
13804 If not emitted contains childStr:
13805 Push child to toAdd.
13806 Set changed to true.
13807 Otherwise:
13808 Let skipF be true.
13809 Repeat for ta in toAdd:
13810 Push ta to allNames.
13811 Repeat for fnKey in allNames:
13812 Let fkStr be "{fnKey}".
13813 If specFuncs contains fkStr:
13814 Let fdef be item fkStr of specFuncs.
13815 Let funcSrc be decompileFunc(fdef).
13816 If the length of funcSrc is greater than 0:
13817 Set output to "{output}{funcSrc}{nl}".
13818 Let mainSrc be decompileBlock(residual, 0).
13819 Set output to "{output}## Main{nl}{mainSrc}".
13820 Show output.
13821"#;
13822
13823 let combined = format!(
13824 "{}\n{}\n{}\n## Main\n{}\n{}",
13825 actual_core_types, pe_source, decompile_source, encoded, driver,
13826 );
13827
13828 Ok(combined)
13829}
13830
13831pub fn finish_projection1_residual(raw_residual: String) -> Result<String, String> {
13834 let fixed = raw_residual
13839 .replace(": Any)", ": Int)")
13840 .replace("-> Any:", "-> Int:")
13841 .replace(" of Any", " of Int")
13842 .replace(" to Any", " to Int");
13843 let trimmed = fixed.trim();
13844
13845 if trimmed.is_empty() {
13846 return Ok("## Main\n".to_string());
13847 }
13848
13849 if trimmed.contains("## To ") || trimmed.starts_with("## Main") {
13850 Ok(trimmed.to_string())
13851 } else {
13852 Ok(format!("## Main\n{}", trimmed))
13853 }
13854}
13855
13856pub fn run_genuine_p2_on_target(
13868 program: &str,
13869 core_types: &str,
13870 interpreter: &str,
13871) -> Result<String, String> {
13872 let combined = genuine_p2_on_target_source(program, core_types, interpreter)?;
13873 with_reference_semantics(|| run_logos_source(&combined))
13874}
13875
13876pub fn genuine_p2_on_target_source(
13878 program: &str,
13879 core_types: &str,
13880 interpreter: &str,
13881) -> Result<String, String> {
13882 let pe_mini = pe_mini_source_text();
13883 let pe = pe_source_text();
13884
13885 let full_source = if program.contains("## Main") || program.contains("## To ") {
13886 program.to_string()
13887 } else {
13888 format!("## Main\n{}", program)
13889 };
13890
13891 let target_encoded = encode_program_source(&full_source)
13896 .map_err(|e| format!("Failed to encode target: {}", describe_parse_error(&e)))?;
13897 let pe_mini_prog = format!(
13898 "{}\n{}\n{}\n## Main\n{}\n\
13899 Let compileEnv be a new Map of Text to CVal.\n\
13900 Let compileState be makePeState(compileEnv, encodedFuncMap, 200).\n\
13901 Let compiled be peBlockM(encodedMain, compileState).\n\
13902 Let runEnv be a new Map of Text to CVal.\n\
13903 coreExecBlock(compiled, runEnv, encodedFuncMap).\n",
13904 core_types, pe_mini, interpreter, target_encoded
13905 );
13906
13907 let encoded = encode_program_source_compact(&pe_mini_prog).map_err(|e| {
13909 format!(
13910 "Failed to encode pe_mini+target for P2: {}",
13911 describe_parse_error(&e)
13912 )
13913 })?;
13914
13915 let driver = r#" Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 500).
13920 Let residual be peBlock(encodedMain, state).
13921 Let allFuncs be peFuncs(state).
13922 Let runEnv be a new Map of Text to CVal.
13923 coreExecBlock(residual, runEnv, allFuncs).
13924"#;
13925 Ok(format!(
13926 "{}\n{}\n{}\n## Main\n{}\n{}",
13927 CORE_TYPES_FOR_PE, pe, interpreter, encoded, driver
13928 ))
13929}
13930
13931pub fn run_genuine_p3_on_target(
13933 program: &str,
13934 core_types: &str,
13935 interpreter: &str,
13936) -> Result<String, String> {
13937 let combined = genuine_p3_on_target_source(program, core_types, interpreter)?;
13938 with_reference_semantics(|| run_logos_source(&combined))
13939}
13940
13941pub fn genuine_p3_on_target_source(
13943 program: &str,
13944 core_types: &str,
13945 interpreter: &str,
13946) -> Result<String, String> {
13947 let pe_bti = pe_bti_source_text();
13948 let pe = pe_source_text();
13949
13950 let full_source = if program.contains("## Main") || program.contains("## To ") {
13951 program.to_string()
13952 } else {
13953 format!("## Main\n{}", program)
13954 };
13955
13956 let bti_types = CORE_TYPES_FOR_PE
13957 .replace("specResults", "memoCache")
13958 .replace("onStack", "callGuard");
13959
13960 let target_encoded = encode_program_source(&full_source)
13961 .map_err(|e| format!("Failed to encode target: {}", describe_parse_error(&e)))?;
13962 let pe_bti_prog = format!(
13963 "{}\n{}\n{}\n## Main\n{}\n\
13964 Let compileEnv be a new Map of Text to CVal.\n\
13965 Let compileState be makePeState(compileEnv, encodedFuncMap, 200).\n\
13966 Let compiled be peBlockB(encodedMain, compileState).\n\
13967 Let runEnv be a new Map of Text to CVal.\n\
13968 coreExecBlock(compiled, runEnv, encodedFuncMap).\n",
13969 bti_types, pe_bti, interpreter, target_encoded
13970 );
13971
13972 let encoded = encode_program_source_compact(&pe_bti_prog).map_err(|e| {
13973 format!(
13974 "Failed to encode pe_bti+target for P3: {}",
13975 describe_parse_error(&e)
13976 )
13977 })?;
13978
13979 let driver = r#" Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
13981 Let residual be peBlock(encodedMain, state).
13982 Let runEnv be a new Map of Text to CVal.
13983 coreExecBlock(residual, runEnv, encodedFuncMap).
13984"#;
13985 Ok(format!(
13986 "{}\n{}\n{}\n## Main\n{}\n{}",
13987 CORE_TYPES_FOR_PE, pe, interpreter, encoded, driver
13988 ))
13989}
13990
13991pub fn projection2_source_real(
14001 _core_types: &str,
14002 _interpreter: &str,
14003) -> Result<GenuineProjectionResult, String> {
14004 let pe_mini = pe_mini_source_text();
14005 let pe = pe_source_text();
14006 let decompile = decompile_source_text();
14007
14008 let program = format!(
14018 "{}\n{}\n## Main\n Let env be a new Map of Text to CVal.\n Let funcs be a new Map of Text to CFunc.\n Let state be makePeState(env, funcs, 200).\n Let result be peBlockM(targetStmts, state).\n Show \"done\".\n",
14019 CORE_TYPES_FOR_PE, pe_mini
14020 );
14021
14022 let encoded = encode_program_source_compact(&program).map_err(|e| {
14024 format!(
14025 "Failed to encode pe_mini for P2: {}",
14026 describe_parse_error(&e)
14027 )
14028 })?;
14029
14030 let driver = r#" Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14034 Let residual be peBlock(encodedMain, state).
14035 Let nl be chr(10).
14036 Let mutable output be "".
14037 Let specFuncs be peFuncs(state).
14038 Let mutable allNames be collectCallNames(residual).
14039 Let mutable emitted be a new Map of Text to Bool.
14040 Let mutable changed be true.
14041 While changed:
14042 Set changed to false.
14043 Let mutable toAdd be a new Seq of Text.
14044 Repeat for fnKey in allNames:
14045 Let fkStr be "{fnKey}".
14046 If emitted contains fkStr:
14047 Let skipE be true.
14048 Otherwise:
14049 Set item fkStr of emitted to true.
14050 Let fkStr2 be "{fnKey}".
14051 If specFuncs contains fkStr2:
14052 Let fdef be item fkStr2 of specFuncs.
14053 Inspect fdef:
14054 When CFuncDef (fn0, ps0, pt0, rt0, body0):
14055 Let children be collectCallNames(body0).
14056 Repeat for child in children:
14057 Let childStr be "{child}".
14058 If not emitted contains childStr:
14059 Push child to toAdd.
14060 Set changed to true.
14061 Otherwise:
14062 Let skipF be true.
14063 Repeat for ta in toAdd:
14064 Push ta to allNames.
14065 Repeat for fnKey in allNames:
14066 Let fkStr be "{fnKey}".
14067 If specFuncs contains fkStr:
14068 Let fdef be item fkStr of specFuncs.
14069 Let funcSrc be decompileFunc(fdef).
14070 If the length of funcSrc is greater than 0:
14071 Set output to "{output}{funcSrc}{nl}".
14072 Let mainSrc be decompileBlock(residual, 0).
14073 Set output to "{output}## Main{nl}{mainSrc}".
14074 Show output.
14075"#;
14076 let combined = format!(
14077 "{}\n{}\n{}\n## Main\n{}\n{}",
14078 CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14079 );
14080
14081 let result = with_reference_semantics(|| run_logos_source(&combined))?;
14082
14083 let result = fix_decompiled_types(&result, &[
14088 ("peExprM_", "(e: CExpr) -> CExpr:"),
14089 ("peBlockM_", "(stmts: Seq of CStmt) -> Seq of CStmt:"),
14090 ("checkLiteralM_", "(e: CExpr) -> Bool:"),
14091 ("exprToValM_", "(e: CExpr) -> CVal:"),
14092 ("valToExprM_", "(v: CVal) -> CExpr:"),
14093 ("evalBinOpM_", "(binOp: Text) and (lv: CVal) and (rv: CVal) -> CVal:"),
14094 ("isCopyPropSafeM_", "(e: CExpr) -> Bool:"),
14095 ("checkVNothingM_", "(v: CVal) -> Bool:"),
14096 ("hasReturnM_", "(stmts: Seq of CStmt) -> Bool:"),
14097 ("extractReturnM_", "(stmts: Seq of CStmt) -> CExpr:"),
14098 ("validateExtractReturnM_", "(result: CExpr) and (bodyStmts: Seq of CStmt) -> CExpr:"),
14099 ("makeKeyM_", "(fnName: Text) and (args: Seq of CExpr) -> Text:"),
14100 ("exprToKeyPartM_", "(e: CExpr) -> Text:"),
14101 ("collectSetVarsM_", "(stmts: Seq of CStmt) -> Seq of Text:"),
14102 ("peEnvM_", "(st: PEMiniState) -> Map of Text to CVal:"),
14103 ("peFuncsM_", "(st: PEMiniState) -> Map of Text to CFunc:"),
14104 ("peDepthM_", "(st: PEMiniState) -> Int:"),
14105 ("peStaticEnvM_", "(st: PEMiniState) -> Map of Text to CExpr:"),
14106 ("peMemoCacheM_", "(st: PEMiniState) -> Map of Text to CExpr:"),
14107 ("peStateWithEnvDepthM_", "(st: PEMiniState) and (newEnv: Map of Text to CVal) and (d: Int) -> PEMiniState:"),
14108 ("peStateWithEnvDepthStaticM_", "(st: PEMiniState) and (newEnv: Map of Text to CVal) and (d: Int) and (newSe: Map of Text to CExpr) -> PEMiniState:"),
14109 ]);
14110
14111 let (block_entry, expr_entry) = discover_entry_points(&result, "peBlockM_", "peExprM_");
14113 if block_entry.is_empty() {
14114 return Err("Genuine P2: no peBlockM_ entry found in residual".to_string());
14115 }
14116
14117 let func_defs_only = strip_main_block(&result);
14120
14121 let pe_mini_helpers = pe_mini_source_text();
14125
14126 let alias = format!(
14130 "\n## To compileBlock (stmts: Seq of CStmt) -> Seq of CStmt:\n Return {}(stmts).\n",
14131 block_entry
14132 );
14133
14134 let combined = format!("{}\n{}\n{}", pe_mini_helpers, func_defs_only, alias);
14138 let full_source = deduplicate_functions(&combined);
14139
14140 Ok(GenuineProjectionResult {
14141 source: full_source,
14142 block_entry: "compileBlock".to_string(),
14143 expr_entry,
14144 })
14145}
14146
14147pub fn genuine_projection2_residual() -> Result<String, String> {
14158 let pe_mini = pe_mini_source_text();
14159 let pe = pe_source_text();
14160 let decompile = decompile_source_text();
14161
14162 let program = format!(
14164 "{}\n{}\n## Main\n Let env be a new Map of Text to CVal.\n Let funcs be a new Map of Text to CFunc.\n Let state be makePeState(env, funcs, 200).\n Let result be peBlockM(targetStmts, state).\n Show \"done\".\n",
14165 CORE_TYPES_FOR_PE, pe_mini
14166 );
14167
14168 let encoded = encode_program_source_compact(&program)
14170 .map_err(|e| format!("Failed to encode pe_mini: {}", describe_parse_error(&e)))?;
14171
14172 let driver = r#" Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14174 Let residual be peBlock(encodedMain, state).
14175 Let nl be chr(10).
14176 Let mutable output be "".
14177 Let specFuncs be peFuncs(state).
14178 Let specNames be collectCallNames(residual).
14179 Repeat for sn in specNames:
14180 Let snKey be "{sn}".
14181 If specFuncs contains snKey:
14182 Let fdef be item snKey of specFuncs.
14183 Let funcSrc be decompileFunc(fdef).
14184 If the length of funcSrc is greater than 0:
14185 Set output to "{output}{funcSrc}{nl}".
14186 Let mainSrc be decompileBlock(residual, 0).
14187 Set output to "{output}## Main{nl}{mainSrc}".
14188 Show output.
14189"#;
14190 let combined = format!(
14191 "{}\n{}\n{}\n## Main\n{}\n{}",
14192 CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14193 );
14194
14195 let result = with_reference_semantics(|| run_logos_source(&combined))?;
14196 Ok(result)
14197}
14198
14199pub fn genuine_projection3_residual() -> Result<String, String> {
14210 let pe_bti = pe_bti_source_text();
14211 let pe = pe_source_text();
14212 let decompile = decompile_source_text();
14213
14214 let bti_types = CORE_TYPES_FOR_PE
14216 .replace("specResults", "memoCache")
14217 .replace("onStack", "callGuard");
14218
14219 let program = format!(
14221 "{}\n{}\n## Main\n Let env be a new Map of Text to CVal.\n Let funcs be a new Map of Text to CFunc.\n Let state be makePeState(env, funcs, 200).\n Let result be peBlockB(targetStmts, state).\n Show \"done\".\n",
14222 bti_types, pe_bti
14223 );
14224
14225 let encoded = encode_program_source_compact(&program)
14227 .map_err(|e| format!("Failed to encode pe_bti: {}", describe_parse_error(&e)))?;
14228
14229 let driver = r#" Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14231 Let residual be peBlock(encodedMain, state).
14232 Let nl be chr(10).
14233 Let mutable output be "".
14234 Let specFuncs be peFuncs(state).
14235 Let specNames be collectCallNames(residual).
14236 Repeat for sn in specNames:
14237 Let snKey be "{sn}".
14238 If specFuncs contains snKey:
14239 Let fdef be item snKey of specFuncs.
14240 Let funcSrc be decompileFunc(fdef).
14241 If the length of funcSrc is greater than 0:
14242 Set output to "{output}{funcSrc}{nl}".
14243 Let mainSrc be decompileBlock(residual, 0).
14244 Set output to "{output}## Main{nl}{mainSrc}".
14245 Show output.
14246"#;
14247 let combined = format!(
14248 "{}\n{}\n{}\n## Main\n{}\n{}",
14249 CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14250 );
14251
14252 let result = with_reference_semantics(|| run_logos_source(&combined))?;
14253 Ok(result)
14254}
14255
14256pub fn projection3_source_real(_core_types: &str) -> Result<GenuineProjectionResult, String> {
14265 let pe_bti = pe_bti_source_text();
14266 let pe = pe_source_text();
14267 let decompile = decompile_source_text();
14268
14269 let bti_types = CORE_TYPES_FOR_PE
14271 .replace("specResults", "memoCache")
14272 .replace("onStack", "callGuard");
14273
14274 let program = format!(
14276 "{}\n{}\n## Main\n Let env be a new Map of Text to CVal.\n Let funcs be a new Map of Text to CFunc.\n Let state be makePeState(env, funcs, 200).\n Let result be peBlockB(targetStmts, state).\n Show \"done\".\n",
14277 bti_types, pe_bti
14278 );
14279
14280 let encoded = encode_program_source_compact(&program).map_err(|e| {
14282 format!(
14283 "Failed to encode pe_bti for P3: {}",
14284 describe_parse_error(&e)
14285 )
14286 })?;
14287
14288 let driver = r#" Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14290 Let residual be peBlock(encodedMain, state).
14291 Let nl be chr(10).
14292 Let mutable output be "".
14293 Let specFuncs be peFuncs(state).
14294 Let mutable allNames be collectCallNames(residual).
14295 Let mutable emitted be a new Map of Text to Bool.
14296 Let mutable changed be true.
14297 While changed:
14298 Set changed to false.
14299 Let mutable toAdd be a new Seq of Text.
14300 Repeat for fnKey in allNames:
14301 Let fkStr be "{fnKey}".
14302 If emitted contains fkStr:
14303 Let skipE be true.
14304 Otherwise:
14305 Set item fkStr of emitted to true.
14306 Let fkStr2 be "{fnKey}".
14307 If specFuncs contains fkStr2:
14308 Let fdef be item fkStr2 of specFuncs.
14309 Inspect fdef:
14310 When CFuncDef (fn0, ps0, pt0, rt0, body0):
14311 Let children be collectCallNames(body0).
14312 Repeat for child in children:
14313 Let childStr be "{child}".
14314 If not emitted contains childStr:
14315 Push child to toAdd.
14316 Set changed to true.
14317 Otherwise:
14318 Let skipF be true.
14319 Repeat for ta in toAdd:
14320 Push ta to allNames.
14321 Repeat for fnKey in allNames:
14322 Let fkStr be "{fnKey}".
14323 If specFuncs contains fkStr:
14324 Let fdef be item fkStr of specFuncs.
14325 Let funcSrc be decompileFunc(fdef).
14326 If the length of funcSrc is greater than 0:
14327 Set output to "{output}{funcSrc}{nl}".
14328 Let mainSrc be decompileBlock(residual, 0).
14329 Set output to "{output}## Main{nl}{mainSrc}".
14330 Show output.
14331"#;
14332 let combined = format!(
14333 "{}\n{}\n{}\n## Main\n{}\n{}",
14334 CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14335 );
14336
14337 let result = with_reference_semantics(|| run_logos_source(&combined))?;
14338
14339 let result = fix_decompiled_types(
14342 &result,
14343 &[
14344 ("peExprB_", "(e: CExpr) -> CExpr:"),
14345 ("peBlockB_", "(stmts: Seq of CStmt) -> Seq of CStmt:"),
14346 ("isStatic_", "(e: CExpr) -> Bool:"),
14347 ("isLiteral_", "(e: CExpr) -> Bool:"),
14348 ("allStatic_", "(args: Seq of CExpr) -> Bool:"),
14349 ("exprToVal_", "(e: CExpr) -> CVal:"),
14350 ("valToExpr_", "(v: CVal) -> CExpr:"),
14351 (
14352 "evalBinOp_",
14353 "(binOp: Text) and (lv: CVal) and (rv: CVal) -> CVal:",
14354 ),
14355 ("isCopyPropSafe_", "(e: CExpr) -> Bool:"),
14356 ("isVNothing_", "(v: CVal) -> Bool:"),
14357 ("hasReturn_", "(stmts: Seq of CStmt) -> Bool:"),
14358 ("extractReturnB_", "(stmts: Seq of CStmt) -> CExpr:"),
14359 (
14360 "makeKey_",
14361 "(fnName: Text) and (args: Seq of CExpr) -> Text:",
14362 ),
14363 ("exprToKeyPartB_", "(e: CExpr) -> Text:"),
14364 ("collectSetVars_", "(stmts: Seq of CStmt) -> Seq of Text:"),
14365 ],
14366 );
14367
14368 let (block_entry, expr_entry) = discover_entry_points(&result, "peBlockB_", "peExprB_");
14370 if block_entry.is_empty() {
14371 return Err("Genuine P3: no peBlockB_ entry found in residual".to_string());
14372 }
14373
14374 let func_defs_only = strip_main_block(&result);
14376
14377 let pe_bti_helpers = pe_bti_source_text();
14379
14380 let alias = format!(
14383 "\n## To cogenBlock (stmts: Seq of CStmt) -> Seq of CStmt:\n Return {}(stmts).\n",
14384 block_entry
14385 );
14386 let combined = format!("{}\n{}\n{}", pe_bti_helpers, func_defs_only, alias);
14387 let full_source = deduplicate_functions(&combined);
14388
14389 Ok(GenuineProjectionResult {
14390 source: full_source,
14391 block_entry: "cogenBlock".to_string(),
14392 expr_entry,
14393 })
14394}
14395
14396fn deduplicate_functions(source: &str) -> String {
14398 let mut seen = std::collections::HashSet::new();
14399 let mut result = String::with_capacity(source.len());
14400 let mut skip_until_next = false;
14401 for line in source.lines() {
14402 let trimmed = line.trim();
14403 if let Some(rest) = trimmed.strip_prefix("## To ") {
14404 let name = rest.split(' ').next().unwrap_or("");
14405 if !seen.insert(name.to_string()) {
14406 skip_until_next = true;
14407 continue;
14408 }
14409 skip_until_next = false;
14410 } else if trimmed.starts_with("## Main") {
14411 skip_until_next = false;
14412 } else if skip_until_next {
14413 if !trimmed.starts_with("## ") {
14415 continue;
14416 }
14417 skip_until_next = false;
14418 }
14419 result.push_str(line);
14420 result.push('\n');
14421 }
14422 result
14423}
14424
14425fn strip_main_block(source: &str) -> String {
14429 let mut result = String::with_capacity(source.len());
14430 let mut in_main = false;
14431 for line in source.lines() {
14432 let trimmed = line.trim();
14433 if trimmed == "## Main" {
14434 in_main = true;
14435 continue;
14436 }
14437 if in_main {
14438 if trimmed.starts_with("## To ") {
14440 in_main = false;
14441 } else {
14442 continue;
14443 }
14444 }
14445 result.push_str(line);
14446 result.push('\n');
14447 }
14448 result
14449}
14450
14451fn extract_main_block(source: &str) -> String {
14453 let mut result = String::new();
14454 let mut in_main = false;
14455 for line in source.lines() {
14456 let trimmed = line.trim();
14457 if trimmed == "## Main" {
14458 in_main = true;
14459 continue;
14460 }
14461 if in_main {
14462 if trimmed.starts_with("## To ") {
14463 break;
14464 }
14465 result.push_str(line);
14466 result.push('\n');
14467 }
14468 }
14469 result
14470}
14471
14472fn fix_decompiled_types(source: &str, type_map: &[(&str, &str)]) -> String {
14476 let mut result = String::with_capacity(source.len());
14477 for line in source.lines() {
14478 let trimmed = line.trim();
14479 if let Some(rest) = trimmed.strip_prefix("## To ") {
14480 let name = rest.split(' ').next().unwrap_or("");
14481 let mut fixed = false;
14482 for (prefix, sig) in type_map {
14483 if name.starts_with(prefix) {
14484 result.push_str(&format!("## To {} {}\n", name, sig));
14485 fixed = true;
14486 break;
14487 }
14488 }
14489 if !fixed {
14490 result.push_str(line);
14491 result.push('\n');
14492 }
14493 } else {
14494 result.push_str(line);
14495 result.push('\n');
14496 }
14497 }
14498 let result = result
14499 .replace("Seq of Any", "Seq of CExpr")
14500 .replace("Set of Any", "Set of CExpr")
14501 .replace(": Any)", ": CExpr)")
14502 .replace("-> Any:", "-> CExpr:");
14503 result
14504}
14505
14506fn replace_word(source: &str, from: &str, to: &str) -> String {
14507 let mut result = String::with_capacity(source.len());
14508 let mut remaining = source;
14509 while let Some(pos) = remaining.find(from) {
14510 let before = if pos > 0 {
14511 remaining.as_bytes()[pos - 1]
14512 } else {
14513 b' '
14514 };
14515 let after_pos = pos + from.len();
14516 let after = if after_pos < remaining.len() {
14517 remaining.as_bytes()[after_pos]
14518 } else {
14519 b' '
14520 };
14521 let is_word = !before.is_ascii_alphanumeric()
14522 && before != b'_'
14523 && !after.is_ascii_alphanumeric()
14524 && after != b'_';
14525 result.push_str(&remaining[..pos]);
14526 if is_word {
14527 result.push_str(to);
14528 } else {
14529 result.push_str(from);
14530 }
14531 remaining = &remaining[after_pos..];
14532 }
14533 result.push_str(remaining);
14534 result
14535}
14536
14537#[cfg(test)]
14538#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/compile/tests.rs"]
14539mod tests;