Repository navigation
Expand file tree
/
Copy pathdocenizer-riscv64.py
More file actions
executable file
·222 lines (192 loc) · 9.02 KB
/
Copy pathdocenizer-riscv64.py
File metadata and controls
executable file
·222 lines (192 loc) · 9.02 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env python3
import argparse
import html
import json
from urllib import request
from urllib import parse
import requests
import yaml
import sys
import re
#opcodes_yaml = "https://five-embeddev.github.io/riscv-docs-html/opcodes.yaml"
opcodes_yaml = "https://five-embeddev.github.io/riscv-docs-html/opcodes.yaml"
htmlhost = "https://five-embeddev.github.io/riscv-docs-html/"
instructionsets_data = "https://instructionsets.com/data/riscv.json"
instructionsets_host = "https://instructionsets.com/risc-v/"
# Records in the InstructionSets data that describe instructions which are not part of the ratified ISA
SUPPLEMENT_SKIPPED_OPCODES = {"URET"}
SUPPLEMENT_SKIPPED_EXTENSION_MARKERS = ("draft",)
parser = argparse.ArgumentParser(description='Scrape the five-embeddev quick reference page and generate the riscv documentation')
parser.add_argument('-i', '--opcode-data', type=str, help='Input opcode data in YAML format.',
default=opcodes_yaml)
parser.add_argument('-s', '--supplement-data', type=str,
help='InstructionSets.com RISC-V data (CC0) in JSON format, used only for opcodes missing from the '
'opcode data. Pass "none" to disable.',
default=instructionsets_data)
parser.add_argument('-o', '--outputpath', type=str, help='Final path of the .ts file. Default is ./asm-docs-riscv64.ts',
default='./asm-docs-riscv64.ts')
def bold_keyword(text, keyword):
for keywordr in (keyword.upper(), keyword.lower()):
rer = re.compile(f"\\b{keywordr}\\b")
text,_ = re.subn(rer,f"<b>{keywordr}</b>",text)
return text
class operation:
def __init__(self, yaml_record, yaml_data):
opcode = yaml_record['opcode'][0].upper()
# Remove "@" and "c." from opcode
# These are
self.opcode = opcode
self.opcode_alias = None
if 'opcode_alias' in yaml_record:
self.opcode_alias = yaml_record['opcode_alias'].upper()
tool_opcode_args = opcode + " " + ', '.join(yaml_record['opcode_args']) + "\n"
html_opcode_args = f"<span class=\"opcode\"><b>{opcode}</b> {', '.join(yaml_record['opcode_args'])}</span>"
# What ISA does this opcode belong to?
# Is it a psuedo opcode?
group=""
if 'main_desc' in yaml_record:
group += yaml_record['main_desc']
if 'psuedo' == yaml_record['opcode_group']:
group += "(pseudo)"
html_code = ""
text_code = ""
html_group = f"<br><div><b>ISA</b>: {group}</div>"
if 'psuedo_to_base' in yaml_record:
html_code += "<br><div><b>Equivalent ASM:</b><pre>"
html_code += "\n".join(yaml_record['psuedo_to_base'])
html_code += "</pre></div>"
text_code += "Equivalent ASM:\n\n" + "\n".join(yaml_record['psuedo_to_base'])
if 'main_url_base' in yaml_record:
main_url_base = yaml_record['main_url_base']
main_desc = yaml_record['main_desc']
main_id = yaml_record['main_id']
opcode_descs = yaml_record['desc'][main_desc][main_id]['text']
tool_desc = "\n".join(opcode_descs) + "\n\n" + text_code + "\n\n(ISA: " + group + ")"
html_desc = "<br><div>" + "<br>".join([bold_keyword(x,opcode) for x in opcode_descs]) + "</div>"
self.url = htmlhost + main_url_base + main_id
self.tooltip = tool_desc
# extract all elements under the second column and the third column which are td
# and put them into a new div tag
self.html = "<div>" + html_opcode_args + html_desc + html_code + html_group + "</div>"
elif 'psuedo_to_base' in yaml_record:
self.url = htmlhost
self.tooltip = "Psuedo Instruction.\n\n" + text_code + "\n\n"
self.html = "<div>" + html_opcode_args + html_code + html_group + "</div>"
else:
self.url = htmlhost
self.tooltip = "\n\n(ISA: " + group + ")"
self.html = "<div>" + html_opcode_args + html_group + "</div>"
def __str__(self):
dic = {
# no opcode here
"tooltip": self.tooltip,
"url": self.url,
"html": self.html
}
return json.dumps(dic, indent=16, separators=(',', ': '), sort_keys=True)
def load_text(location):
if location[:4] == "http":
r = requests.get(location)
r.raise_for_status()
r.encoding = 'utf-8'
return r.text
with open(location, 'r') as fin:
return fin.read()
def supplement_record(instruction):
opcode = instruction['mnemonic'].upper()
syntax = instruction['syntax'].strip()
operands = syntax[len(opcode):].strip() if syntax.upper().startswith(opcode) else ""
group = "pseudo" if instruction['extension'] == 'Pseudo' else instruction['extension']
description = instruction['description'].strip()
html_code = f'<span class="opcode"><b>{opcode}</b> {html.escape(operands)}</span>'
html_desc = f"<br><div>{html.escape(description)}</div>"
html_group = f"<br><div><b>ISA</b>: {html.escape(group)}</div>"
return {
"html": f"<div>{html_code}{html_desc}{html_group}</div>",
"tooltip": f"{description}\n\n(ISA: {group})",
"url": instructionsets_host + instruction['mnemonic'].lower().replace('.', '_') + "/",
}
def supplement_opcodes(supplement_data, known_opcodes):
for instruction in supplement_data['instructions']:
opcode = instruction['mnemonic'].upper()
extension = instruction['extension'].lower()
if opcode in known_opcodes or opcode in SUPPLEMENT_SKIPPED_OPCODES:
continue
if any(marker in extension for marker in SUPPLEMENT_SKIPPED_EXTENSION_MARKERS):
continue
yield opcode, supplement_record(instruction)
if __name__ == '__main__':
args = parser.parse_args()
yaml_text=None
try:
if args.opcode_data[:4] == "http":
r = requests.get(args.opcode_data)
r.encoding = 'utf-8'
yaml_text = r.text
else:
with open(args.opcode_data, 'r') as fin :
yaml_text=fin.read()
except:
print("ERROR: Loading YAML file or URL: " + args.opcode_data + ":")
print(exc)
sys.exit(-1)
yaml_data=None
try:
yaml_data = yaml.safe_load(yaml_text)
except yaml.YAMLError as exc:
print("ERROR: Parsing YAML file: " + args.opcode_data + ":")
print(exc)
sys.exit(-1)
with open(args.outputpath, "w") as output:
output.write("""
import type {AssemblyInstructionInfo} from '../../../types/assembly-docs.interfaces.js';
export function getAsmOpcode(opcode: string | undefined): AssemblyInstructionInfo | undefined {
if (!opcode) return;
switch (opcode.toUpperCase()) {
""".lstrip())
# Pseudoinstructions missing from the upstream YAML data
extra_pseudos = [
{
"opcode": "SGT",
"args": "rd, rs, rt",
"equivalent": "slt rd, rt, rs",
},
{
"opcode": "SGTU",
"args": "rd, rs, rt",
"equivalent": "sltu rd, rt, rs",
},
]
known_opcodes = {pseudo["opcode"] for pseudo in extra_pseudos}
for record in [operation(o, yaml_data) for o in yaml_data['opcodes'].values()]:
# for each opcode
known_opcodes.add(record.opcode)
output.write(f' case "{record.opcode}":\n')
if record.opcode_alias:
known_opcodes.add(record.opcode_alias)
output.write(f' case "{record.opcode_alias}":\n')
output.write(f' return {str(record)[:-1]} }};\n\n')
# Opcodes missing from the upstream YAML data (newer extensions), from the InstructionSets.com data
if args.supplement_data != "none":
supplement_data = json.loads(load_text(args.supplement_data))
for opcode, info in supplement_opcodes(supplement_data, known_opcodes):
info_json = json.dumps(info, indent=16, separators=(',', ': '), sort_keys=True)
output.write(f' case "{opcode}":\n')
output.write(f' return {info_json[:-1]} }};\n\n')
for pseudo in extra_pseudos:
op = pseudo["opcode"]
args = pseudo["args"]
equiv = pseudo["equivalent"]
html = (
f'<div><span class="opcode"><b>{op}</b> {args}</span>'
f'<br><div><b>Equivalent ASM:</b><pre>{equiv}</pre></div>'
f'<br><div><b>ISA</b>: (pseudo)</div></div>'
)
tooltip = f"Psuedo Instruction.\n\nEquivalent ASM:\n\n{equiv}\n\n"
info = json.dumps({"html": html, "tooltip": tooltip, "url": htmlhost}, indent=16, separators=(',', ': '), sort_keys=True)
output.write(f' case "{op}":\n')
output.write(f' return {info[:-1]} }};\n\n')
output.write("""
}
}
""")