diff --git a/pip/qsharp/_qsharp.py b/pip/qsharp/_qsharp.py index 83b6d2a819..0face0728f 100644 --- a/pip/qsharp/_qsharp.py +++ b/pip/qsharp/_qsharp.py @@ -86,10 +86,22 @@ def compile(entry_expr): :param entry_expr: The Q# expression that will be used as the entrypoint for the program. + + :returns QirInputData: The compiled program. + + To get the QIR string from the compiled program, use `str()`. + + Example: + + .. code-block:: python + program = qsharp.compile("...") + with open('myfile.ll', 'w') as file: + file.write(str(program)) """ ll_str = get_interpreter().qir(entry_expr) return QirInputData("main", ll_str) + def estimate(entry_expr, params: Union[dict, List, EstimatorParams] = None) -> EstimatorResult: """ Estimates resources for Q# source code. @@ -112,6 +124,7 @@ def estimate(entry_expr, params: Union[dict, List, EstimatorParams] = None) -> E json.loads(get_interpreter().estimate(entry_expr, json.dumps(params))) ) + def dump_machine() -> StateDump: """ Returns the sparse state vector of the simulator as a StateDump object. @@ -140,3 +153,6 @@ def __init__(self, name: str, ll_str: str): # by the protocol and must remain unchanged. def _repr_qir_(self, **kwargs) -> bytes: return self._ll_str.encode("utf-8") + + def __str__(self) -> str: + return self._ll_str diff --git a/pip/tests/test_qsharp.py b/pip/tests/test_qsharp.py index 1b508a8472..a847629b80 100644 --- a/pip/tests/test_qsharp.py +++ b/pip/tests/test_qsharp.py @@ -32,6 +32,7 @@ def test_stdout_multiple_lines() -> None: assert f.getvalue() == "STATE:\n|0⟩: 1.0000+0.0000𝑖\nHello!\n" + def test_dump_machine() -> None: qsharp.init(target_profile=qsharp.TargetProfile.Full) qsharp.eval( @@ -58,3 +59,11 @@ def test_compile_qir_input_data() -> None: operation = qsharp.compile("Program()") qir = operation._repr_qir_() assert isinstance(qir, bytes) + + +def test_compile_qir_str() -> None: + qsharp.init(target_profile=qsharp.TargetProfile.Base) + qsharp.eval("operation Program() : Result { use q = Qubit(); return M(q) }") + operation = qsharp.compile("Program()") + qir = str(operation) + assert "define void @ENTRYPOINT__main()" in qir