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 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
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
1 change: 1 addition & 0 deletions compiler/qsc_frontend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ pub mod id;
mod lex;
mod parse;
pub mod resolve;
mod validate;
119 changes: 119 additions & 0 deletions compiler/qsc_frontend/src/validate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#[cfg(test)]
mod tests;

use miette::Diagnostic;
use qsc_ast::{
ast::{CallableDecl, CallableKind, Expr, ExprKind, Package, Pat, Span, Ty, TyKind},
visit::{walk_callable_decl, walk_expr, walk_ty, 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 visit_ty(&mut self, ty: &'a Ty) {
if let TyKind::Hole = ty.kind {
self.validation_errors
.push(Error::NotCurrentlySupported("type holes", ty.span));
}

walk_ty(self, ty);
}
}

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,
}
}
231 changes: 231 additions & 0 deletions compiler/qsc_frontend/src/validate/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::{parse::namespaces, validate::Validator};
use expect_test::{expect, Expect};
use indoc::indoc;
use qsc_ast::{ast::Namespace, visit::Visitor};

use super::Error;

fn check(input: &str, expect: &Expect) {
let (parsed, errs) = &mut namespaces(input);
assert!(errs.is_empty());
let errs: Vec<Error> = parsed.iter().flat_map(validate).collect();
expect.assert_debug_eq(&errs);
}

fn validate(ns: &Namespace) -> Vec<Error> {
let mut validator = Validator {
validation_errors: Vec::new(),
};
validator.visit_namespace(ns);
validator.validation_errors
}

#[test]
fn test_untyped_params() {
check(
"namespace input { operation Foo(a, b, c) : Unit {} }",
&expect![[r#"
[
ParameterNotTyped(
"a",
Span {
lo: 32,
hi: 33,
},
),
ParameterNotTyped(
"b",
Span {
lo: 35,
hi: 36,
},
),
ParameterNotTyped(
"c",
Span {
lo: 38,
hi: 39,
},
),
]
"#]],
);
}

#[test]
fn test_untyped_nested_params() {
check(
"namespace input { operation Foo(a : Int, (b : Int, c), d : Int) : Unit {} }",
&expect![[r#"
[
ParameterNotTyped(
"c",
Span {
lo: 51,
hi: 52,
},
),
]
"#]],
);
}

#[test]
fn test_callable_params() {
check(
"namespace input { operation Foo(a : Int -> Int) : Unit {} }",
&expect![[r#"
[
NotCurrentlySupported(
"callables as parameters",
Span {
lo: 32,
hi: 46,
},
),
]
"#]],
);
}

#[test]
fn test_callable_nested_params() {
check(
"namespace input { operation Foo(a : Int, (b : Int, c : Int => Int), d : Int) : Unit {} }",
&expect![[r#"
[
NotCurrentlySupported(
"callables as parameters",
Span {
lo: 51,
hi: 65,
},
),
]
"#]],
);
}

#[test]
fn test_adj_return_int() {
check(
"namespace input { operation Foo() : Int is Adj {} }",
&expect![[r#"
[
NonUnitReturn(
"Foo",
Span {
lo: 36,
hi: 39,
},
),
]
"#]],
);
}

#[test]
fn test_ctl_return_int() {
check(
"namespace input { operation Foo() : Int is Ctl {} }",
&expect![[r#"
[
NonUnitReturn(
"Foo",
Span {
lo: 36,
hi: 39,
},
),
]
"#]],
);
}

#[test]
fn test_lambda() {
check("namespace input { operation Foo() : Int { let lambda = (x, y) -> x + y; return lambda(1, 2); } }",
&expect![[r#"
[
NotCurrentlySupported(
"lambdas",
Span {
lo: 55,
hi: 70,
},
),
]
"#]],);
}

#[test]
fn test_partial() {
check(
indoc! {"
namespace input {
operation Foo(x : Int, y : Int) : Unit {}
operation Bar() : Unit {
let foo = Foo(_, 2);
foo(1);
}
}
"},
&expect![[r#"
[
NotCurrentlySupported(
"partial applications",
Span {
lo: 111,
hi: 120,
},
),
]
"#]],
);
}

#[test]
fn test_type_hole_param() {
check(
"namespace input { operation Foo(a : Int, b : _) : Unit { return b; } }",
&expect![[r#"
[
NotCurrentlySupported(
"type holes",
Span {
lo: 45,
hi: 46,
},
),
]
"#]],
);
}

#[test]
fn test_nested_type_hole_param() {
check(
indoc! {"
namespace input {
operation Foo(a : Int, b : (Int, _, Double)) : Unit {
let (_, x, _) = b;
return x;
}
}
"},
&expect![[r#"
[
NotCurrentlySupported(
"type holes",
Span {
lo: 55,
hi: 56,
},
),
]
"#]],
);
}