Coverage for /home/runner/work/tket/tket/pytket/pytket/qasm/includes/load_includes.py: 76%
32 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-14 11:30 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-14 11:30 +0000
1# Copyright Quantinuum
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15"""Helper file to convert gate definitions of any .inc files in this directory
16in to python files containing dictionaries of pytket CustomGateDefs. To be used
17with qasm parsing."""
19from pathlib import Path
20from typing import Dict, Iterator, TextIO, cast
21from lark import Lark
22from pytket.qasm.qasm import grammar, CircuitTransformer
24_WARNING = '"""DO NOT EDIT! GENERATED BY load_includes.py."""\n'
27def _get_files() -> Iterator[Path]:
28 return Path(__file__).parent.glob("*.inc")
31def _get_defpath(incfile: Path) -> Path:
32 return Path(__file__).parent / f"_{incfile.stem}_defs.py"
35def _get_declpath(incfile: Path) -> Path:
36 return Path(__file__).parent / f"_{incfile.stem}_decls.py"
39def _load_gdict(fi: Path) -> Dict[str, Dict]:
40 with open(fi) as inc_file:
41 parser = Lark(
42 grammar,
43 start="prog",
44 debug=False,
45 parser="lalr",
46 cache=True,
47 transformer=CircuitTransformer(return_gate_dict=True),
48 )
49 return cast(Dict[str, Dict], parser.parse(inc_file.read()))
52def _write_defs(f_out: TextIO, gdict: Dict[str, Dict]) -> None:
53 f_out.write(_WARNING)
54 f_out.write("_INCLUDE_DEFS=")
55 f_out.write(repr(gdict))
58def _write_decls(f_out: TextIO, gdict: Dict[str, Dict]) -> None:
59 for gate in gdict:
60 del gdict[gate]["definition"]
61 f_out.write(_WARNING)
62 f_out.write("_INCLUDE_DECLS=")
63 f_out.write(repr(gdict))
66if __name__ == "__main__": 66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true
67 for fi in _get_files():
68 gdict = _load_gdict(fi)
69 with open(_get_defpath(fi), "w") as f_out:
70 _write_defs(f_out, gdict)
71 with open(_get_declpath(fi), "w") as f_out:
72 _write_decls(f_out, gdict)