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

Add default RustIrDatabase::*_name impls #575

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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: 7 additions & 3 deletions chalk-integration/src/interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use crate::tls;
use chalk_ir::interner::{HasInterner, Interner};
use chalk_ir::{
AdtId, AliasTy, ApplicationTy, AssocTypeId, CanonicalVarKind, CanonicalVarKinds, ConstData,
Constraint, Goals, InEnvironment, Lifetime, OpaqueTy, OpaqueTyId, ProgramClauseImplication,
ProgramClauses, ProjectionTy, QuantifiedWhereClauses, SeparatorTraitRef, Substitution, TraitId,
Ty, VariableKind, VariableKinds,
Constraint, FnDefId, Goals, InEnvironment, Lifetime, OpaqueTy, OpaqueTyId,
ProgramClauseImplication, ProgramClauses, ProjectionTy, QuantifiedWhereClauses,
SeparatorTraitRef, Substitution, TraitId, Ty, VariableKind, VariableKinds,
};
use chalk_ir::{
GenericArg, GenericArgData, Goal, GoalData, LifetimeData, ProgramClause, ProgramClauseData,
Expand Down Expand Up @@ -87,6 +87,10 @@ impl Interner for ChalkIr {
tls::with_current_program(|prog| Some(prog?.debug_opaque_ty_id(id, fmt)))
}

fn debug_fn_def_id(id: FnDefId<Self>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
tls::with_current_program(|prog| Some(prog?.debug_fn_def_id(id, fmt)))
}

fn debug_alias(alias: &AliasTy<ChalkIr>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
tls::with_current_program(|prog| Some(prog?.debug_alias(alias, fmt)))
}
Expand Down
44 changes: 22 additions & 22 deletions chalk-integration/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ impl tls::DebugContext for Program {
if let Some(d) = self.associated_ty_data.get(&assoc_type_id) {
write!(fmt, "({:?}::{})", d.trait_id, d.name)
} else {
fmt.debug_struct("InvalidItemId")
fmt.debug_struct("InvalidAssocTypeId")
.field("index", &assoc_type_id.0)
.finish()
}
Expand All @@ -153,12 +153,26 @@ impl tls::DebugContext for Program {
if let Some(k) = self.opaque_ty_kinds.get(&opaque_ty_id) {
write!(fmt, "{}", k.name)
} else {
fmt.debug_struct("InvalidItemId")
fmt.debug_struct("InvalidOpaqueTyId")
.field("index", &opaque_ty_id.0)
.finish()
}
}

fn debug_fn_def_id(
&self,
fn_def_id: FnDefId<ChalkIr>,
fmt: &mut fmt::Formatter<'_>,
) -> Result<(), fmt::Error> {
if let Some(k) = self.fn_def_kinds.get(&fn_def_id) {
write!(fmt, "{}", k.name)
} else {
fmt.debug_struct("InvalidFnDefId")
.field("index", &fn_def_id.0)
.finish()
}
}

fn debug_alias(
&self,
alias_ty: &AliasTy<ChalkIr>,
Expand Down Expand Up @@ -471,31 +485,17 @@ impl RustIrDatabase<ChalkIr> for Program {
substs.clone()
}

fn trait_name(&self, trait_id: TraitId<ChalkIr>) -> String {
self.trait_kinds.get(&trait_id).unwrap().name.to_string()
}

fn adt_name(&self, struct_id: AdtId<ChalkIr>) -> String {
self.adt_kinds.get(&struct_id).unwrap().name.to_string()
}

// The default implementation for `RustIrDatabase::assoc_type_name` outputs
// the name in the format `(Trait::AssocTypeName)`, which is reformatted to
// `_Trait__AssocTypeName_`. This doesn't match the input names, which is
// normally acceptable, but causes the re-parse tests for the .chalk syntax
// writer to fail. This is because they use the `Eq` implementation on
// Program, which checks for name equality.
Comment on lines +488 to +493
Copy link
Member

Choose a reason for hiding this comment

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

If the Trait::AssocTypeName output is (mostly) valid, maybe the formatting can be skipped for assoc_type_name?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The display test suite currently relies on exact name equality, so we need to do something to get the assoc_type_name type name output to exactly match the input.

One alternative would be to make a RustIrDatabase wrapper for Program which just overwrites assoc_type_name, but I'm not sure that would be worth it. Especially since having this one method overwrite also means that the debug printer can have fully exact names when printing output from the chalk command line, and this code is run in no other situations. At least to my knowledge, neither rustc nor rust-analyzer integration uses Program, right?

We could try to create a test equality that doesn't depend on names, but it would also be more effort - and I'm not sure we want to allow names to slip in those tests without us noticing. They're otherwise fairly exact output correctness tests.

fn assoc_type_name(&self, assoc_type_id: AssocTypeId<ChalkIr>) -> String {
self.associated_ty_data
.get(&assoc_type_id)
.unwrap()
.name
.to_string()
}

fn opaque_type_name(&self, opaque_ty_id: OpaqueTyId<ChalkIr>) -> String {
self.opaque_ty_kinds
.get(&opaque_ty_id)
.unwrap()
.name
.to_string()
}

fn fn_def_name(&self, fn_def_id: FnDefId<ChalkIr>) -> String {
self.fn_def_kinds.get(&fn_def_id).unwrap().name.to_string()
}
}
8 changes: 7 additions & 1 deletion chalk-integration/src/tls.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::interner::ChalkIr;
use chalk_ir::{
debug::SeparatorTraitRef, AdtId, AliasTy, ApplicationTy, AssocTypeId, CanonicalVarKinds,
GenericArg, Goal, Goals, Lifetime, OpaqueTy, OpaqueTyId, ProgramClause,
FnDefId, GenericArg, Goal, Goals, Lifetime, OpaqueTy, OpaqueTyId, ProgramClause,
ProgramClauseImplication, ProgramClauses, ProjectionTy, QuantifiedWhereClauses, Substitution,
TraitId, Ty, VariableKinds,
};
Expand Down Expand Up @@ -38,6 +38,12 @@ pub trait DebugContext {
fmt: &mut fmt::Formatter<'_>,
) -> Result<(), fmt::Error>;

fn debug_fn_def_id(
&self,
fn_def_id: FnDefId<ChalkIr>,
fmt: &mut fmt::Formatter<'_>,
) -> Result<(), fmt::Error>;

fn debug_alias(
&self,
alias: &AliasTy<ChalkIr>,
Expand Down
1 change: 1 addition & 0 deletions chalk-solve/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod ty;

pub use self::render_trait::*;
pub use self::state::*;
pub use self::utils::sanitize_debug_name;

use self::utils::as_display;

Expand Down
29 changes: 29 additions & 0 deletions chalk-solve/src/display/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,32 @@ macro_rules! write_joined_non_empty_list {
}
}};
}

