File: gen_interpreter_utils.py

package info (click to toggle)
webkit2gtk 2.51.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 457,708 kB
  • sloc: cpp: 3,884,629; javascript: 198,661; ansic: 165,298; python: 49,171; asm: 21,849; ruby: 18,095; perl: 16,914; xml: 4,623; sh: 2,397; yacc: 2,356; java: 2,019; lex: 1,330; pascal: 372; makefile: 197
file content (185 lines) | stat: -rw-r--r-- 5,340 bytes parent folder | download | duplicates (8)
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
#!/usr/bin/python3
#
# Copyright 2022 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# gen_interpreter_utils.py:
#   Code generator for the GLC interpreter.
#   NOTE: don't run this script directly. Run scripts/run_code_generation.py.

import os
import re
import sys

import registry_xml

EXIT_SUCCESS = 0
EXIT_FAILURE = 1

BASE_PATH = '../util/capture/trace_interpreter_autogen'

CPP_TEMPLATE = """\
// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {data_source_name}.
//
// Copyright 2022 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// {file_name}.cpp:
//   Helper code for trace interpreter.

#include "angle_trace_gl.h"
#include "trace_fixture.h"
#include "trace_interpreter.h"

namespace angle
{{
CallCapture ParseCallCapture(const Token &nameToken, size_t numParamTokens, const Token *paramTokens, const TraceStringMap &strings)
{{
{parse_cases}
    if (numParamTokens > 0)
    {{
        printf("Expected zero parameter tokens for %s\\n", nameToken);
        UNREACHABLE();
    }}
    return CallCapture(nameToken, ParamBuffer());
}}

{dispatch_cases}

void ReplayCustomFunctionCall(const CallCapture &call, const TraceFunctionMap &customFunctions)
{{
    ASSERT(call.entryPoint == EntryPoint::Invalid);
    const Captures &captures = call.params.getParamCaptures();

{custom_dispatch_cases}

    auto iter = customFunctions.find(call.customFunctionName);
    if (iter == customFunctions.end())
    {{
        printf("Unknown custom function: %s\\n", call.customFunctionName.c_str());
        UNREACHABLE();
    }}
    else
    {{
        ASSERT(call.params.empty());
        const TraceFunction &customFunc = iter->second;
        for (const CallCapture &customCall : customFunc)
        {{
            ReplayTraceFunctionCall(customCall, customFunctions);
        }}
    }}
}}
}}  // namespace angle
"""

PARSE_CASE = """\
    if (strcmp(nameToken, "{ep}") == 0)
    {{
        ParamBuffer params = ParseParameters<{pfn}>(paramTokens, strings);
        return CallCapture({call}, std::move(params));
    }}
"""

CUSTOM_DISPATCH_CASE = """\
    if (call.customFunctionName == "{fn}")
    {{
        DispatchCallCapture({fn}, captures);
        return;
    }}
"""

DISPATCH_CASE = """\
template <typename Fn, EnableIfNArgs<Fn, {nargs}> = 0>
void DispatchCallCapture(Fn *fn, const Captures &cap)
{{
    (*fn)({args});
}}
"""

FIXTURE_H = '../util/capture/trace_fixture.h'


def GetFunctionsFromFixture():
    funcs = []
    arg_counts = set()
    pattern = 'void '
    with open(FIXTURE_H) as f:
        lines = f.read().split(';')
        for line in lines:
            line = re.sub('// .*\n', '', line.strip())
            if line.startswith(pattern):
                func_name_end_index = line.find('(')
                func_name = line[len(pattern):func_name_end_index]
                args_start_index = func_name_end_index + 1
                args_end_index = line.find(')', args_start_index)
                args_str = line[args_start_index:args_end_index].strip()
                if args_str:
                    func_args = args_str.count(',') + 1
                else:
                    func_args = 0
                funcs.append(func_name)
                arg_counts.add(func_args)
        f.close()
    return sorted(list(set(funcs))), arg_counts


def get_dispatch(n):
    return ', '.join(['Arg<Fn, %d>(cap)' % i for i in range(n)])


def main(cpp_output_path):
    gles = registry_xml.GetGLES()
    egl = registry_xml.GetEGL()

    def fn(ep):
        return 'std::remove_pointer<PFN%sPROC>::type' % ep.upper()

    fixture_functions, arg_counts = GetFunctionsFromFixture()

    eps_and_enums = sorted(list(set(gles.GetEnums() + egl.GetEnums())))
    parse_cases = [
        PARSE_CASE.format(ep=ep, pfn=fn(ep), call='EntryPoint::%s' % enum)
        for (enum, ep) in eps_and_enums
    ]
    parse_cases += [
        PARSE_CASE.format(ep=fn, pfn='decltype(%s)' % fn, call='"%s"' % fn)
        for fn in fixture_functions
    ]

    dispatch_cases = [DISPATCH_CASE.format(nargs=n, args=get_dispatch(n)) for n in arg_counts]

    custom_dispatch_cases = [CUSTOM_DISPATCH_CASE.format(fn=fn) for fn in fixture_functions]

    format_args = {
        'script_name': os.path.basename(sys.argv[0]),
        'data_source_name': 'gl.xml and gl_angle_ext.xml',
        'file_name': os.path.basename(BASE_PATH),
        'parse_cases': ''.join(parse_cases),
        'dispatch_cases': '\n'.join(dispatch_cases),
        'custom_dispatch_cases': ''.join(custom_dispatch_cases),
    }

    cpp_content = CPP_TEMPLATE.format(**format_args)
    cpp_output_path = registry_xml.script_relative(cpp_output_path)
    with open(cpp_output_path, 'w') as f:
        f.write(cpp_content)

    return EXIT_SUCCESS


if __name__ == '__main__':
    inputs = registry_xml.xml_inputs + [FIXTURE_H]
    outputs = [
        '%s.cpp' % BASE_PATH,
    ]

    if len(sys.argv) > 1:
        if sys.argv[1] == 'inputs':
            print(','.join(inputs))
        elif sys.argv[1] == 'outputs':
            print(','.join(outputs))
    else:
        sys.exit(main(registry_xml.script_relative(outputs[0])))