Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Static C++ code generator.
 
The single :class:`StaticCodeGenerator` class implements both
``static-cpp`` (uses a string table) and ``static-cpp-literal``
(inlines string literals); the only difference is the constructor
flag.
"""
 
from __future__ import annotations
 
import builtins
import hashlib
import json
from dataclasses import dataclass
 
from ..types import TemplatePass2, TemplateRepository
 
# ----------------------------------------------------------------------
# Code segment data model
# ----------------------------------------------------------------------
 
 
@dataclass
class CodeSegment:
    type: str  # "raw" | "code" | "expression"
    content: str
 
 
@dataclass
class CodeSegmentArg:
    type: str  # "expression" | "string" | "auto"
    code: list[CodeSegment]
 
 
# ----------------------------------------------------------------------
# String literal renderer (JSON-style escaping)
# ----------------------------------------------------------------------
 
 
def _js_stringify(s: str) -> str:
    """Render ``s`` as a double-quoted, JSON-escaped C++ string literal.
 
    Non-ASCII characters are escaped via ``\\uXXXX`` so the output is
    pure ASCII and stable across hosts.
    """
    return json.dumps(s, ensure_ascii=True)
 
 
# ----------------------------------------------------------------------
# Static code generator
# ----------------------------------------------------------------------
 
 
class StaticCodeGenerator:
    """Emits C++ from PASS2 :class:`CodeSegment` lists.
 
    With ``use_string_table=True`` (the ``static-cpp`` Release mode),
    every WGSL string literal is replaced with a short ``__str_N``
    identifier and dedup'd across the whole build. With
    ``use_string_table=False`` (Debug mode), strings appear inline as
    ``"..."`` literals.
    """
 
    def __init__(self, use_string_table: bool = True) -> None:
        self.use_string_table = use_string_table
        # Maps unique string content to its assigned __str_N id.
        # Insertion order is the assignment order.
        self._string_table: dict[str, int] | None = {} if use_string_table else None
 
    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------
 
    def _render_string(self, s: str) -> str:
        if self._string_table is not None:
            existing = self._string_table.get(s)
            if existing is None:
                existing = len(self._string_table)
                self._string_table[s] = existing
            return f"__str_{existing}"
        return _js_stringify(s)
 
    def _render_arg(self, arg: CodeSegmentArg) -> str:
        if not arg.code:
            return ""
 
        if len(arg.code) == 1:
            seg = arg.code[0]
            if arg.type == "string" and seg.type == "expression":
                return f"wgsl_detail::pass_as_string({seg.content})"
            if arg.type != "expression" and seg.type == "code":
                return self._render_string(seg.content)
            return seg.content
 
        # Multi-segment argument.
        if arg.type != "expression":
            rendered = []
            for seg in arg.code:
                if seg.type == "code":
                    rendered.append(self._render_string(seg.content))
                else:
                    rendered.append(seg.content)
            return f"absl::StrCat({', '.join(rendered)})"
        return "".join(seg.content for seg in arg.code)
 
    # ------------------------------------------------------------------
    # CodeGenerator interface (called from the PASS2 generator)
    # ------------------------------------------------------------------
 
    def emit(self, code: list[CodeSegment]) -> str:
        out = []
        for seg in code:
            if seg.type == "raw":
                out.append(seg.content)
            elif seg.type == "code":
                out.append(f"ss << {self._render_string(seg.content)};\n")
            elif seg.type == "expression":
                out.append(f"ss << {seg.content};\n")
            else:  # pragma: no cover  defensive
                raise ValueError(f"Unknown segment type: {seg.type!r}")
        return "".join(out)
 
    def param(self, name: str) -> str:
        return f"__param_{name}"
 
    def variable(self, name: str) -> str:
        return f"(*__var_{name})"
 
    def property(self, obj: str, property_name: str) -> str:
        return f"__var_{obj}->{property_name}"
 
    def function(self, name: str, args: list[CodeSegmentArg]) -> str:
        rendered = ", ".join(self._render_arg(a) for a in args)
        return f"{name}({rendered})"
 
    def method(self, obj: str, method_name: str, args: list[CodeSegmentArg]) -> str:
        rendered = ", ".join(self._render_arg(a) for a in args)
        return f"__var_{obj}->{method_name}({rendered})"
 
    # ------------------------------------------------------------------
    # Read-only access to the string table (used by build() to emit
    # string_table.h).
    # ------------------------------------------------------------------
 
    @builtins.property
    def string_table(self) -> dict[str, int] | None:
        return self._string_table
 
    # ------------------------------------------------------------------
    # build() — produce the per-template files plus index.h /
    # index_impl.h / string_table.h.
    # ------------------------------------------------------------------
 
    def build(
        self,
        repo: TemplateRepository,
        *,
        template_ext: str,
        include_path_prefix: str = "",
    ) -> TemplateRepository:
        result_files: dict[str, str] = {}
        impl_hashes: dict[str, str] = {}
 
        # STEP 1 — per-template implementation files.
        for name, template in repo.templates.items():
            assert isinstance(template, TemplatePass2)
            if not name.endswith(template_ext):
                raise ValueError(f'Template name "{name}" does not end with the expected extension "{template_ext}"')
            base = name[: -len(template_ext)]
            content = self._build_template_implementation(name, template)
            result_files[f"generated/{base}.h"] = content
            impl_hashes[name] = hashlib.sha256(content.encode("utf-8")).hexdigest()
 
        # STEP 2 — string_table.h if enabled.
        if self._string_table is not None:
            content = self._build_generate_string_table()
            result_files["string_table.h"] = content
            impl_hashes["string_table.h"] = hashlib.sha256(content.encode("utf-8")).hexdigest()
 
        # STEP 3 — index_impl.h.
        result_files["index_impl.h"] = self._build_generate_index_impl(
            repo, impl_hashes, include_path_prefix, template_ext
        )
 
        # STEP 4 — index.h.
        result_files["index.h"] = self._build_generate_index(repo)
 
        return TemplateRepository(base_path=repo.base_path, templates=dict(result_files))
 
    # ---- internal builders -------------------------------------------
 
    def _build_generate_index(self, repo: TemplateRepository) -> str:
        out: list[str] = []
        out.append("// This file is auto-generated by wgsl-gen. Do not edit manually.")
        out.append("")
        out.append("#ifndef INCLUDED_BY_WGSL_GEN_HEADER")
        out.append('#error "This file is expected to be included by wgsl-gen header. Do not include it directly."')
        out.append("#endif")
        out.append("")
        for name, template in repo.templates.items():
            assert isinstance(template, TemplatePass2)
            out.append("//")
            out.append(f"// Template: {name}")
            out.append("//")
            out.append("")
            quoted = _js_stringify(name)
            out.append("template <>")
            out.append(f"struct TemplateParameter<{quoted}> {{")
            out.append("  using type = struct {")
            for param_name in template.generate_result.params:
                out.append(f"    int param_{param_name};")
            for var_name in template.generate_result.variables:
                out.append(f"    const ShaderVariableHelper* var_{var_name};")
            out.append("  };")
            out.append("};")
            out.append("")
            out.append("template <>")
            out.append(
                f"Status ApplyTemplate<{quoted}>(ShaderHelper& shader_helper, "
                f"TemplateParameter<{quoted}>::type params);"
            )
            out.append("")
        return "\n".join(out)
 
    def _build_generate_string_table(self) -> str:
        if self._string_table is None:
            raise RuntimeError("String table is not enabled")
 
        out: list[str] = []
        out.append("// This file is auto-generated by wgsl-gen. Do not edit manually.")
        out.append("")
        out.append("#pragma once")
        out.append("#ifndef INCLUDED_BY_WGSL_GEN_IMPL")
        out.append('#error "This file is expected to be included by wgsl-gen impl. Do not include it directly."')
        out.append("#endif")
        out.append("")
        out.append("// String table constants")
 
        # Sort by id to ensure consistent output.
        sorted_entries = sorted(self._string_table.items(), key=lambda kv: kv[1])
        for s, sid in sorted_entries:
            out.append(f"constexpr const char* __str_{sid} = {_js_stringify(s)};")
 
        out.append("")
        return "\n".join(out)
 
    def _build_generate_index_impl(
        self,
        repo: TemplateRepository,
        impl_hashes: dict[str, str],
        include_path_prefix: str,
        template_ext: str,
    ) -> str:
        out: list[str] = []
        out.append(
            "// This file is auto-generated by wgsl-gen. Do not edit manually.\n"
            "\n"
            "#pragma once\n"
            "#ifndef INCLUDED_BY_WGSL_GEN_IMPL\n"
            '#error "This file is expected to be included by wgsl-gen impl. '
            'Do not include it directly."\n'
            "#endif\n"
            "\n"
            "// Helper functions or macros\n"
            "\n"
            '#pragma push_macro("MainFunctionStart")\n'
            "#undef MainFunctionStart\n"
            "#define MainFunctionStart() { [[maybe_unused]] auto& ss = "
            "shader_helper.MainFunctionBody();\n"
            '#pragma push_macro("MainFunctionEnd")\n'
            "#undef MainFunctionEnd\n"
            "#define MainFunctionEnd() }\n"
            "\n"
            "// Helper templates\n"
            "\n"
            "namespace wgsl_detail {\n"
            "template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>\n"
            "std::string pass_as_string(T&& v) {\n"
            "  return std::to_string(std::forward<T>(v));\n"
            "}\n"
            "template <typename...>\n"
            "std::string_view pass_as_string(std::string_view sv) {\n"
            "  return sv;\n"
            "}\n"
            "template <typename T>\n"
            "std::string pass_as_string(T&& v) {\n"
            "  return std::forward<T>(v);\n"
            "}\n"
            "}  // namespace wgsl_detail\n"
        )
 
        if self._string_table is not None:
            sthash = impl_hashes.get("string_table.h", "")
            out.append(f'#include "{include_path_prefix}string_table.h"  // {sthash}')
        out.append("")
        out.append("// Include template implementations")
        out.append("")
 
        for name in repo.templates:
            if not name.endswith(template_ext):
                raise ValueError(f'Template name "{name}" does not end with the expected extension "{template_ext}"')
            base = name[: -len(template_ext)]
            h = impl_hashes.get(name, "")
            out.append(f'#include "{include_path_prefix}generated/{base}.h"  // {h}')
 
        out.append("")
        out.append('#pragma pop_macro("MainFunctionStart")')
        out.append('#pragma pop_macro("MainFunctionEnd")')
 
        return "\n".join(out)
 
    def _build_template_implementation(self, file_path: str, template: TemplatePass2) -> str:
        out: list[str] = []
        out.append("// This file is auto-generated by wgsl-gen. Do not edit manually.")
        out.append("")
        out.append("#pragma once")
        out.append("")
        out.append("// Template implementation")
        out.append(f"// Source: {file_path}")
        out.append("")
 
        gr = template.generate_result
        params_unused = len(gr.params) == 0 and len(gr.variables) == 0
        quoted = _js_stringify(file_path)
 
        out.append("template <>")
        params_arg = "" if params_unused else "params"
        out.append(
            f"Status ApplyTemplate<{quoted}>(ShaderHelper& shader_helper, "
            f"TemplateParameter<{quoted}>::type {params_arg}) {{"
        )
        out.append("  [[maybe_unused]] auto& ss = shader_helper.AdditionalImplementation();")
        out.append("")
 
        if gr.params:
            out.append("  // Extract parameters")
            for param_name in gr.params:
                out.append(f"  auto& {self.param(param_name)} = params.param_{param_name};")
            out.append("")
 
        if gr.variables:
            out.append("  // Extract variables")
            for var_name in gr.variables:
                out.append(f"  auto* __var_{var_name} = params.var_{var_name};")
            out.append("")
 
        out.append(gr.code)
 
        out.append("")
        out.append("  return Status::OK();")
        out.append("}")
 
        return "\n".join(out)