openqasm 0.1.2

Parser and translator for OpenQASM 2.0
Documentation

This crate implements a parser, type-checker and translator for OpenQASM 2.0.

Parsing

The main interface for parsing is the parser::Parser struct, and this produces either a ast::Program or a list of parser::ParseErrors. Example Usage:

let mut cache = SourceCache::new();
let mut parser = Parser::new(&mut cache);
parser.parse_file("test.qasm");
parser.parse_source("
    OPENQASM 2.0;
    qreg a;
    creg b;
    cx a, b;
");

match parser.done().to_errors() {
    Ok(program) => ..., // do something with this
    Err(errors) => errors.print(&mut cache).unwrap()
}

Type-Checking

Once you have a Program, you can type-check it with the ast::Program::type_check method. This detects many types of errors before translation.

Example Usage:

let mut cache = SourceCache::new();
let program: Program = ...; // obtain a program somehow

if let Err(errors) = program.type_check().to_errors() {
    errors.print(&mut cache).unwrap();
}

Translating

There are three different interfaces for translating parsed programs into different formats:

  1. Linearize/GateWriter is the high-level interface, and converts a program to a linear list of primitive and opaque gates, computing all the parameters and substituting arguments.

  2. ProgramVisitor/ExprVisitor is the low-level interface, and just walks the AST, with user-defined callbacks for definitions, statements etc.

Example Usage:

let program = ...; // acquire a program from somewhere.
program.type_check().unwrap(); // make sure to type check.
let mut l = Linearize::new(...); // linearize into into someoutput.
l.visit_program(&program).unwrap();

Error Handling

Specific error types for each process (parsing, checking etc.) are provided. However, if you don't need to handle these individually, you can use GenericError trait and GenericError::to_errors to convert and Result<_, SomeSpecificError> into a generic Result<_, Errors> type. This can then be handled, printed or converted to a Report as detailed below.

Features

The ariadne feature is disabled by default and allows pretty-printing of errors using the ariadne crate by providing to_report functions on all error types, as well as Errors::eprint/print.

The pretty feature is disabled by default and allows pretty-printing of AST objects using the pretty crate. This will implement the pretty::Pretty trait on these objects, and also provides the to_pretty method to easily render to a string.

The serde feature is disabled by default and implements serde::Serialize and serde::Deserialize for all the AST types.