Skip to main content

ruxla_stablehlo/
link.rs

1//! Linking StableHLO modules at the text level.
2//!
3//! A module exported from JAX (`jax.export`) defines a public function named
4//! `main` and possibly private helper functions. To call it from a program
5//! generated by ruxla, [`import`] renames every symbol it defines with a
6//! prefix (`@main` becomes `@policy_main`, for example) and makes the
7//! functions private. [`link`] then places the imported functions and the
8//! caller's functions in one module, where the caller reaches them through
9//! `func.call`. XLA inlines the callees, so the whole program is optimized
10//! together.
11//!
12//! The functions work on the MLIR text format without parsing it fully. They
13//! understand symbol references (`@name`), attribute and type aliases
14//! (`#name`, `!name`), string literals, and the nesting of braces, which is
15//! enough for modules produced by JAX.
16//!
17//! # Examples
18//!
19//! ```
20//! use ruxla_stablehlo::link;
21//!
22//! let exported = r#"
23//! module @jit_f attributes {mhlo.num_replicas = 1 : i32} {
24//!   func.func public @main(%x: tensor<f32>) -> tensor<f32> {
25//!     %0 = func.call @helper(%x) : (tensor<f32>) -> tensor<f32>
26//!     return %0 : tensor<f32>
27//!   }
28//!   func.func private @helper(%x: tensor<f32>) -> tensor<f32> {
29//!     return %x : tensor<f32>
30//!   }
31//! }
32//! "#;
33//! let f = link::import(exported, "f")?;
34//! assert_eq!(f.symbol("main"), Some("f_main"));
35//!
36//! let main = r#"
37//! func.func public @main(%x: tensor<f32>) -> tensor<f32> {
38//!   %0 = func.call @f_main(%x) : (tensor<f32>) -> tensor<f32>
39//!   return %0 : tensor<f32>
40//! }
41//! "#;
42//! let linked = link::link(main, &[f]);
43//! assert!(linked.contains("func.func private @f_helper"));
44//! # Ok::<(), link::LinkError>(())
45//! ```
46
47use std::collections::HashMap;
48use std::fmt;
49
50/// Errors returned by [`import`].
51#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
52#[non_exhaustive]
53pub enum LinkError {
54    /// The text does not contain a `module` with a body.
55    #[error("no module found")]
56    NoModule,
57    /// Braces or string literals are not balanced.
58    #[error("unbalanced braces or string literals")]
59    Unbalanced,
60    /// The module uses a quoted symbol name (`@"name"`), which is not supported.
61    #[error("quoted symbol names are not supported")]
62    QuotedSymbol,
63}
64
65/// Functions taken from a module by [`import`], ready to be linked.
66#[derive(Clone)]
67pub struct Imported {
68    /// Alias definitions (`#name = ...`), renamed, one per line.
69    aliases: String,
70    /// The functions of the module body, renamed and made private.
71    functions: String,
72    /// Original symbol names mapped to their new names.
73    symbols: HashMap<String, String>,
74}
75
76impl Imported {
77    /// Returns the new name of a symbol defined by the imported module, such
78    /// as `"policy_main"` for `"main"`.
79    pub fn symbol(&self, original: &str) -> Option<&str> {
80        self.symbols.get(original).map(String::as_str)
81    }
82
83    /// Returns the renamed functions as MLIR text.
84    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
97/// Takes the functions out of a module and renames its symbols with `prefix`.
98///
99/// Every function defined in the module, and every attribute or type alias
100/// defined next to it, is renamed to `{prefix}_{name}`. All functions become
101/// private, so that the linked module has only the caller's `main` as its
102/// entry point. Attributes of the module itself are dropped.
103///
104/// # Errors
105///
106/// Returns an error if the text has no module, if its braces or string
107/// literals are unbalanced, or if it uses quoted symbol names.
108pub 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
144/// Places the caller's functions and imported functions in one module.
145///
146/// `main` holds the caller's functions (not wrapped in a `module`), one of
147/// which should be the public `@main` entry point.
148pub 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
166/// Splits a module into the text outside it and the body inside its braces.
167fn 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    // `module @name attributes {...} {...}`: the first brace may open the
173    // attribute dictionary rather than the body.
174    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
185/// Finds `keyword` as a whole word at the start of a line, outside strings.
186fn 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
200/// Finds the first `target` outside string literals.
201fn 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
213/// Returns the index of the brace that closes the one at `open`.
214fn 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
233/// Advances past the end of a string literal whose opening quote was consumed.
234fn 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
247/// Returns the alias name (with its sigil) if `line` defines one, such as
248/// `#loc1` in `#loc1 = loc("x")`.
249fn 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
260/// Returns the names of the functions defined in a module body.
261fn 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
278/// Replaces symbol and alias references found in `renames`, leaving string
279/// literals untouched.
280fn 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
324/// Makes every function definition private.
325fn 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        // Module attributes are dropped.
366        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        // References inside alias definitions are renamed, but string
371        // literals are not.
372        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}