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

Rollup of 6 pull requests #108890

Closed
wants to merge 16 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Session.vim
.project
.favorites.json
.settings/
.vs/

## Tool
.valgrindrc
Expand Down
10 changes: 2 additions & 8 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4669,15 +4669,9 @@ dependencies = [
name = "rustc_smir"
version = "0.0.0"
dependencies = [
"rustc_borrowck",
"rustc_driver",
"rustc_hir",
"rustc_interface",
"rustc_middle",
"rustc_mir_dataflow",
"rustc_mir_transform",
"rustc_serialize",
"rustc_trait_selection",
"rustc_span",
"tracing",
]

[[package]]
Expand Down
27 changes: 26 additions & 1 deletion compiler/rustc_builtin_macros/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use rustc_errors::Applicability;
use rustc_expand::base::*;
use rustc_session::Session;
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
use rustc_span::{FileNameDisplayPreference, Span};
use std::iter;
use thin_vec::{thin_vec, ThinVec};

Expand Down Expand Up @@ -231,6 +231,8 @@ pub fn expand_test_or_bench(
&item.ident,
));

let location_info = get_location_info(cx, &item);

let mut test_const = cx.item(
sp,
Ident::new(item.ident.name, sp),
Expand Down Expand Up @@ -280,6 +282,16 @@ pub fn expand_test_or_bench(
cx.expr_none(sp)
},
),
// source_file: <relative_path_of_source_file>
field("source_file", cx.expr_str(sp, location_info.0)),
// start_line: start line of the test fn identifier.
field("start_line", cx.expr_usize(sp, location_info.1)),
// start_col: start column of the test fn identifier.
field("start_col", cx.expr_usize(sp, location_info.2)),
// end_line: end line of the test fn identifier.
field("end_line", cx.expr_usize(sp, location_info.3)),
// end_col: end column of the test fn identifier.
field("end_col", cx.expr_usize(sp, location_info.4)),
// compile_fail: true | false
field("compile_fail", cx.expr_bool(sp, false)),
// no_run: true | false
Expand Down Expand Up @@ -364,6 +376,19 @@ pub fn expand_test_or_bench(
}
}

fn get_location_info(cx: &ExtCtxt<'_>, item: &ast::Item) -> (Symbol, usize, usize, usize, usize) {
let span = item.ident.span;
let (source_file, lo_line, lo_col, hi_line, hi_col) =
cx.sess.source_map().span_to_location_info(span);

let file_name = match source_file {
Some(sf) => sf.name.display(FileNameDisplayPreference::Local).to_string(),
None => "no-location".to_string(),
};

(Symbol::intern(&file_name), lo_line, lo_col, hi_line, hi_col)
}

fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String {
mod_path
.iter()
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_hir_analysis/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,10 @@ hir_analysis_pass_to_variadic_function = can't pass `{$ty}` to variadic function
.help = cast the value to `{$cast_ty}`

hir_analysis_cast_thin_pointer_to_fat_pointer = cannot cast thin pointer `{$expr_ty}` to fat pointer `{$cast_ty}`

hir_analysis_invalid_union_field =
field must implement `Copy` or be wrapped in `ManuallyDrop<...>` to be used in a union
.note = union fields must not have drop side-effects, which is currently enforced via either `Copy` or `ManuallyDrop<...>`

hir_analysis_invalid_union_field_sugg =
wrap the field type in `ManuallyDrop<...>`
32 changes: 11 additions & 21 deletions compiler/rustc_hir_analysis/src/check/check.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::check::intrinsicck::InlineAsmCtxt;
use crate::errors::LinkageType;
use crate::errors::{self, LinkageType};

use super::compare_impl_item::check_type_bounds;
use super::compare_impl_item::{compare_impl_method, compare_impl_ty};
Expand Down Expand Up @@ -114,9 +114,11 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b
allowed_union_field(*elem, tcx, param_env)
}
_ => {
// Fallback case: allow `ManuallyDrop` and things that are `Copy`.
// Fallback case: allow `ManuallyDrop` and things that are `Copy`,
// also no need to report an error if the type is unresolved.
ty.ty_adt_def().is_some_and(|adt_def| adt_def.is_manually_drop())
|| ty.is_copy_modulo_regions(tcx, param_env)
|| ty.references_error()
}
}
}
Expand All @@ -131,26 +133,14 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b
Some(Node::Field(field)) => (field.span, field.ty.span),
_ => unreachable!("mir field has to correspond to hir field"),
};
struct_span_err!(
tcx.sess,
tcx.sess.emit_err(errors::InvalidUnionField {
field_span,
E0740,
"unions cannot contain fields that may need dropping"
)
.note(
"a type is guaranteed not to need dropping \
when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type",
)
.multipart_suggestion_verbose(
"when the type does not implement `Copy`, \
wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
vec![
(ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
(ty_span.shrink_to_hi(), ">".into()),
],
Applicability::MaybeIncorrect,
)
.emit();
sugg: errors::InvalidUnionFieldSuggestion {
lo: ty_span.shrink_to_lo(),
hi: ty_span.shrink_to_hi(),
},
note: (),
});
return false;
} else if field_ty.needs_drop(tcx, param_env) {
// This should never happen. But we can get here e.g. in case of name resolution errors.
Expand Down
22 changes: 21 additions & 1 deletion compiler/rustc_hir_analysis/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use rustc_errors::{
error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler, IntoDiagnostic,
MultiSpan,
};
use rustc_macros::Diagnostic;
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_middle::ty::Ty;
use rustc_span::{symbol::Ident, Span, Symbol};

Expand Down Expand Up @@ -430,3 +430,23 @@ pub(crate) struct CastThinPointerToFatPointer<'tcx> {
pub expr_ty: Ty<'tcx>,
pub cast_ty: String,
}

