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

Implement unsafe trait support #128

Closed
wants to merge 6 commits into from
Closed
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
21 changes: 19 additions & 2 deletions crates/formality-check/src/impls.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::bail;

use fn_error_context::context;
use formality_prove::Env;
use formality_prove::{Env, Safety};
use formality_rust::{
grammar::{
AssociatedTy, AssociatedTyBoundData, AssociatedTyValue, AssociatedTyValueBoundData, Fn,
Expand All @@ -19,7 +19,7 @@ use formality_types::{
impl super::Check<'_> {
#[context("check_trait_impl({v:?})")]
pub(super) fn check_trait_impl(&self, v: &TraitImpl) -> Fallible<()> {
let TraitImpl { binder } = v;
let TraitImpl { binder, safety } = v;

let mut env = Env::default();

Expand All @@ -45,6 +45,8 @@ impl super::Check<'_> {
trait_items,
} = trait_decl.binder.instantiate_with(&trait_ref.parameters)?;

self.check_safety_matches(&trait_decl.safety, safety)?;

for impl_item in &impl_items {
self.check_trait_impl_item(&env, &where_clauses, &trait_items, impl_item)?;
}
Expand All @@ -71,6 +73,21 @@ impl super::Check<'_> {
Ok(())
}

/// Validate `unsafe trait` and `unsafe impl` line up
fn check_safety_matches(&self, trait_decl: &Safety, trait_impl: &Safety) -> Fallible<()> {
match trait_decl {
Safety::Safe => anyhow::ensure!(
matches!(trait_impl, Safety::Safe),
"implementing the trait is not `unsafe`"
),
Safety::Unsafe => anyhow::ensure!(
matches!(trait_impl, Safety::Unsafe),
"the trait requires an `unsafe impl` declaration"
),
}
Ok(())
}

fn check_trait_impl_item(
&self,
env: &Env,
Expand Down
6 changes: 5 additions & 1 deletion crates/formality-check/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ use formality_types::grammar::Fallible;
impl super::Check<'_> {
#[context("check_trait({:?})", t.id)]
pub(super) fn check_trait(&self, t: &Trait) -> Fallible<()> {
let Trait { id: _, binder } = t;
let Trait {
safety: _,
id: _,
binder,
} = t;
let mut env = Env::default();

let TraitBoundData {
Expand Down
76 changes: 73 additions & 3 deletions crates/formality-prove/src/decls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ use formality_macros::term;
use formality_types::{
cast::Upcast,
collections::Set,
derive_links::{DowncastTo, UpcastFrom},
fold::Fold,
grammar::{
AdtId, AliasName, AliasTy, Binder, Parameter, Predicate, Relation, TraitId, TraitRef, Ty,
Wc, Wcs, PR,
},
parse::{self, Parse},
set,
term::Term,
visit::Visit,
};

#[term]
Expand Down Expand Up @@ -95,8 +100,9 @@ impl Decls {
}
}

#[term(impl $binder)]
#[term($safety impl $binder)]
pub struct ImplDecl {
pub safety: Safety,
pub binder: Binder<ImplDeclBoundData>,
}

Expand All @@ -106,8 +112,9 @@ pub struct ImplDeclBoundData {
pub where_clause: Wcs,
}

#[term(impl $binder)]
#[term($safety impl $binder)]
pub struct NegImplDecl {
pub safety: Safety,
pub binder: Binder<NegImplDeclBoundData>,
}

Expand All @@ -117,8 +124,71 @@ pub struct NegImplDeclBoundData {
pub where_clause: Wcs,
}

#[term(trait $id $binder)]
/// Mark a trait or trait impl as `unsafe`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Safety {
Safe,
Unsafe,
}

// NOTE(yosh): `Debug` is currently used to print error messages with. In order
// to not print `safe impl` / `safe trait` where none is written, we leave the impl blank.
impl std::fmt::Debug for Safety {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Safe => write!(f, ""),
Self::Unsafe => write!(f, "unsafe"),
}
}
}

impl Term for Safety {}

impl DowncastTo<Self> for Safety {
fn downcast_to(&self) -> Option<Self> {
Some(Self::clone(self))
}
}

impl UpcastFrom<Self> for Safety {
fn upcast_from(term: Self) -> Self {
term
}
}

impl Fold for Safety {
fn substitute(&self, _substitution_fn: formality_types::fold::SubstitutionFn<'_>) -> Self {
self.clone()
}
}

impl Visit for Safety {
fn free_variables(&self) -> Vec<formality_types::grammar::Variable> {
vec![]
}

fn size(&self) -> usize {
1
}

fn assert_valid(&self) {}
}

impl Parse for Safety {
fn parse<'t>(
_scope: &formality_types::parse::Scope,
text0: &'t str,
) -> formality_types::parse::ParseResult<'t, Self> {
match parse::expect_optional_keyword("unsafe", text0) {
Some(text1) => Ok((Self::Unsafe, text1)),
None => Ok((Self::Safe, text0)),
}
}
}