/// Processes a name given by an [`Interner`][chalk_ir::Interner] debug
/// method into something usable by the `display` module.
///
/// This is specifically useful when implementing
/// [`RustIrDatabase`][crate::RustIrDatabase] `name_*` methods.
pub fn sanitize_debug_name(func: impl Fn(&mut Formatter<'_>) -> Option<Result>) -> String {
use std::fmt::Write;

// First, write the debug method contents to a String.
let mut debug_out = String::new();
// ignore if the result is `None`, as we can just as easily tell by looking
// to see if anything was written to `debug_out`.
write!(
debug_out,
"{}",
as_display(|fmt| { func(fmt).unwrap_or(Ok(())) })
)
.expect("expected writing to a String to succeed");
if debug_out.is_empty() {
return "Unknown".to_owned();
}

// now the actual sanitization
debug_out
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect()
detrumi marked this conversation as resolved.
Show resolved Hide resolved
}
55 changes: 44 additions & 11 deletions chalk-solve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,25 @@ pub mod solve;
pub mod split;
pub mod wf;

/// Trait representing access to a database of rust types.
///
/// # `*_name` methods
///
/// This trait has a number of `*_name` methods with default implementations.
/// These are used in the implementation for [`LoggingRustIrDatabase`], so that
/// when printing `.chalk` files equivalent to the data used, we can use real
/// names.
///
/// The default implementations simply fall back to calling [`Interner`] debug
/// methods, and printing `"UnknownN"` (where `N` is the demultiplexing integer)
/// if those methods return `None`.
///
/// The [`display::sanitize_debug_name`] utility is used in the default
/// implementations, and might be useful when providing custom implementations.
///
/// [`LoggingRustIrDatabase`]: crate::logging_db::LoggingRustIrDatabase
/// [`display::sanitize_debug_name`]: crate::display::sanitize_debug_name
/// [`Interner`]: Interner
pub trait RustIrDatabase<I: Interner>: Debug {
/// Returns any "custom program clauses" that do not derive from
/// Rust IR. Used only in testing the underlying solver.
Expand Down Expand Up @@ -144,21 +163,35 @@ pub trait RustIrDatabase<I: Interner>: Debug {
substs: &Substitution<I>,
) -> Substitution<I>;

/// Retrieves a trait's original name. No uniqueness guarantees.
/// TODO: remove this, use only interner debug methods
fn trait_name(&self, trait_id: TraitId<I>) -> String;
/// Retrieves a trait's original name. No uniqueness guarantees, but must
/// a valid Rust identifier.
fn trait_name(&self, trait_id: TraitId<I>) -> String {
crate::display::sanitize_debug_name(|f| I::debug_trait_id(trait_id, f))
detrumi marked this conversation as resolved.
Show resolved Hide resolved
}

/// Retrieves a struct's original name. No uniqueness guarantees.
fn adt_name(&self, struct_id: AdtId<I>) -> String;
/// Retrieves a struct's original name. No uniqueness guarantees, but must
/// a valid Rust identifier.
fn adt_name(&self, adt_id: AdtId<I>) -> String {
crate::display::sanitize_debug_name(|f| I::debug_adt_id(adt_id, f))
}

/// Retrieves the name of an associated type.
fn assoc_type_name(&self, assoc_ty_id: AssocTypeId<I>) -> String;
/// Retrieves the name of an associated type. No uniqueness guarantees, but must
/// a valid Rust identifier.
fn assoc_type_name(&self, assoc_ty_id: AssocTypeId<I>) -> String {
crate::display::sanitize_debug_name(|f| I::debug_assoc_type_id(assoc_ty_id, f))
}

/// Retrieves the name of an opaque type.
fn opaque_type_name(&self, opaque_ty_id: OpaqueTyId<I>) -> String;
/// Retrieves the name of an opaque type. No uniqueness guarantees, but must
/// a valid Rust identifier.
fn opaque_type_name(&self, opaque_ty_id: OpaqueTyId<I>) -> String {
crate::display::sanitize_debug_name(|f| I::debug_opaque_ty_id(opaque_ty_id, f))
}

/// Retrieves the name of a function definition
fn fn_def_name(&self, fn_def_id: FnDefId<I>) -> String;
/// Retrieves the name of a function definition. No uniqueness guarantees, but must
/// a valid Rust identifier.
fn fn_def_name(&self, fn_def_id: FnDefId<I>) -> String {
crate::display::sanitize_debug_name(|f| I::debug_fn_def_id(fn_def_id, f))
}
}

pub use clauses::program_clauses_for_env;
Expand Down
20 changes: 0 additions & 20 deletions tests/integration/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,26 +225,6 @@ impl RustIrDatabase<ChalkIr> for MockDatabase {
) -> Substitution<ChalkIr> {
unimplemented!()
}

fn trait_name(&self, trait_id: TraitId<ChalkIr>) -> String {
unimplemented!()
}

fn adt_name(&self, struct_id: AdtId<ChalkIr>) -> String {
unimplemented!()
}

fn assoc_type_name(&self, assoc_ty_id: AssocTypeId<ChalkIr>) -> String {
unimplemented!()
}

fn opaque_type_name(&self, opaque_ty_id: OpaqueTyId<ChalkIr>) -> String {
unimplemented!()
}

fn fn_def_name(&self, fn_def_id: FnDefId<ChalkIr>) -> String {
unimplemented!()
}
}

fn prepare_goal() -> UCanonical<InEnvironment<Goal<ChalkIr>>> {
Expand Down
12 changes: 6 additions & 6 deletions tests/logging_db/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ pub fn logging_db_output_sufficient(

let program = db.program_ir().unwrap();
let wrapped = LoggingRustIrDatabase::<_, Program, _>::new(program.clone());
for (goal_text, solver_choice, expected) in goals.clone() {
let mut solver: SolverImpl = solver_choice.into();
chalk_integration::tls::set_current_program(&program, || {
for (goal_text, solver_choice, expected) in goals.clone() {
let mut solver: SolverImpl = solver_choice.into();

chalk_integration::tls::set_current_program(&program, || {
println!("----------------------------------------------------------------------");
println!("---- first run on original test code ---------------------------------");
println!("goal {}", goal_text);
Expand All @@ -63,10 +63,10 @@ pub fn logging_db_output_sufficient(
}
_ => panic!("only aggregated test goals supported for logger goals"),
}
});
}
}

wrapped.to_string()
wrapped.to_string()
})
};

println!("----------------------------------------------------------------------");
Expand Down