lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

kotlin.rs (8883B)


      1 //! UniFFI0.32.2 close policy. The upstream automatic AutoCloseable helper
      2 //! collides with a real exported close method (upstream issue2955).
      3 //! Only remove the handle-destruction alias for objects whose extracted Rust
      4 //! metadata declares close; keep the source lifecycle call and destroy intact.
      5 use anyhow::{Result, ensure};
      6 
      7 const SHIM: &str = "    @Synchronized\n    override fun close() {\n        this.destroy()\n    }\n";
      8 
      9 /// A native string field named `message` is the actual Throwable message.
     10 /// Retain it and every converter field; remove only the conflicting diagnostic
     11 /// getter generated by the pinned upstream template for that exact variant.
     12 pub(super) fn preserve_error_messages(
     13     source: &str,
     14     variants: &[(String, String)],
     15 ) -> Result<String> {
     16     let mut output = source.to_owned();
     17     for (error, variant) in variants {
     18         let canonical = |name: &str| {
     19             ensure!(
     20                 name.bytes().all(|v| v.is_ascii_alphanumeric())
     21                     && name.as_bytes().first().is_some_and(u8::is_ascii_uppercase),
     22                 "unsupported Kotlin error naming"
     23             );
     24             Ok::<_, anyhow::Error>(
     25                 name.strip_suffix("Error")
     26                     .map_or_else(|| name.to_owned(), |v| format!("{v}Exception")),
     27             )
     28         };
     29         let error = canonical(error)?;
     30         let variant = canonical(variant)?;
     31         let header = format!("sealed class {error}: kotlin.Exception()");
     32         ensure!(
     33             output.matches(&header).count() == 1,
     34             "unexpected Kotlin error header"
     35         );
     36         let start = output.find(&header).expect("counted error");
     37         let end = output[start..]
     38             .find("    companion object ErrorHandler")
     39             .ok_or_else(|| anyhow::anyhow!("unexpected Kotlin error boundary"))?
     40             + start;
     41         let declaration = format!("\n    class {variant}(");
     42         let body = &output[start..end];
     43         ensure!(
     44             body.matches(&declaration).count() == 1,
     45             "unexpected Kotlin error variant"
     46         );
     47         let variant_start = body.find(&declaration).expect("counted variant") + start;
     48         let variant_end = output[variant_start..end]
     49             .find("\n    }\n")
     50             .ok_or_else(|| anyhow::anyhow!("unexpected Kotlin variant boundary"))?
     51             + variant_start;
     52         let body = &output[variant_start..variant_end];
     53         let field = "        val `message`: kotlin.String";
     54         let getter = "        override val message\n            get() = \"";
     55         ensure!(
     56             body.matches(field).count() == 1 && body.matches(getter).count() == 1,
     57             "unexpected Kotlin message field/getter"
     58         );
     59         let getter_start = body.find(getter).expect("counted getter");
     60         let getter_end = body[getter_start..]
     61             .find('\n')
     62             .and_then(|first| {
     63                 body[getter_start + first + 1..]
     64                     .find('\n')
     65                     .map(|second| getter_start + first + 1 + second + 1)
     66             })
     67             .unwrap_or(body.len());
     68         let removed = &body[getter_start..getter_end];
     69         ensure!(
     70             removed.trim_end().ends_with('"') && removed.lines().count() == 2,
     71             "unexpected Kotlin message getter layout"
     72         );
     73         let mut replacement =
     74             body[..getter_start].replace(field, "        override val `message`: kotlin.String");
     75         replacement.push_str(&body[getter_end..]);
     76         output.replace_range(variant_start..variant_end, &replacement);
     77     }
     78     Ok(output)
     79 }
     80 
     81 pub(super) fn preserve_close(source: &str, methods: &[(String, bool)]) -> Result<String> {
     82     let mut output = source.to_owned();
     83     for (name, asynchronous) in methods {
     84         let header = format!("open class {name}: Disposable, AutoCloseable, {name}Interface");
     85         ensure!(
     86             output.matches(&header).count() == 1,
     87             "unexpected Kotlin object header for {name}"
     88         );
     89         let start = output.find(&header).expect("counted header");
     90         let end = start
     91             + output[start..]
     92                 .find("    internal inline fun <R> callWithHandle(")
     93                 .ok_or_else(|| anyhow::anyhow!("unexpected Kotlin handle layout for {name}"))?;
     94         let prefix = &output[start..end];
     95         ensure!(
     96             prefix.matches(SHIM).count() == 1,
     97             "unexpected Kotlin close helper for {name}"
     98         );
     99         let method = if *asynchronous {
    100             "override suspend fun `close`()"
    101         } else {
    102             "override fun `close`()"
    103         };
    104         // Scope the exported method to this object, rather than another class.
    105         let tail_end = output[end..]
    106             .find("\nopen class ")
    107             .map_or(output.len(), |offset| end + offset);
    108         ensure!(
    109             output[end..tail_end].matches(method).count() == 1,
    110             "missing source close for {name}"
    111         );
    112         let replacement = prefix
    113             .replace(&header, &header.replace(", AutoCloseable", ""))
    114             .replacen(SHIM, "", 1);
    115         output.replace_range(start..end, &replacement);
    116     }
    117     Ok(output)
    118 }
    119 
    120 #[cfg(test)]
    121 mod tests {
    122     use super::*;
    123     fn error_source(name: &str, variant: &str) -> String {
    124         format!(
    125             "sealed class {name}: kotlin.Exception() {{\n    class {variant}(\n        val `code`: kotlin.String,\n        val `message`: kotlin.String\n    ) : {name}() {{\n        override val message\n            get() = \"code=${{ `code` }}, message=${{ `message` }}\"\n    }}\n    companion object ErrorHandler\n}}\n"
    126         )
    127     }
    128     #[test]
    129     fn preserves_native_message_field_without_a_conflicting_diagnostic_getter() {
    130         let metadata = [("Error".to_owned(), "Sdk".to_owned())];
    131         let untouched = error_source("OtherException", "Sdk");
    132         let source = format!("{}{untouched}", error_source("Exception", "Sdk"));
    133         let actual = preserve_error_messages(&source, &metadata).unwrap();
    134         assert!(actual.starts_with("sealed class Exception"));
    135         assert!(actual.contains("override val `message`: kotlin.String"));
    136         assert!(actual.contains("val `code`: kotlin.String"));
    137         assert_eq!(actual.matches("        override val message\n").count(), 1);
    138         assert!(actual.ends_with(&untouched));
    139         assert!(preserve_error_messages(&actual, &metadata).is_err());
    140         assert!(
    141             preserve_error_messages(&source.replace("kotlin.String", "kotlin.Int"), &metadata)
    142                 .is_err()
    143         );
    144         assert!(
    145             preserve_error_messages(&source.replace("get() =", "changed ="), &metadata).is_err()
    146         );
    147         assert!(
    148             preserve_error_messages(&source, &[("missing_name".into(), "Sdk".into())]).is_err()
    149         );
    150     }
    151     fn object(name: &str, asynchronous: bool) -> String {
    152         format!(
    153             "open class {name}: Disposable, AutoCloseable, {name}Interface\n{{\n    override fun destroy() {{ actualFree() }}\n{SHIM}\n    internal inline fun <R> callWithHandle(block: (Long) -> R): R {{ actualCall() }}\n    override {}fun `close`() {{ actualSourceClose() }}\n}}\n",
    154             if asynchronous { "suspend " } else { "" }
    155         )
    156     }
    157     #[test]
    158     fn preserves_actual_sync_and_async_close_and_other_objects() {
    159         let host = object("Host", false);
    160         let source = format!(
    161             "{}{}{}",
    162             object("NativeClient", true),
    163             object("Workspace", false),
    164             host
    165         );
    166         let actual = preserve_close(
    167             &source,
    168             &[("NativeClient".into(), true), ("Workspace".into(), false)],
    169         )
    170         .unwrap();
    171         assert!(actual.ends_with(&host));
    172         assert_eq!(actual.matches("actualSourceClose()").count(), 3);
    173         assert_eq!(actual.matches("actualFree()").count(), 3);
    174         assert_eq!(actual.matches(SHIM).count(), 1);
    175         assert!(!actual.contains("NativeClient: Disposable, AutoCloseable"));
    176         assert!(!actual.contains("Workspace: Disposable, AutoCloseable"));
    177     }
    178     #[test]
    179     fn rejects_drift_missing_source_and_reapplication() {
    180         let metadata = [("NativeClient".into(), true)];
    181         let source = object("NativeClient", true);
    182         assert!(preserve_close(&source.replace(SHIM, ""), &metadata).is_err());
    183         assert!(
    184             preserve_close(
    185                 &source.replace("override suspend fun `close`", "fun other"),
    186                 &metadata
    187             )
    188             .is_err()
    189         );
    190         assert!(preserve_close(&source.replace("callWithHandle", "changed"), &metadata).is_err());
    191         assert!(preserve_close(&format!("{source}{source}"), &metadata).is_err());
    192         assert!(preserve_close(&preserve_close(&source, &metadata).unwrap(), &metadata).is_err());
    193         assert_eq!(preserve_close(&source, &[]).unwrap(), source);
    194     }
    195 }