Kaya Çelebi
Home About GitHub PyPI Contribute Contact

Instructions

Follow @kcelebi Star Watch

Let's check out how to use Instructions. The AssemblyConverter utilizes these functionalities automatically, so familiarizing yourself with them only serves for utility/debugging purposes. First, let's import it into our Python file:

from riscv_assembler.instr_arr import *

From this, we now have access to the functions to parse instructions and organize them to their binary outputs. Let us examine both.

Organizers

These functions are most useful if you know the instruction, rs1, rs2, rd, etc. already. Example usage:

# outputs instruction as string in binary
res = R(instr = "add", rs1 = "x0", rs2 = "x1", rd = "x1")
res = I(instr = "addi", rs1 = "x0", imm = 10, rd = "x0")
These organizers work for all types, R, I, S, SB, U, UJ.

Parsers

These functions are most useful if you have only tokenized an instruction and have not determined which token corresponds to what parameters. There is a parser built into the package that can tokenize/clean the instruction for you, if you wish to use it. Observe:

# get built-in Parser
from riscv_assembler.parse import Parser

line = "add x0 x0 x1"
tokens = Parser.tokenize(line) # Get clean line

f = Parser.determine_type(tokens[0]) # determine which parser to use
result = f(tokens)

If you know the parsing function to use in advance, you can also apply it directly. The functions for each instruction type, respectively, are Rp, Ip, Sp, SBp, Up, UJp. All of this can also be accomplished with a built-in function:

# get built-in Parser
from riscv_assembler.parse import Parser

line = "add x0 x0 x1"
result = Parser.interpret(line)