#[term($safety trait $id $binder)]
pub struct TraitDecl {
pub safety: Safety,
pub id: TraitId,
pub binder: Binder<TraitDeclBoundData>,
}
Expand Down
10 changes: 7 additions & 3 deletions crates/formality-rust/src/grammar.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::sync::Arc;

use formality_macros::term;
use formality_prove::Safety;
use formality_types::{
cast::Upcast,
grammar::{
Expand Down Expand Up @@ -161,8 +162,9 @@ pub struct Variant {
pub fields: Vec<Field>,
}

#[term(trait $id $binder)]
#[term($safety trait $id $binder)]
pub struct Trait {
pub safety: Safety,
pub id: TraitId,
pub binder: TraitBinder<TraitBoundData>,
}
Expand Down Expand Up @@ -242,8 +244,9 @@ pub struct AssociatedTyBoundData {
pub where_clauses: Vec<WhereClause>,
}

#[term(impl $binder)]
#[term($safety impl $binder)]
pub struct TraitImpl {
pub safety: Safety,
pub binder: Binder<TraitImplBoundData>,
}

Expand All @@ -268,8 +271,9 @@ impl TraitImplBoundData {
}
}

#[term(impl $binder)]
#[term($safety impl $binder)]
pub struct NegTraitImpl {
pub safety: Safety,
pub binder: Binder<NegTraitImplBoundData>,
}

Expand Down
12 changes: 8 additions & 4 deletions crates/formality-rust/src/prove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl Crate {
self.items
.iter()
.flat_map(|item| match item {
CrateItem::Trait(Trait { id, binder }) => {
CrateItem::Trait(Trait { id, binder, safety }) => {
let (
vars,
TraitBoundData {
Expand All @@ -89,6 +89,7 @@ impl Crate {
},
) = binder.open();
Some(prove::TraitDecl {
safety: safety.clone(),
id: id.clone(),
binder: Binder::new(
&vars,
Expand All @@ -110,7 +111,7 @@ impl Crate {
self.items
.iter()
.flat_map(|item| match item {
CrateItem::TraitImpl(TraitImpl { binder }) => {
CrateItem::TraitImpl(TraitImpl { binder, safety }) => {
let (
vars,
TraitImplBoundData {
Expand All @@ -122,6 +123,7 @@ impl Crate {
},
) = binder.open();
Some(prove::ImplDecl {
safety: safety.clone(),
binder: Binder::new(
&vars,
prove::ImplDeclBoundData {
Expand All @@ -140,7 +142,7 @@ impl Crate {
self.items
.iter()
.flat_map(|item| match item {
CrateItem::NegTraitImpl(NegTraitImpl { binder }) => {
CrateItem::NegTraitImpl(NegTraitImpl { binder, safety }) => {
let (
vars,
NegTraitImplBoundData {
Expand All @@ -151,6 +153,7 @@ impl Crate {
},
) = binder.open();
Some(prove::NegImplDecl {
safety: safety.clone(),
binder: Binder::new(
&vars,
prove::NegImplDeclBoundData {
Expand All @@ -169,7 +172,7 @@ impl Crate {
self.items
.iter()
.flat_map(|item| match item {
CrateItem::TraitImpl(TraitImpl { binder }) => {
CrateItem::TraitImpl(TraitImpl { binder, safety: _ }) => {
let (
impl_vars,
TraitImplBoundData {
Expand Down Expand Up @@ -225,6 +228,7 @@ impl Crate {
.iter()
.flat_map(|item| match item {
CrateItem::Trait(Trait {
safety: _,
id: trait_id,
binder,
}) => {
Expand Down
9 changes: 9 additions & 0 deletions crates/formality-types/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,15 @@ pub fn expect_keyword<'t>(expected: &str, text0: &'t str) -> ParseResult<'t, ()>
}
}

/// Attempt to consume next identifier if it is equal to `expected`.
#[tracing::instrument(level = "trace", ret)]
pub fn expect_optional_keyword<'t>(expected: &str, text0: &'t str) -> Option<&'t str> {
match identifier(text0) {
Ok((ident, text1)) if &*ident == expected => Some(text1),
_ => None,
}
}

/// Reject next identifier if it is the given keyword. Consumes nothing.
#[tracing::instrument(level = "trace", ret)]
pub fn reject_keyword<'t>(expected: &str, text0: &'t str) -> ParseResult<'t, ()> {
Expand Down
10 changes: 5 additions & 5 deletions tests/coherence_orphan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ fn test_orphan_CoreTrait_for_CoreStruct_in_Foo() {
expect_test::expect![[r#"
Err(
Error {
context: "orphan_check(impl <> CoreTrait < > for (rigid (adt CoreStruct)) where [] { })",
context: "orphan_check( impl <> CoreTrait < > for (rigid (adt CoreStruct)) where [] { })",
source: "failed to prove {@ IsLocal(CoreTrait((rigid (adt CoreStruct))))} given {}, got {}",
},
)
Expand All @@ -31,7 +31,7 @@ fn test_orphan_neg_CoreTrait_for_CoreStruct_in_Foo() {
expect_test::expect![[r#"
Err(
Error {
context: "orphan_check_neg(impl <> ! CoreTrait < > for (rigid (adt CoreStruct)) where [] {})",
context: "orphan_check_neg( impl <> ! CoreTrait < > for (rigid (adt CoreStruct)) where [] {})",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm this is annoying :)

source: "failed to prove {@ IsLocal(CoreTrait((rigid (adt CoreStruct))))} given {}, got {}",
},
)
Expand All @@ -54,7 +54,7 @@ fn test_orphan_mirror_CoreStruct() {
expect_test::expect![[r#"
Err(
Error {
context: "orphan_check(impl <> CoreTrait < > for (alias (Mirror :: Assoc) (rigid (adt CoreStruct))) where [] { })",
context: "orphan_check( impl <> CoreTrait < > for (alias (Mirror :: Assoc) (rigid (adt CoreStruct))) where [] { })",
source: "failed to prove {@ IsLocal(CoreTrait((alias (Mirror :: Assoc) (rigid (adt CoreStruct)))))} given {}, got {}",
},
)
Expand Down Expand Up @@ -119,7 +119,7 @@ fn test_orphan_alias_to_unit() {
expect_test::expect![[r#"
Err(
Error {
context: "orphan_check(impl <> CoreTrait < > for (alias (Unit :: Assoc) (rigid (adt FooStruct))) where [] { })",
context: "orphan_check( impl <> CoreTrait < > for (alias (Unit :: Assoc) (rigid (adt FooStruct))) where [] { })",
source: "failed to prove {@ IsLocal(CoreTrait((alias (Unit :: Assoc) (rigid (adt FooStruct)))))} given {}, got {}",
},
)
Expand Down Expand Up @@ -150,7 +150,7 @@ fn test_orphan_uncovered_T() {
expect_test::expect![[r#"
Err(
Error {
context: "orphan_check(impl <ty> CoreTrait < (rigid (adt FooStruct)) > for ^ty0_0 where [] { })",
context: "orphan_check( impl <ty> CoreTrait < (rigid (adt FooStruct)) > for ^ty0_0 where [] { })",
source: "failed to prove {@ IsLocal(CoreTrait(!ty_1, (rigid (adt FooStruct))))} given {}, got {}",
},
)
Expand Down
Loading