summaryrefslogtreecommitdiff
path: root/js/src/vm/make_opcode_doc.py
blob: 454d8b8d5e98d715db94597399e849c7621e0bf0 (plain)
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/usr/bin/python -B

""" Usage: make_opcode_doc.py PATH_TO_MOZILLA_CENTRAL

    This script generates SpiderMonkey bytecode documentation
    from js/src/vm/Opcodes.h.

    Output is written to stdout and should be pasted into the following
    MDN page:
    https://developer.mozilla.org/en-US/docs/SpiderMonkey/Internals/Bytecode
"""

from __future__ import print_function
import re
import sys
from xml.sax.saxutils import escape

SOURCE_BASE = 'http://dxr.mozilla.org/mozilla-central/source'

def error(message):
    print("Error: {message}".format(message=message), file=sys.stderr)
    sys.exit(1)

quoted_pat = re.compile(r"([^A-Za-z0-9]|^)'([^']+)'")
js_pat = re.compile(r"([^A-Za-z0-9]|^)(JS[A-Z0-9_\*]+)")
def codify(text):
    text = re.sub(quoted_pat, '\\1<code>\\2</code>', text)
    text = re.sub(js_pat, '\\1<code>\\2</code>', text)

    return text

space_star_space_pat = re.compile('^\s*\* ?', re.M)
def get_comment_body(comment):
    return re.sub(space_star_space_pat, '', comment).split('\n')

def parse_index(comment):
    index = []
    current_types = None
    category_name = ''
    category_pat = re.compile('\[([^\]]+)\]')
    for line in get_comment_body(comment):
        m = category_pat.search(line)
        if m:
            category_name = m.group(1)
            if category_name == 'Index':
                continue
            current_types = []
            index.append((category_name, current_types))
        else:
            type_name = line.strip()
            if type_name and current_types is not None:
                current_types.append((type_name, []))

    return index

class OpcodeInfo:
    def __init__(self):
        self.name = ''
        self.value = ''
        self.length = ''
        self.length_override = ''
        self.nuses = ''
        self.nuses_override = ''
        self.ndefs = ''
        self.ndefs_override = ''
        self.flags = ''
        self.operands = ''
        self.stack_uses = ''
        self.stack_defs = ''

        self.desc = ''

        self.category_name = ''
        self.type_name = ''

        self.group = []
        self.sort_key = ''

def find_by_name(list, name):
    for (n, body) in list:
        if n == name:
            return body

    return None

def add_to_index(index, opcode):
    types = find_by_name(index, opcode.category_name)
    if types is None:
        error("Category is not listed in index: "
              "{name}".format(name=opcode.category_name))
    opcodes = find_by_name(types, opcode.type_name)
    if opcodes is None:
        if opcode.type_name:
            error("Type is not listed in {category}: "
                  "{name}".format(category=opcode.category_name,
                                  name=opcode.type_name))
        types.append((opcode.type_name, [opcode]))
        return

    opcodes.append(opcode)

def format_desc(descs):
    current_type = ''
    desc = ''
    for (type, line) in descs:
        if type != current_type:
            if current_type:
                desc += '</{name}>\n'.format(name=current_type)
            current_type = type
            if type:
                desc += '<{name}>'.format(name=current_type)
        if current_type:
            desc += line + "\n"
    if current_type:
        desc += '</{name}>'.format(name=current_type)

    return desc

tag_pat = re.compile('^\s*[A-Za-z]+:\s*|\s*$')
def get_tag_value(line):
    return re.sub(tag_pat, '', line)

