use std::sync::OnceLock;
const REFERENCE: &str = include_str!("../docs/reference.md");
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Availability {
Both,
OfflineasmOnly,
RloopOnly,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Audience {
Offlineasm,
Onlineasm,
}
impl Audience {
pub fn includes(self, availability: Availability) -> bool {
self == Audience::Offlineasm || availability == Availability::Both
}
}
#[derive(Clone, Debug)]
pub struct Entry {
pub mnemonics: Vec<&'static str>,
pub form: &'static str,
pub body: &'static str,
pub scratch: String,
pub availability: Availability,
}
pub fn entries() -> &'static [Entry] {
static ENTRIES: OnceLock<Vec<Entry>> = OnceLock::new();
ENTRIES.get_or_init(parse)
}
pub fn entry_for(mnemonic: &str) -> Option<&'static Entry> {
entries()
.iter()
.find(|entry| entry.mnemonics.contains(&mnemonic))
}
fn code_spans(text: &str) -> impl Iterator<Item = &str> {
text.split('`').skip(1).step_by(2)
}
fn parse() -> Vec<Entry> {
let mut sections: Vec<(&'static str, usize, usize)> = Vec::new();
let mut in_fence = false;
let mut offset = 0;
for line in REFERENCE.split_inclusive('\n') {
let start = offset;
offset += line.len();
if line.trim_start().starts_with("```") {
in_fence = !in_fence;
}
if in_fence || !line.starts_with('#') {
continue;
}
if let Some(last) = sections.last_mut() {
last.2 = start;
}
sections.push((line.trim_end(), offset, REFERENCE.len()));
}
let mut entries = Vec::new();
let mut entry_sections = Vec::new();
let mut scratch_bodies = Vec::new();
let mut restricted: Vec<(&str, Availability)> = Vec::new();
let mut section = 0;
for &(heading, start, end) in §ions {
let body = REFERENCE[start..end].trim();
if heading.starts_with("## ") {
section += 1;
}
if heading == "### Scratch registers" {
scratch_bodies.push((section, body));
continue;
}
if heading == "## Availability" {
for line in body.lines().filter(|line| line.starts_with("- ")) {
let (label, names) = line.split_once(':').unwrap_or(("", line));
let availability = if label.contains("rloop") {
Availability::RloopOnly
} else {
Availability::OfflineasmOnly
};
restricted.extend(code_spans(names).map(|name| (name, availability)));
}
continue;
}
if !heading.starts_with("### `") {
continue;
}
let mut spans = code_spans(heading);
let first = spans.next().unwrap_or_default();
let (head, form) = first.split_once(' ').unwrap_or((first, ""));
let mut mnemonics = vec![head];
mnemonics.extend(spans);
entries.push(Entry {
mnemonics,
form: form.trim(),
body,
scratch: String::new(),
availability: Availability::Both,
});
entry_sections.push(section);
}
let known: Vec<&str> = entries.iter().flat_map(|e| e.mnemonics.clone()).collect();
for (section, body) in scratch_bodies {
let (intro, groups) = scratch_groups(body, &known);
for (entry, _) in entries
.iter_mut()
.zip(&entry_sections)
.filter(|(_, s)| **s == section)
{
let group = groups
.iter()
.find(|(names, _)| entry.mnemonics.iter().any(|m| names.iter().any(|n| n == m)));
let parts: Vec<&str> = match group {
Some((_, text)) => [intro.as_str(), text].into(),
None if groups.is_empty() => vec![intro.as_str()],
None => continue,
};
let parts: Vec<&str> = parts.into_iter().filter(|p| !p.is_empty()).collect();
entry.scratch = parts.join("\n\n");
}
}
for entry in &mut entries {
if let Some(&(_, availability)) = restricted
.iter()
.find(|(name, _)| entry.mnemonics.contains(name))
{
entry.availability = availability;
}
}
entries
}
fn scratch_groups(body: &str, known: &[&str]) -> (String, Vec<(Vec<String>, String)>) {
let is_start = |block: &str| {
let lead = block.split('`').next().unwrap_or_default();
block.contains('`')
&& (lead.trim_end().ends_with(':') || block.contains("clobber no scratch register"))
};
let blocks: Vec<&str> = body
.split("\n\n")
.map(str::trim)
.filter(|block| !block.is_empty())
.collect();
let first = blocks
.iter()
.position(|b| is_start(b))
.unwrap_or(blocks.len());
let intro = blocks[..first].join("\n\n");
let mut groups = Vec::new();
let mut index = first;
while index < blocks.len() {
let head = blocks[index];
let end = blocks[index + 1..]
.iter()
.position(|b| is_start(b))
.map_or(blocks.len(), |p| index + 1 + p);
let rest = &blocks[index + 1..end];
let split = head.find(". ").or_else(|| head.find(".\n"));
let (list, note) = match split {
Some(at) => (&head[..at], head[at + 2..].trim()),
None => (head, ""),
};
let names = group_names(list, known);
let mut parts: Vec<&str> = Vec::new();
if rest.is_empty() {
parts.push(head);
} else {
if !note.is_empty() {
parts.push(note);
}
parts.extend(rest);
}
groups.push((names, parts.join("\n\n")));
index = end;
}
(intro, groups)
}
fn group_names(list: &str, known: &[&str]) -> Vec<String> {
let mut explicit = Vec::new();
let mut wildcards = Vec::new();
for span in code_spans(list) {
if let Some(prefix) = span.strip_suffix('*') {
wildcards.push(prefix);
} else if let Some((stem, suffixes)) =
span.strip_suffix('}').and_then(|s| s.split_once('{'))
{
explicit.extend(suffixes.split(',').map(|suffix| format!("{stem}{suffix}")));
} else {
explicit.push(span.to_string());
}
}
let stem =
explicit
.iter()
.skip(1)
.fold(explicit.first().map_or(0, String::len), |len, name| {
let first = &explicit[0];
first
.bytes()
.zip(name.bytes())
.take(len)
.take_while(|(a, b)| a == b)
.count()
});
let mut names = explicit.clone();
for prefix in wildcards {
for name in &explicit {
names.push(format!("{prefix}{}", &name[stem..]));
}
}
names.retain(|name| known.contains(&name.as_str()));
names
}
pub fn mnemonic_doc(mnemonic: &str, audience: Audience) -> Option<String> {
let entry = entry_for(mnemonic).filter(|entry| audience.includes(entry.availability))?;
let signature = if entry.form.is_empty() {
mnemonic.to_string()
} else {
format!("{} {}", mnemonic, entry.form)
};
let mut doc = format!("`{}`\n\n{}", signature, entry.body);
if !entry.scratch.is_empty() {
doc.push_str("\n\n# Scratch registers\n\n");
doc.push_str(&entry.scratch);
}
Some(doc)
}
pub fn method_doc(mnemonic: &str) -> Option<String> {
mnemonic_doc(mnemonic, Audience::Onlineasm)
}
pub fn mnemonics(audience: Audience) -> Vec<&'static str> {
let mut names: Vec<&'static str> = Vec::new();
for entry in entries() {
if !audience.includes(entry.availability) {
continue;
}
for name in &entry.mnemonics {
if !names.contains(name) {
names.push(name);
}
}
}
names
}
fn is_keyword(name: &str) -> bool {
matches!(
name,
"as" | "async"
| "await"
| "break"
| "const"
| "continue"
| "crate"
| "dyn"
| "else"
| "enum"
| "extern"
| "false"
| "fn"
| "for"
| "if"
| "impl"
| "in"
| "let"
| "loop"
| "match"
| "mod"
| "move"
| "mut"
| "pub"
| "ref"
| "return"
| "self"
| "static"
| "struct"
| "super"
| "trait"
| "true"
| "type"
| "unsafe"
| "use"
| "where"
| "while"
| "abstract"
| "become"
| "box"
| "do"
| "final"
| "macro"
| "override"
| "priv"
| "try"
| "typeof"
| "unsized"
| "virtual"
| "yield"
)
}
fn const_ident(name: &str) -> String {
if is_keyword(name) {
format!("r#{}", name)
} else {
name.to_string()
}
}
pub fn render_mnem_module(audience: Audience) -> String {
let mut out = String::new();
let names = mnemonics(audience);
for name in &names {
for line in mnemonic_doc(name, audience).unwrap_or_default().lines() {
if line.is_empty() {
out.push_str("///\n");
} else {
out.push_str("/// ");
out.push_str(line);
out.push('\n');
}
}
let ident = const_ident(name);
out.push_str(&match audience {
Audience::Onlineasm => format!(
"pub const {ident}: ::offlineasm_ir::Mnemonic = ::offlineasm_ir::mnem::{ident};\n\n"
),
Audience::Offlineasm => format!("pub const {ident}: &str = \"{name}\";\n\n"),
});
}
out.push_str("/// Every mnemonic this module has a constant for, in reference order.\n");
out.push_str("pub const TABLE: &[&str] = &[\n");
for name in &names {
out.push_str(&format!(" \"{name}\",\n"));
}
out.push_str("];\n");
out
}