#[derive(Diagnostic)]
#[diag(hir_analysis_invalid_union_field, code = "E0740")]
pub(crate) struct InvalidUnionField {
#[primary_span]
pub field_span: Span,
#[subdiagnostic]
pub sugg: InvalidUnionFieldSuggestion,
#[note]
pub note: (),
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(hir_analysis_invalid_union_field_sugg, applicability = "machine-applicable")]
pub(crate) struct InvalidUnionFieldSuggestion {
#[suggestion_part(code = "std::mem::ManuallyDrop<")]
pub lo: Span,
#[suggestion_part(code = ">")]
pub hi: Span,
}
19 changes: 3 additions & 16 deletions compiler/rustc_smir/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,12 @@ version = "0.0.0"
edition = "2021"

[dependencies]
rustc_borrowck = { path = "../rustc_borrowck", optional = true }
rustc_driver = { path = "../rustc_driver", optional = true }
rustc_hir = { path = "../rustc_hir", optional = true }
rustc_interface = { path = "../rustc_interface", optional = true }
rustc_middle = { path = "../rustc_middle", optional = true }
rustc_mir_dataflow = { path = "../rustc_mir_dataflow", optional = true }
rustc_mir_transform = { path = "../rustc_mir_transform", optional = true }
rustc_serialize = { path = "../rustc_serialize", optional = true }
rustc_trait_selection = { path = "../rustc_trait_selection", optional = true }
rustc_span = { path = "../rustc_span", optional = true }
tracing = "0.1"

[features]
default = [
"rustc_borrowck",
"rustc_driver",
"rustc_hir",
"rustc_interface",
"rustc_middle",
"rustc_mir_dataflow",
"rustc_mir_transform",
"rustc_serialize",
"rustc_trait_selection",
"rustc_span",
]
37 changes: 37 additions & 0 deletions compiler/rustc_smir/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,40 @@ git subtree pull --prefix=compiler/rustc_smir https://github.com/rust-lang/proje
Note: only ever sync to rustc from the project-stable-mir's `smir` branch. Do not sync with your own forks.

Then open a PR against rustc just like a regular PR.

## Stable MIR Design

The stable-mir will follow a similar approach to proc-macro2. It’s
implementation will eventually be broken down into two main crates:

- `stable_mir`: Public crate, to be published on crates.io, which will contain
the stable data structure as well as proxy APIs to make calls to the
compiler.
- `rustc_smir`: The compiler crate that will translate from internal MIR to
SMIR. This crate will also implement APIs that will be invoked by
stable-mir to query the compiler for more information.

This will help tools to communicate with the rust compiler via stable APIs. Tools will depend on
`stable_mir` crate, which will invoke the compiler using APIs defined in `rustc_smir`. I.e.:

```
┌──────────────────────────────────┐ ┌──────────────────────────────────┐
│ External Tool ┌──────────┐ │ │ ┌──────────┐ Rust Compiler │
│ │ │ │ │ │ │ │
│ │stable_mir| │ │ │rustc_smir│ │
│ │ │ ├──────────►| │ │ │
│ │ │ │◄──────────┤ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ └──────────┘ │ │ └──────────┘ │
└──────────────────────────────────┘ └──────────────────────────────────┘
```

More details can be found here:
https://hackmd.io/XhnYHKKuR6-LChhobvlT-g?view

For now, the code for these two crates are in separate modules of this crate.
The modules have the same name for simplicity. We also have a third module,
`rustc_internal` which will expose APIs and definitions that allow users to
gather information from internal MIR constructs that haven't been exposed in
the `stable_mir` module.
2 changes: 1 addition & 1 deletion compiler/rustc_smir/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2022-06-01"
channel = "nightly-2023-02-28"
components = [ "rustfmt", "rustc-dev" ]
8 changes: 4 additions & 4 deletions compiler/rustc_smir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
test(attr(allow(unused_variables), deny(warnings)))
)]
#![cfg_attr(not(feature = "default"), feature(rustc_private))]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]

pub mod mir;
pub mod rustc_internal;
pub mod stable_mir;

pub mod very_unstable;
// Make this module private for now since external users should not call these directly.
mod rustc_smir;
10 changes: 0 additions & 10 deletions compiler/rustc_smir/src/mir.rs

This file was deleted.

15 changes: 15 additions & 0 deletions compiler/rustc_smir/src/rustc_internal/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//! Module that implements the bridge between Stable MIR and internal compiler MIR.
//!
//! For that, we define APIs that will temporarily be public to 3P that exposes rustc internal APIs
//! until stable MIR is complete.

use crate::stable_mir;
pub use rustc_span::def_id::{CrateNum, DefId};

pub fn item_def_id(item: &stable_mir::CrateItem) -> DefId {
item.0
}

pub fn crate_num(item: &stable_mir::Crate) -> CrateNum {
item.id.into()
}
48 changes: 48 additions & 0 deletions compiler/rustc_smir/src/rustc_smir/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//! Module that implements what will become the rustc side of Stable MIR.
//!
//! This module is responsible for building Stable MIR components from internal components.
//!
//! This module is not intended to be invoked directly by users. It will eventually
//! become the public API of rustc that will be invoked by the `stable_mir` crate.
//!
//! For now, we are developing everything inside `rustc`, thus, we keep this module private.

use crate::stable_mir::{self};
use rustc_middle::ty::{tls::with, TyCtxt};
use rustc_span::def_id::{CrateNum, LOCAL_CRATE};
use tracing::debug;

/// Get information about the local crate.
pub fn local_crate() -> stable_mir::Crate {
with(|tcx| smir_crate(tcx, LOCAL_CRATE))
}

/// Retrieve a list of all external crates.
pub fn external_crates() -> Vec<stable_mir::Crate> {
with(|tcx| tcx.crates(()).iter().map(|crate_num| smir_crate(tcx, *crate_num)).collect())
}

/// Find a crate with the given name.
pub fn find_crate(name: &str) -> Option<stable_mir::Crate> {
with(|tcx| {
[LOCAL_CRATE].iter().chain(tcx.crates(()).iter()).find_map(|crate_num| {
let crate_name = tcx.crate_name(*crate_num).to_string();
(name == crate_name).then(|| smir_crate(tcx, *crate_num))
})
})
}

/// Retrieve all items of the local crate that have a MIR associated with them.
pub fn all_local_items() -> stable_mir::CrateItems {
with(|tcx| {
tcx.mir_keys(()).iter().map(|item| stable_mir::CrateItem(item.to_def_id())).collect()
})
}

/// Build a stable mir crate from a given crate number.
fn smir_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> stable_mir::Crate {
let crate_name = tcx.crate_name(crate_num).to_string();
let is_local = crate_num == LOCAL_CRATE;
debug!(?crate_name, ?crate_num, "smir_crate");
stable_mir::Crate { id: crate_num.into(), name: crate_name, is_local }
}
Loading