def get_opcodes(dir):
    iter_pat = re.compile(r"/\*(.*?)\*/"  # either a documentation comment...
                          r"|"
                          r"macro\("      # or a macro(...) call
                                 r"([^,]+),\s*"     # op
                                 r"([0-9]+),\s*"    # val
                                 r"[^,]+,\s*"       # name
                                 r"[^,]+,\s*"       # image
                                 r"([0-9\-]+),\s*"  # length
                                 r"([0-9\-]+),\s*"  # nuses
                                 r"([0-9\-]+),\s*"  # ndefs
                                 r"([^\)]+)"        # format
                          r"\)", re.S)
    stack_pat = re.compile('^(.*?)\s*=>\s*(.*?)$')

    index = []

    opcode = OpcodeInfo()
    merged = opcode

    with open('{dir}/js/src/vm/Opcodes.h'.format(dir=dir), 'r') as f:
        data = f.read()

    for m in re.finditer(iter_pat, data):
        comment = m.group(1)
        name = m.group(2)

        if comment:
            if '[Index]' in comment:
                index = parse_index(comment)
                continue

            if 'Operands:' not in comment:
                continue

            state = 'desc'
            stack = ''
            descs = []

            for line in get_comment_body(comment):
                if line.startswith('  Category:'):
                    state = 'category'
                    opcode.category_name = get_tag_value(line)
                elif line.startswith('  Type:'):
                    state = 'type'
                    opcode.type_name = get_tag_value(line)
                elif line.startswith('  Operands:'):
                    state = 'operands'
                    opcode.operands = get_tag_value(line)
                elif line.startswith('  Stack:'):
                    state = 'stack'
                    stack = get_tag_value(line)
                elif line.startswith('  len:'):
                    state = 'len'
                    opcode.length_override = get_tag_value(line)
                elif line.startswith('  nuses:'):
                    state = 'nuses'
                    opcode.nuses_override = get_tag_value(line)
                elif line.startswith('  ndefs:'):
                    state = 'ndefs'
                    opcode.ndefs_override = get_tag_value(line)
                elif state == 'desc':
                    if line.startswith(' '):
                        descs.append(('pre', escape(line[1:])))
                    else:
                        line = line.strip()
                        if line == '':
                            descs.append(('', line))
                        else:
                            descs.append(('p', codify(escape(line))))
                elif line.startswith('  '):
                    if state == 'operands':
                        opcode.operands += line.strip()
                    elif state == 'stack':
                        stack += line.strip()
                    elif state == 'len':
                        opcode.length_override += line.strip()
                    elif state == 'nuses':
                        opcode.nuses_override += line.strip()
                    elif state == 'ndefs':
                        opcode.ndefs_override += line.strip()

            opcode.desc = format_desc(descs)

            m2 = stack_pat.search(stack)
            if m2:
                opcode.stack_uses = m2.group(1)
                opcode.stack_defs = m2.group(2)

            merged = opcode
        elif name and not name.startswith('JSOP_UNUSED'):
            opcode.name = name
            opcode.value = int(m.group(3))
            opcode.length = m.group(4)
            opcode.nuses = m.group(5)
            opcode.ndefs = m.group(6)

            flags = []
            for flag in m.group(7).split('|'):
                if flag != 'JOF_BYTE':
                    flags.append(flag.replace('JOF_', ''))
            opcode.flags = ', '.join(flags)

            if merged == opcode:
                opcode.sort_key = opcode.name
                if opcode.category_name == '':
                    error("Category is not specified for "
                          "{name}".format(name=opcode.name))
                add_to_index(index, opcode)
            else:
                if merged.length != opcode.length:
                    error("length should be same for merged section: "
                          "{value1}({name1}) != "
                          "{value2}({name2})".format(name1=merged.name,
                                                     value1=merged.length,
                                                     name2=opcode.name,
                                                     value2=opcode.length))
                if merged.nuses != opcode.nuses:
                    error("nuses should be same for merged section: "
                          "{value1}({name1}) != "
                          "{value2}({name2})".format(name1=merged.name,
                                                     value1=merged.nuses,
                                                     name2=opcode.name,
                                                     value2=opcode.nuses))
                if merged.ndefs != opcode.ndefs:
                    error("ndefs should be same for merged section: "
                          "{value1}({name1}) != "
                          "{value2}({name2})".format(name1=merged.name,
                                                     value1=merged.ndefs,
                                                     name2=opcode.name,
                                                     value2=opcode.ndefs))
                merged.group.append(opcode)
                if opcode.name < merged.name:
                    merged.sort_key = opcode.name

            opcode = OpcodeInfo()

    return index

