1use crate::registry::normalize_language;
2use std::collections::{BTreeMap, BTreeSet};
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4pub enum PreservationMode {
5 Direct,
6 Rewrite,
7 Helper,
8 Emulate,
9 Runtime,
10 Error,
11}
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct PreservationRule {
14 pub capability: String,
15 pub target: String,
16 pub mode: PreservationMode,
17 pub preconditions: Vec<String>,
18 pub requirements: Vec<String>,
19 pub handler: String,
20 pub test: String,
21}
22#[derive(Debug, Clone, Default)]
23pub struct PreservationRegistry {
24 pub rules: Vec<PreservationRule>,
25}
26impl PreservationRegistry {
27 pub fn solve(&self, target: &str, capability: &str) -> Option<&PreservationRule> {
28 let t = normalize_language(target);
29 [
30 PreservationMode::Direct,
31 PreservationMode::Rewrite,
32 PreservationMode::Helper,
33 PreservationMode::Emulate,
34 PreservationMode::Runtime,
35 ]
36 .into_iter()
37 .find_map(|m| {
38 self.rules
39 .iter()
40 .find(|r| r.target == t && r.capability == capability && r.mode == m)
41 })
42 }
43}
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum RequirementKind {
46 Import,
47 Helper,
48 Emulation,
49 Runtime,
50}
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Requirement {
53 pub id: String,
54 pub kind: RequirementKind,
55 pub target: String,
56 pub dependencies: Vec<String>,
57 pub preconditions: Vec<String>,
58 pub tests: Vec<String>,
59 pub emit: String,
60}
61#[derive(Debug, Clone, Default)]
62pub struct RequirementRegistry {
63 pub rules: BTreeMap<String, Requirement>,
64}
65impl RequirementRegistry {
66 pub fn resolve(&self, ids: &[String]) -> Result<Vec<&Requirement>, String> {
67 fn visit<'a>(
68 id: &str,
69 r: &'a RequirementRegistry,
70 state: &mut BTreeMap<String, u8>,
71 out: &mut Vec<&'a Requirement>,
72 ) -> Result<(), String> {
73 match state.get(id).copied().unwrap_or(0) {
74 1 => return Err(format!("cyclic requirement: {id}")),
75 2 => return Ok(()),
76 _ => {}
77 }
78 let rule = r
79 .rules
80 .get(id)
81 .ok_or_else(|| format!("unknown requirement: {id}"))?;
82 state.insert(id.into(), 1);
83 for d in &rule.dependencies {
84 visit(d, r, state, out)?;
85 }
86 state.insert(id.into(), 2);
87 out.push(rule);
88 Ok(())
89 }
90 let mut state = BTreeMap::new();
91 let mut out = Vec::new();
92 let mut uniq = BTreeSet::new();
93 for id in ids {
94 uniq.insert(id.clone());
95 }
96 for id in uniq {
97 visit(&id, self, &mut state, &mut out)?;
98 }
99 Ok(out)
100 }
101}
102
103pub fn target_name(target: &str, preferred: &str) -> String {
104 let mut s: String = preferred
105 .chars()
106 .map(|c| {
107 if c.is_ascii_alphanumeric() || c == '_' {
108 c
109 } else {
110 '_'
111 }
112 })
113 .collect();
114 if s.is_empty() {
115 s = "value".into();
116 }
117 if s.chars().next().unwrap().is_ascii_digit() {
118 s.insert(0, '_');
119 }
120 if reserved(target).contains(s.as_str()) {
121 format!("__uast_{s}")
122 } else {
123 s
124 }
125}
126fn reserved(target: &str) -> BTreeSet<&'static str> {
127 let words=match normalize_language(target).as_str(){"go"=>"var const func type package import return if else for switch case default range go defer map struct interface","rust"=>"as break const continue crate else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while","cpp"=>"auto class struct template typename namespace return if else for while switch case default const static void int double float char bool",_=>""};
128 words.split_whitespace().collect()
129}
130pub fn target_na(target: &str) -> &'static str {
131 match normalize_language(target).as_str() {
132 "rust" => "RValue::Num(f64::NAN)",
133 "go" => "math.NaN()",
134 "julia" => "NaN",
135 "python" => "float('nan')",
136 _ => "NaN",
137 }
138}
139pub fn target_inf(target: &str) -> &'static str {
140 match normalize_language(target).as_str() {
141 "rust" => "RValue::Num(f64::INFINITY)",
142 "go" => "math.Inf(1)",
143 "julia" => "Inf",
144 "python" => "float('inf')",
145 _ => "Inf",
146 }
147}
148pub fn emit_dispatch(target: &str, name: &str, args: &[&str]) -> Result<String, String> {
149 let k = if let Some(op) = name.strip_prefix("__binary_") {
150 if ["+", "-", "*", "/", "^", "**", "%%", "%/%"].contains(&op) {
151 "arithmetic"
152 } else if ["==", "!=", "<", "<=", ">", ">="].contains(&op) {
153 "relational"
154 } else if ["&", "|", "&&", "||"].contains(&op) {
155 "logical"
156 } else {
157 "language"
158 }
159 } else if name.starts_with("__unary_") {
160 "arithmetic"
161 } else {
162 "runtime"
163 };
164 let a = args.join(", ");
165 match normalize_language(target).as_str() {
166 "rust" => Ok(format!("r_call({k:?}, {name:?}, vec![{a}])")),
167 "go" => Ok(format!("rCall({k:?}, {name:?}, []any{{{a}}})")),
168 "julia" => Ok(format!("r_call({k:?}, {name:?}, Any[{a}])")),
169 "python" => Ok(format!("r_call({k:?}, {name:?}, [{a}])")),
170 _ => Err(format!("target dispatch not yet native for {target}")),
171 }
172}