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

Compiler Validator Pass #79

Merged
merged 9 commits into from
Mar 21, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
10 changes: 10 additions & 0 deletions compiler/qsc_frontend/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::{
id::Assigner,
parse,
resolve::{self, GlobalTable, Resolutions},
validate::{self, validate},
};
use miette::Diagnostic;
use qsc_ast::{
Expand Down Expand Up @@ -87,6 +88,7 @@ pub struct Error(ErrorKind);
enum ErrorKind {
Parse(OffsetError<parse::Error>),
Resolve(resolve::Error),
Validate(validate::Error),
}

#[derive(Default)]
Expand Down Expand Up @@ -144,17 +146,25 @@ pub fn compile(
entry_expr: &str,
) -> CompileUnit {
let (mut package, parse_errors, offsets) = parse_all(sources, entry_expr);

let mut assigner = Assigner::new();
assigner.visit_package(&mut package);
let (resolutions, resolve_errors) = resolve_all(store, dependencies, &package);

let validation_errors = validate(&package);

let mut errors = Vec::new();
errors.extend(parse_errors.into_iter().map(|e| Error(ErrorKind::Parse(e))));
errors.extend(
resolve_errors
.into_iter()
.map(|e| Error(ErrorKind::Resolve(e))),
);
errors.extend(
validation_errors
.into_iter()
.map(|e| Error(ErrorKind::Validate(e))),
);

CompileUnit {
package,
Expand Down
4 changes: 4 additions & 0 deletions compiler/qsc_frontend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ pub mod id;
mod lex;
mod parse;
pub mod resolve;
mod validate;

#[cfg(test)]
mod tests;
ScottCarda-MS marked this conversation as resolved.
Show resolved Hide resolved
73 changes: 73 additions & 0 deletions compiler/qsc_frontend/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::{parse::namespaces, validate::Validator};
use qsc_ast::visit::Visitor;

pub(super) fn check(input: &str) {
let (parsed, errs) = &mut namespaces(input);
assert!(errs.is_empty());
let validator = &mut Validator {};
parsed
.iter_mut()
.for_each(|ns| validator.visit_namespace(ns));
}

#[test]
#[should_panic(expected = "Callable parameters must be type annotated.")]
swernli marked this conversation as resolved.
Show resolved Hide resolved
fn test_untyped_params() {
check("namespace input { operation Foo(a, b, c) : Unit {} }");
}

#[test]
#[should_panic(expected = "Callable parameters must be type annotated.")]
fn test_untyped_nested_params() {
check("namespace input { operation Foo(a : Int, (b : Int, c), d : Int) : Unit {} }");
}

#[test]
#[should_panic(expected = "Callables as parameters are not currently supported.")]
fn test_callable_params() {
check("namespace input { operation Foo(a : Int -> Int) : Unit {} }");
}

#[test]
#[should_panic(expected = "Callables as parameters are not currently supported.")]
fn test_callable_nested_params() {
check(
"namespace input { operation Foo(a : Int, (b : Int, c : Int => Int), d : Int) : Unit {} }",
);
}

#[test]
#[should_panic(expected = "Adjointable and Controllable Operations must return Unit.")]
fn test_adj_return_int() {
check("namespace input { operation Foo() : Int is Adj {} }");
}

#[test]
#[should_panic(expected = "Adjointable and Controllable Operations must return Unit.")]
fn test_ctl_return_int() {
check("namespace input { operation Foo() : Int is Ctl {} }");
}

#[test]
#[should_panic(expected = "Lambdas are not currently supported.")]
fn test_lambda() {
check("namespace input { operation Foo() : Int { let lambda = (x, y) -> x + y; return lambda(1, 2); } }");
}

#[test]
#[should_panic(expected = "Partial applications are not currently supported.")]
fn test_partial() {
check(
r#"
namespace input {
operation Foo(x : Int, y : Int) : Unit {}
operation Bar() : Unit {
let foo = Foo(_, 2);
foo(1);
}
}"#,
);
}
108 changes: 108 additions & 0 deletions compiler/qsc_frontend/src/validate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use miette::Diagnostic;
use qsc_ast::{
ast::{CallableDecl, CallableKind, Expr, ExprKind, Package, Pat, Span, Ty, TyKind},
visit::{walk_callable_decl, walk_expr, Visitor},
};
use thiserror::Error;

#[derive(Clone, Debug, Diagnostic, Error)]
pub(super) enum Error {
#[error("adjointable/controllable operation `{0}` must return Unit")]
NonUnitReturn(String, #[label("must return Unit")] Span),

#[error("callable parameter `{0}` must be type annotated")]
ParameterNotTyped(String, #[label("missing type annotation")] Span),

#[error("{0} are not currently supported")]
NotCurrentlySupported(&'static str, #[label("not currently supported")] Span),
}

pub(super) fn validate(package: &Package) -> Vec<Error> {
let mut validator = Validator {
validation_errors: Vec::new(),
};
validator.visit_package(package);
validator.validation_errors
}

struct Validator {
validation_errors: Vec<Error>,
}

impl Validator {
fn validate_params(&mut self, params: &Pat) {
match &params.kind {
qsc_ast::ast::PatKind::Bind(id, ty) => match &ty {
None => self
.validation_errors
.push(Error::ParameterNotTyped(id.name.clone(), params.span)),
Some(t) => self.validate_type(t, params.span),
},
qsc_ast::ast::PatKind::Paren(item) => self.validate_params(item),
qsc_ast::ast::PatKind::Tuple(items) => {
items.iter().for_each(|i| self.validate_params(i));
}
_ => {}
}
}

fn validate_type(&mut self, ty: &Ty, span: Span) {
match &ty.kind {
TyKind::App(ty, tys) => {
self.validate_type(ty, span);
tys.iter().for_each(|t| self.validate_type(t, span));
}
TyKind::Arrow(_, _, _, _) => self.validation_errors.push(Error::NotCurrentlySupported(
"callables as parameters",
span,
)),
TyKind::Paren(ty) => self.validate_type(ty, span),
TyKind::Tuple(tys) => tys.iter().for_each(|t| self.validate_type(t, span)),
_ => {}
}
}
}

impl<'a> Visitor<'a> for Validator {
fn visit_callable_decl(&mut self, decl: &'a CallableDecl) {
if CallableKind::Operation == decl.kind && decl.functors.is_some() {
match &decl.output.kind {
TyKind::Tuple(items) if items.is_empty() => {}
_ => {
self.validation_errors.push(Error::NonUnitReturn(
decl.name.name.clone(),
decl.output.span,
));
}
}
}

self.validate_params(&decl.input);
walk_callable_decl(self, decl);
}

fn visit_expr(&mut self, expr: &'a Expr) {
match &expr.kind {
ExprKind::Lambda(_, _, _) => self
.validation_errors
.push(Error::NotCurrentlySupported("lambdas", expr.span)),
ExprKind::Call(_, arg) if has_hole(arg) => self.validation_errors.push(
Error::NotCurrentlySupported("partial applications", expr.span),
),
_ => {}
};
walk_expr(self, expr);
}
}

fn has_hole(expr: &Expr) -> bool {
match &expr.kind {
ExprKind::Hole => true,
ExprKind::Paren(sub_expr) => has_hole(sub_expr),
ExprKind::Tuple(sub_exprs) => sub_exprs.iter().any(has_hole),
_ => false,
}
}