co9olguy / qdata

1 stars 3 forks source link

Parser now returns a QasmProgram object #8

Closed josh146 closed 4 years ago

josh146 commented 4 years ago

This PR completes the process of having the parser return a structured QasmProgram object. The serialization is now contained completely within the QasmProgram object.

Note: This PR merges into #7

Fixes #2

Example:

>>> from parser import qasm_parser, QASMToIRTransformer
>>> with open("example_data/example.qasm", "r") as f:
...     qasm_str = "".join(f.readlines())
>>> tree = qasm_parser.parse(qasm_str)
>>> prog = QASMToIRTransformer().transform(tree)
>>> print(tree)
<QasmProgram: version=2.0>
>>> print(tree.serialize())
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg c[3];
gate p(lambda) q
{
        U(0,0,lambda/2) q;
}
rx(0.5139579386183292) q[0];
rx(0.6455803303572194) q[1];
rx(0.11260132213935614) q[2];
cx q[0],q[1];
cx q[1],q[2];
cx q[2],q[0];
rx(0.192503855821187) q[0];
rx(0.32684939912569166) q[1];
rx(0.7591596781480794) q[2];
cx q[0],q[1];
cx q[1],q[2];
cx q[2],q[0];
rx(0.192503855821187) q[0];
rx(0.32684939912569166) q[1];
rx(0.7591596781480794) q[2];
cx q[0],q[1];
cx q[1],q[2];
cx q[2],q[0];
h q[0];
z q[2];
s q[2];
h q[2];
measure ['q', 0],['c', 0];
measure ['q', 1],['c', 1];
measure ['q', 2],['c', 2];

The produced QasmProgram objects contains a nested list of statements, with statements being either declarations, operations, etc, or even another QasmProgram in the case of the include statement.

You can even serialize the full program inserting any included files, via prog.serialize(insert_includes=True).