Skip to main content

offlineasm_backend/
reference.rs

1//! The instruction reference, parsed from `docs/reference.md`.
2//!
3//! Every `` ### `mnemonic operands` `` heading in that file is one entry: its
4//! body (pseudocode and notes) becomes the rustdoc of the `mnem` constant and,
5//! in `onlineasm`, of the typed `Assembler` method. Each numbered section's
6//! `### Scratch registers` block adds the clobber table for the entry's
7//! group, and the trailing `## Availability` section says which mnemonics
8//! only `offlineasm` accepts.
9
10use std::sync::OnceLock;
11
12const REFERENCE: &str = include_str!("../docs/reference.md");
13
14/// Which assemblers accept a mnemonic.
15#[derive(Clone, Copy, PartialEq, Eq, Debug)]
16pub enum Availability {
17    /// Both `offlineasm` and `onlineasm` accept it.
18    Both,
19    /// Only `offlineasm` accepts it.
20    OfflineasmOnly,
21    /// Only `offlineasm`'s `rloop` backend accepts it.
22    RloopOnly,
23}
24
25/// The crate a rendered reference is for.
26#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27pub enum Audience {
28    Offlineasm,
29    Onlineasm,
30}
31
32impl Audience {
33    pub fn includes(self, availability: Availability) -> bool {
34        self == Audience::Offlineasm || availability == Availability::Both
35    }
36}
37
38/// One `### ...` entry of the reference.
39#[derive(Clone, Debug)]
40pub struct Entry {
41    /// Every spelling the heading names, first one first.
42    pub mnemonics: Vec<&'static str>,
43    /// Operand form shared by all spellings, such as `O1, O2`. Empty for
44    /// bare mnemonics like `ret`.
45    pub form: &'static str,
46    /// Everything between the heading and the next one, trimmed.
47    pub body: &'static str,
48    /// The scratch registers the entry clobbers: its section's scratch
49    /// intro plus its group's table and notes. Empty if the reference has
50    /// none.
51    pub scratch: String,
52    pub availability: Availability,
53}
54
55/// Returns every entry, in document order.
56pub fn entries() -> &'static [Entry] {
57    static ENTRIES: OnceLock<Vec<Entry>> = OnceLock::new();
58    ENTRIES.get_or_init(parse)
59}
60
61/// Returns the entry covering `mnemonic`, if the reference has one.
62pub fn entry_for(mnemonic: &str) -> Option<&'static Entry> {
63    entries()
64        .iter()
65        .find(|entry| entry.mnemonics.contains(&mnemonic))
66}
67
68/// Returns the contents of each `` `...` `` span in `text`.
69fn code_spans(text: &str) -> impl Iterator<Item = &str> {
70    text.split('`').skip(1).step_by(2)
71}
72
73fn parse() -> Vec<Entry> {
74    // Split into (heading, body start, body end) sections. `#` lines inside
75    // code fences are not headings.
76    let mut sections: Vec<(&'static str, usize, usize)> = Vec::new();
77    let mut in_fence = false;
78    let mut offset = 0;
79    for line in REFERENCE.split_inclusive('\n') {
80        let start = offset;
81        offset += line.len();
82        if line.trim_start().starts_with("```") {
83            in_fence = !in_fence;
84        }
85        if in_fence || !line.starts_with('#') {
86            continue;
87        }
88        if let Some(last) = sections.last_mut() {
89            last.2 = start;
90        }
91        sections.push((line.trim_end(), offset, REFERENCE.len()));
92    }
93
94    let mut entries = Vec::new();
95    let mut entry_sections = Vec::new();
96    let mut scratch_bodies = Vec::new();
97    let mut restricted: Vec<(&str, Availability)> = Vec::new();
98    let mut section = 0;
99    for &(heading, start, end) in &sections {
100        let body = REFERENCE[start..end].trim();
101        if heading.starts_with("## ") {
102            section += 1;
103        }
104        if heading == "### Scratch registers" {
105            scratch_bodies.push((section, body));
106            continue;
107        }
108        if heading == "## Availability" {
109            for line in body.lines().filter(|line| line.starts_with("- ")) {
110                let (label, names) = line.split_once(':').unwrap_or(("", line));
111                let availability = if label.contains("rloop") {
112                    Availability::RloopOnly
113                } else {
114                    Availability::OfflineasmOnly
115                };
116                restricted.extend(code_spans(names).map(|name| (name, availability)));
117            }
118            continue;
119        }
120        if !heading.starts_with("### `") {
121            continue;
122        }
123        // `tls_loadb O1, O2` / `tls_loadh` / ...: the first span carries the
124        // operand form, later spans are more spellings.
125        let mut spans = code_spans(heading);
126        let first = spans.next().unwrap_or_default();
127        let (head, form) = first.split_once(' ').unwrap_or((first, ""));
128        let mut mnemonics = vec![head];
129        mnemonics.extend(spans);
130        entries.push(Entry {
131            mnemonics,
132            form: form.trim(),
133            body,
134            scratch: String::new(),
135            availability: Availability::Both,
136        });
137        entry_sections.push(section);
138    }
139
140    let known: Vec<&str> = entries.iter().flat_map(|e| e.mnemonics.clone()).collect();
141    for (section, body) in scratch_bodies {
142        let (intro, groups) = scratch_groups(body, &known);
143        for (entry, _) in entries
144            .iter_mut()
145            .zip(&entry_sections)
146            .filter(|(_, s)| **s == section)
147        {
148            let group = groups
149                .iter()
150                .find(|(names, _)| entry.mnemonics.iter().any(|m| names.iter().any(|n| n == m)));
151            let parts: Vec<&str> = match group {
152                Some((_, text)) => [intro.as_str(), text].into(),
153                None if groups.is_empty() => vec![intro.as_str()],
154                None => continue,
155            };
156            let parts: Vec<&str> = parts.into_iter().filter(|p| !p.is_empty()).collect();
157            entry.scratch = parts.join("\n\n");
158        }
159    }
160
161    for entry in &mut entries {
162        if let Some(&(_, availability)) = restricted
163            .iter()
164            .find(|(name, _)| entry.mnemonics.contains(name))
165        {
166            entry.availability = availability;
167        }
168    }
169    entries
170}
171
172/// Splits a `### Scratch registers` body into its intro and its groups.
173///
174/// A group starts at a `Label: \`name\`, ...` paragraph, or at a paragraph
175/// saying its names "clobber no scratch register", and runs to the next one.
176/// Each group pairs the mnemonics it names with its table and notes.
177fn scratch_groups(body: &str, known: &[&str]) -> (String, Vec<(Vec<String>, String)>) {
178    let is_start = |block: &str| {
179        let lead = block.split('`').next().unwrap_or_default();
180        block.contains('`')
181            && (lead.trim_end().ends_with(':') || block.contains("clobber no scratch register"))
182    };
183    let blocks: Vec<&str> = body
184        .split("\n\n")
185        .map(str::trim)
186        .filter(|block| !block.is_empty())
187        .collect();
188    let first = blocks
189        .iter()
190        .position(|b| is_start(b))
191        .unwrap_or(blocks.len());
192    let intro = blocks[..first].join("\n\n");
193    let mut groups = Vec::new();
194    let mut index = first;
195    while index < blocks.len() {
196        let head = blocks[index];
197        let end = blocks[index + 1..]
198            .iter()
199            .position(|b| is_start(b))
200            .map_or(blocks.len(), |p| index + 1 + p);
201        let rest = &blocks[index + 1..end];
202        // The name list ends at the paragraph's first sentence; anything
203        // after it is a note about the group.
204        let split = head.find(". ").or_else(|| head.find(".\n"));
205        let (list, note) = match split {
206            Some(at) => (&head[..at], head[at + 2..].trim()),
207            None => (head, ""),
208        };
209        let names = group_names(list, known);
210        let mut parts: Vec<&str> = Vec::new();
211        if rest.is_empty() {
212            parts.push(head);
213        } else {
214            if !note.is_empty() {
215                parts.push(note);
216            }
217            parts.extend(rest);
218        }
219        groups.push((names, parts.join("\n\n")));
220        index = end;
221    }
222    (intro, groups)
223}
224
225/// Expands the names a group paragraph lists into known mnemonics.
226///
227/// Handles `atomicxchg{b,h,i,q}` suffix sets and `cb*` wildcards, which
228/// reuse the conditions of the paragraph's explicit names (`cieq` and
229/// `cineq` give `cbeq` and `cbneq`).
230fn group_names(list: &str, known: &[&str]) -> Vec<String> {
231    let mut explicit = Vec::new();
232    let mut wildcards = Vec::new();
233    for span in code_spans(list) {
234        if let Some(prefix) = span.strip_suffix('*') {
235            wildcards.push(prefix);
236        } else if let Some((stem, suffixes)) =
237            span.strip_suffix('}').and_then(|s| s.split_once('{'))
238        {
239            explicit.extend(suffixes.split(',').map(|suffix| format!("{stem}{suffix}")));
240        } else {
241            explicit.push(span.to_string());
242        }
243    }
244    // The conditions are what follows the explicit names' common stem:
245    // `baddio`, `baddis`, ... give `o`, `s`, ..., so `bori*` means `borio`, ...
246    let stem =
247        explicit
248            .iter()
249            .skip(1)
250            .fold(explicit.first().map_or(0, String::len), |len, name| {
251                let first = &explicit[0];
252                first
253                    .bytes()
254                    .zip(name.bytes())
255                    .take(len)
256                    .take_while(|(a, b)| a == b)
257                    .count()
258            });
259    let mut names = explicit.clone();
260    for prefix in wildcards {
261        for name in &explicit {
262            names.push(format!("{prefix}{}", &name[stem..]));
263        }
264    }
265    names.retain(|name| known.contains(&name.as_str()));
266    names
267}
268
269/// Builds the rustdoc for one mnemonic: its signature, its entry's body, and
270/// its scratch registers.
271///
272/// Returns `None` for unknown spellings and entries `audience` excludes.
273pub fn mnemonic_doc(mnemonic: &str, audience: Audience) -> Option<String> {
274    let entry = entry_for(mnemonic).filter(|entry| audience.includes(entry.availability))?;
275    let signature = if entry.form.is_empty() {
276        mnemonic.to_string()
277    } else {
278        format!("{} {}", mnemonic, entry.form)
279    };
280    let mut doc = format!("`{}`\n\n{}", signature, entry.body);
281    if !entry.scratch.is_empty() {
282        doc.push_str("\n\n# Scratch registers\n\n");
283        doc.push_str(&entry.scratch);
284    }
285    Some(doc)
286}
287
288/// Builds the rustdoc body for `onlineasm`'s typed `Assembler` method.
289pub fn method_doc(mnemonic: &str) -> Option<String> {
290    mnemonic_doc(mnemonic, Audience::Onlineasm)
291}
292
293/// Returns every mnemonic `audience` accepts, in reference order.
294pub fn mnemonics(audience: Audience) -> Vec<&'static str> {
295    let mut names: Vec<&'static str> = Vec::new();
296    for entry in entries() {
297        if !audience.includes(entry.availability) {
298            continue;
299        }
300        for name in &entry.mnemonics {
301            if !names.contains(name) {
302                names.push(name);
303            }
304        }
305    }
306    names
307}
308
309/// Reports whether `name` is a Rust keyword, which needs raw form (`r#move`).
310fn is_keyword(name: &str) -> bool {
311    matches!(
312        name,
313        "as" | "async"
314            | "await"
315            | "break"
316            | "const"
317            | "continue"
318            | "crate"
319            | "dyn"
320            | "else"
321            | "enum"
322            | "extern"
323            | "false"
324            | "fn"
325            | "for"
326            | "if"
327            | "impl"
328            | "in"
329            | "let"
330            | "loop"
331            | "match"
332            | "mod"
333            | "move"
334            | "mut"
335            | "pub"
336            | "ref"
337            | "return"
338            | "self"
339            | "static"
340            | "struct"
341            | "super"
342            | "trait"
343            | "true"
344            | "type"
345            | "unsafe"
346            | "use"
347            | "where"
348            | "while"
349            | "abstract"
350            | "become"
351            | "box"
352            | "do"
353            | "final"
354            | "macro"
355            | "override"
356            | "priv"
357            | "try"
358            | "typeof"
359            | "unsized"
360            | "virtual"
361            | "yield"
362    )
363}
364
365/// Formats `name` as a Rust identifier.
366fn const_ident(name: &str) -> String {
367    if is_keyword(name) {
368        format!("r#{}", name)
369    } else {
370        name.to_string()
371    }
372}
373
374/// Renders the documented `mnem` module for `audience`.
375///
376/// `onlineasm` constants re-export `offlineasm_ir::mnem`; `offlineasm`
377/// constants are the spellings themselves.
378pub fn render_mnem_module(audience: Audience) -> String {
379    let mut out = String::new();
380    let names = mnemonics(audience);
381    for name in &names {
382        for line in mnemonic_doc(name, audience).unwrap_or_default().lines() {
383            if line.is_empty() {
384                out.push_str("///\n");
385            } else {
386                out.push_str("/// ");
387                out.push_str(line);
388                out.push('\n');
389            }
390        }
391        let ident = const_ident(name);
392        out.push_str(&match audience {
393            Audience::Onlineasm => format!(
394                "pub const {ident}: ::offlineasm_ir::Mnemonic = ::offlineasm_ir::mnem::{ident};\n\n"
395            ),
396            Audience::Offlineasm => format!("pub const {ident}: &str = \"{name}\";\n\n"),
397        });
398    }
399    out.push_str("/// Every mnemonic this module has a constant for, in reference order.\n");
400    out.push_str("pub const TABLE: &[&str] = &[\n");
401    for name in &names {
402        out.push_str(&format!("    \"{name}\",\n"));
403    }
404    out.push_str("];\n");
405    out
406}