Skip to main content

neo_decompiler/
web.rs

1//! Browser-friendly reports and optional WebAssembly bindings.
2
3use crate::disassembler::UnknownHandling;
4use crate::error::Result;
5use crate::manifest::ContractManifest;
6use crate::nef::NefParser;
7use crate::{Decompiler, OutputFormat};
8
9mod report;
10
11pub use report::{WebDecompileReport, WebDisasmReport, WebInfoReport};
12
13/// Options for browser-oriented disassembly.
14#[derive(Debug, Clone, Copy, Default)]
15pub struct WebDisasmOptions {
16    /// Fail fast instead of emitting `UNKNOWN_0x..` instructions and warnings.
17    pub fail_on_unknown_opcodes: bool,
18}
19
20/// Options for browser-oriented decompilation.
21#[derive(Debug, Clone)]
22pub struct WebDecompileOptions {
23    /// Optional manifest JSON string to load alongside the NEF bytes.
24    pub manifest_json: Option<String>,
25    /// Enforce strict manifest validation when `manifest_json` is provided.
26    pub strict_manifest: bool,
27    /// Fail fast instead of emitting `UNKNOWN_0x..` instructions and warnings.
28    pub fail_on_unknown_opcodes: bool,
29    /// Inline single-use temporaries into their consumers in the
30    /// rendered high-level / C# output. Defaults to `true` so the
31    /// browser surface mirrors the CLI's clean output by default;
32    /// callers wanting the un-inlined form (e.g. for cross-
33    /// referencing temps against trace comments) can flip this off.
34    pub inline_single_use_temps: bool,
35    /// Emit per-instruction `// XXXX: OPCODE` trace comments above
36    /// each lifted statement. Defaults to `false` — the rendered
37    /// output is human-readable by default; callers debugging a
38    /// specific contract can opt back into trace comments.
39    pub emit_trace_comments: bool,
40    /// Use conservative inferred C# declaration types. Defaults to `true`
41    /// for readable contract output; set to `false` for compatibility with
42    /// the legacy dynamic/var rendering.
43    pub typed_declarations: bool,
44    /// Drive high-level method bodies through the structured IR spine.
45    /// Defaults to `true` to match the library/CLI default; set to `false`
46    /// for the legacy stack-emitter path (required for trace comments).
47    pub high_level_from_ir: bool,
48    /// Select which rendered outputs should be generated.
49    pub output_format: OutputFormat,
50}
51
52impl Default for WebDecompileOptions {
53    fn default() -> Self {
54        Self {
55            manifest_json: None,
56            strict_manifest: false,
57            fail_on_unknown_opcodes: false,
58            inline_single_use_temps: true,
59            emit_trace_comments: false,
60            typed_declarations: true,
61            high_level_from_ir: true,
62            // The browser-facing decompile API produces the generated C#
63            // contract by default. Analysis views remain available through
64            // an explicit `output_format` selection.
65            output_format: OutputFormat::CSharp,
66        }
67    }
68}
69
70/// Build a browser-friendly NEF info report from in-memory bytes.
71///
72/// The optional manifest input should be a UTF-8 JSON string.
73///
74/// # Errors
75///
76/// Returns an error if the NEF container or manifest is invalid.
77pub fn info_report(nef_bytes: &[u8], manifest_json: Option<&str>) -> Result<WebInfoReport> {
78    let nef = NefParser::new().parse(nef_bytes)?;
79    let manifest = parse_manifest(manifest_json, false)?;
80    Ok(report::build_info_report(&nef, manifest.as_ref()))
81}
82
83/// Build a browser-friendly disassembly report from in-memory bytes.
84///
85/// # Errors
86///
87/// Returns an error if the NEF container is invalid or disassembly fails.
88pub fn disasm_report(nef_bytes: &[u8], options: WebDisasmOptions) -> Result<WebDisasmReport> {
89    let handling = unknown_handling(options.fail_on_unknown_opcodes);
90    // Parse the NEF directly so the report can surface script_hash
91    // alongside the instruction stream — parity with WebInfoReport
92    // and WebDecompileReport. The internal `disassemble_bytes` call
93    // also parses, but discards the NefFile after extracting the
94    // script.
95    let nef = NefParser::new().parse(nef_bytes)?;
96    let output = Decompiler::with_unknown_handling(handling).disassemble_bytes(nef_bytes)?;
97    Ok(report::build_disasm_report(&nef, output))
98}
99
100/// Build a browser-friendly decompilation report from in-memory bytes.
101///
102/// # Errors
103///
104/// Returns an error if the NEF container or optional manifest is invalid, or
105/// if disassembly/decompilation fails.
106pub fn decompile_report(
107    nef_bytes: &[u8],
108    options: WebDecompileOptions,
109) -> Result<WebDecompileReport> {
110    let manifest = parse_manifest(options.manifest_json.as_deref(), options.strict_manifest)?;
111    let handling = unknown_handling(options.fail_on_unknown_opcodes);
112    let decompiler = Decompiler::with_unknown_handling(handling)
113        .with_inline_single_use_temps(options.inline_single_use_temps)
114        .with_trace_comments(options.emit_trace_comments)
115        .with_typed_declarations(options.typed_declarations)
116        .with_high_level_from_ir(options.high_level_from_ir);
117    let result =
118        decompiler.decompile_bytes_with_manifest(nef_bytes, manifest, options.output_format)?;
119    Ok(report::build_decompile_report(result))
120}
121
122fn parse_manifest(manifest_json: Option<&str>, strict: bool) -> Result<Option<ContractManifest>> {
123    manifest_json
124        .map(|json| {
125            if strict {
126                ContractManifest::from_json_str_strict(json)
127            } else {
128                ContractManifest::from_json_str(json)
129            }
130        })
131        .transpose()
132}
133
134fn unknown_handling(fail_on_unknown_opcodes: bool) -> UnknownHandling {
135    if fail_on_unknown_opcodes {
136        UnknownHandling::Error
137    } else {
138        UnknownHandling::Permit
139    }
140}
141
142#[cfg(target_arch = "wasm32")]
143use crate::Error;
144#[cfg(target_arch = "wasm32")]
145use serde::de::DeserializeOwned;
146#[cfg(target_arch = "wasm32")]
147use serde::Deserialize;
148#[cfg(target_arch = "wasm32")]
149use wasm_bindgen::prelude::*;
150
151#[cfg(target_arch = "wasm32")]
152#[derive(Debug, Default, Deserialize)]
153#[serde(default)]
154struct JsInfoOptions {
155    manifest_json: Option<String>,
156    strict_manifest: bool,
157}
158
159#[cfg(target_arch = "wasm32")]
160#[derive(Debug, Default, Deserialize)]
161#[serde(default)]
162struct JsDisasmOptions {
163    fail_on_unknown_opcodes: bool,
164}
165
166#[cfg(target_arch = "wasm32")]
167#[derive(Debug, Deserialize)]
168#[serde(default)]
169struct JsDecompileOptions {
170    manifest_json: Option<String>,
171    strict_manifest: bool,
172    fail_on_unknown_opcodes: bool,
173    inline_single_use_temps: bool,
174    emit_trace_comments: bool,
175    typed_declarations: bool,
176    high_level_from_ir: bool,
177    output_format: Option<String>,
178}
179
180#[cfg(target_arch = "wasm32")]
181impl Default for JsDecompileOptions {
182    fn default() -> Self {
183        let defaults = WebDecompileOptions::default();
184        Self {
185            manifest_json: None,
186            strict_manifest: false,
187            fail_on_unknown_opcodes: false,
188            inline_single_use_temps: defaults.inline_single_use_temps,
189            emit_trace_comments: defaults.emit_trace_comments,
190            typed_declarations: defaults.typed_declarations,
191            high_level_from_ir: defaults.high_level_from_ir,
192            output_format: None,
193        }
194    }
195}
196
197#[cfg(target_arch = "wasm32")]
198#[wasm_bindgen(js_name = initPanicHook)]
199/// Install a panic hook that forwards Rust panics to the browser console.
200pub fn init_panic_hook() {
201    console_error_panic_hook::set_once();
202}
203
204#[cfg(target_arch = "wasm32")]
205/// Serialize a report to a `JsValue` with BigInt enabled for 64/128-bit
206/// integers. The default serde-wasm-bindgen serializer throws on any i64/u64
207/// outside the JS safe-integer range — e.g. a `PUSHINT64` operand near
208/// `i64::MAX` (routine bytecode) or a large integer in a manifest
209/// `extra`/`features` passthrough — which aborts the whole report for
210/// otherwise-valid input. The CLI serializes via serde_json and already handles
211/// the full range; this keeps the web boundary lossless. Serde routes `usize`
212/// through `u64` even on wasm32, so the TypeScript wrapper converts safe-range
213/// BigInts back to numbers. Keep maps as JS Maps here: serde-wasm-bindgen's
214/// object map serializer assigns keys using `object[key] = value`, which would
215/// treat an untrusted `__proto__` key as a prototype mutation. The wrapper uses
216/// `Object.fromEntries` to preserve all map keys as ordinary own properties.
217fn report_to_js<T: serde::Serialize>(value: &T) -> std::result::Result<JsValue, JsValue> {
218    let serializer = serde_wasm_bindgen::Serializer::new()
219        .serialize_maps_as_objects(false)
220        .serialize_large_number_types_as_bigints(true);
221    serde::Serialize::serialize(value, &serializer)
222        .map_err(|err| JsValue::from_str(&err.to_string()))
223}
224
225#[cfg(target_arch = "wasm32")]
226#[wasm_bindgen(js_name = infoReport)]
227/// Build an info report from NEF bytes and a JS options object.
228pub fn info_report_wasm(
229    nef_bytes: &[u8],
230    options: JsValue,
231) -> std::result::Result<JsValue, JsValue> {
232    let options: JsInfoOptions = parse_js_options(options)?;
233    let manifest = parse_manifest(options.manifest_json.as_deref(), options.strict_manifest)
234        .map_err(to_js_error)?;
235    let nef = NefParser::new().parse(nef_bytes).map_err(to_js_error)?;
236    report_to_js(&report::build_info_report(&nef, manifest.as_ref()))
237}
238
239#[cfg(target_arch = "wasm32")]
240#[wasm_bindgen(js_name = disasmReport)]
241/// Build a disassembly report from NEF bytes and a JS options object.
242pub fn disasm_report_wasm(
243    nef_bytes: &[u8],
244    options: JsValue,
245) -> std::result::Result<JsValue, JsValue> {
246    let options: JsDisasmOptions = parse_js_options(options)?;
247    let report = disasm_report(
248        nef_bytes,
249        WebDisasmOptions {
250            fail_on_unknown_opcodes: options.fail_on_unknown_opcodes,
251        },
252    )
253    .map_err(to_js_error)?;
254    report_to_js(&report)
255}
256
257#[cfg(target_arch = "wasm32")]
258#[wasm_bindgen(js_name = decompileReport)]
259/// Build a decompilation report from NEF bytes and a JS options object.
260pub fn decompile_report_wasm(
261    nef_bytes: &[u8],
262    options: JsValue,
263) -> std::result::Result<JsValue, JsValue> {
264    let options: JsDecompileOptions = parse_js_options(options)?;
265    let output_format = parse_output_format(options.output_format.as_deref())
266        .map_err(|err| JsValue::from_str(&err))?;
267    let report = decompile_report(
268        nef_bytes,
269        WebDecompileOptions {
270            manifest_json: options.manifest_json,
271            strict_manifest: options.strict_manifest,
272            fail_on_unknown_opcodes: options.fail_on_unknown_opcodes,
273            inline_single_use_temps: options.inline_single_use_temps,
274            emit_trace_comments: options.emit_trace_comments,
275            typed_declarations: options.typed_declarations,
276            high_level_from_ir: options.high_level_from_ir,
277            output_format,
278        },
279    )
280    .map_err(to_js_error)?;
281    report_to_js(&report)
282}
283
284#[cfg(target_arch = "wasm32")]
285fn parse_js_options<T>(value: JsValue) -> std::result::Result<T, JsValue>
286where
287    T: Default + DeserializeOwned,
288{
289    if value.is_null() || value.is_undefined() {
290        Ok(T::default())
291    } else {
292        serde_wasm_bindgen::from_value(value)
293            .map_err(|err| JsValue::from_str(&format!("invalid options: {err}")))
294    }
295}
296
297#[cfg(target_arch = "wasm32")]
298fn parse_output_format(value: Option<&str>) -> std::result::Result<OutputFormat, String> {
299    match value.unwrap_or("csharp") {
300        "all" => Ok(OutputFormat::All),
301        "pseudocode" => Ok(OutputFormat::Pseudocode),
302        "high_level" | "highLevel" => Ok(OutputFormat::HighLevel),
303        "csharp" | "c_sharp" => Ok(OutputFormat::CSharp),
304        other => Err(format!("invalid output_format: {other}")),
305    }
306}
307
308#[cfg(target_arch = "wasm32")]
309fn to_js_error(err: Error) -> JsValue {
310    JsValue::from_str(&err.to_string())
311}