Skip to main content

onlineasm_macros/
lib.rs

1//! `onlineasm!` emits runtime assembly using offlineasm mnemonics.
2//!
3//! ```ignore
4//! use onlineasm::{onlineasm, Assembler, JitAllocator};
5//!
6//! let mut asm = Assembler::native();
7//! let mut jit = JitAllocator::new(Default::default());
8//! onlineasm!(asm;
9//!     #[patch = slot] move t0, 0;
10//!     ret;
11//! );
12//! // `slot` is the `PatchHandle`, usable after the macro like a `=>` binding.
13//! let code = asm.finish().expect("finish");
14//! let location = code.location(slot).expect("slot is bound");
15//! let mut span = code.allocate(&mut jit).expect("allocate");
16//! // SAFETY: `span` holds `code`, and nothing executes the patched
17//! // instruction while it is rewritten.
18//! unsafe {
19//!     onlineasm::repatch_u64(&mut jit, &mut span, &location, 42).expect("repatch");
20//! }
21//! ```
22//!
23//! Rules:
24//!
25//! * The first argument is the assembler expression (evaluated once). The
26//!   rest are `;`-separated statements.
27//! * `.name:` defines a local label, referenced as `.name`. `=>name` binds a
28//!   fresh label at the current position to the Rust variable `name`.
29//!   Bindings introduced by `=>`, `extern`, and `#[patch]` are returned from
30//!   the macro (statement position) so they stay usable afterwards. There are
31//!   no string label maps.
32//! * Operands: integer literals (decimal/`0x`/`0o`/`0b`, signed), offlineasm
33//!   vregs such as `t0`, `ft0`, and `sp` (there is no built-in `arg0`-`arg7`.
34//!   Declare your own `VReg` constant and splice it. A bare `argN` is a
35//!   compile error pointing at that), physical registers such as `rax`,
36//!   `xmm0`, `x9`, and `d0`, spelled bare or with a `%` prefix (`%rax`;
37//!   unchecked, including reserved and scratch ones - `%` additionally
38//!   reaches ABI names with no bare/vreg meaning, such as `%sp`/`%fp`/`%lr`
39//!   on AArch64 and the full psABI name set on RISC-V), `.name` label
40//!   references, `[base + index*scale + disp]` memory, and `{expr}` splices
41//!   of Rust values (`VReg`, `Gpr`, `Fpr`, `Mem`, `Label`, integers).
42//! * `#[patch = name]` emits the instruction through a patchable site and
43//!   binds its `PatchHandle` to `name`. Patchable instructions:
44//!   `jmp`/`call` with a label target (a jump site), `move` with a register
45//!   destination and an immediate source (an immediate site), and conditional
46//!   branches (a jump site), except float conditions that expand to several
47//!   branches and the overflow-of-`or` arithmetic branch (`borio`/`borqo`),
48//!   which emits no branch at all. An external symbol is never a patch site.
49//!   `#[patch]` on anything but an instruction is a compile error; a
50//!   non-patchable mnemonic or operand shape panics at emission, naming the
51//!   mnemonic. After `finish`, `Finished::location` turns the handle into a
52//!   `PatchLocation`: retarget a jump with `asmkit::repatch_jump_span`, or
53//!   rewrite an immediate with `onlineasm::repatch_u64`.
54//! * `#[patch_abs = name]` on `jmp`/`call` with an integer or `{expr}` target
55//!   reserves a 64-bit absolute-address slot: it emits a patchable `move` of
56//!   the target into the expansion scratch GPR followed by an indirect
57//!   jump/call through it, and binds the `move`'s `PatchHandle` (an immediate
58//!   site) to `name`, for `onlineasm::repatch_u64` to fill in after
59//!   allocation. The scratch GPR is clobbered. Any other mnemonic, or a
60//!   target that is neither an integer nor `{expr}`, is a compile error.
61//!
62//! * `extern name = {expr};` declares the external symbol `{expr}` (anything
63//!   `Into<onlineasm::ExternalName>`) and binds the `onlineasm::Extern` to
64//!   `name`, which later operands name bare (`call name`) and the macro
65//!   returns like a `=>` binding. `extern near name = {expr};` declares a
66//!   direct (near) reference. An operand can also declare one in place:
67//!   `call extern {expr}` or `call extern near {expr}`. An extern is a
68//!   `jmp`/`call` target or the source of `move`/`leap`/`globaladdr`/`la`;
69//!   the image is then loaded with `Finished::load`.
70//!
71//! External symbols can also be brought in by splicing an address
72//! (`move reg, {sym as u64}`) or by reserving a `#[patch]` slot and
73//! repatching it at runtime.
74
75use proc_macro::TokenStream;
76use proc_macro2::Span;
77use proc_macro2::TokenStream as TokenStream2;
78use quote::quote;
79use syn::ext::IdentExt;
80use syn::parse::{Parse, ParseStream};
81use syn::{braced, bracketed, Attribute, Error, Expr, Ident, Lit, LitInt, Token};
82
83/// Names the register class of a classified physical register.
84#[derive(Clone, Copy, PartialEq, Eq)]
85enum RegClass {
86    Gpr,
87    Fpr,
88}
89
90/// Names a portable vreg spelling or a physical machine-register number.
91///
92/// The target resolves the vreg spelling at runtime.
93enum RegId {
94    VReg(String),
95    Phys { id: u8, class: RegClass },
96}
97
98/// Returns the numeric x86-64 GPR id for `name`.
99///
100/// Aliases share their physical register's id.
101fn x86_gpr(name: &str) -> Option<u8> {
102    Some(match name {
103        "rax" | "eax" | "ax" | "al" | "ah" => 0,
104        "rcx" | "ecx" | "cx" | "cl" | "ch" => 1,
105        "rdx" | "edx" | "dx" | "dl" | "dh" => 2,
106        "rbx" | "ebx" | "bx" | "bl" | "bh" => 3,
107        "rsp" | "esp" | "spl" => 4,
108        "rbp" | "ebp" | "bpl" => 5,
109        "rsi" | "esi" | "sil" => 6,
110        "rdi" | "edi" | "dil" => 7,
111        "r8" | "r8d" | "r8w" | "r8b" => 8,
112        "r9" | "r9d" | "r9w" | "r9b" => 9,
113        "r10" | "r10d" | "r10w" | "r10b" => 10,
114        "r11" | "r11d" | "r11w" | "r11b" => 11,
115        "r12" | "r12d" | "r12w" | "r12b" => 12,
116        "r13" | "r13d" | "r13w" | "r13b" => 13,
117        "r14" | "r14d" | "r14w" | "r14b" => 14,
118        "r15" | "r15d" | "r15w" | "r15b" => 15,
119        _ => return None,
120    })
121}
122
123/// Returns the numeric x86 XMM id for `name`.
124///
125/// Accepts `xmm0` through `xmm15`.
126fn x86_fpr(name: &str) -> Option<u8> {
127    let id: u32 = name.strip_prefix("xmm")?.parse().ok()?;
128    (id <= 15).then_some(id as u8)
129}
130
131/// Returns the numeric AArch64 GPR id for `name`.
132///
133/// Accepts `x0`-`x30`, `w0`-`w30`, `xzr`/`wzr`, and `wsp`. Runs after the
134/// vreg spelling table so `sp`/`zr` keep their vreg meaning.
135fn aarch64_gpr(name: &str) -> Option<u8> {
136    match name {
137        "xzr" | "wzr" => return Some(63),
138        "wsp" => return Some(31),
139        _ => {}
140    }
141    let body = name.strip_prefix('x').or_else(|| name.strip_prefix('w'))?;
142    let id: u32 = body.parse().ok()?;
143    (id <= 30).then_some(id as u8)
144}
145
146/// Returns the numeric AArch64 FPR id for `name`.
147///
148/// Accepts `d`, `q`, or `s` plus `0`-`31`.
149fn aarch64_fpr(name: &str) -> Option<u8> {
150    let body = name
151        .strip_prefix('d')
152        .or_else(|| name.strip_prefix('q'))
153        .or_else(|| name.strip_prefix('s'))?;
154    let id: u32 = body.parse().ok()?;
155    (id <= 31).then_some(id as u8)
156}
157
158/// Returns the numeric RISC-V GPR id for `name`.
159///
160/// Accepts `x0` through `x31`.
161fn riscv_gpr(name: &str) -> Option<u8> {
162    let id: u32 = name.strip_prefix('x')?.parse().ok()?;
163    (id <= 31).then_some(id as u8)
164}
165
166/// Returns the numeric RISC-V FPR id for `name`.
167///
168/// Accepts `f0` through `f31`.
169fn riscv_fpr(name: &str) -> Option<u8> {
170    let id: u32 = name.strip_prefix('f')?.parse().ok()?;
171    (id <= 31).then_some(id as u8)
172}
173
174/// Reports whether `name` is exactly `arg0`-`arg7`.
175///
176/// Those non-upstream ABI aliases have no `onlineasm::regs` constants.
177/// Callers report a targeted hint instead of the generic downstream
178/// "cannot find value" error.
179fn is_bare_arg_name(name: &str) -> bool {
180    matches!(
181        name,
182        "arg0" | "arg1" | "arg2" | "arg3" | "arg4" | "arg5" | "arg6" | "arg7"
183    )
184}
185
186/// Returns the numeric AArch64 GPR id for an ABI alias not covered by
187/// [`aarch64_gpr`]'s indexed spellings: `sp`, `fp` (frame pointer, `x29`),
188/// `lr` (link register, `x30`).
189///
190/// Kept separate from `aarch64_gpr` because bare `sp` already resolves to
191/// the portable `::onlineasm::regs::sp` vreg; only the `%`-escaped physical
192/// path consults this table.
193fn aarch64_abi_gpr(name: &str) -> Option<u8> {
194    Some(match name {
195        "sp" => 31,
196        "fp" => 29,
197        "lr" => 30,
198        _ => return None,
199    })
200}
201
202/// Returns the numeric RISC-V GPR id for a psABI register name (`ra`, `sp`,
203/// `gp`, `tp`, `t0`-`t6`, `s0`-`s11`, `a0`-`a7`, `fp`, `zero`).
204///
205/// Kept separate from `riscv_gpr`'s `xN` spellings for the same reason as
206/// [`aarch64_abi_gpr`]: bare ABI names already resolve to portable vregs.
207fn riscv_abi_gpr(name: &str) -> Option<u8> {
208    Some(match name {
209        "zero" => 0,
210        "ra" => 1,
211        "sp" => 2,
212        "gp" => 3,
213        "tp" => 4,
214        "t0" => 5,
215        "t1" => 6,
216        "t2" => 7,
217        "s0" | "fp" => 8,
218        "s1" => 9,
219        "a0" => 10,
220        "a1" => 11,
221        "a2" => 12,
222        "a3" => 13,
223        "a4" => 14,
224        "a5" => 15,
225        "a6" => 16,
226        "a7" => 17,
227        "s2" => 18,
228        "s3" => 19,
229        "s4" => 20,
230        "s5" => 21,
231        "s6" => 22,
232        "s7" => 23,
233        "s8" => 24,
234        "s9" => 25,
235        "s10" => 26,
236        "s11" => 27,
237        "t3" => 28,
238        "t4" => 29,
239        "t5" => 30,
240        "t6" => 31,
241        _ => return None,
242    })
243}
244
245/// Returns the numeric RISC-V FPR id for a psABI register name (`ft0`-`ft11`,
246/// `fs0`-`fs11`, `fa0`-`fa7`).
247fn riscv_abi_fpr(name: &str) -> Option<u8> {
248    Some(match name {
249        "ft0" => 0,
250        "ft1" => 1,
251        "ft2" => 2,
252        "ft3" => 3,
253        "ft4" => 4,
254        "ft5" => 5,
255        "ft6" => 6,
256        "ft7" => 7,
257        "fs0" => 8,
258        "fs1" => 9,
259        "fa0" => 10,
260        "fa1" => 11,
261        "fa2" => 12,
262        "fa3" => 13,
263        "fa4" => 14,
264        "fa5" => 15,
265        "fa6" => 16,
266        "fa7" => 17,
267        "fs2" => 18,
268        "fs3" => 19,
269        "fs4" => 20,
270        "fs5" => 21,
271        "fs6" => 22,
272        "fs7" => 23,
273        "fs8" => 24,
274        "fs9" => 25,
275        "fs10" => 26,
276        "fs11" => 27,
277        "ft8" => 28,
278        "ft9" => 29,
279        "ft10" => 30,
280        "ft11" => 31,
281        _ => return None,
282    })
283}
284
285/// Tries every indexed physical-register table, shared by the bare-name and
286/// `%`-escaped classifiers.
287fn try_physical(s: &str) -> Option<RegId> {
288    if let Some(id) = x86_gpr(s) {
289        return Some(RegId::Phys {
290            id,
291            class: RegClass::Gpr,
292        });
293    }
294    if let Some(id) = x86_fpr(s) {
295        return Some(RegId::Phys {
296            id,
297            class: RegClass::Fpr,
298        });
299    }
300    if let Some(id) = aarch64_gpr(s) {
301        return Some(RegId::Phys {
302            id,
303            class: RegClass::Gpr,
304        });
305    }
306    if let Some(id) = aarch64_fpr(s) {
307        return Some(RegId::Phys {
308            id,
309            class: RegClass::Fpr,
310        });
311    }
312    if let Some(id) = riscv_gpr(s) {
313        return Some(RegId::Phys {
314            id,
315            class: RegClass::Gpr,
316        });
317    }
318    if let Some(id) = riscv_fpr(s) {
319        return Some(RegId::Phys {
320            id,
321            class: RegClass::Fpr,
322        });
323    }
324    None
325}
326
327/// Classifies a `%`-escaped physical-register spelling (`%rax`, `%sp`,
328/// `%a0`, `%ft3`).
329///
330/// Accepts every spelling `classify_reg` accepts as a bare physical name,
331/// plus the ABI aliases (`%sp`, `%fp`, `%lr` on AArch64; the full psABI
332/// names on RISC-V) that would otherwise resolve as portable vregs when
333/// written bare. Unlike `classify_reg`, an unrecognized name is a hard
334/// error rather than falling back to a portable vreg.
335fn classify_phys(name: &Ident) -> syn::Result<RegId> {
336    let s = name.to_string();
337    if let Some(reg) = try_physical(&s) {
338        return Ok(reg);
339    }
340    if let Some(id) = aarch64_abi_gpr(&s) {
341        return Ok(RegId::Phys {
342            id,
343            class: RegClass::Gpr,
344        });
345    }
346    if let Some(id) = riscv_abi_gpr(&s) {
347        return Ok(RegId::Phys {
348            id,
349            class: RegClass::Gpr,
350        });
351    }
352    if let Some(id) = riscv_abi_fpr(&s) {
353        return Ok(RegId::Phys {
354            id,
355            class: RegClass::Fpr,
356        });
357    }
358    Err(Error::new_spanned(
359        name,
360        format!("`%{s}` is not a known physical register"),
361    ))
362}
363
364/// Classifies a bare register spelling.
365///
366/// Physical names become numeric machine-register ids. Anything else becomes
367/// a portable `::onlineasm::regs::<name>` constant, validated at compile
368/// time there.
369fn classify_reg(name: &Ident) -> syn::Result<RegId> {
370    let s = name.to_string();
371    if is_bare_arg_name(&s) {
372        return Err(Error::new_spanned(
373            name,
374            format!(
375                "`{s}` is not a register; onlineasm has no built-in argument-register \
376                 aliases, declare it yourself, e.g. \
377                 `const {upper}: ::onlineasm::VReg = ::onlineasm::regs::t6;` and use \
378                 `{{{upper}}}`",
379                s = s,
380                upper = s.to_uppercase(),
381            ),
382        ));
383    }
384    if let Some(reg) = try_physical(&s) {
385        return Ok(reg);
386    }
387    Ok(RegId::VReg(s))
388}
389
390struct AsmInput {
391    asm: Expr,
392    stmts: Vec<Stmt>,
393}
394
395enum Stmt {
396    /// `.name:`: a local label, referenced as `.name`.
397    LocalDef { name: String },
398    /// `=>name`: a fresh label bound to the Rust variable `name`.
399    DynDef { name: Ident },
400    /// `extern [near] name = {expr}`: an external symbol bound to the Rust
401    /// variable `name`.
402    ExternDef { name: Ident, near: bool, expr: Expr },
403    Instr {
404        patch: Option<PatchAttr>,
405        mnemonic: String,
406        mnemonic_span: Span,
407        operands: Vec<Operand>,
408    },
409}
410
411/// `#[patch = name]` (relative site/block) or `#[patch_abs = name]`
412/// (movable 64-bit absolute target, for cross-image inline caches).
413#[derive(Clone, Copy, PartialEq, Eq)]
414enum PatchMode {
415    Site,
416    Abs,
417}
418
419struct PatchAttr {
420    name: Ident,
421    mode: PatchMode,
422}
423
424enum Operand {
425    Imm {
426        lit: LitInt,
427        neg: bool,
428    },
429    Reg(RegId),
430    /// A bare identifier that is not a register: an `extern` binding, or
431    /// `err` if no `extern` declares it.
432    Name {
433        name: Ident,
434        err: Error,
435    },
436    /// `extern [near] {expr}`: an external symbol declared in place.
437    Extern {
438        near: bool,
439        expr: Expr,
440    },
441    LocalLabel(String),
442    Splice(Expr),
443    Mem(MemOp),
444}
445
446struct MemOp {
447    base: MemAtom,
448    index: Option<(MemAtom, u8)>,
449    disp: MemDisp,
450}
451
452enum MemAtom {
453    Reg(RegId),
454    Splice(Box<Expr>),
455}
456
457enum MemDisp {
458    None,
459    Imm(i32),
460    Splice(Box<Expr>),
461    NegSplice(Box<Expr>),
462}
463
464impl Parse for AsmInput {
465    fn parse(input: ParseStream) -> syn::Result<Self> {
466        let asm: Expr = input.parse()?;
467        input.parse::<Token![;]>()?;
468        let mut stmts = Vec::new();
469        while !input.is_empty() {
470            stmts.push(parse_stmt(input)?);
471            // Labels are not `;`-terminated. Instructions may or may not be.
472            if input.peek(Token![;]) {
473                input.parse::<Token![;]>()?;
474            }
475        }
476        Ok(AsmInput { asm, stmts })
477    }
478}
479
480fn parse_patch_attr(attrs: &[Attribute]) -> syn::Result<Option<PatchAttr>> {
481    let mut patch = None;
482    for attr in attrs {
483        let syn::Meta::NameValue(nv) = &attr.meta else {
484            return Err(Error::new_spanned(attr, "expected #[patch = name]"));
485        };
486        let mode = if nv.path.is_ident("patch") {
487            PatchMode::Site
488        } else if nv.path.is_ident("patch_abs") {
489            PatchMode::Abs
490        } else {
491            return Err(Error::new_spanned(
492                attr,
493                "unsupported attribute (only #[patch = name] and #[patch_abs = name])",
494            ));
495        };
496        let syn::Expr::Path(p) = &nv.value else {
497            return Err(Error::new_spanned(&nv.value, "expected #[patch = name]"));
498        };
499        let name = p
500            .path
501            .get_ident()
502            .cloned()
503            .ok_or_else(|| Error::new_spanned(&p.path, "expected #[patch = name]"))?;
504        if patch.is_some() {
505            return Err(Error::new_spanned(attr, "duplicate #[patch]"));
506        }
507        patch = Some(PatchAttr { name, mode });
508    }
509    Ok(patch)
510}
511
512fn parse_stmt(input: ParseStream) -> syn::Result<Stmt> {
513    let attrs = Attribute::parse_outer(input)?;
514    let patch = parse_patch_attr(&attrs)?;
515
516    // =>name: fresh label definition bound to a Rust variable.
517    if input.peek(Token![=>]) {
518        input.parse::<Token![=>]>()?;
519        let name: Ident = input.parse()?;
520        if patch.is_some() {
521            return Err(Error::new_spanned(name, "#[patch] needs an instruction"));
522        }
523        if input.peek(Token![:]) {
524            input.parse::<Token![:]>()?;
525        }
526        return Ok(Stmt::DynDef { name });
527    }
528
529    // extern [near] name = {expr}: an external symbol bound to `name`.
530    if input.peek(Token![extern]) {
531        input.parse::<Token![extern]>()?;
532        let near = parse_near(input)?;
533        let name: Ident = input.call(Ident::parse_any)?;
534        if patch.is_some() {
535            return Err(Error::new_spanned(name, "#[patch] needs an instruction"));
536        }
537        if is_register_name(&name) {
538            return Err(Error::new_spanned(
539                &name,
540                format!("extern `{name}` shadows a register name"),
541            ));
542        }
543        input.parse::<Token![=]>()?;
544        let content;
545        let _ = braced!(content in input);
546        let expr: Expr = content.parse()?;
547        return Ok(Stmt::ExternDef { name, near, expr });
548    }
549
550    // .name: local label definition.
551    if input.peek(Token![.]) {
552        let fork = input.fork();
553        if fork.parse::<Token![.]>().is_ok()
554            && fork.call(Ident::parse_any).is_ok()
555            && fork.peek(Token![:])
556        {
557            input.parse::<Token![.]>()?;
558            let name: Ident = input.call(Ident::parse_any)?;
559            input.parse::<Token![:]>()?;
560            if patch.is_some() {
561                return Err(Error::new_spanned(name, "#[patch] needs an instruction"));
562            }
563            return Ok(Stmt::LocalDef {
564                name: format!(".{}", name),
565            });
566        }
567    }
568
569    // Rejects bare `name:` labels with a useful error instead of parsing
570    // `name` as a register.
571    {
572        let fork = input.fork();
573        if fork.call(Ident::parse_any).is_ok() && fork.peek(Token![:]) {
574            let span = input.span();
575            let _ = input.call(Ident::parse_any)?;
576            let _ = input.parse::<Token![:]>()?;
577            return Err(Error::new(
578                span,
579                "bare labels are not supported: use `.name:` for a local label, \
580                 `=>name` for a Rust binding, or create a label with `asm.label()` \
581                 and splice it as `{name}`",
582            ));
583        }
584    }
585
586    // Instruction: mnemonic + comma-separated operands.
587    let mnemonic_span = input.span();
588    let mnemonic = if input.peek(Token![move]) {
589        input.parse::<Token![move]>()?;
590        "move".to_string()
591    } else if input.peek(Token![break]) {
592        input.parse::<Token![break]>()?;
593        "break".to_string()
594    } else {
595        input.call(Ident::parse_any)?.to_string()
596    };
597    let mut operands = Vec::new();
598    loop {
599        if input.peek(Token![;]) || input.is_empty() {
600            break;
601        }
602        operands.push(parse_operand(input)?);
603        if input.peek(Token![,]) {
604            input.parse::<Token![,]>()?;
605            // Trailing comma before `;` is allowed.
606            if input.peek(Token![;]) || input.is_empty() {
607                break;
608            }
609        } else {
610            break;
611        }
612    }
613    Ok(Stmt::Instr {
614        patch,
615        mnemonic,
616        mnemonic_span,
617        operands,
618    })
619}
620
621fn parse_lit_int(lit: &LitInt) -> syn::Result<i64> {
622    let s = lit.to_string();
623    let digits = strip_int_suffix(&s).replace('_', "");
624    let v: i128 = if let Some(h) = digits
625        .strip_prefix("0x")
626        .or_else(|| digits.strip_prefix("0X"))
627    {
628        i128::from_str_radix(h, 16)
629    } else if let Some(h) = digits
630        .strip_prefix("0o")
631        .or_else(|| digits.strip_prefix("0O"))
632    {
633        i128::from_str_radix(h, 8)
634    } else if let Some(h) = digits
635        .strip_prefix("0b")
636        .or_else(|| digits.strip_prefix("0B"))
637    {
638        i128::from_str_radix(h, 2)
639    } else {
640        digits.parse::<i128>()
641    }
642    .map_err(|_| Error::new_spanned(lit, "integer literal out of range"))?;
643    i64::try_from(v).map_err(|_| Error::new_spanned(lit, "integer literal out of range"))
644}
645
646fn strip_int_suffix(s: &str) -> &str {
647    for suffix in [
648        "usize", "isize", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8",
649    ] {
650        if let Some(d) = s.strip_suffix(suffix) {
651            if d.ends_with(|c: char| c.is_ascii_digit() || c == '_') {
652                return d;
653            }
654        }
655    }
656    s
657}
658
659/// Reports whether `name` spells a register: a portable vreg or a bare
660/// physical register.
661fn is_register_name(name: &Ident) -> bool {
662    use offlineasm_ir::regs::{FPRS, GPRS, VECS};
663    let s = name.to_string();
664    GPRS.iter().chain(FPRS).chain(VECS).any(|r| *r == s) || try_physical(&s).is_some()
665}
666
667/// Parses the optional `near` after `extern`.
668fn parse_near(input: ParseStream) -> syn::Result<bool> {
669    let fork = input.fork();
670    if fork.call(Ident::parse_any).is_ok_and(|i| i == "near") {
671        let _ = input.call(Ident::parse_any)?;
672        return Ok(true);
673    }
674    Ok(false)
675}
676
677fn parse_operand(input: ParseStream) -> syn::Result<Operand> {
678    if input.peek(Token![extern]) {
679        input.parse::<Token![extern]>()?;
680        let near = parse_near(input)?;
681        let content;
682        let _ = braced!(content in input);
683        let expr: Expr = content.parse()?;
684        return Ok(Operand::Extern { near, expr });
685    }
686    // -N: negative immediate.
687    if input.peek(Token![-]) && input.peek2(Lit) {
688        input.parse::<Token![-]>()?;
689        let lit: LitInt = input.parse()?;
690        let _ = parse_lit_int(&lit)?;
691        return Ok(Operand::Imm { lit, neg: true });
692    }
693    if input.peek(Lit) {
694        let lit: Lit = input.parse()?;
695        match lit {
696            Lit::Int(i) => {
697                let _ = parse_lit_int(&i)?;
698                return Ok(Operand::Imm { lit: i, neg: false });
699            }
700            other => {
701                return Err(Error::new_spanned(
702                    other,
703                    "only integer literals are operands",
704                ))
705            }
706        }
707    }
708    if input.peek(syn::token::Brace) {
709        let content;
710        let _ = braced!(content in input);
711        let expr: Expr = content.parse()?;
712        return Ok(Operand::Splice(expr));
713    }
714    if input.peek(syn::token::Bracket) {
715        let content;
716        let _ = bracketed!(content in input);
717        return Ok(Operand::Mem(parse_mem(&content)?));
718    }
719    // Possibly dotted local label reference (`.loop`).
720    if input.peek(Token![.]) {
721        let fork = input.fork();
722        if fork.parse::<Token![.]>().is_ok() && fork.call(Ident::parse_any).is_ok() {
723            input.parse::<Token![.]>()?;
724            let name: Ident = input.call(Ident::parse_any)?;
725            return Ok(Operand::LocalLabel(format!(".{}", name)));
726        }
727    }
728    // %rax: an explicit physical-register escape, matching offlineasm's
729    // `%`-prefixed spelling.
730    if input.peek(Token![%]) {
731        input.parse::<Token![%]>()?;
732        let name: Ident = input.call(Ident::parse_any)?;
733        return Ok(Operand::Reg(classify_phys(&name)?));
734    }
735    if input.peek(Ident) {
736        let name: Ident = input.call(Ident::parse_any)?;
737        return Ok(match classify_reg(&name) {
738            Ok(reg) => Operand::Reg(reg),
739            Err(err) => Operand::Name { name, err },
740        });
741    }
742    Err(input.error("expected an operand"))
743}
744
745fn parse_mem_atom(input: ParseStream) -> syn::Result<MemAtom> {
746    if input.peek(syn::token::Brace) {
747        let content;
748        let _ = braced!(content in input);
749        return Ok(MemAtom::Splice(Box::new(content.parse()?)));
750    }
751    if input.peek(Token![%]) {
752        input.parse::<Token![%]>()?;
753        let name: Ident = input.call(Ident::parse_any)?;
754        return Ok(MemAtom::Reg(classify_phys(&name)?));
755    }
756    if input.peek(Ident) {
757        let name: Ident = input.call(Ident::parse_any)?;
758        return Ok(MemAtom::Reg(classify_reg(&name)?));
759    }
760    Err(input.error("expected a register or {expr}"))
761}
762
763fn parse_mem(input: ParseStream) -> syn::Result<MemOp> {
764    let base = parse_mem_atom(input)?;
765    let mut index = None;
766    let mut disp = MemDisp::None;
767    // [base + index*scale] and/or [+/- disp]
768    if input.peek(Token![+]) {
769        input.parse::<Token![+]>()?;
770        let fork = input.fork();
771        let is_index = fork.peek(syn::token::Brace) || fork.peek(Ident);
772        if is_index {
773            let atom = parse_mem_atom(input)?;
774            let mut scale: u8 = 1;
775            if input.peek(Token![*]) {
776                input.parse::<Token![*]>()?;
777                if input.peek(Lit) {
778                    let lit: LitInt = input.parse()?;
779                    let v = parse_lit_int(&lit)?;
780                    if ![1, 2, 4, 8].contains(&v) {
781                        return Err(Error::new_spanned(lit, "scale must be 1, 2, 4, or 8"));
782                    }
783                    scale = v as u8;
784                } else {
785                    return Err(input.error("scale must be an integer literal"));
786                }
787            }
788            index = Some((atom, scale));
789            if input.peek(Token![+]) || input.peek(Token![-]) {
790                disp = parse_mem_disp(input)?;
791            }
792        } else {
793            disp = parse_mem_disp_after_plus(input)?;
794        }
795    } else if input.peek(Token![-]) {
796        disp = parse_mem_disp(input)?;
797    }
798    if !input.is_empty() {
799        return Err(input.error("unexpected tokens in memory operand"));
800    }
801    Ok(MemOp { base, index, disp })
802}
803
804fn parse_mem_disp(input: ParseStream) -> syn::Result<MemDisp> {
805    let neg = input.peek(Token![-]);
806    if neg {
807        input.parse::<Token![-]>()?;
808    } else {
809        input.parse::<Token![+]>()?;
810    }
811    parse_mem_disp_after_sign(input, neg)
812}
813
814fn parse_mem_disp_after_plus(input: ParseStream) -> syn::Result<MemDisp> {
815    parse_mem_disp_after_sign(input, false)
816}
817
818fn parse_mem_disp_after_sign(input: ParseStream, neg: bool) -> syn::Result<MemDisp> {
819    if input.peek(syn::token::Brace) {
820        let content;
821        let _ = braced!(content in input);
822        let expr: Expr = content.parse()?;
823        return Ok(if neg {
824            MemDisp::NegSplice(Box::new(expr))
825        } else {
826            MemDisp::Splice(Box::new(expr))
827        });
828    }
829    if input.peek(Lit) {
830        let lit: LitInt = input.parse()?;
831        let v = parse_lit_int(&lit)?;
832        let v = if neg { -v } else { v };
833        let d =
834            i32::try_from(v).map_err(|_| Error::new_spanned(lit, "displacement out of range"))?;
835        return Ok(MemDisp::Imm(d));
836    }
837    Err(input.error("displacement must be an integer literal or {expr}"))
838}
839
840/// Emits runtime assembly using offlineasm mnemonics.
841///
842/// See the [crate-level documentation](crate) for the syntax and rules.
843#[proc_macro]
844pub fn onlineasm(input: TokenStream) -> TokenStream {
845    match onlineasm_inner(input.into()) {
846        Ok(ts) => ts.into(),
847        Err(e) => e.to_compile_error().into(),
848    }
849}
850
851/// Holds one call-site binding from `=>name` or `#[patch = name]`.
852struct Binding {
853    /// The identifier visible at the call site (and inside the block).
854    public: Ident,
855    /// `true` for `=>name` (the block must declare the label), `false` for
856    /// `#[patch]` (the statement declares the handle).
857    is_label: bool,
858}
859
860fn onlineasm_inner(input: TokenStream2) -> syn::Result<TokenStream2> {
861    let parsed = syn::parse2::<AsmInput>(input)?;
862    let asm_expr = &parsed.asm;
863
864    let mut locals: Vec<(String, Ident)> = Vec::new();
865    let mut bindings: Vec<Binding> = Vec::new();
866    for stmt in &parsed.stmts {
867        match stmt {
868            Stmt::LocalDef { name } => {
869                local_ident(&mut locals, name, Span::mixed_site());
870            }
871            Stmt::DynDef { name } => bindings.push(Binding {
872                public: name.clone(),
873                is_label: true,
874            }),
875            Stmt::ExternDef { name, .. } => bindings.push(Binding {
876                public: name.clone(),
877                is_label: false,
878            }),
879            Stmt::Instr {
880                patch, operands, ..
881            } => {
882                for op in operands {
883                    if let Operand::LocalLabel(name) = op {
884                        local_ident(&mut locals, name, Span::mixed_site());
885                    }
886                }
887                if let Some(p) = patch {
888                    bindings.push(Binding {
889                        public: p.name.clone(),
890                        is_label: false,
891                    });
892                }
893            }
894        }
895    }
896
897    let mut prelude = TokenStream2::new();
898    for (_, id) in &locals {
899        prelude.extend(quote! {
900            let #id = __onlineasm_asm.label();
901        });
902    }
903    for binding in bindings.iter().filter(|b| b.is_label) {
904        let id = &binding.public;
905        prelude.extend(quote! {
906            let #id = __onlineasm_asm.label();
907        });
908    }
909
910    let mut stmts = TokenStream2::new();
911    let mut externs: Vec<Ident> = Vec::new();
912    for stmt in &parsed.stmts {
913        stmts.extend(emit_stmt(&locals, &externs, &bindings, stmt)?);
914        if let Stmt::ExternDef { name, .. } = stmt {
915            externs.push(name.clone());
916        }
917    }
918
919    let temps: Vec<&Ident> = bindings.iter().map(|b| &b.public).collect();
920    let publics = temps.clone();
921
922    let tail = if temps.is_empty() {
923        TokenStream2::new()
924    } else {
925        quote! { ( #(#temps,)* ) }
926    };
927
928    let body = quote! {{
929        let __onlineasm_asm = &mut #asm_expr;
930        #prelude
931        #stmts
932        #tail
933    }};
934
935    if bindings.is_empty() {
936        // No call-site bindings: a plain block keeps the borrow scoped.
937        Ok(quote! { { #body } })
938    } else {
939        Ok(quote! {
940            let ( #(#publics,)* ) = #body;
941        })
942    }
943}
944
945fn local_ident(locals: &mut Vec<(String, Ident)>, name: &str, span: Span) -> Ident {
946    if let Some((_, id)) = locals.iter().find(|(n, _)| n == name) {
947        return id.clone();
948    }
949    let id = Ident::new(&format!("__onlineasm_local_{}", locals.len()), span);
950    locals.push((name.to_string(), id.clone()));
951    id
952}
953
954fn emit_stmt(
955    locals: &[(String, Ident)],
956    externs: &[Ident],
957    bindings: &[Binding],
958    stmt: &Stmt,
959) -> syn::Result<TokenStream2> {
960    match stmt {
961        Stmt::LocalDef { name } => {
962            let id = local_ident_ref(locals, name);
963            Ok(quote! {
964                __onlineasm_asm.bind(#id);
965            })
966        }
967        Stmt::DynDef { name } => Ok(quote! {
968            __onlineasm_asm.bind(#name);
969        }),
970        Stmt::ExternDef { name, near, expr } => {
971            let reach = reach_tokens(*near);
972            Ok(quote! {
973                let #name = __onlineasm_asm.extern_name(#expr, #reach);
974            })
975        }
976        Stmt::Instr {
977            patch,
978            mnemonic,
979            mnemonic_span,
980            operands,
981        } => {
982            let mnem = mnemonic_ident(mnemonic, *mnemonic_span);
983            let mut prologue = TokenStream2::new();
984            let mut ops = Vec::new();
985            for (i, op) in operands.iter().enumerate() {
986                let expr = emit_value(locals, externs, op)?;
987                let id = Ident::new(&format!("__onlineasm_op{i}"), Span::mixed_site());
988                prologue.extend(quote! {
989                    let #id = #expr;
990                });
991                ops.push(id);
992            }
993            if let Some(attr) = patch {
994                let binding = bindings
995                    .iter()
996                    .find(|b| b.public == attr.name)
997                    .expect("patch binding");
998                let handle = &binding.public;
999                match attr.mode {
1000                    PatchMode::Site => Ok(quote! {
1001                        #prologue
1002                        let #handle = match __onlineasm_asm.emit_patched(#mnem, &[#(#ops),*]) {
1003                            ::std::result::Result::Ok(__h) => __h,
1004                            ::std::result::Result::Err(__e) => {
1005                                ::std::panic!("onlineasm: lowering `{}` failed: {}", #mnemonic, __e)
1006                            }
1007                        };
1008                    }),
1009                    PatchMode::Abs => {
1010                        if mnemonic != "jmp" && mnemonic != "call" {
1011                            return Err(Error::new(
1012                                *mnemonic_span,
1013                                "onlineasm: #[patch_abs] applies to `jmp`/`call` only",
1014                            ));
1015                        }
1016                        let target =
1017                            match (operands.first(), operands.len()) {
1018                                (Some(Operand::Imm { .. }) | Some(Operand::Splice(_)), 1) => {
1019                                    ops[0].clone()
1020                                }
1021                                (Some(_), _) => return Err(Error::new(
1022                                    *mnemonic_span,
1023                                    "onlineasm: #[patch_abs] target must be an integer or {expr}",
1024                                )),
1025                                (None, _) => {
1026                                    return Err(Error::new(
1027                                        *mnemonic_span,
1028                                        "onlineasm: #[patch_abs] needs a target operand",
1029                                    ))
1030                                }
1031                            };
1032                        let move_ident = mnemonic_ident("move", *mnemonic_span);
1033                        Ok(quote! {
1034                            #prologue
1035                            let __onlineasm_scratch = __onlineasm_asm.scratch().gpr;
1036                            let #handle = match __onlineasm_asm.emit_patched(
1037                                #move_ident,
1038                                &[::onlineasm::Op::Gpr(__onlineasm_scratch), #target],
1039                            ) {
1040                                ::std::result::Result::Ok(__h) => __h,
1041                                ::std::result::Result::Err(__e) => {
1042                                    ::std::panic!("onlineasm: lowering `move` failed: {}", __e)
1043                                }
1044                            };
1045                            let __onlineasm_scratch_op = ::onlineasm::Op::Gpr(__onlineasm_scratch);
1046                            if let ::std::result::Result::Err(__e) =
1047                                __onlineasm_asm.emit(#mnem, &[__onlineasm_scratch_op])
1048                            {
1049                                ::std::panic!("onlineasm: lowering `{}` failed: {}", #mnemonic, __e)
1050                            }
1051                        })
1052                    }
1053                }
1054            } else {
1055                Ok(quote! {
1056                    #prologue
1057                    if let ::std::result::Result::Err(__e) =
1058                        __onlineasm_asm.emit(#mnem, &[#(#ops),*])
1059                    {
1060                        ::std::panic!("onlineasm: lowering `{}` failed: {}", #mnemonic, __e)
1061                    }
1062                })
1063            }
1064        }
1065    }
1066}
1067
1068fn local_ident_ref(locals: &[(String, Ident)], name: &str) -> Ident {
1069    locals
1070        .iter()
1071        .find(|(n, _)| n == name)
1072        .map(|(_, id)| id.clone())
1073        .expect("local label")
1074}
1075
1076/// Maps a mnemonic to its `::onlineasm::mnem::<name>` constant.
1077///
1078/// Encodes Rust keywords as raw idents.
1079fn mnemonic_ident(mnemonic: &str, span: Span) -> TokenStream2 {
1080    let ident = match mnemonic {
1081        "move" => Ident::new_raw("move", span),
1082        "break" => Ident::new_raw("break", span),
1083        other => Ident::new(other, span),
1084    };
1085    quote! { ::onlineasm::mnem::#ident }
1086}
1087
1088fn reach_tokens(near: bool) -> TokenStream2 {
1089    if near {
1090        quote! { ::onlineasm::Reach::Near }
1091    } else {
1092        quote! { ::onlineasm::Reach::Far }
1093    }
1094}
1095
1096/// Emits an operand expression evaluating to an `Op`.
1097fn emit_value(
1098    locals: &[(String, Ident)],
1099    externs: &[Ident],
1100    op: &Operand,
1101) -> syn::Result<TokenStream2> {
1102    Ok(match op {
1103        Operand::Name { name, err } => {
1104            if !externs.contains(name) {
1105                return Err(err.clone());
1106            }
1107            quote! { __onlineasm_asm.op(#name) }
1108        }
1109        Operand::Extern { near, expr } => {
1110            let reach = reach_tokens(*near);
1111            quote! {{
1112                let __onlineasm_ext = __onlineasm_asm.extern_name(#expr, #reach);
1113                __onlineasm_asm.op(__onlineasm_ext)
1114            }}
1115        }
1116        Operand::Imm { lit, neg } => {
1117            if *neg {
1118                quote! { __onlineasm_asm.op(-(#lit as i64)) }
1119            } else {
1120                quote! { __onlineasm_asm.op(#lit as i64) }
1121            }
1122        }
1123        Operand::Reg(RegId::VReg(name)) => {
1124            if let Some(ext) = externs.iter().find(|e| *e == name) {
1125                quote! { __onlineasm_asm.op(#ext) }
1126            } else {
1127                let ident = Ident::new(name, Span::call_site());
1128                quote! { __onlineasm_asm.op(::onlineasm::regs::#ident) }
1129            }
1130        }
1131        Operand::Reg(RegId::Phys {
1132            id,
1133            class: RegClass::Gpr,
1134        }) => quote! { __onlineasm_asm.op(::onlineasm::Gpr(#id)) },
1135        Operand::Reg(RegId::Phys {
1136            id,
1137            class: RegClass::Fpr,
1138        }) => quote! { __onlineasm_asm.op(::onlineasm::Fpr(#id)) },
1139        Operand::LocalLabel(name) => {
1140            let id = local_ident_ref(locals, name);
1141            quote! { __onlineasm_asm.op(#id) }
1142        }
1143        Operand::Splice(e) => quote! { __onlineasm_asm.op(#e) },
1144        Operand::Mem(m) => {
1145            let base = emit_mem_atom(m.base_ref());
1146            let op = match &m.index {
1147                None => {
1148                    let disp = emit_disp(&m.disp);
1149                    quote! { __onlineasm_asm.mem(#base, #disp) }
1150                }
1151                Some((atom, scale)) => {
1152                    let idx = emit_mem_atom(atom);
1153                    let disp = emit_disp(&m.disp);
1154                    quote! { __onlineasm_asm.mem_indexed(#base, #idx, #scale, #disp) }
1155                }
1156            };
1157            quote! { ::onlineasm::Op::Mem(#op) }
1158        }
1159    })
1160}
1161
1162impl MemOp {
1163    fn base_ref(&self) -> &MemAtom {
1164        &self.base
1165    }
1166}
1167
1168fn emit_mem_atom(atom: &MemAtom) -> TokenStream2 {
1169    match atom {
1170        MemAtom::Reg(RegId::VReg(name)) => {
1171            let ident = Ident::new(name, Span::call_site());
1172            quote! { ::onlineasm::regs::#ident }
1173        }
1174        MemAtom::Reg(RegId::Phys {
1175            id,
1176            class: RegClass::Gpr,
1177        }) => quote! { ::onlineasm::Gpr(#id) },
1178        MemAtom::Reg(RegId::Phys {
1179            id,
1180            class: RegClass::Fpr,
1181        }) => quote! { ::onlineasm::Fpr(#id) },
1182        MemAtom::Splice(e) => quote! { #e },
1183    }
1184}
1185
1186fn emit_disp(disp: &MemDisp) -> TokenStream2 {
1187    match disp {
1188        MemDisp::None => quote! { 0i32 },
1189        MemDisp::Imm(d) => quote! { #d },
1190        MemDisp::Splice(e) => quote! { (#e as i32) },
1191        MemDisp::NegSplice(e) => quote! { (0i32 - (#e as i32)) },
1192    }
1193}