Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap io::Error in QASM2ParseError on failed file read #9958

Merged
merged 1 commit into from
Apr 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion crates/qasm2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use pyo3::prelude::*;
use pyo3::Python;

use crate::error::QASM2ParseError;

mod bytecode;
mod error;
mod expr;
Expand Down Expand Up @@ -94,14 +96,22 @@ fn bytecode_from_string(
/// without loading the entire token and parse tree into memory at once.
#[pyfunction]
fn bytecode_from_file(
py: Python<'_>,
path: std::ffi::OsString,
include_path: Vec<std::path::PathBuf>,
custom_instructions: Vec<CustomInstruction>,
custom_classical: Vec<CustomClassical>,
strict: bool,
) -> PyResult<bytecode::BytecodeIterator> {
bytecode::BytecodeIterator::new(
lex::TokenStream::from_path(path, strict)?,
lex::TokenStream::from_path(&path, strict).map_err(|err| {
let exc = QASM2ParseError::new_err(format!(
"failed to read a token stream from file '{}'",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super minor nitpick, you don't want to start this with a capital f?

Suggested change
"failed to read a token stream from file '{}'",
"Failed to read a token stream from file '{}'",

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's actually what I originally typed, but it turns out that I started all my other error messages with lower-case letters, which matches Python's built-in style.

path.to_string_lossy()
));
exc.set_cause(py, Some(err.into()));
exc
})?,
include_path,
&custom_instructions,
&custom_classical,
Expand Down
5 changes: 5 additions & 0 deletions test/python/qasm2/test_parse_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ def test_eof(self, statement):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"):
qiskit.qasm2.loads(full)

def test_loading_directory(self):
"""Test that the correct error is raised when a file fails to open."""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"):
qiskit.qasm2.load(".")


class TestVersion(QiskitTestCase):
def test_invalid_version(self):
Expand Down