def override(value, override_value):
    if override_value != '':
        return override_value

    return value

def format_flags(flags):
    if flags == '':
        return ''

    return ' ({flags})'.format(flags=flags)

def print_opcode(opcode):
    names_template = '{name} [-{nuses}, +{ndefs}]{flags}'
    opcodes = sorted([opcode] + opcode.group,
                     key=lambda opcode: opcode.name)
    names = map(lambda code: names_template.format(name=escape(code.name),
                                                   nuses=override(code.nuses,
                                                                  opcode.nuses_override),
                                                   ndefs=override(code.ndefs,
                                                                  opcode.ndefs_override),
                                                   flags=format_flags(code.flags)),
                opcodes)
    if len(opcodes) == 1:
        values = ['{value} (0x{value:02x})'.format(value=opcode.value)]
    else:
        values_template = '{name}: {value} (0x{value:02x})'
        values = map(lambda code: values_template.format(name=escape(code.name),
                                                         value=code.value),
                    opcodes)

    print("""<dt id="{id}">{names}</dt>
<dd>
<table class="standard-table">
<tbody>
<tr><th>Value</th><td><code>{values}</code></td></tr>
<tr><th>Operands</th><td><code>{operands}</code></td></tr>
<tr><th>Length</th><td><code>{length}</code></td></tr>
<tr><th>Stack Uses</th><td><code>{stack_uses}</code></td></tr>
<tr><th>Stack Defs</th><td><code>{stack_defs}</code></td></tr>
</tbody>
</table>

{desc}
</dd>
""".format(id=opcodes[0].name,
           names='<br>'.join(names),
           values='<br>'.join(values),
           operands=escape(opcode.operands) or "&nbsp;",
           length=escape(override(opcode.length,
                                  opcode.length_override)),
           stack_uses=escape(opcode.stack_uses) or "&nbsp;",
           stack_defs=escape(opcode.stack_defs) or "&nbsp;",
           desc=opcode.desc)) # desc is already escaped

id_cache = dict()
id_count = dict()

def make_element_id(category, type=''):
    key = '{}:{}'.format(category, type)
    if key in id_cache:
        return id_cache[key]

    if type == '':
        id = category.replace(' ', '_')
    else:
        id = type.replace(' ', '_')

    if id in id_count:
        id_count[id] += 1
        id = '{}_{}'.format(id, id_count[id])
    else:
        id_count[id] = 1

    id_cache[key] = id
    return id

def print_doc(index):
    print("""<div>{{{{SpiderMonkeySidebar("Internals")}}}}</div>

<h2 id="Bytecode_Listing">Bytecode Listing</h2>

<p>This document is automatically generated from
<a href="{source_base}/js/src/vm/Opcodes.h">Opcodes.h</a> by
<a href="{source_base}/js/src/vm/make_opcode_doc.py">make_opcode_doc.py</a>.</p>
""".format(source_base=SOURCE_BASE))

    for (category_name, types) in index:
        print('<h3 id="{id}">{name}</h3>'.format(name=category_name,
                                                 id=make_element_id(category_name)))
        for (type_name, opcodes) in types:
            if type_name:
                print('<h4 id="{id}">{name}</h4>'.format(name=type_name,
                                                         id=make_element_id(category_name, type_name)))
            print('<dl>')
            for opcode in sorted(opcodes,
                                 key=lambda opcode: opcode.sort_key):
                print_opcode(opcode)
            print('</dl>')

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: make_opcode_doc.py PATH_TO_MOZILLA_CENTRAL",
              file=sys.stderr)
        sys.exit(1)
    dir = sys.argv[1]
    index = get_opcodes(dir)
    print_doc(index)