1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use std::fs::File;
use std::io::Write;
use std::path::Path;

use anyhow::Result;
use colored::*;
use rustc_hash::FxHashMap;

use crate::error::*;
use crate::instruction::*;

struct Context {
    label_addrs: FxHashMap<String, usize>,
}

impl Context {
    fn new() -> Context {
        Context {
            label_addrs: FxHashMap::default(),
        }
    }

    fn get_addr_by_label(&self, name: &str) -> Result<usize> {
        Ok(self
            .label_addrs
            .get(name)
            .cloned()
            .ok_or_else(|| Error::LabelNotDefined(name.to_string()))?)
    }
}

type Code = u32;
type Codes = Vec<Code>;

pub fn dump_instructions(insts: &[InstructionWithLabel]) {
    println!("{}", "RISC-V Instructions:".red());
    for (addr, InstructionWithLabel { inst, labels, ir }) in insts.iter().enumerate() {
        for label in labels {
            let addr = format!("; 0x{:x}", addr * 4);
            println!("{}: {}", &label.name, addr.dimmed());
        }

        if let Some(ir) = ir {
            let ir = format!(";{}", ir);
            println!("  {}", ir.dimmed());
        }
        println!("  {}", inst);
    }
    println!();
}

fn replace_label(imm: Immediate, ctx: &Context) -> Result<Immediate> {
    match imm {
        Immediate::Value(_) => Ok(imm),
        Immediate::Label(label) => Ok(Immediate::new(ctx.get_addr_by_label(&label.name)? as i32)),
    }
}

fn replace_redaddr_label(rel_addr: RelAddress, addr: usize, ctx: &Context) -> Result<RelAddress> {
    match rel_addr {
        RelAddress::Immediate(_) => Ok(rel_addr),
        RelAddress::Label(label) => Ok(RelAddress::Immediate(Immediate::Value(
            ctx.get_addr_by_label(&label.name)? as i32 - addr as i32,
        ))),
    }
}

fn replace_labels(inst: InstructionWithLabel, ctx: &Context) -> Result<InstructionWithLabel> {
    use Instruction::*;

    let InstructionWithLabel { inst, labels, ir } = inst;
    let replaced = match inst {
        R(_) => inst,
        I(IInstruction { op, imm, rs1, rd }) => I(IInstruction {
            op,
            imm: replace_label(imm, ctx)?,
            rs1,
            rd,
        }),
        S(SInstruction { op, imm, rs1, rs2 }) => S(SInstruction {
            op,
            imm: replace_label(imm, ctx)?,
            rs1,
            rs2,
        }),
        J(_) => inst,
        U(UInstruction { op, imm, rd }) => U(UInstruction {
            op,
            imm: replace_label(imm, ctx)?,
            rd,
        }),
        SB(_) => inst,
    };
    Ok(InstructionWithLabel::new(replaced, labels, ir))
}

fn replace_reladdr_labels(
    inst: InstructionWithLabel,
    addr: usize,
    ctx: &Context,
) -> Result<InstructionWithLabel> {
    use Instruction::*;

    let InstructionWithLabel { inst, labels, ir } = inst;
    let replaced = match inst {
        J(JInstruction { op, imm, rd }) => J(JInstruction {
            op,
            imm: replace_redaddr_label(imm, addr, ctx)?,
            rd,
        }),
        SB(SBInstruction { op, imm, rs1, rs2 }) => SB(SBInstruction {
            op,
            imm: replace_redaddr_label(imm, addr, ctx)?,
            rs1,
            rs2,
        }),
        _ => inst,
    };
    Ok(InstructionWithLabel::new(replaced, labels, ir))
}

pub fn assemble<P>(instructions: Vec<InstructionWithLabel>, dump_to: Option<P>) -> Result<Codes>
where
    P: AsRef<Path>,
{
    use Instruction::*;

    let mut ctx = Context::new();

    for (idx, inst) in instructions.iter().enumerate() {
        for label in &inst.labels {
            ctx.label_addrs.insert(label.name.clone(), idx * 4);
        }
    }

    let mut insts = Vec::with_capacity(instructions.len());
    for (addr, inst) in instructions.into_iter().enumerate() {
        let inst = replace_labels(inst, &ctx)?;
        insts.push(replace_reladdr_labels(inst, addr * 4, &ctx)?);
    }

    if let Some(dump_to) = dump_to {
        let mut asm = File::create(dump_to)?;
        for (addr, InstructionWithLabel { inst, ir, labels }) in insts.iter().enumerate() {
            for label in labels {
                writeln!(asm, "{}: # 0x{:x}", &label.name, addr * 4)?;
            }

            if let Some(ir) = ir {
                writeln!(asm, "  #{}", ir)?;
            }
            let a = match inst {
                R(ri) => ri.generate_asm(),
                I(ii) => ii.generate_asm(),
                S(si) => si.generate_asm(),
                J(ji) => ji.generate_asm(),
                U(ui) => ui.generate_asm(),
                SB(sbi) => sbi.generate_asm(),
            };
            writeln!(asm, "  {}", a)?;
        }
    }

    let result = insts
        .into_iter()
        .map(|InstructionWithLabel { inst, .. }| match inst {
            R(ri) => ri.generate_code(),
            I(ii) => ii.generate_code(),
            S(si) => si.generate_code(),
            J(ji) => ji.generate_code(),
            U(ui) => ui.generate_code(),
            SB(sbi) => sbi.generate_code(),
        })
        .collect();

    Ok(result)
}