1use std::collections::HashMap;
48use std::fmt;
49
50#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
52#[non_exhaustive]
53pub enum LinkError {
54 #[error("no module found")]
56 NoModule,
57 #[error("unbalanced braces or string literals")]
59 Unbalanced,
60 #[error("quoted symbol names are not supported")]
62 QuotedSymbol,
63}
64
65#[derive(Clone)]
67pub struct Imported {
68 aliases: String,
70 functions: String,
72 symbols: HashMap<String, String>,
74}
75
76impl Imported {
77 pub fn symbol(&self, original: &str) -> Option<&str> {
80 self.symbols.get(original).map(String::as_str)
81 }
82
83 pub fn functions(&self) -> &str {
85 &self.functions
86 }
87}
88
89impl fmt::Debug for Imported {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.debug_struct("Imported")
92 .field("symbols", &self.symbols)
93 .finish_non_exhaustive()
94 }
95}
96
97pub fn import(module: &str, prefix: &str) -> Result<Imported, LinkError> {
109 let (outside, body) = split_module(module)?;
110
111 let mut renames = HashMap::new();
112 let mut aliases = Vec::new();
113 for line in outside.lines() {
114 let line = line.trim();
115 if let Some(name) = alias_definition(line) {
116 let (sigil, ident) = name.split_at(1);
117 renames.insert(name.to_string(), format!("{sigil}{prefix}_{ident}"));
118 aliases.push(line);
119 }
120 }
121 let mut symbols = HashMap::new();
122 for name in function_definitions(body)? {
123 symbols.insert(name.to_string(), format!("{prefix}_{name}"));
124 }
125 renames.extend(
126 symbols
127 .iter()
128 .map(|(k, v)| (format!("@{k}"), format!("@{v}"))),
129 );
130
131 let aliases = aliases
132 .iter()
133 .map(|line| rename(line, &renames))
134 .collect::<Result<Vec<_>, _>>()?
135 .join("\n");
136 let functions = make_private(&rename(body, &renames)?);
137 Ok(Imported {
138 aliases,
139 functions,
140 symbols,
141 })
142}
143
144pub fn link(main: &str, imports: &[Imported]) -> String {
149 let mut out = String::new();
150 for import in imports {
151 if !import.aliases.is_empty() {
152 out.push_str(&import.aliases);
153 out.push('\n');
154 }
155 }
156 out.push_str("module @ruxla {\n");
157 for import in imports {
158 out.push_str(import.functions.trim_matches('\n'));
159 out.push('\n');
160 }
161 out.push_str(main.trim_matches('\n'));
162 out.push_str("\n}\n");
163 out
164}
165
166fn split_module(text: &str) -> Result<(String, &str), LinkError> {
168 let start = find_keyword(text, "module").ok_or(LinkError::NoModule)?;
169 let mut open = find_outside_strings(&text[start..], '{')
170 .map(|i| start + i)
171 .ok_or(LinkError::NoModule)?;
172 if text[start..open].trim_end().ends_with("attributes") {
175 let attrs_end = matching_brace(text, open)?;
176 open = find_outside_strings(&text[attrs_end + 1..], '{')
177 .map(|i| attrs_end + 1 + i)
178 .ok_or(LinkError::NoModule)?;
179 }
180 let close = matching_brace(text, open)?;
181 let outside = format!("{}\n{}", &text[..start], &text[close + 1..]);
182 Ok((outside, &text[open + 1..close]))
183}
184
185fn find_keyword(text: &str, keyword: &str) -> Option<usize> {
187 let mut offset = 0;
188 for line in text.split_inclusive('\n') {
189 let trimmed = line.trim_start();
190 if let Some(rest) = trimmed.strip_prefix(keyword)
191 && rest.starts_with(|c: char| c.is_whitespace() || c == '@' || c == '{')
192 {
193 return Some(offset + (line.len() - trimmed.len()));
194 }
195 offset += line.len();
196 }
197 None
198}
199
200fn find_outside_strings(text: &str, target: char) -> Option<usize> {
202 let mut chars = text.char_indices();
203 while let Some((i, c)) = chars.next() {
204 match c {
205 '"' => skip_string(&mut chars)?,
206 c if c == target => return Some(i),
207 _ => {}
208 }
209 }
210 None
211}
212
213fn matching_brace(text: &str, open: usize) -> Result<usize, LinkError> {
215 let mut depth = 0usize;
216 let mut chars = text[open..].char_indices();
217 while let Some((i, c)) = chars.next() {
218 match c {
219 '"' => skip_string(&mut chars).ok_or(LinkError::Unbalanced)?,
220 '{' => depth += 1,
221 '}' => {
222 depth -= 1;
223 if depth == 0 {
224 return Ok(open + i);
225 }
226 }
227 _ => {}
228 }
229 }
230 Err(LinkError::Unbalanced)
231}
232
233fn skip_string(chars: &mut std::str::CharIndices<'_>) -> Option<()> {
235 let mut escaped = false;
236 for (_, c) in chars.by_ref() {
237 match c {
238 _ if escaped => escaped = false,
239 '\\' => escaped = true,
240 '"' => return Some(()),
241 _ => {}
242 }
243 }
244 None
245}
246
247fn alias_definition(line: &str) -> Option<&str> {
250 if !line.starts_with(['#', '!']) {
251 return None;
252 }
253 let end = 1 + line[1..].find(|c: char| !is_ident_char(c))?;
254 line[end..]
255 .trim_start()
256 .starts_with('=')
257 .then(|| &line[..end])
258}
259
260fn function_definitions(body: &str) -> Result<Vec<&str>, LinkError> {
262 let mut names = Vec::new();
263 let mut rest = body;
264 while let Some(i) = rest.find("func.func") {
265 let after = &rest[i + "func.func".len()..];
266 let at = after.find('@').ok_or(LinkError::NoModule)?;
267 let name = &after[at + 1..];
268 if name.starts_with('"') {
269 return Err(LinkError::QuotedSymbol);
270 }
271 let end = name.find(|c: char| !is_ident_char(c)).unwrap_or(name.len());
272 names.push(&name[..end]);
273 rest = &name[end..];
274 }
275 Ok(names)
276}
277
278fn rename(text: &str, renames: &HashMap<String, String>) -> Result<String, LinkError> {
281 let mut out = String::with_capacity(text.len());
282 let mut chars = text.char_indices().peekable();
283 while let Some((i, c)) = chars.next() {
284 match c {
285 '"' => {
286 let mut end = text.len();
287 let mut escaped = false;
288 out.push('"');
289 for (j, c) in chars.by_ref() {
290 match c {
291 _ if escaped => escaped = false,
292 '\\' => escaped = true,
293 '"' => {
294 end = j;
295 break;
296 }
297 _ => {}
298 }
299 }
300 if end == text.len() {
301 return Err(LinkError::Unbalanced);
302 }
303 out.push_str(&text[i + 1..=end]);
304 }
305 '@' | '#' | '!' => {
306 let start = i;
307 let mut end = i + 1;
308 while let Some(&(j, c)) = chars.peek() {
309 if !is_ident_char(c) {
310 break;
311 }
312 end = j + c.len_utf8();
313 chars.next();
314 }
315 let token = &text[start..end];
316 out.push_str(renames.get(token).map_or(token, String::as_str));
317 }
318 c => out.push(c),
319 }
320 }
321 Ok(out)
322}
323
324fn make_private(text: &str) -> String {
326 text.replace("func.func public @", "func.func private @")
327 .replace("func.func @", "func.func private @")
328}
329
330fn is_ident_char(c: char) -> bool {
331 c.is_ascii_alphanumeric() || matches!(c, '_' | '$' | '.' | '-')
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337
338 const EXPORTED: &str = r#"#loc1 = loc("x")
339module @jit_f attributes {jax.uses_shape_polymorphism = false, mhlo.num_partitions = 1 : i32} {
340 func.func public @main(%arg0: tensor<2xf32> loc("x")) -> (tensor<2xf32> {jax.result_info = "result"}) {
341 %0 = call @helper(%arg0) : (tensor<2xf32>) -> tensor<2xf32> loc(#loc2)
342 return %0 : tensor<2xf32> loc(#loc)
343 } loc(#loc)
344 func.func private @helper(%arg0: tensor<2xf32>) -> tensor<2xf32> {
345 %0 = stablehlo.add %arg0, %arg0 : tensor<2xf32> loc(#loc1)
346 return %0 : tensor<2xf32> loc(#loc)
347 } loc(#loc)
348} loc(#loc)
349#loc = loc(unknown)
350#loc2 = loc("jit(f)/helper @main"(#loc1))
351"#;
352
353 #[test]
354 fn import_renames_functions_and_aliases() {
355 let f = import(EXPORTED, "p").unwrap();
356 assert_eq!(f.symbol("main"), Some("p_main"));
357 assert_eq!(f.symbol("helper"), Some("p_helper"));
358
359 let text = f.functions();
360 assert!(text.contains("func.func private @p_main("));
361 assert!(text.contains("func.func private @p_helper("));
362 assert!(text.contains("call @p_helper("));
363 assert!(text.contains("loc(#p_loc2)"));
364 assert!(text.contains("loc(#p_loc1)"));
365 assert!(!text.contains("mhlo.num_partitions"));
367
368 assert!(f.aliases.contains("#p_loc1 = loc(\"x\")"));
369 assert!(f.aliases.contains("#p_loc = loc(unknown)"));
370 assert!(
373 f.aliases
374 .contains("#p_loc2 = loc(\"jit(f)/helper @main\"(#p_loc1))")
375 );
376 }
377
378 #[test]
379 fn rename_respects_token_boundaries() {
380 let renames = HashMap::from([("#loc".to_string(), "#p_loc".to_string())]);
381 assert_eq!(
382 rename("loc(#loc) loc(#loc1)", &renames).unwrap(),
383 "loc(#p_loc) loc(#loc1)"
384 );
385 }
386
387 #[test]
388 fn module_without_attributes() {
389 let f = import("module {\n func.func @main() {\n return\n }\n}\n", "q").unwrap();
390 assert!(f.functions().contains("func.func private @q_main()"));
391 }
392
393 #[test]
394 fn link_places_functions_in_one_module() {
395 let f = import(EXPORTED, "p").unwrap();
396 let linked = link("func.func public @main() {\n return\n}", &[f]);
397 assert!(linked.starts_with("#p_loc1 = "));
398 assert!(linked.contains("module @ruxla {\n"));
399 assert!(linked.contains("func.func public @main()"));
400 assert!(linked.trim_end().ends_with('}'));
401 }
402
403 #[test]
404 fn errors() {
405 assert_eq!(
406 import("func.func @f()", "p").unwrap_err(),
407 LinkError::NoModule
408 );
409 assert_eq!(import("module {", "p").unwrap_err(), LinkError::Unbalanced);
410 assert_eq!(
411 import("module { func.func @\"f\"() }", "p").unwrap_err(),
412 LinkError::QuotedSymbol
413 );
414 }
415}