xur-std 0.1.11

The standard library of the Xur language
Documentation
//! Method bodies for scripts: their instructions (with byte offsets and the
//! tokens they refer to), editing them (`insert`, `remove`, `replace`, then
//! `method.set_body`), finding calls to a well-known method, and metadata
//! tokens for entries.

use facet::Facet;
use hao::dotnet::il::{Instruction, MemberToken, Operand, instruction_offsets};
use hao::prelude::*;
use xur_runtime::registry::ModuleBuilder;
use xur_runtime::{OneOf, OptionalArg};

use super::WellKnownMethodArg;
use super::types::DotnetMethodBody;

/// One instruction of a body, as `body.at(i)` / `body.list()` give it.
#[derive(Facet, Clone)]
pub struct IlInstruction {
    /// Its position in the body (what `insert` / `remove` take).
    pub index: i64,
    /// Its byte offset in the method (`IL_xxxx`).
    pub offset: i64,
    pub opcode: String,
    /// The operand as text (a member's full name, a branch's `IL_xxxx`, ...).
    pub operand: String,
    /// The metadata token of a member or type operand.
    pub token: Option<i64>,
    /// A branch's target, as a byte offset.
    pub target: Option<i64>,
}

/// The metadata token of an entry: its table in the top byte, its row below.
pub fn token(table: u32, rid: u32) -> i64 {
    i64::from((table << 24) | rid)
}

/// The metadata token an operand refers to.
pub fn member_token(token_: &MemberToken) -> i64 {
    match token_ {
        MemberToken::TypeRef(e) => token(0x01, e.rid()),
        MemberToken::TypeDef(e) => token(0x02, e.rid()),
        MemberToken::Field(e) => token(0x04, e.rid()),
        MemberToken::Method(e) => token(0x06, e.rid()),
        MemberToken::MemberRef(e) => token(0x0a, e.rid()),
        MemberToken::TypeSpec(e) => token(0x1b, e.rid()),
        MemberToken::MethodSpec(e) => token(0x2b, e.rid()),
    }
}

/// A member operand's name: `Ns.Type::Member`.
fn member_name(token_: &MemberToken) -> String {
    match token_ {
        MemberToken::Method(m) => {
            let g = m.get();
            let ty = g
                .declaring_type
                .upgrade()
                .map(|t| t.get().full_name())
                .unwrap_or_default();
            format!("{ty}::{}", g.name)
        }
        MemberToken::Field(f) => {
            let g = f.get();
            let ty = g
                .declaring_type
                .upgrade()
                .map(|t| t.get().full_name())
                .unwrap_or_default();
            format!("{ty}::{}", g.name)
        }
        MemberToken::MemberRef(mr) => {
            let g = mr.get();
            let class = g
                .parent
                .as_type()
                .map(|t| t.full_name())
                .unwrap_or_default();
            format!("{class}::{}", g.name)
        }
        MemberToken::TypeDef(t) => t.get().full_name(),
        MemberToken::TypeRef(t) => t.get().full_name(),
        MemberToken::TypeSpec(_) => "<typespec>".into(),
        MemberToken::MethodSpec(s) => s.get().method.name().to_string(),
    }
}

fn label(offsets: &[u32], index: usize) -> String {
    format!("IL_{:04x}", offsets.get(index).copied().unwrap_or(0))
}

/// The operand of `instr` as text, branch targets as byte offsets.
fn operand_text(op: &Operand, offsets: &[u32]) -> String {
    match op {
        Operand::None => String::new(),
        Operand::Int32(v) => v.to_string(),
        Operand::Int64(v) => v.to_string(),
        Operand::Float32(v) => v.to_string(),
        Operand::Float64(v) => v.to_string(),
        Operand::Target(l) => label(offsets, l.0),
        Operand::Switch(targets) => {
            let labels: Vec<String> = targets.iter().map(|l| label(offsets, l.0)).collect();
            format!("({})", labels.join(", "))
        }
        Operand::Local(idx) => format!("V_{idx}"),
        Operand::Arg(idx) => format!("A_{idx}"),
        Operand::String(s) => format!("\"{s}\""),
        Operand::Sig(_) => "<sig>".into(),
        Operand::Token(t) => member_name(t),
    }
}

fn info(
    body: &hao::dotnet::il::MethodBody,
    offsets: &[u32],
    index: usize,
) -> Option<IlInstruction> {
    let instr = body.instructions.get(index)?;
    Some(IlInstruction {
        index: index as i64,
        offset: i64::from(offsets[index]),
        opcode: instr.opcode.to_string(),
        operand: operand_text(&instr.operand, offsets),
        token: match &instr.operand {
            Operand::Token(t) => Some(member_token(t)),
            _ => None,
        },
        target: match &instr.operand {
            Operand::Target(l) => offsets.get(l.0).map(|&o| i64::from(o)),
            _ => None,
        },
    })
}

/// `other`'s instructions, ready to go into `body`: its locals are appended
/// to `body`'s and its local operands moved past them.
fn take_instructions(
    body: &mut hao::dotnet::il::MethodBody,
    other: &hao::dotnet::il::MethodBody,
) -> Vec<Instruction> {
    let base = body.locals.len() as u16;
    body.locals.extend(other.locals.iter().cloned());
    other
        .instructions
        .iter()
        .cloned()
        .map(|mut i| {
            if let Operand::Local(n) = &mut i.operand {
                *n += base;
            }
            i
        })
        .collect()
}

