Skip to content

Commit

Permalink
update checker and bump version
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanhill1 committed Sep 26, 2024
1 parent 30399ed commit b4f7118
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 40 deletions.
2 changes: 1 addition & 1 deletion qbraid_qir/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@
Version number (major.minor.patch[-label])
"""
__version__ = "0.2.3.dev"
__version__ = "0.2.3"
7 changes: 3 additions & 4 deletions qbraid_qir/qasm3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
:toctree: ../stubs/
qasm3_to_qir
validate_qasm
Classes
---------
Expand All @@ -31,7 +31,6 @@
Qasm3Module
BasicQasmVisitor
Exceptions
-----------
Expand All @@ -41,14 +40,14 @@
Qasm3ConversionError
"""
from .checker import semantic_check
from .checker import validate_qasm
from .convert import qasm3_to_qir
from .elements import Qasm3Module
from .exceptions import Qasm3ConversionError
from .visitor import BasicQasmVisitor

__all__ = [
"semantic_check",
"validate_qasm",
"qasm3_to_qir",
"Qasm3Module",
"Qasm3ConversionError",
Expand Down
44 changes: 18 additions & 26 deletions qbraid_qir/qasm3/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,53 +12,45 @@
Module containing OpenQASM semantic checker function
"""
from typing import Optional, Union
from typing import Union

import openqasm3
from openqasm3.parser import QASM3ParsingError
from pyqir import Context, qir_module

from .elements import Qasm3Module, generate_module_id
from .exceptions import Qasm3ConversionError
from .visitor import BasicQasmVisitor


def semantic_check(
program: Union[openqasm3.ast.Program, str],
name: Optional[str] = None,
**kwargs,
) -> None:
"""Validates a given OpenQASM 3 program for semantic correctness.
class QasmValidationError(Exception):
"""Exception raised when a QASM program fails validation."""

Args:
program (openqasm3.ast.Program or str): The OpenQASM 3 program to convert.
name (str, optional): Identifier for created QIR module. Auto-generated if not provided.

Keyword Args:
initialize_runtime (bool): Whether to perform quantum runtime environment initialization,
default `True`.
record_output (bool): Whether to record output calls for registers, default `True`
def validate_qasm(program: Union[openqasm3.ast.Program, str]) -> None:
"""Validates a given OpenQASM 3 program for semantic correctness.
Returns:
Optional[Exception]: None if the program is semantically correct, otherwise an exception.
Args:
program (openqasm3.ast.Program or str): The OpenQASM 3 program to validate.
Raises:
Exception: If the input is not a valid OpenQASM 3 program.
Qasm3ConversionError: If the program is semantically incorrect.
TypeError: If the input is not a string or an `openqasm3.ast.Program` instance.
QasmValidationError: If the program fails parsing or semantic validation.
"""
if isinstance(program, str):
program = openqasm3.parse(program)

try:
program = openqasm3.parse(program)
except QASM3ParsingError as err:
raise QasmValidationError(f"Failed to parse OpenQASM string: {err}") from err

Check warning on line 44 in qbraid_qir/qasm3/checker.py

View check run for this annotation

Codecov / codecov/patch

qbraid_qir/qasm3/checker.py#L43-L44

Added lines #L43 - L44 were not covered by tests
elif not isinstance(program, openqasm3.ast.Program):
raise TypeError("Input quantum program must be of type openqasm3.ast.Program or str.")

if name is None:
name = generate_module_id()
raise TypeError("Input quantum program must be of type 'str' or 'openqasm3.ast.Program'.")

name = generate_module_id()
llvm_module = qir_module(Context(), name)
module = Qasm3Module.from_program(program, llvm_module)

try:
visitor = BasicQasmVisitor(check_only=True, **kwargs)
visitor = BasicQasmVisitor(check_only=True)
module.accept(visitor)
except (Qasm3ConversionError, TypeError, ValueError) as err:
raise err
raise QasmValidationError(f"Semantic validation failed: {err}") from err
16 changes: 7 additions & 9 deletions tests/qasm3_qir/test_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,16 @@

import pytest

from qbraid_qir.qasm3.checker import semantic_check
from qbraid_qir.qasm3.exceptions import Qasm3ConversionError
from qbraid_qir.qasm3.checker import validate_qasm, QasmValidationError


def test_correct_check():
assert semantic_check("OPENQASM 3; include 'stdgates.inc'; qubit q;") is None
assert validate_qasm("OPENQASM 3; include 'stdgates.inc'; qubit q;") is None


def test_incorrect_check():
with pytest.raises(Qasm3ConversionError):
semantic_check(
with pytest.raises(QasmValidationError):
validate_qasm(
"""
//semantically incorrect program
OPENQASM 3;
Expand All @@ -35,13 +34,12 @@ def test_incorrect_check():
h q;
}
rx(3.14) q[2];
""",
name="test",
"""
)


def test_incorrect_program_type():
with pytest.raises(
TypeError, match="Input quantum program must be of type openqasm3.ast.Program or str."
TypeError, match="Input quantum program must be of type 'str' or 'openqasm3.ast.Program'."
):
semantic_check(1234)
validate_qasm(1234)

0 comments on commit b4f7118

Please sign in to comment.