qcheck-quantum 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
qcheck/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """qcheck - verify LLM-generated quantum code (Qiskit / OpenQASM) statically and safely."""
2
+
3
+ __version__ = "0.2.0"
qcheck/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
qcheck/checks_qasm.py ADDED
@@ -0,0 +1,169 @@
1
+ """Lightweight static checks for OpenQASM 2/3, pure stdlib (regex + line scan).
2
+
3
+ Not a full parser. It catches the failure modes LLMs commonly produce: missing
4
+ header, undeclared registers, out-of-range indices, malformed measurements,
5
+ unsupported includes, and suspicious non-QASM content. One statement per line is
6
+ assumed (true for almost all generated QASM); spanning statements degrade to a
7
+ malformed-statement warning rather than a crash.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import List, Tuple
13
+
14
+ from .report import Finding
15
+
16
+ _INDEXED = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)\s*\[\s*(\d+)\s*\]")
17
+ _QREG2 = re.compile(r"^qreg\s+([A-Za-z_]\w*)\s*\[\s*(\d+)\s*\]$")
18
+ _CREG2 = re.compile(r"^creg\s+([A-Za-z_]\w*)\s*\[\s*(\d+)\s*\]$")
19
+ _QUBIT3 = re.compile(r"^qubit\s*\[\s*(\d+)\s*\]\s*([A-Za-z_]\w*)$")
20
+ _BIT3 = re.compile(r"^bit\s*\[\s*(\d+)\s*\]\s*([A-Za-z_]\w*)$")
21
+ _INCLUDE = re.compile(r'include\s+"([^"]+)"')
22
+ _SUSPICIOUS = re.compile(
23
+ r"(import\s+os|subprocess|os\.system|__import__|<script|rm\s+-rf|eval\(|exec\(|;\s*rm\s)",
24
+ re.IGNORECASE)
25
+ _SAFE_INCLUDES = {"qelib1.inc", "stdgates.inc"}
26
+
27
+
28
+ def check_qasm(text: str, framework: str) -> Tuple[bool, List[Finding], List[str]]:
29
+ findings: List[Finding] = []
30
+ fixes: List[str] = []
31
+ qregs: dict[str, int] = {}
32
+ cregs: dict[str, int] = {}
33
+ header_seen = False
34
+
35
+ for i, raw in enumerate(text.split("\n"), start=1):
36
+ line = raw.split("//", 1)[0].strip()
37
+ if not line:
38
+ continue
39
+
40
+ if _SUSPICIOUS.search(line):
41
+ findings.append(Finding(
42
+ "QASM-SUSPICIOUS", "error",
43
+ f"Suspicious non-QASM content on this line: {line[:50]!r}", i))
44
+ continue
45
+
46
+ if not line.endswith(";"):
47
+ # Block openers (gate defs) end with { -- ignore those.
48
+ if line.endswith("{") or line.endswith("}"):
49
+ continue
50
+ findings.append(Finding(
51
+ "QASM-NO-SEMICOLON", "warning",
52
+ "Statement does not end with ';' (possibly malformed or split "
53
+ "across lines).", i))
54
+ continue
55
+
56
+ stmt = line[:-1].strip()
57
+ low = stmt.lower()
58
+
59
+ if low.startswith("openqasm"):
60
+ header_seen = True
61
+ continue
62
+ if low.startswith("include"):
63
+ m = _INCLUDE.search(stmt)
64
+ inc = m.group(1) if m else ""
65
+ if inc not in _SAFE_INCLUDES:
66
+ findings.append(Finding(
67
+ "QASM-INCLUDE", "warning",
68
+ f"Unsupported/unknown include {inc!r}.", i))
69
+ continue
70
+ if low in ("", "qelib1.inc"):
71
+ continue
72
+
73
+ m = _QREG2.match(stmt)
74
+ if m:
75
+ qregs[m.group(1)] = int(m.group(2))
76
+ continue
77
+ m = _CREG2.match(stmt)
78
+ if m:
79
+ cregs[m.group(1)] = int(m.group(2))
80
+ continue
81
+ m = _QUBIT3.match(stmt)
82
+ if m:
83
+ qregs[m.group(2)] = int(m.group(1))
84
+ continue
85
+ m = _BIT3.match(stmt)
86
+ if m:
87
+ cregs[m.group(2)] = int(m.group(1))
88
+ continue
89
+
90
+ if low.startswith("gate ") or low.startswith("def "):
91
+ continue # custom gate / subroutine definition, skip in v0
92
+
93
+ # measurement
94
+ if "measure" in low:
95
+ _check_measure(stmt, qregs, cregs, i, findings, fixes)
96
+ continue
97
+
98
+ # generic gate application: validate every indexed register reference
99
+ _check_refs(stmt, qregs, cregs, i, findings, declared_required=True)
100
+
101
+ if framework == "qasm2" and not header_seen:
102
+ findings.insert(0, Finding(
103
+ "QASM-NO-HEADER", "error",
104
+ "Missing 'OPENQASM 2.0;' header.", 1))
105
+ fixes.append("Add 'OPENQASM 2.0;' as the first line.")
106
+
107
+ syntax_valid = not any(f.id in ("QASM-SUSPICIOUS",) for f in findings)
108
+ return syntax_valid, findings, fixes
109
+
110
+
111
+ def _check_refs(stmt, qregs, cregs, line, findings, declared_required):
112
+ for name, idx in _INDEXED.findall(stmt):
113
+ idx = int(idx)
114
+ if name in qregs:
115
+ size = qregs[name]
116
+ elif name in cregs:
117
+ size = cregs[name]
118
+ else:
119
+ if declared_required:
120
+ findings.append(Finding(
121
+ "QASM-UNDECLARED-REG", "error",
122
+ f"Register {name!r} used before declaration.", line))
123
+ continue
124
+ if idx >= size:
125
+ findings.append(Finding(
126
+ "QASM-INDEX-RANGE", "error",
127
+ f"Index {name}[{idx}] out of range (register size {size}).", line))
128
+
129
+
130
+ def _check_measure(stmt, qregs, cregs, line, findings, fixes):
131
+ # qasm2: measure q[i] -> c[j] ; qasm3: c[j] = measure q[i]
132
+ if "->" in stmt:
133
+ src, _, tgt = stmt.partition("->")
134
+ src = src.replace("measure", "").strip()
135
+ tgt = tgt.strip()
136
+ elif "=" in stmt:
137
+ tgt, _, src = stmt.partition("=")
138
+ tgt = tgt.strip()
139
+ src = src.replace("measure", "").strip()
140
+ else:
141
+ # bare `measure q;` broadcast -- accept, just validate refs
142
+ _check_refs(stmt, qregs, cregs, line, findings, declared_required=True)
143
+ return
144
+
145
+ # source must be a qubit register, target a classical register
146
+ for name, idx in _INDEXED.findall(src):
147
+ idx = int(idx)
148
+ if name not in qregs:
149
+ findings.append(Finding(
150
+ "QASM-MEASURE-SRC", "error",
151
+ f"Measurement source {name!r} is not a declared qubit register.",
152
+ line))
153
+ elif idx >= qregs[name]:
154
+ findings.append(Finding(
155
+ "QASM-INDEX-RANGE", "error",
156
+ f"Index {name}[{idx}] out of range (register size {qregs[name]}).",
157
+ line))
158
+ for name, idx in _INDEXED.findall(tgt):
159
+ idx = int(idx)
160
+ if name not in cregs:
161
+ findings.append(Finding(
162
+ "QASM-MEASURE-TGT", "error",
163
+ f"Measurement target {name!r} is not a declared classical register.",
164
+ line))
165
+ elif idx >= cregs[name]:
166
+ findings.append(Finding(
167
+ "QASM-INDEX-RANGE", "error",
168
+ f"Index {name}[{idx}] out of range (register size {cregs[name]}).",
169
+ line))
@@ -0,0 +1,107 @@
1
+ """Static checks for Qiskit Python snippets via the stdlib `ast` module.
2
+
3
+ No execution. Detects: syntax errors, missing QuantumCircuit import, missing
4
+ measurement, and Qiskit 1.0 breaking changes that LLMs still emit constantly
5
+ (execute(), `from qiskit import Aer/execute`, deprecated gate aliases).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ from typing import List, Tuple
11
+
12
+ from .report import Finding
13
+ from .safety import scan_python_safety
14
+
15
+ _REMOVED_FROM_QISKIT = {"execute", "Aer", "IBMQ", "BasicAer"}
16
+ _DEPRECATED_METHODS = {
17
+ "cnot": "cx", "toffoli": "ccx", "fredkin": "cswap", "iden": "id",
18
+ "mct": "mcx",
19
+ }
20
+
21
+
22
+ def check_qiskit(text: str) -> Tuple[bool, bool, List[Finding], List[str]]:
23
+ """Return (syntax_valid, unsafe, findings, suggested_fixes)."""
24
+ findings: List[Finding] = []
25
+ fixes: List[str] = []
26
+
27
+ try:
28
+ tree = ast.parse(text)
29
+ except SyntaxError as e:
30
+ findings.append(Finding(
31
+ "PY-SYNTAX", "error", f"Python syntax error: {e.msg}", e.lineno))
32
+ return False, False, findings, fixes
33
+
34
+ safety = scan_python_safety(tree)
35
+ if safety:
36
+ findings.extend(safety)
37
+ return True, True, findings, [
38
+ "Remove filesystem/network/process/dynamic-exec code; quantum "
39
+ "circuit snippets should not need it."]
40
+
41
+ imported_names: set[str] = set()
42
+ module_imports: set[str] = set()
43
+ uses_quantumcircuit = False
44
+ has_measure = False
45
+
46
+ for node in ast.walk(tree):
47
+ if isinstance(node, ast.ImportFrom):
48
+ mod = (node.module or "")
49
+ for alias in node.names:
50
+ imported_names.add(alias.asname or alias.name)
51
+ if mod == "qiskit" and alias.name in _REMOVED_FROM_QISKIT:
52
+ findings.append(Finding(
53
+ "QISKIT-REMOVED-IMPORT", "error",
54
+ f"'from qiskit import {alias.name}' was removed in "
55
+ f"Qiskit 1.0; this code will not run on modern Qiskit.",
56
+ getattr(node, "lineno", None)))
57
+ if alias.name == "execute":
58
+ fixes.append("Replace execute() with a primitive "
59
+ "(Sampler/Estimator) or backend.run().")
60
+ if alias.name == "Aer":
61
+ fixes.append("Import Aer from qiskit_aer: "
62
+ "'from qiskit_aer import Aer'.")
63
+ elif isinstance(node, ast.Import):
64
+ for alias in node.names:
65
+ module_imports.add(alias.name.split(".")[0])
66
+ elif isinstance(node, ast.Call):
67
+ func = node.func
68
+ if isinstance(func, ast.Name):
69
+ if func.id == "QuantumCircuit":
70
+ uses_quantumcircuit = True
71
+ elif func.id == "execute":
72
+ findings.append(Finding(
73
+ "QISKIT-EXECUTE", "error",
74
+ "execute() was removed in Qiskit 1.0; use Sampler/"
75
+ "Estimator primitives or backend.run().",
76
+ getattr(node, "lineno", None)))
77
+ elif isinstance(func, ast.Attribute):
78
+ if func.attr in ("measure", "measure_all", "measure_active"):
79
+ has_measure = True
80
+ elif func.attr in _DEPRECATED_METHODS:
81
+ repl = _DEPRECATED_METHODS[func.attr]
82
+ findings.append(Finding(
83
+ "QISKIT-DEPRECATED-GATE", "warning",
84
+ f"QuantumCircuit.{func.attr}() is deprecated; use "
85
+ f".{repl}().", getattr(node, "lineno", None)))
86
+ fixes.append(f"Replace .{func.attr}() with .{repl}().")
87
+
88
+ if uses_quantumcircuit and "QuantumCircuit" not in imported_names:
89
+ findings.append(Finding(
90
+ "QISKIT-MISSING-IMPORT", "error",
91
+ "QuantumCircuit is used but never imported "
92
+ "('from qiskit import QuantumCircuit').", 1))
93
+ fixes.append("Add 'from qiskit import QuantumCircuit'.")
94
+
95
+ if uses_quantumcircuit and not has_measure:
96
+ findings.append(Finding(
97
+ "QISKIT-NO-MEASURE", "warning",
98
+ "Circuit has no measurement; sampling it returns nothing useful.",
99
+ None))
100
+ fixes.append("Add qc.measure_all() (or explicit measure) before running.")
101
+
102
+ if not uses_quantumcircuit:
103
+ findings.append(Finding(
104
+ "QISKIT-NO-CIRCUIT", "warning",
105
+ "No QuantumCircuit(...) construction detected.", None))
106
+
107
+ return True, False, findings, fixes
qcheck/cli.py ADDED
@@ -0,0 +1,292 @@
1
+ """qcheck command-line interface (argparse, stdlib only).
2
+
3
+ Exit codes:
4
+ 0 pass (or pass-with-warnings)
5
+ 1 verification failed (errors found)
6
+ 2 unsafe input / unsupported framework
7
+ 3 internal error
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import ast
13
+ import json
14
+ import os
15
+ import sys
16
+ from typing import List, Optional, Tuple
17
+
18
+ from . import __version__
19
+ from .detect import detect_framework
20
+ from .report import Report
21
+ from .checks_qasm import check_qasm
22
+ from .checks_qiskit import check_qiskit
23
+ from .safety import scan_python_safety
24
+ from .sarif import build_sarif
25
+
26
+ EXIT_PASS = 0
27
+ EXIT_FAIL = 1
28
+ EXIT_UNSAFE = 2
29
+ EXIT_INTERNAL = 3
30
+
31
+
32
+ def verify_text(path: str, text: str) -> Report:
33
+ framework = detect_framework(path, text)
34
+
35
+ if framework in ("qasm2", "qasm3"):
36
+ syntax_valid, findings, fixes = check_qasm(text, framework)
37
+ return Report(framework=framework, syntax_valid=syntax_valid,
38
+ findings=findings, suggested_fixes=fixes)
39
+
40
+ if framework == "qiskit":
41
+ syntax_valid, unsafe, findings, fixes = check_qiskit(text)
42
+ return Report(framework=framework, syntax_valid=syntax_valid,
43
+ findings=findings, suggested_fixes=fixes, unsafe=unsafe)
44
+
45
+ # Any .py is safety-screened even if it does not look like qiskit: the RCE
46
+ # threat is identical regardless of imports (defense in depth).
47
+ if framework == "python_unknown":
48
+ r = Report(framework=framework, syntax_valid=True)
49
+ try:
50
+ safety = scan_python_safety(ast.parse(text))
51
+ except SyntaxError as e:
52
+ r.syntax_valid = False
53
+ from .report import Finding
54
+ r.findings.append(Finding("PY-SYNTAX", "error",
55
+ f"Python syntax error: {e.msg}", e.lineno))
56
+ return r
57
+ if safety:
58
+ r.unsafe = True
59
+ r.findings.extend(safety)
60
+ else:
61
+ r.findings.append(_unsupported_finding(framework))
62
+ return r
63
+
64
+ # unknown extension / non-python, non-qasm
65
+ r = Report(framework=framework, syntax_valid=True)
66
+ r.findings.append(_unsupported_finding(framework))
67
+ return r
68
+
69
+
70
+ def _unsupported_finding(framework):
71
+ from .report import Finding
72
+ return Finding(
73
+ "UNSUPPORTED", "error",
74
+ f"Framework '{framework}' is not supported in qcheck v0 "
75
+ f"(supported: OpenQASM 2/3, Qiskit Python).", None)
76
+
77
+
78
+ def _exit_code(report: Report) -> int:
79
+ if report.unsafe:
80
+ return EXIT_UNSAFE
81
+ if any(f.id == "UNSUPPORTED" for f in report.findings):
82
+ return EXIT_UNSAFE
83
+ if report.status == "fail":
84
+ return EXIT_FAIL
85
+ return EXIT_PASS
86
+
87
+
88
+ def _print_human(report: Report, path: str) -> None:
89
+ icon = {"pass": "PASS", "warning": "WARN", "fail": "FAIL"}[report.status]
90
+ print(f"qcheck {__version__} [{icon}] {path} ({report.framework})")
91
+ print(f" syntax_valid={report.syntax_valid} "
92
+ f"unsafe={report.unsafe} confidence={report.confidence}")
93
+ print(f" runnable_in_simulator={report.runnable_in_simulator} "
94
+ f"(static-only in v0)")
95
+ if not report.findings:
96
+ print(" no issues found.")
97
+ for f in report.findings:
98
+ loc = f" (line {f.line})" if f.line else ""
99
+ print(f" [{f.level}] {f.id}: {f.message}{loc}")
100
+ for fix in report.suggested_fixes:
101
+ print(f" fix -> {fix}")
102
+
103
+
104
+ _LANG_EXT = {"qasm2": ".qasm", "qasm3": ".qasm", "qiskit": ".py", "python": ".py"}
105
+
106
+ # Directories skipped during recursion: virtualenvs, VCS, caches, build output,
107
+ # vendored deps. Without this, `qcheck verify .` in a repo with a .venv would
108
+ # review thousands of third-party files (pip, etc.) and flag them as unsafe.
109
+ # Explicit file/dir paths passed on the command line are never pruned.
110
+ _SKIP_DIRS = frozenset({
111
+ ".git", ".hg", ".svn", ".venv", "venv", "env", "ENV", "virtualenv",
112
+ "node_modules", "__pycache__", ".tox", ".nox", ".mypy_cache",
113
+ ".pytest_cache", ".ruff_cache", "site-packages", "build", "dist",
114
+ ".eggs", ".idea", ".vscode",
115
+ })
116
+
117
+
118
+ def _expand_targets(paths: List[str]) -> List[str]:
119
+ """Expand directories into their .py/.qasm files (recursive, sorted).
120
+ Keeps '-' (stdin) and explicit file paths. Deterministic order.
121
+ Recursion skips vendored/build/VCS dirs (see _SKIP_DIRS); hidden dirs
122
+ (dot-prefixed) are skipped too, but an explicitly named dir still descends."""
123
+ out: List[str] = []
124
+ for p in paths:
125
+ if p == "-":
126
+ out.append("-")
127
+ elif os.path.isdir(p):
128
+ found = []
129
+ for root, dirs, files in os.walk(p):
130
+ # Prune in place (topdown walk): don't descend into vendor/hidden dirs.
131
+ dirs[:] = [d for d in dirs
132
+ if d not in _SKIP_DIRS and not d.startswith(".")]
133
+ for fn in files:
134
+ if fn.endswith((".py", ".qasm")):
135
+ found.append(os.path.join(root, fn))
136
+ out.extend(sorted(found))
137
+ else:
138
+ out.append(p)
139
+ # de-dupe while preserving first occurrence
140
+ seen, uniq = set(), []
141
+ for t in out:
142
+ if t not in seen:
143
+ seen.add(t)
144
+ uniq.append(t)
145
+ return uniq
146
+
147
+
148
+ def _detect_name(display: str, text: str, lang: Optional[str]) -> str:
149
+ if lang:
150
+ return "stdin" + _LANG_EXT[lang]
151
+ if display == "-":
152
+ return "stdin.qasm" if "openqasm" in text.lower() else "stdin.py"
153
+ return display
154
+
155
+
156
+ def _verify_one(display: str, lang: Optional[str], stdin_text: Optional[str]) -> Tuple[str, Optional[Report], Optional[str]]:
157
+ """Return (display, report, read_error)."""
158
+ try:
159
+ text = stdin_text if display == "-" else open(display, "r", encoding="utf-8").read()
160
+ except OSError as e:
161
+ return (display, None, f"cannot read {display}: {e}")
162
+ try:
163
+ return (display, verify_text(_detect_name(display, text, lang), text), None)
164
+ except Exception as e: # never crash on one bad file
165
+ return (display, None, f"internal error: {e}")
166
+
167
+
168
+ def _worst_exit(units) -> int:
169
+ """Worst-case exit code across verified units (findings-based, not format)."""
170
+ worst = EXIT_PASS
171
+ for _display, report, err in units:
172
+ if err is not None:
173
+ worst = max(worst, EXIT_INTERNAL)
174
+ continue
175
+ rc = _exit_code(report)
176
+ worst = EXIT_UNSAFE if EXIT_UNSAFE in (worst, rc) else max(worst, rc)
177
+ return worst
178
+
179
+
180
+ def main(argv: Optional[List[str]] = None) -> int:
181
+ parser = argparse.ArgumentParser(
182
+ prog="qcheck",
183
+ description="Review LLM-generated quantum code (Qiskit / OpenQASM).")
184
+ parser.add_argument("--version", action="version",
185
+ version=f"qcheck {__version__}")
186
+ sub = parser.add_subparsers(dest="command")
187
+ p_verify = sub.add_parser("verify", help="review .qasm/.py files, directories, or stdin")
188
+ p_verify.add_argument("paths", nargs="+",
189
+ help="one or more files or directories, or '-' for stdin")
190
+ p_verify.add_argument("--format", choices=("human", "json", "sarif"),
191
+ default=None,
192
+ help="output format (default: human). 'sarif' emits "
193
+ "SARIF 2.1.0 for GitHub Code Scanning.")
194
+ p_verify.add_argument("--json", action="store_true",
195
+ help="alias for --format json (backwards compatible)")
196
+ p_verify.add_argument("--output", metavar="FILE",
197
+ help="write SARIF output to FILE instead of stdout "
198
+ "(used with --format sarif)")
199
+ p_verify.add_argument("--lang", choices=sorted(_LANG_EXT),
200
+ help="force language for stdin input")
201
+
202
+ args = parser.parse_args(argv)
203
+ if args.command != "verify":
204
+ parser.print_help()
205
+ return EXIT_INTERNAL
206
+
207
+ # Resolve format. --format wins when given; --json is a backwards-compatible
208
+ # alias; default stays human. Exit codes never depend on the format.
209
+ if args.format is not None:
210
+ fmt = args.format
211
+ elif args.json:
212
+ fmt = "json"
213
+ else:
214
+ fmt = "human"
215
+ emit_json = fmt == "json"
216
+
217
+ targets = _expand_targets(args.paths)
218
+ if not targets:
219
+ print("qcheck: no .py or .qasm files found.", file=sys.stderr)
220
+ return EXIT_PASS
221
+
222
+ stdin_text = sys.stdin.read() if "-" in targets else None
223
+ units = [_verify_one(t, args.lang, stdin_text) for t in targets]
224
+
225
+ # SARIF: a single-run document over all units, regardless of count.
226
+ if fmt == "sarif":
227
+ doc = build_sarif(
228
+ [(d, r) for (d, r, e) in units if r is not None],
229
+ execution_successful=all(e is None for (_d, _r, e) in units))
230
+ text = json.dumps(doc, indent=2)
231
+ if args.output:
232
+ with open(args.output, "w", encoding="utf-8") as fh:
233
+ fh.write(text + "\n")
234
+ else:
235
+ print(text)
236
+ return _worst_exit(units)
237
+
238
+ # Single unit -> preserve legacy output + exit code exactly.
239
+ if len(units) == 1:
240
+ display, report, err = units[0]
241
+ if err is not None:
242
+ print(f"qcheck: {err}", file=sys.stderr)
243
+ return EXIT_INTERNAL
244
+ if emit_json:
245
+ print(json.dumps(report.to_dict(), indent=2))
246
+ else:
247
+ _print_human(report, display)
248
+ return _exit_code(report)
249
+
250
+ # Aggregate over multiple units.
251
+ results, worst = [], EXIT_PASS
252
+ passed = failed = unsafe = err_count = 0
253
+ for display, report, err in units:
254
+ if err is not None:
255
+ err_count += 1
256
+ worst = max(worst, EXIT_INTERNAL)
257
+ results.append({"path": display, "error": err})
258
+ if not emit_json:
259
+ print(f" [ERROR] {display}: {err}")
260
+ continue
261
+ rc = _exit_code(report)
262
+ worst = EXIT_UNSAFE if EXIT_UNSAFE in (worst, rc) else max(worst, rc)
263
+ if report.unsafe:
264
+ unsafe += 1
265
+ elif report.status == "fail":
266
+ failed += 1
267
+ else:
268
+ passed += 1
269
+ if emit_json:
270
+ d = report.to_dict()
271
+ d["path"] = display
272
+ results.append(d)
273
+ else:
274
+ icon = "UNSAFE" if report.unsafe else {"pass": "PASS", "warning": "WARN", "fail": "FAIL"}[report.status]
275
+ errs = len(report.errors)
276
+ print(f" [{icon}] {display} ({report.framework})"
277
+ + (f" {errs} error(s)" if errs else ""))
278
+
279
+ summary = {"files": len(units), "passed": passed, "failed": failed,
280
+ "unsafe": unsafe, "read_errors": err_count}
281
+ if emit_json:
282
+ print(json.dumps({"qcheck_version": __version__, "results": results,
283
+ "summary": summary}, indent=2))
284
+ else:
285
+ print(f"qcheck {__version__}: {summary['files']} file(s) - "
286
+ f"{passed} passed, {failed} failed, {unsafe} unsafe"
287
+ + (f", {err_count} unreadable" if err_count else ""))
288
+ return worst
289
+
290
+
291
+ if __name__ == "__main__":
292
+ sys.exit(main())
qcheck/detect.py ADDED
@@ -0,0 +1,28 @@
1
+ """Detect which framework a snippet is, from extension + content."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+
6
+
7
+ def detect_framework(path: str, text: str) -> str:
8
+ """Return one of: qasm2, qasm3, qiskit, python_unknown, unknown."""
9
+ ext = os.path.splitext(path)[1].lower()
10
+ low = text.lower()
11
+
12
+ if ext == ".qasm" or "openqasm" in low:
13
+ if "openqasm 3" in low:
14
+ return "qasm3"
15
+ if "openqasm 2" in low:
16
+ return "qasm2"
17
+ if "qubit[" in low or "bit[" in low:
18
+ return "qasm3"
19
+ if "qreg" in low or "creg" in low:
20
+ return "qasm2"
21
+ return "qasm2"
22
+
23
+ if ext == ".py":
24
+ if "qiskit" in low or "quantumcircuit" in low:
25
+ return "qiskit"
26
+ return "python_unknown"
27
+
28
+ return "unknown"
qcheck/report.py ADDED
@@ -0,0 +1,73 @@
1
+ """Report and Finding data structures + status/confidence logic.
2
+
3
+ Pure stdlib (dataclasses) so qcheck v0 installs with zero runtime dependencies.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, asdict, field
8
+ from typing import List, Optional
9
+
10
+ from . import __version__
11
+
12
+
13
+ @dataclass
14
+ class Finding:
15
+ id: str # stable check id, e.g. "QASM-UNDECLARED-REG"
16
+ level: str # "error" | "warning" | "info"
17
+ message: str
18
+ line: Optional[int] = None
19
+
20
+
21
+ @dataclass
22
+ class Report:
23
+ framework: str
24
+ syntax_valid: bool
25
+ findings: List[Finding] = field(default_factory=list)
26
+ suggested_fixes: List[str] = field(default_factory=list)
27
+ unsafe: bool = False
28
+ # v0 does NOT execute code. This field documents that explicitly.
29
+ runnable_in_simulator: str = "not_run"
30
+ runnable_reason: str = (
31
+ "qcheck v0 performs static verification only; it never executes the "
32
+ "input. Simulator execution is deferred to a sandboxed v1 (see SECURITY.md)."
33
+ )
34
+
35
+ @property
36
+ def errors(self) -> List[Finding]:
37
+ return [f for f in self.findings if f.level == "error"]
38
+
39
+ @property
40
+ def warnings(self) -> List[Finding]:
41
+ return [f for f in self.findings if f.level == "warning"]
42
+
43
+ @property
44
+ def status(self) -> str:
45
+ if not self.syntax_valid or self.errors:
46
+ return "fail"
47
+ if self.warnings:
48
+ return "warning"
49
+ return "pass"
50
+
51
+ @property
52
+ def confidence(self) -> float:
53
+ """Deterministic rubric: high when it parses cleanly with no findings."""
54
+ c = 1.0 - 0.4 * len(self.errors) - 0.1 * len(self.warnings)
55
+ if not self.syntax_valid:
56
+ c = min(c, 0.2)
57
+ return round(max(0.0, min(1.0, c)), 2)
58
+
59
+ def to_dict(self) -> dict:
60
+ return {
61
+ "qcheck_version": __version__,
62
+ "status": self.status,
63
+ "framework": self.framework,
64
+ "syntax_valid": self.syntax_valid,
65
+ "unsafe": self.unsafe,
66
+ "runnable_in_simulator": self.runnable_in_simulator,
67
+ "runnable_reason": self.runnable_reason,
68
+ "static_checks": [asdict(f) for f in self.findings],
69
+ "errors": [asdict(f) for f in self.errors],
70
+ "warnings": [asdict(f) for f in self.warnings],
71
+ "suggested_fixes": self.suggested_fixes,
72
+ "confidence": self.confidence,
73
+ }
qcheck/safety.py ADDED
@@ -0,0 +1,61 @@
1
+ """Static safety screen for Python snippets, using the stdlib `ast` module.
2
+
3
+ qcheck NEVER executes the input. This module only inspects the parsed AST and
4
+ flags constructs that would let an untrusted snippet touch the filesystem,
5
+ network, processes, or dynamic code execution. If any are present the snippet is
6
+ marked unsafe and qcheck refuses to treat it as a benign circuit.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ from typing import List
12
+
13
+ from .report import Finding
14
+
15
+ UNSAFE_MODULES = {
16
+ "os", "sys", "subprocess", "shutil", "socket", "requests", "urllib",
17
+ "http", "ctypes", "pickle", "marshal", "importlib", "pty", "signal",
18
+ "multiprocessing", "threading", "asyncio", "pathlib", "glob", "tempfile",
19
+ }
20
+
21
+ UNSAFE_BUILTINS = {"eval", "exec", "compile", "__import__", "open", "input"}
22
+
23
+ UNSAFE_ATTRS = {
24
+ "system", "popen", "spawn", "spawnl", "spawnv", "call", "run", "Popen",
25
+ "remove", "rmtree", "unlink", "rename", "chmod", "chown", "kill",
26
+ "connect", "urlopen", "get", "post", "request", "load", "loads",
27
+ }
28
+
29
+
30
+ def scan_python_safety(tree: ast.AST) -> List[Finding]:
31
+ findings: List[Finding] = []
32
+ for node in ast.walk(tree):
33
+ if isinstance(node, ast.Import):
34
+ for alias in node.names:
35
+ root = alias.name.split(".")[0]
36
+ if root in UNSAFE_MODULES:
37
+ findings.append(Finding(
38
+ "PY-UNSAFE-IMPORT", "error",
39
+ f"Unsafe import '{alias.name}' is not allowed in quantum "
40
+ f"code; qcheck rejects it as a potential RCE vector.",
41
+ getattr(node, "lineno", None)))
42
+ elif isinstance(node, ast.ImportFrom):
43
+ root = (node.module or "").split(".")[0]
44
+ if root in UNSAFE_MODULES:
45
+ findings.append(Finding(
46
+ "PY-UNSAFE-IMPORT", "error",
47
+ f"Unsafe import 'from {node.module} import ...' is not allowed.",
48
+ getattr(node, "lineno", None)))
49
+ elif isinstance(node, ast.Call):
50
+ func = node.func
51
+ if isinstance(func, ast.Name) and func.id in UNSAFE_BUILTINS:
52
+ findings.append(Finding(
53
+ "PY-UNSAFE-CALL", "error",
54
+ f"Unsafe call '{func.id}(...)' is not allowed.",
55
+ getattr(node, "lineno", None)))
56
+ elif isinstance(func, ast.Attribute) and func.attr in UNSAFE_ATTRS:
57
+ findings.append(Finding(
58
+ "PY-UNSAFE-CALL", "error",
59
+ f"Unsafe call '.{func.attr}(...)' is not allowed.",
60
+ getattr(node, "lineno", None)))
61
+ return findings
qcheck/sarif.py ADDED
@@ -0,0 +1,95 @@
1
+ """SARIF 2.1.0 formatter for qcheck results (GitHub Code Scanning compatible).
2
+
3
+ Pure formatter over Report objects - no execution, no new dependencies, and it
4
+ does not touch the human or --json output. SARIF reports static qcheck findings;
5
+ it does not assert quantum correctness. Output ordering is deterministic.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import List, Optional, Tuple
10
+
11
+ from . import __version__
12
+ from .report import Report
13
+
14
+ INFORMATION_URI = "https://github.com/JCQuankey/qcheck"
15
+ SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"
16
+
17
+ # qcheck level -> SARIF level. SARIF levels: none | note | warning | error.
18
+ _LEVEL = {"error": "error", "warning": "warning", "info": "note"}
19
+
20
+ # Stable, human-readable rule metadata. Unknown ids still get a rule entry
21
+ # (falling back to the id) so results always reference a defined rule.
22
+ _RULE_DESC = {
23
+ "QASM-NO-HEADER": "OpenQASM header missing",
24
+ "QASM-UNDECLARED-REG": "Use of an undeclared quantum/classical register",
25
+ "QASM-INDEX-RANGE": "Register index out of declared range",
26
+ "QASM-MEASURE-SRC": "Invalid measurement source operand",
27
+ "QASM-MEASURE-TGT": "Invalid measurement target operand",
28
+ "QASM-INCLUDE": "Unsupported or missing include",
29
+ "QASM-NO-SEMICOLON": "Statement missing a terminating semicolon",
30
+ "QASM-SUSPICIOUS": "Content does not look like valid OpenQASM",
31
+ "QISKIT-MISSING-IMPORT": "QuantumCircuit used without importing it",
32
+ "QISKIT-NO-CIRCUIT": "No QuantumCircuit construction detected",
33
+ "QISKIT-NO-MEASURE": "Circuit has no measurement",
34
+ "QISKIT-EXECUTE": "Use of execute(), removed in Qiskit 1.0",
35
+ "QISKIT-REMOVED-IMPORT": "Import removed in Qiskit 1.0 (e.g. execute, Aer)",
36
+ "QISKIT-DEPRECATED-GATE": "Deprecated gate alias",
37
+ "PY-SYNTAX": "Python syntax error",
38
+ "PY-UNSAFE-IMPORT": "Unsafe import (potential remote-code-execution vector)",
39
+ "PY-UNSAFE-CALL": "Unsafe call (potential remote-code-execution vector)",
40
+ "UNSUPPORTED": "Unsupported framework or file type",
41
+ }
42
+
43
+
44
+ def _sarif_uri(display: str) -> str:
45
+ # stdin has no path on disk; use a stable synthetic URI (not uploadable).
46
+ return "stdin" if display == "-" else display.replace("\\", "/")
47
+
48
+
49
+ def build_sarif(results: List[Tuple[str, Report]],
50
+ execution_successful: bool = True) -> dict:
51
+ """Build a single-run SARIF 2.1.0 document from (display_path, Report) pairs."""
52
+ sarif_results = []
53
+ rule_ids = set()
54
+ for display, report in results:
55
+ uri = _sarif_uri(display)
56
+ for f in report.findings:
57
+ rule_ids.add(f.id)
58
+ loc = {"physicalLocation": {"artifactLocation": {"uri": uri}}}
59
+ if f.line:
60
+ loc["physicalLocation"]["region"] = {"startLine": int(f.line)}
61
+ sarif_results.append({
62
+ "ruleId": f.id,
63
+ "level": _LEVEL.get(f.level, "warning"),
64
+ "message": {"text": f.message},
65
+ "locations": [loc],
66
+ })
67
+
68
+ # Deterministic ordering: by file, then rule, then line, then message.
69
+ sarif_results.sort(key=lambda r: (
70
+ r["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
71
+ r["ruleId"],
72
+ r["locations"][0]["physicalLocation"].get("region", {}).get("startLine", 0),
73
+ r["message"]["text"],
74
+ ))
75
+
76
+ rules = [{
77
+ "id": rid,
78
+ "name": rid,
79
+ "shortDescription": {"text": _RULE_DESC.get(rid, rid)},
80
+ } for rid in sorted(rule_ids)]
81
+
82
+ return {
83
+ "version": "2.1.0",
84
+ "$schema": SCHEMA,
85
+ "runs": [{
86
+ "tool": {"driver": {
87
+ "name": "qcheck",
88
+ "informationUri": INFORMATION_URI,
89
+ "version": __version__,
90
+ "rules": rules,
91
+ }},
92
+ "results": sarif_results,
93
+ "invocations": [{"executionSuccessful": bool(execution_successful)}],
94
+ }],
95
+ }
@@ -0,0 +1,226 @@
1
+ Metadata-Version: 2.4
2
+ Name: qcheck-quantum
3
+ Version: 0.2.0
4
+ Summary: Verify LLM-generated quantum code (Qiskit / OpenQASM) statically and safely.
5
+ Author: qcheck contributors
6
+ Maintainer-email: JCQuankey <dev@quankey.xyz>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/JCQuankey/qcheck
9
+ Project-URL: Repository, https://github.com/JCQuankey/qcheck
10
+ Project-URL: Issues, https://github.com/JCQuankey/qcheck/issues
11
+ Keywords: quantum,qiskit,openqasm,llm,linter,code-review,static-analysis,sarif
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Classifier: Topic :: Scientific/Engineering :: Physics
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ License-File: NOTICE
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7; extra == "dev"
29
+ Provides-Extra: release
30
+ Requires-Dist: build>=1; extra == "release"
31
+ Requires-Dist: twine>=5; extra == "release"
32
+ Dynamic: license-file
33
+
34
+ # qcheck
35
+
36
+ **AI writes quantum code. qcheck reviews it.**
37
+
38
+ `qcheck` is a lightweight review layer for AI-generated Qiskit and OpenQASM
39
+ snippets. It catches common issues early - removed-in-1.0 APIs, unsafe patterns,
40
+ missing measurements, parse errors - so agents and developers can improve quantum
41
+ code before it reaches humans, CI, or simulators. Tiny, dependency-free, and it
42
+ reviews code without ever executing it.
43
+
44
+ Why it matters: LLMs write quantum code that fails to run **40-70% of the time**
45
+ one-shot (QuanBench+ 2026: Qiskit 59.5% / PennyLane 42.9% pass; QCoder 2026: ~70%
46
+ one-shot failure). qcheck catches the avoidable share of that early.
47
+
48
+ ```bash
49
+ qcheck verify circuit.qasm
50
+ qcheck verify snippet.py --json
51
+ ```
52
+
53
+ ## Why this exists
54
+
55
+ An LLM agent (or a developer pasting from a chat assistant) produces a Qiskit/QASM snippet.
56
+ Will it run? Is it using an API that was removed in Qiskit 1.0? Does it measure?
57
+ Is it even safe to touch? Today you find out by running it - wasting time, and
58
+ in an agent loop, running untrusted model output. `qcheck` answers in
59
+ milliseconds, statically.
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ # From source (works today)
65
+ git clone https://github.com/JCQuankey/qcheck && cd qcheck
66
+ pip install -e ".[dev]" # editable install + pytest
67
+ ```
68
+
69
+ Once the first release is published, install from PyPI:
70
+
71
+ ```bash
72
+ pip install qcheck-quantum # available after the first PyPI release
73
+ ```
74
+
75
+ The PyPI **distribution** name is `qcheck-quantum` (the bare `qcheck` name is
76
+ taken on PyPI); the installed **command** and the import package are both
77
+ `qcheck`. v0 has **zero runtime dependencies** (standard library only). Release
78
+ process: [`docs/RELEASING.md`](https://github.com/JCQuankey/qcheck/blob/main/docs/RELEASING.md).
79
+
80
+ ## Quickstart
81
+
82
+ ```bash
83
+ qcheck verify examples/broken_qiskit_execute.py # one file
84
+ qcheck verify examples/ # a whole directory (recursive)
85
+ qcheck verify a.py b.qasm circuits/ # several paths at once
86
+ cat snippet.py | qcheck verify - # stdin (for agents)
87
+ ```
88
+
89
+ Example output:
90
+
91
+ ```
92
+ qcheck 0.2.0 [FAIL] examples/broken_qiskit_execute.py (qiskit)
93
+ [error] QISKIT-REMOVED-IMPORT: 'from qiskit import execute' was removed in Qiskit 1.0
94
+ [warning] QISKIT-DEPRECATED-GATE: QuantumCircuit.cnot() is deprecated; use .cx().
95
+ fix -> Replace execute() with a primitive (Sampler/Estimator) or backend.run().
96
+ ```
97
+
98
+ Reviewing multiple files prints a per-file summary and exits with the worst
99
+ result found (unsafe > failed > passed). Directory recursion skips virtualenvs,
100
+ VCS, caches, and build output (`.venv`, `node_modules`, `.git`, `site-packages`,
101
+ `build`, `dist`, ...) so it reviews your code, not your dependencies. To review a
102
+ file inside one of those, pass it explicitly.
103
+
104
+ ## JSON output (for agents & CI)
105
+
106
+ ```bash
107
+ qcheck verify snippet.py --json
108
+ ```
109
+
110
+ For a single file, returns `{status, framework, syntax_valid, unsafe,
111
+ static_checks, errors, warnings, suggested_fixes, confidence,
112
+ runnable_in_simulator, qcheck_version}`. For multiple files or a directory,
113
+ returns an envelope `{qcheck_version, results: [<per-file object + "path">...],
114
+ summary: {files, passed, failed, unsafe, read_errors}}`. Designed to be parsed by
115
+ an LLM agent that just generated the code, or by a CI gate. Exit codes: `0` pass,
116
+ `1` verification failed, `2` unsafe/unsupported, `3` internal error.
117
+
118
+ ## Use it in CI (GitHub Action)
119
+
120
+ qcheck ships a composite GitHub Action. In your repo's
121
+ `.github/workflows/qcheck.yml`:
122
+
123
+ ```yaml
124
+ - uses: actions/checkout@v4
125
+ - uses: JCQuankey/qcheck@main
126
+ with:
127
+ paths: "." # or a folder, e.g. "circuits/"
128
+ ```
129
+
130
+ The step fails the job when qcheck finds errors or unsafe code. See
131
+ [`examples/github-action.yml`](https://github.com/JCQuankey/qcheck/blob/main/examples/github-action.yml).
132
+
133
+ ## SARIF output (GitHub Code Scanning)
134
+
135
+ qcheck can emit SARIF 2.1.0 so findings show up as **code scanning alerts** on
136
+ the Security tab and inline on pull requests, instead of only in the log:
137
+
138
+ ```bash
139
+ qcheck verify . --format sarif --output qcheck.sarif
140
+ ```
141
+
142
+ In a workflow, generate the SARIF and let the caller upload it (upload needs
143
+ `security-events: write`, best granted by the consuming repo):
144
+
145
+ ```yaml
146
+ permissions:
147
+ contents: read
148
+ security-events: write
149
+ steps:
150
+ - uses: actions/checkout@v4
151
+ - uses: JCQuankey/qcheck@main
152
+ with:
153
+ format: sarif
154
+ output: qcheck.sarif
155
+ - uses: github/codeql-action/upload-sarif@v3
156
+ with:
157
+ sarif_file: qcheck.sarif
158
+ ```
159
+
160
+ SARIF reports static qcheck findings (rule id, level, file, line) - it does not
161
+ prove quantum correctness. `stdin` input uses a synthetic `stdin` URI and is not
162
+ meant for code-scanning upload.
163
+
164
+ ## What v0 checks
165
+
166
+ **OpenQASM 2/3:** missing header, undeclared registers, index-out-of-range,
167
+ malformed measurements, unsupported includes, suspicious non-QASM content.
168
+ **Qiskit Python:** Python syntax, missing `QuantumCircuit` import, missing
169
+ measurement, and Qiskit-1.0 breaking changes LLMs still emit (`execute()`,
170
+ `from qiskit import Aer/execute`, deprecated gate aliases like `cnot`->`cx`).
171
+
172
+ ## Safety policy
173
+
174
+ `qcheck` **never executes the input.** Qiskit snippets are analyzed with the
175
+ Python `ast` module (parse, don't run). Any filesystem/network/process/dynamic-
176
+ exec construct (`os`, `subprocess`, `eval`, `open`, ...) marks the snippet
177
+ **unsafe** and exits `2`. QASM input is text-scanned. This is deliberate: an
178
+ agent-facing verifier that *ran* untrusted model output would be a remote-code-
179
+ execution vector (see Qiskit CVE-2025-2000 for the QPY/pickle precedent). See
180
+ [`SECURITY.md`](https://github.com/JCQuankey/qcheck/blob/main/SECURITY.md) for the full threat model.
181
+
182
+ ## Scope
183
+
184
+ qcheck v0 focuses on static review signals for Qiskit and OpenQASM: API usage
185
+ (including Qiskit 1.0 removals), unsafe patterns, missing measurements, parse
186
+ issues, and common LLM-generated mistakes. It reviews code without executing it,
187
+ so it's safe to run on untrusted model output inside an agent loop or CI.
188
+
189
+ It's a fast first-pass reviewer - pair it with your tests and simulators for the
190
+ rest. For methodology and scope details, see the
191
+ [leaderboard methodology](https://github.com/JCQuankey/qcheck/blob/main/leaderboard/methodology.md).
192
+
193
+ ## Roadmap
194
+
195
+ - v0 (this): CLI, Qiskit + OpenQASM static checks, JSON, safety screen. **Zero runtime deps.**
196
+ - v1: sandboxed simulation (opt-in), PennyLane + Cirq, LLM-powered fix suggestions, GitHub Action, MCP server (`verify_quantum_code`).
197
+ - Public **static-check leaderboard** for LLM-generated quantum code (see `leaderboard/`) + anonymized error dataset.
198
+
199
+ ## Leaderboard
200
+
201
+ qcheck includes a **static review benchmark** for AI-generated quantum code: it
202
+ tracks how often model outputs pass qcheck's current review checks
203
+ (`static_pass_rate`) on a small public Qiskit/OpenQASM task set - an early quality
204
+ signal for agents and LLM workflows. The rows shown today are labelled **SAMPLE/demo**.
205
+
206
+ - [`leaderboard/README.md`](https://github.com/JCQuankey/qcheck/blob/main/leaderboard/README.md) - how to add a submission and run it
207
+ - [`leaderboard/methodology.md`](https://github.com/JCQuankey/qcheck/blob/main/leaderboard/methodology.md) - scope and methodology
208
+ - [`leaderboard/site/leaderboard.md`](https://github.com/JCQuankey/qcheck/blob/main/leaderboard/site/leaderboard.md) - the generated table
209
+
210
+ ## Contributing
211
+
212
+ Issues and PRs welcome - especially new failure fixtures (a real LLM-generated
213
+ snippet that should fail but currently passes, or vice versa). Each fixture
214
+ makes qcheck sharper and feeds the public error taxonomy.
215
+
216
+ ## Contact
217
+
218
+ - Technical questions / maintainer contact: **dev@quankey.xyz**
219
+ - Security issues: **security@quankey.xyz** (see [`SECURITY.md`](https://github.com/JCQuankey/qcheck/blob/main/SECURITY.md))
220
+
221
+ Maintained by JCQuankey / qcheck contributors. qcheck runs locally, sends no
222
+ telemetry, and reviews code without executing it.
223
+
224
+ ## License
225
+
226
+ Apache-2.0.
@@ -0,0 +1,16 @@
1
+ qcheck/__init__.py,sha256=THEuFJgbl0NHWNs7Lv1pxuv6zQzMPcVt3JZWdFUrE_U,115
2
+ qcheck/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
3
+ qcheck/checks_qasm.py,sha256=Go-8YSUvZrIICcGN7su5UDrpCjU-6rKyOEOCokB1JbE,6265
4
+ qcheck/checks_qiskit.py,sha256=o079k31bvSIn4mAHridX33zhK-QgJZDX8TahpT3iZlk,4585
5
+ qcheck/cli.py,sha256=GjhvqAZfbgCi7SpWClucVQu_f1HGJyUQFYaBK08lLBA,11032
6
+ qcheck/detect.py,sha256=OCSShS_x-XQv9oM48CVYEVnT3kIYzEUdBVfCAqH4p6Y,794
7
+ qcheck/report.py,sha256=-92ArAfcjloFR6oGxI-qSckC_74cZQoh33xFyRN6Dik,2420
8
+ qcheck/safety.py,sha256=rGpl2nwSfKn6sqy7osNs4cNm5GmgAttRp8nj_Dgz4XY,2680
9
+ qcheck/sarif.py,sha256=VFBY86TkR5nNUcjyRAwddqP6m6p32fmC_JH372xhMO4,3913
10
+ qcheck_quantum-0.2.0.dist-info/licenses/LICENSE,sha256=1uosaGUyZNi9NB1owMQ3fBSvbYKsYsJ0npz8LkOpfp4,11349
11
+ qcheck_quantum-0.2.0.dist-info/licenses/NOTICE,sha256=RllYEZnvRdNM-pKatYuabngvGfJwoYz2AHDoW82Abq8,260
12
+ qcheck_quantum-0.2.0.dist-info/METADATA,sha256=Kr12giY4ZQWD6bUtJplvi3toi0eZNaQ3Wmjbh1hnFew,9262
13
+ qcheck_quantum-0.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
+ qcheck_quantum-0.2.0.dist-info/entry_points.txt,sha256=s4vW7QZCD9UgdLowDyb8InjTUztIe5xE5_kF0bgXquY,43
15
+ qcheck_quantum-0.2.0.dist-info/top_level.txt,sha256=iUSFtYU7wY0yWnHxUFu0PDq7VvtK4_3QW8T7f7U3YAQ,7
16
+ qcheck_quantum-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ qcheck = qcheck.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 qcheck contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ qcheck
2
+ Copyright 2026 qcheck contributors
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1 @@
1
+ qcheck