Skip to content

Compile annotations into attributes #2271

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

Merged
merged 7 commits into from
Apr 1, 2025
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
75 changes: 54 additions & 21 deletions compiler/qsc_qasm3/src/ast_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use qsc_ast::ast::{
use qsc_data_structures::span::Span;

use crate::{
parser::ast::list_from_iter,
parser::ast::{list_from_iter, List},
runtime::RuntimeFunctions,
stdlib::angle::Angle,
types::{ArrayDimensions, Complex},
Expand Down Expand Up @@ -1459,15 +1459,14 @@ pub(crate) fn build_end_stmt(span: Span) -> Stmt {
};

let kind = ExprKind::Fail(Box::new(message));
Stmt {
kind: Box::new(StmtKind::Expr(Box::new(Expr {
kind: Box::new(kind),
span,
..Default::default()
}))),

let expr = Expr {
kind: Box::new(kind),
span,
..Default::default()
}
};

build_stmt_semi_from_expr_with_span(expr, span)
}

pub(crate) fn build_index_expr(expr: Expr, index_expr: Expr, span: Span) -> Expr {
Expand All @@ -1484,19 +1483,6 @@ pub(crate) fn build_barrier_call(span: Span) -> Stmt {
build_stmt_semi_from_expr(expr)
}

pub(crate) fn build_attr(text: String, span: Span) -> Attr {
Attr {
id: NodeId::default(),
span,
name: Box::new(Ident {
name: Rc::from(text),
span,
..Default::default()
}),
arg: Box::new(create_unit_expr(span)),
}
}

pub(crate) fn build_gate_decl(
name: String,
cargs: Vec<(String, Ty, Pat)>,
Expand Down Expand Up @@ -1703,6 +1689,7 @@ pub(crate) fn build_function_or_operation(
return_type: Option<Ty>,
kind: CallableKind,
functors: Option<FunctorExpr>,
attrs: List<Attr>,
) -> Stmt {
let args = cargs
.into_iter()
Expand Down Expand Up @@ -1763,6 +1750,7 @@ pub(crate) fn build_function_or_operation(
let item = Item {
span: gate_span,
kind: Box::new(ast::ItemKind::Callable(Box::new(decl))),
attrs,
..Default::default()
};

Expand Down Expand Up @@ -1807,3 +1795,48 @@ fn build_idents(idents: &[&str]) -> Option<Box<[Ident]>> {
Some(idents.into())
}
}

pub(crate) fn build_attr<S>(name: S, value: Option<S>, span: Span) -> Attr
where
S: AsRef<str>,
{
let name = Box::new(Ident {
span,
name: name.as_ref().into(),
..Default::default()
});

let arg = if let Some(value) = value {
Box::new(Expr {
span,
kind: Box::new(ExprKind::Paren(Box::new(Expr {
span,
kind: Box::new(ExprKind::Path(PathKind::Ok(Box::new(Path {
id: Default::default(),
span,
segments: None,
name: Box::new(Ident {
span,
name: value.as_ref().into(),
..Default::default()
}),
})))),
id: Default::default(),
}))),
id: Default::default(),
})
} else {
Box::new(Expr {
span,
kind: Box::new(ExprKind::Tuple(Box::default())),
id: Default::default(),
})
};

Attr {
span,
name,
arg,
id: Default::default(),
}
}
2 changes: 1 addition & 1 deletion compiler/qsc_qasm3/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ impl QasmCompiler {
let span = span_for_syntax_node(stmt.syntax());
if let "@SimulatableIntrinsic" = text.as_str() {
let (_at, name) = text.split_at(1);
Some(build_attr(name.to_string(), span))
Some(build_attr(name.to_string(), None, span))
} else {
let span = span_for_syntax_node(stmt.syntax());
let kind = SemanticErrorKind::UnknownAnnotation(text.to_string(), span);
Expand Down
82 changes: 64 additions & 18 deletions compiler/qsc_qasm3/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ use qsc_frontend::{compile::SourceMap, error::WithSource};
use crate::{
ast_builder::{
build_adj_plus_ctl_functor, build_arg_pat, build_array_reverse_expr,
build_assignment_statement, build_barrier_call, build_binary_expr, build_call_no_params,
build_call_with_param, build_call_with_params, build_cast_call_by_name,
build_classical_decl, build_complex_from_expr, build_convert_call_expr,
build_expr_array_expr, build_for_stmt, build_function_or_operation,
build_gate_call_param_expr, build_gate_call_with_params_and_callee,
build_global_call_with_two_params, build_if_expr_then_block,
build_if_expr_then_block_else_block, build_if_expr_then_block_else_expr,
build_if_expr_then_expr_else_expr, build_implicit_return_stmt,
build_indexed_assignment_statement, build_lit_angle_expr, build_lit_bigint_expr,
build_lit_bool_expr, build_lit_complex_expr, build_lit_double_expr, build_lit_int_expr,
build_lit_result_array_expr_from_bitstring, build_lit_result_expr,
build_assignment_statement, build_attr, build_barrier_call, build_binary_expr,
build_call_no_params, build_call_with_param, build_call_with_params,
build_cast_call_by_name, build_classical_decl, build_complex_from_expr,
build_convert_call_expr, build_end_stmt, build_expr_array_expr, build_for_stmt,
build_function_or_operation, build_gate_call_param_expr,
build_gate_call_with_params_and_callee, build_global_call_with_two_params,
build_if_expr_then_block, build_if_expr_then_block_else_block,
build_if_expr_then_block_else_expr, build_if_expr_then_expr_else_expr,
build_implicit_return_stmt, build_indexed_assignment_statement, build_lit_angle_expr,
build_lit_bigint_expr, build_lit_bool_expr, build_lit_complex_expr, build_lit_double_expr,
build_lit_int_expr, build_lit_result_array_expr_from_bitstring, build_lit_result_expr,
build_managed_qubit_alloc, build_math_call_from_exprs, build_math_call_no_params,
build_measure_call, build_operation_with_stmts, build_path_ident_expr,
build_qasm_import_decl, build_qasm_import_items, build_range_expr, build_reset_call,
Expand Down Expand Up @@ -379,6 +379,19 @@ impl QasmCompiler {
}

fn compile_stmt(&mut self, stmt: &crate::semantic::ast::Stmt) -> Option<qsast::Stmt> {
if !stmt.annotations.is_empty()
&& !matches!(
stmt.kind.as_ref(),
semast::StmtKind::QuantumGateDefinition(..) | semast::StmtKind::Def(..)
)
{
for annotation in &stmt.annotations {
self.push_semantic_error(SemanticErrorKind::InvalidAnnotationTarget(
annotation.span,
));
}
}

match stmt.kind.as_ref() {
semast::StmtKind::Alias(stmt) => self.compile_alias_decl_stmt(stmt),
semast::StmtKind::Assign(stmt) => self.compile_assign_stmt(stmt),
Expand All @@ -391,10 +404,10 @@ impl QasmCompiler {
self.compile_calibration_grammar_stmt(stmt)
}
semast::StmtKind::ClassicalDecl(stmt) => self.compile_classical_decl(stmt),
semast::StmtKind::Def(stmt) => self.compile_def_stmt(stmt),
semast::StmtKind::Def(def_stmt) => self.compile_def_stmt(def_stmt, &stmt.annotations),
semast::StmtKind::DefCal(stmt) => self.compile_def_cal_stmt(stmt),
semast::StmtKind::Delay(stmt) => self.compile_delay_stmt(stmt),
semast::StmtKind::End(stmt) => self.compile_end_stmt(stmt),
semast::StmtKind::End(stmt) => Self::compile_end_stmt(stmt),
semast::StmtKind::ExprStmt(stmt) => self.compile_expr_stmt(stmt),
semast::StmtKind::ExternDecl(stmt) => self.compile_extern_stmt(stmt),
semast::StmtKind::For(stmt) => self.compile_for_stmt(stmt),
Expand All @@ -405,7 +418,9 @@ impl QasmCompiler {
semast::StmtKind::OutputDeclaration(stmt) => self.compile_output_decl_stmt(stmt),
semast::StmtKind::MeasureArrow(stmt) => self.compile_measure_stmt(stmt),
semast::StmtKind::Pragma(stmt) => self.compile_pragma_stmt(stmt),
semast::StmtKind::QuantumGateDefinition(stmt) => self.compile_gate_decl_stmt(stmt),
semast::StmtKind::QuantumGateDefinition(gate_stmt) => {
self.compile_gate_decl_stmt(gate_stmt, &stmt.annotations)
}
semast::StmtKind::QubitDecl(stmt) => self.compile_qubit_decl_stmt(stmt),
semast::StmtKind::QubitArrayDecl(stmt) => self.compile_qubit_array_decl_stmt(stmt),
semast::StmtKind::Reset(stmt) => self.compile_reset_stmt(stmt),
Expand Down Expand Up @@ -600,7 +615,11 @@ impl QasmCompiler {
Some(stmt)
}

fn compile_def_stmt(&mut self, stmt: &semast::DefStmt) -> Option<qsast::Stmt> {
fn compile_def_stmt(
&mut self,
stmt: &semast::DefStmt,
annotations: &List<semast::Annotation>,
) -> Option<qsast::Stmt> {
let symbol = self.symbols[stmt.symbol_id].clone();
let name = symbol.name.clone();

Expand All @@ -627,6 +646,10 @@ impl QasmCompiler {
qsast::CallableKind::Function
};

let attrs = annotations
.iter()
.filter_map(|annotation| self.compile_annotation(annotation));

// We use the same primitives used for declaring gates, because def declarations
// in QASM3 can take qubits as arguments and call quantum gates.
Some(build_function_or_operation(
Expand All @@ -640,6 +663,7 @@ impl QasmCompiler {
return_type,
kind,
None,
list_from_iter(attrs),
))
}

Expand All @@ -653,9 +677,8 @@ impl QasmCompiler {
None
}

fn compile_end_stmt(&mut self, stmt: &semast::EndStmt) -> Option<qsast::Stmt> {
self.push_unimplemented_error_message("end statements", stmt.span);
None
fn compile_end_stmt(stmt: &semast::EndStmt) -> Option<qsast::Stmt> {
Some(build_end_stmt(stmt.span))
}

fn compile_expr_stmt(&mut self, stmt: &semast::ExprStmt) -> Option<qsast::Stmt> {
Expand Down Expand Up @@ -866,6 +889,7 @@ impl QasmCompiler {
fn compile_gate_decl_stmt(
&mut self,
stmt: &semast::QuantumGateDefinition,
annotations: &List<semast::Annotation>,
) -> Option<qsast::Stmt> {
let symbol = self.symbols[stmt.symbol_id].clone();
let name = symbol.name.clone();
Expand Down Expand Up @@ -902,6 +926,10 @@ impl QasmCompiler {

let body = Some(self.compile_block(&stmt.body));

let attrs = annotations
.iter()
.filter_map(|annotation| self.compile_annotation(annotation));

Some(build_function_or_operation(
name,
cargs,
Expand All @@ -913,9 +941,27 @@ impl QasmCompiler {
None,
qsast::CallableKind::Operation,
Some(build_adj_plus_ctl_functor()),
list_from_iter(attrs),
))
}

fn compile_annotation(&mut self, annotation: &semast::Annotation) -> Option<qsast::Attr> {
match annotation.identifier.as_ref() {
"SimulatableIntrinsic" | "Config" => Some(build_attr(
&annotation.identifier,
annotation.value.as_ref(),
annotation.span,
)),
_ => {
self.push_semantic_error(SemanticErrorKind::UnknownAnnotation(
format!("@{}", annotation.identifier),
annotation.span,
));
None
}
}
}

fn compile_qubit_decl_stmt(&mut self, stmt: &semast::QubitDeclaration) -> Option<qsast::Stmt> {
let symbol = self.symbols[stmt.symbol_id].clone();
let name = &symbol.name;
Expand Down
2 changes: 1 addition & 1 deletion compiler/qsc_qasm3/src/parser/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ pub enum ErrorKind {
#[error("Empty statements are not supported")]
#[diagnostic(code("Qasm3.Parse.EmptyStatement"))]
EmptyStatement(#[label] Span),
#[error("expected statement after annotation")]
#[error("Annotation missing target statement.")]
#[diagnostic(code("Qasm3.Parse.FloatingAnnotation"))]
FloatingAnnotation(#[label] Span),
#[error("expected {0}, found {1}")]
Expand Down
15 changes: 10 additions & 5 deletions compiler/qsc_qasm3/src/parser/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,16 @@ pub(super) fn parse(s: &mut ParserContext) -> Result<Stmt> {
} else if let Some(stmt) = opt(s, parse_measure_stmt)? {
StmtKind::Measure(stmt)
} else {
return Err(Error::new(ErrorKind::Rule(
"statement",
s.peek().kind,
s.peek().span,
)));
return if attrs.is_empty() {
Err(Error::new(ErrorKind::Rule(
"statement",
s.peek().kind,
s.peek().span,
)))
} else {
let span = attrs.last().expect("there is at least one annotation").span;
Err(Error::new(ErrorKind::FloatingAnnotation(span)))
};
};

Ok(Stmt {
Expand Down
2 changes: 1 addition & 1 deletion compiler/qsc_qasm3/src/semantic/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub enum SemanticErrorKind {
#[error("Indexed must be a single expression.")]
#[diagnostic(code("Qsc.Qasm3.Compile.IndexMustBeSingleExpr"))]
IndexMustBeSingleExpr(#[label] Span),
#[error("Annotations only valid on gate definitions.")]
#[error("Annotations only valid on def and gate statements.")]
#[diagnostic(code("Qsc.Qasm3.Compile.InvalidAnnotationTarget"))]
InvalidAnnotationTarget(#[label] Span),
#[error("Assigning {0} values to {1} must be in a range that be converted to {1}.")]
Expand Down
Loading
Loading