Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

232 lines
8.8 KiB
Rust
Raw Normal View History

use rustc_ast::entry::EntryPointType;
use rustc_errors::struct_span_err;
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::itemlikevisit::ItemLikeVisitor;
2021-12-05 13:07:51 +01:00
use rustc_hir::{ForeignItem, ImplItem, Item, ItemKind, Node, TraitItem, CRATE_HIR_ID};
2020-03-29 17:19:48 +02:00
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{DefIdTree, TyCtxt};
use rustc_session::config::{CrateType, EntryFnType};
use rustc_session::parse::feature_err;
use rustc_session::Session;
2020-01-01 19:30:57 +01:00
use rustc_span::symbol::sym;
use rustc_span::{Span, DUMMY_SP};
struct EntryContext<'tcx> {
tcx: TyCtxt<'tcx>,
/// The function that has attribute named `main`.
2021-12-05 13:07:51 +01:00
attr_main_fn: Option<(LocalDefId, Span)>,
/// The function that has the attribute 'start' on it.
2021-12-05 13:07:51 +01:00
start_fn: Option<(LocalDefId, Span)>,
/// The functions that one might think are `main` but aren't, e.g.
/// main functions not defined at the top level. For diagnostics.
2021-12-05 13:07:51 +01:00
non_main_fns: Vec<Span>,
}
impl<'tcx> ItemLikeVisitor<'tcx> for EntryContext<'tcx> {
2019-11-28 19:28:50 +01:00
fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
let at_root = self.tcx.opt_local_parent(item.def_id) == Some(CRATE_DEF_ID);
find_item(item, self, at_root);
}
2019-11-28 21:47:10 +01:00
fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
// Entry fn is never a trait item.
}
2016-10-28 22:58:32 +02:00
2019-11-28 22:16:44 +01:00
fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
// Entry fn is never a trait item.
}
2020-11-11 21:57:54 +01:00
2020-11-26 19:11:43 +01:00
fn visit_foreign_item(&mut self, _: &'tcx ForeignItem<'tcx>) {
// Entry fn is never a foreign item.
}
}
2021-05-11 12:00:59 +02:00
fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
2020-05-15 21:44:28 -07:00
let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
if !any_exe {
// No need to find a main function.
2019-01-13 13:06:26 +01:00
return None;
}
// If the user wants no main function at all, then stop here.
2020-11-26 23:38:53 +01:00
if tcx.sess.contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) {
2019-01-13 13:06:26 +01:00
return None;
}
let mut ctxt =
EntryContext { tcx, attr_main_fn: None, start_fn: None, non_main_fns: Vec::new() };
tcx.hir().visit_all_item_likes(&mut ctxt);
2019-01-13 13:06:26 +01:00
configure_main(tcx, &ctxt)
}
// Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
// (with `ast::Item`), so make sure to keep them in sync.
fn entry_point_type(ctxt: &EntryContext<'_>, item: &Item<'_>, at_root: bool) -> EntryPointType {
let attrs = ctxt.tcx.hir().attrs(item.hir_id());
if ctxt.tcx.sess.contains_name(attrs, sym::start) {
2020-10-03 20:45:39 +02:00
EntryPointType::Start
} else if ctxt.tcx.sess.contains_name(attrs, sym::rustc_main) {
2020-10-03 20:45:39 +02:00
EntryPointType::MainAttr
} else if item.ident.name == sym::main {
if at_root {
// This is a top-level function so can be `main`.
EntryPointType::MainNamed
} else {
EntryPointType::OtherMain
2015-07-31 00:04:06 -07:00
}
2020-10-03 20:45:39 +02:00
} else {
EntryPointType::None
2015-07-31 00:04:06 -07:00
}
}
2020-10-03 20:45:39 +02:00
fn throw_attr_err(sess: &Session, span: Span, attr: &str) {
sess.struct_span_err(span, &format!("`{}` attribute can only be used on functions", attr))
.emit();
}
fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_>, at_root: bool) {
2021-01-24 13:17:54 +01:00
match entry_point_type(ctxt, item, at_root) {
2020-10-03 20:45:39 +02:00
EntryPointType::None => (),
_ if !matches!(item.kind, ItemKind::Fn(..)) => {
let attrs = ctxt.tcx.hir().attrs(item.hir_id());
if let Some(attr) = ctxt.tcx.sess.find_by_name(attrs, sym::start) {
throw_attr_err(&ctxt.tcx.sess, attr.span, "start");
2020-10-03 20:45:39 +02:00
}
if let Some(attr) = ctxt.tcx.sess.find_by_name(attrs, sym::rustc_main) {
throw_attr_err(&ctxt.tcx.sess, attr.span, "rustc_main");
2020-10-03 20:45:39 +02:00
}
}
EntryPointType::MainNamed => (),
EntryPointType::OtherMain => {
2021-12-05 13:07:51 +01:00
ctxt.non_main_fns.push(item.span);
}
EntryPointType::MainAttr => {
if ctxt.attr_main_fn.is_none() {
2021-12-05 13:07:51 +01:00
ctxt.attr_main_fn = Some((item.def_id, item.span));
} else {
2016-08-04 20:27:11 +01:00
struct_span_err!(
ctxt.tcx.sess,
2016-08-04 20:27:11 +01:00
item.span,
E0137,
"multiple functions with a `#[main]` attribute"
)
.span_label(item.span, "additional `#[main]` function")
.span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
2016-08-04 20:27:11 +01:00
.emit();
}
}
EntryPointType::Start => {
if ctxt.start_fn.is_none() {
2021-12-05 13:07:51 +01:00
ctxt.start_fn = Some((item.def_id, item.span));
} else {
struct_span_err!(ctxt.tcx.sess, item.span, E0138, "multiple `start` functions")
2020-01-05 00:17:46 +00:00
.span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
.span_label(item.span, "multiple `start` functions")
2016-08-11 00:38:12 +08:00
.emit();
}
2019-01-13 13:06:26 +01:00
}
}
}
fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, EntryFnType)> {
2021-12-05 13:07:51 +01:00
if let Some((def_id, _)) = visitor.start_fn {
Some((def_id.to_def_id(), EntryFnType::Start))
} else if let Some((def_id, _)) = visitor.attr_main_fn {
Some((def_id.to_def_id(), EntryFnType::Main))
2021-04-04 14:40:35 +02:00
} else {
if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() {
// non-local main imports are handled below
if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
tcx.sess
.struct_span_err(
tcx.def_span(def_id),
"the `main` function cannot be declared in an `extern` block",
)
.emit();
return None;
}
if main_def.is_import && !tcx.features().imported_main {
let span = main_def.span;
feature_err(
&tcx.sess.parse_sess,
sym::imported_main,
span,
"using an imported function as entry point `main` is experimental",
)
.emit();
}
return Some((def_id, EntryFnType::Main));
}
no_main_err(tcx, visitor);
2019-01-13 13:06:26 +01:00
None
}
}
2019-01-13 13:06:26 +01:00
fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) {
let sp = tcx.def_span(CRATE_DEF_ID);
if *tcx.sess.parse_sess.reached_eof.borrow() {
// There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
// the missing `fn main()` then as it might have been hidden inside an unclosed block.
tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
return;
}
// There is no main function.
let mut err = struct_span_err!(
tcx.sess,
DUMMY_SP,
E0601,
"`main` function not found in crate `{}`",
tcx.crate_name(LOCAL_CRATE)
);
let filename = &tcx.sess.local_crate_source_file;
let note = if !visitor.non_main_fns.is_empty() {
2021-12-05 13:07:51 +01:00
for &span in &visitor.non_main_fns {
err.span_note(span, "here is a function named `main`");
}
err.note("you have one or more functions named `main` not defined at the crate level");
2021-04-08 21:37:38 +08:00
err.help("consider moving the `main` function definitions");
// There were some functions named `main` though. Try to give the user a hint.
format!(
"the main function must be defined at the crate level{}",
filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
2019-12-22 17:42:04 -05:00
)
} else if let Some(filename) = filename {
format!("consider adding a `main` function to `{}`", filename.display())
} else {
String::from("consider adding a `main` function at the crate level")
};
// The file may be empty, which leads to the diagnostic machinery not emitting this
// note. This is a relatively simple way to detect that case and emit a span-less
// note instead.
if tcx.sess.source_map().lookup_line(sp.hi()).is_ok() {
err.set_span(sp.shrink_to_hi());
err.span_label(sp.shrink_to_hi(), &note);
} else {
err.note(&note);
}
if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none(){
// There is something at `crate::main`, but it is not a function definition.
err.span_label(main_def.span, "non-function item at `crate::main` is found");
}
if tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"If you don't know the basics of Rust, you can go look to the Rust Book \
to get started: https://doc.rust-lang.org/book/",
);
}
err.emit();
}
pub fn provide(providers: &mut Providers) {
2019-01-13 13:06:26 +01:00
*providers = Providers { entry_fn, ..*providers };
}