/// Whether `instr` calls (or `newobj`s) the well-known method `m`.
fn calls(instr: &Instruction, m: WellKnownMethod) -> bool {
    let (ns, ty) = m.declaring().full_name();
    let full = if ns.is_empty() {
        ty.to_string()
    } else {
        format!("{ns}.{ty}")
    };
    let (name, sig) = match &instr.operand {
        Operand::Token(MemberToken::MemberRef(r)) => {
            let g = r.get();
            let class = g
                .parent
                .as_type()
                .map(|t| t.full_name())
                .unwrap_or_default();
            if class != full {
                return false;
            }
            let params = match &g.signature {
                hao::dotnet::signature::MemberRefSig::Method(s) => Some(s.params.len()),
                _ => None,
            };
            (g.name.to_string(), params)
        }
        Operand::Token(MemberToken::Method(md)) => {
            let g = md.get();
            let class = g
                .declaring_type
                .upgrade()
                .map(|t| t.get().full_name())
                .unwrap_or_default();
            if class != full {
                return false;
            }
            (g.name.to_string(), Some(g.signature.params.len()))
        }
        _ => return false,
    };
    name == m.method_name() && sig.is_none_or(|n| n == m.param_count())
}

pub(super) fn register(dotnet: &mut ModuleBuilder<'_>) {
    dotnet.ty::<IlInstruction>("Instruction");
    dotnet
        .ty::<DotnetMethodBody>("MethodBody")
        .method("size", |b: &DotnetMethodBody| b.0.instructions.len() as i64)
        // `IL_xxxx: opcode operand`, one line per instruction.
        .method("instructions", |b: &DotnetMethodBody| -> Vec<String> {
            let offsets = instruction_offsets(&b.0.instructions);
            (0..b.0.instructions.len())
                .filter_map(|i| info(&b.0, &offsets, i))
                .map(|i| {
                    let label = format!("IL_{:04x}", i.offset);
                    if i.operand.is_empty() {
                        format!("{label}: {}", i.opcode)
                    } else {
                        format!("{label}: {} {}", i.opcode, i.operand)
                    }
                })
                .collect()
        })
        .named_method(
            "at",
            &["index"],
            |b: &DotnetMethodBody, index: i64| -> Option<IlInstruction> {
                let offsets = instruction_offsets(&b.0.instructions);
                usize::try_from(index)
                    .ok()
                    .and_then(|i| info(&b.0, &offsets, i))
            },
        )
        .method("list", |b: &DotnetMethodBody| -> Vec<IlInstruction> {
            let offsets = instruction_offsets(&b.0.instructions);
            (0..b.0.instructions.len())
                .filter_map(|i| info(&b.0, &offsets, i))
                .collect()
        })
        .method("offsets", |b: &DotnetMethodBody| -> Vec<i64> {
            instruction_offsets(&b.0.instructions)
                .into_iter()
                .map(i64::from)
                .collect()
        })
        // Where it calls a well-known method: instruction indices.
        .named_method(
            "find_calls",
            &["method"],
            |b: &DotnetMethodBody, m: OneOf<WellKnownMethodArg>| -> Vec<i64> {
                let m: WellKnownMethod = m.0.into();
                b.0.instructions
                    .iter()
                    .enumerate()
                    .filter(|(_, i)| calls(i, m))
                    .map(|(i, _)| i as i64)
                    .collect()
            },
        )
        // Puts `other`'s instructions (an emitter's `finish()`) before `index`;
        // branches into the body keep their targets.
        .named_method_mut(
            "insert",
            &["index", "body"],
            |b: &mut DotnetMethodBody, index: i64, other: DotnetMethodBody| -> Result<(), String> {
                let index = usize::try_from(index)
                    .ok()
                    .filter(|&i| i <= b.0.instructions.len())
                    .ok_or_else(|| format!("no instruction {index} to insert before"))?;
                let added = take_instructions(&mut b.0, &other.0);
                b.0.insert(index, added);
                Ok(())
            },
        )
        // Removes `count` (1) instructions from `index`; branches to them go to the next.
        .named_method_mut(
            "remove",
            &["index", "count"],
            |b: &mut DotnetMethodBody, index: i64, count: OptionalArg<i64>| -> Result<(), String> {
                let count = count.0.unwrap_or(1).max(0) as usize;
                let index = usize::try_from(index)
                    .ok()
                    .filter(|&i| i + count <= b.0.instructions.len())
                    .ok_or_else(|| format!("no {count} instruction(s) at {index}"))?;
                for _ in 0..count {
                    b.0.remove(index);
                }
                Ok(())
            },
        )
        // `count` instructions from `index` become `other`'s.
        .named_method_mut(
            "replace",
            &["index", "count", "body"],
            |b: &mut DotnetMethodBody,
             index: i64,
             count: i64,
             other: DotnetMethodBody|
             -> Result<(), String> {
                let count = count.max(0) as usize;
                let at = usize::try_from(index)
                    .ok()
                    .filter(|&i| i + count <= b.0.instructions.len())
                    .ok_or_else(|| format!("no {count} instruction(s) at {index}"))?;
                let added = take_instructions(&mut b.0, &other.0);
                b.0.insert(at, added.clone());
                for _ in 0..count {
                    b.0.remove(at + added.len());
                }
                Ok(())
            },
        );
}

/// `System.Console::WriteLine`: a well-known method's full name.
pub(super) fn well_known_method_name(m: OneOf<WellKnownMethodArg>) -> String {
    let m: WellKnownMethod = m.0.into();
    let (ns, ty) = m.declaring().full_name();
    if ns.is_empty() {
        format!("{ty}::{}", m.method_name())
    } else {
        format!("{ns}.{ty}::{}", m.method_name())
    }
}