Debian Codegraph @

Tools/cases_generator/opcode_id_generator.py

raw
1 """Generate the list of opcode IDs.
2 Reads the instruction definitions from bytecodes.c.
3 Writes the IDs to opcode_ids.h by default.
4 """
5
6 import argparse
7
8 from analyzer import (
9 Analysis,
10 analyze_files,
11 )
12 from generators_common import (
13 DEFAULT_INPUT,
14 ROOT,
15 write_header,
16 )
17 from cwriter import CWriter
18 from typing import TextIO
19
20
21 DEFAULT_OUTPUT = ROOT / "Include/opcode_ids.h"
22
23
24 def generate_opcode_header(
25 filenames: list[str], analysis: Analysis, outfile: TextIO
26 ) -> None:
27 write_header(__file__, filenames, outfile)
28 out = CWriter(outfile, 0, False)
29 with out.header_guard("Py_OPCODE_IDS_H"):
30 out.emit("/* Instruction opcodes for compiled code */\n")
31
32 def write_define(name: str, op: int) -> None:
33 out.emit(f"#define {name:<38} {op:>3}\n")
34
35 for op, name in sorted([(op, name) for (name, op) in analysis.opmap.items()]):
36 write_define(name, op)
37
38 out.emit("\n")
39 write_define("HAVE_ARGUMENT", analysis.have_arg)
40 write_define("MIN_SPECIALIZED_OPCODE", analysis.opmap["RESUME"]+1)
41 write_define("MIN_INSTRUMENTED_OPCODE", analysis.min_instrumented)
42
43
44 arg_parser = argparse.ArgumentParser(
45 description="Generate the header file with all opcode IDs.",
46 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
47 )
48
49 arg_parser.add_argument(
50 "-o", "--output", type=str, help="Generated code", default=DEFAULT_OUTPUT
51 )
52
53 arg_parser.add_argument(
54 "input", nargs=argparse.REMAINDER, help="Instruction definition file(s)"
55 )
56
57 if __name__ == "__main__":
58 args = arg_parser.parse_args()
59 if len(args.input) == 0:
60 args.input.append(DEFAULT_INPUT)
61 data = analyze_files(args.input)
62 with open(args.output, "w") as outfile:
63 generate_opcode_header(args.input, data, outfile)