|
| 1 | +import dataclasses |
| 2 | +import typing |
| 3 | + |
| 4 | +from misc.codegen.loaders import schemaloader |
| 5 | +from . import qlgen |
| 6 | + |
| 7 | + |
| 8 | +@dataclasses.dataclass |
| 9 | +class Param: |
| 10 | + name: str |
| 11 | + type: str |
| 12 | + first: bool = False |
| 13 | + |
| 14 | + |
| 15 | +@dataclasses.dataclass |
| 16 | +class Function: |
| 17 | + name: str |
| 18 | + generic_params: list[Param] |
| 19 | + params: list[Param] |
| 20 | + return_type: str |
| 21 | + |
| 22 | + def __post_init__(self): |
| 23 | + if self.generic_params: |
| 24 | + self.generic_params[0].first = True |
| 25 | + if self.params: |
| 26 | + self.params[0].first = True |
| 27 | + |
| 28 | + |
| 29 | +@dataclasses.dataclass |
| 30 | +class TestCode: |
| 31 | + template: typing.ClassVar[str] = "rust_test_code" |
| 32 | + |
| 33 | + code: str |
| 34 | + function: Function | None = None |
| 35 | + |
| 36 | + |
| 37 | +def generate(opts, renderer): |
| 38 | + assert opts.ql_test_output |
| 39 | + schema = schemaloader.load_file(opts.schema) |
| 40 | + with renderer.manage(generated=opts.ql_test_output.rglob("gen_*.rs"), |
| 41 | + stubs=(), |
| 42 | + registry=opts.generated_registry, |
| 43 | + force=opts.force) as renderer: |
| 44 | + for cls in schema.classes.values(): |
| 45 | + if (qlgen.should_skip_qltest(cls, schema.classes) or |
| 46 | + "rust_skip_test_from_doc" in cls.pragmas or |
| 47 | + not cls.doc |
| 48 | + ): |
| 49 | + continue |
| 50 | + fn = cls.rust_doc_test_function |
| 51 | + if fn: |
| 52 | + generic_params = [Param(k, v) for k, v in fn.params.items() if k[0].isupper() or k[0] == "'"] |
| 53 | + params = [Param(k, v) for k, v in fn.params.items() if k[0].islower()] |
| 54 | + fn = Function(fn.name, generic_params, params, fn.return_type) |
| 55 | + code = [] |
| 56 | + adding_code = False |
| 57 | + for line in cls.doc: |
| 58 | + match line, adding_code: |
| 59 | + case "```", _: |
| 60 | + adding_code = not adding_code |
| 61 | + case _, False: |
| 62 | + code.append(f"// {line}") |
| 63 | + case _, True: |
| 64 | + code.append(line) |
| 65 | + if fn: |
| 66 | + indent = 4 * " " |
| 67 | + code = [indent + l for l in code] |
| 68 | + test_with = schema.classes[cls.test_with] if cls.test_with else cls |
| 69 | + test = opts.ql_test_output / test_with.group / test_with.name / f"gen_{cls.name.lower()}.rs" |
| 70 | + renderer.render(TestCode(code="\n".join(code), function=fn), test) |
0 commit comments