220 lines
7.7 KiB
Rust
Raw Normal View History

2019-12-22 17:42:04 -05:00
use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc::hir::itemlikevisit::ItemLikeVisitor;
2019-10-04 10:37:40 -04:00
use rustc::hir::map as hir_map;
2019-12-22 17:42:04 -05:00
use rustc::hir::{HirId, ImplItem, Item, ItemKind, TraitItem};
2019-10-04 10:37:40 -04:00
use rustc::session::config::EntryFnType;
2019-12-22 17:42:04 -05:00
use rustc::session::{config, Session};
use rustc::ty::query::Providers;
use rustc::ty::TyCtxt;
2020-01-01 19:30:57 +01:00
use rustc_span::symbol::sym;
use rustc_span::Span;
use syntax::attr;
use syntax::entry::EntryPointType;
use rustc_error_codes::*;
struct EntryContext<'a, 'tcx> {
2014-03-05 16:36:01 +02:00
session: &'a Session,
2017-01-26 03:21:50 +02:00
map: &'a hir_map::Map<'tcx>,
/// The top-level function called `main`.
2019-02-27 17:35:24 +01:00
main_fn: Option<(HirId, Span)>,
/// The function that has attribute named `main`.
2019-02-27 17:35:24 +01:00
attr_main_fn: Option<(HirId, Span)>,
/// The function that has the attribute 'start' on it.
2019-02-27 17:35:24 +01:00
start_fn: Option<(HirId, Span)>,
/// The functions that one might think are `main` but aren't, e.g.
/// main functions not defined at the top level. For diagnostics.
2019-12-22 17:42:04 -05:00
non_main_fns: Vec<(HirId, Span)>,
}
impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
2019-11-28 19:28:50 +01:00
fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
let def_id = self.map.local_def_id(item.hir_id);
let def_key = self.map.def_key(def_id);
let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
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.
}
}
2019-06-14 00:48:52 +03:00
fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
2019-01-13 13:06:26 +01:00
assert_eq!(cnum, LOCAL_CRATE);
2019-12-22 17:42:04 -05:00
let any_exe =
tcx.sess.crate_types.borrow().iter().any(|ty| *ty == config::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.
if attr::contains_name(&tcx.hir().krate().attrs, sym::no_main) {
2019-01-13 13:06:26 +01:00
return None;
}
let mut ctxt = EntryContext {
2019-01-13 13:06:26 +01:00
session: tcx.sess,
map: tcx.hir(),
main_fn: None,
attr_main_fn: None,
start_fn: None,
non_main_fns: Vec::new(),
};
2019-01-13 13:06:26 +01:00
tcx.hir().krate().visit_all_item_likes(&mut ctxt);
2019-01-13 13:06:26 +01:00
configure_main(tcx, &ctxt)
}
// Beware, this is duplicated in `libsyntax/entry.rs`, so make sure to keep
2015-07-31 00:04:06 -07:00
// them in sync.
2019-11-28 19:28:50 +01:00
fn entry_point_type(item: &Item<'_>, at_root: bool) -> EntryPointType {
2019-09-26 17:51:36 +01:00
match item.kind {
2018-07-11 23:36:06 +08:00
ItemKind::Fn(..) => {
if attr::contains_name(&item.attrs, sym::start) {
2015-07-31 00:04:06 -07:00
EntryPointType::Start
} else if attr::contains_name(&item.attrs, sym::main) {
2015-07-31 00:04:06 -07:00
EntryPointType::MainAttr
} else if item.ident.name == sym::main {
if at_root {
// This is a top-level function so can be `main`.
2015-07-31 00:04:06 -07:00
EntryPointType::MainNamed
} else {
EntryPointType::OtherMain
}
} else {
EntryPointType::None
}
}
_ => EntryPointType::None,
}
}
2019-11-28 19:28:50 +01:00
fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
match entry_point_type(item, at_root) {
EntryPointType::MainNamed => {
if ctxt.main_fn.is_none() {
2019-02-27 17:35:24 +01:00
ctxt.main_fn = Some((item.hir_id, item.span));
} else {
2019-12-22 17:42:04 -05:00
span_err!(ctxt.session, item.span, E0136, "multiple `main` functions");
}
2019-12-22 17:42:04 -05:00
}
EntryPointType::OtherMain => {
2019-02-27 17:35:24 +01:00
ctxt.non_main_fns.push((item.hir_id, item.span));
2019-12-22 17:42:04 -05:00
}
EntryPointType::MainAttr => {
if ctxt.attr_main_fn.is_none() {
2019-02-27 17:35:24 +01:00
ctxt.attr_main_fn = Some((item.hir_id, item.span));
} else {
2019-12-22 17:42:04 -05:00
struct_span_err!(
ctxt.session,
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();
}
2019-12-22 17:42:04 -05:00
}
EntryPointType::Start => {
if ctxt.start_fn.is_none() {
2019-02-27 17:35:24 +01:00
ctxt.start_fn = Some((item.hir_id, item.span));
} else {
struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
.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
}
EntryPointType::None => (),
}
}
fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(DefId, EntryFnType)> {
2019-02-27 17:35:24 +01:00
if let Some((hir_id, _)) = visitor.start_fn {
Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start))
2019-02-27 17:35:24 +01:00
} else if let Some((hir_id, _)) = visitor.attr_main_fn {
Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
2019-02-27 17:35:24 +01:00
} else if let Some((hir_id, _)) = visitor.main_fn {
Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
} else {
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.hir().krate().span;
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.
2019-12-22 17:42:04 -05:00
let mut err = struct_err!(
tcx.sess,
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() {
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");
2019-12-22 17:42:04 -05:00
err.help(
"either move the `main` function definitions or attach the `#[main]` attribute \
to one of them",
);
// There were some functions named `main` though. Try to give the user a hint.
2019-12-22 17:42:04 -05:00
format!(
"the main function must be defined at the crate level{}",
filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
)
} 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 let Ok(_) = tcx.sess.source_map().lookup_line(sp.lo()) {
err.set_span(sp);
err.span_label(sp, &note);
} else {
err.note(&note);
}
if tcx.sess.teach(&err.get_code().unwrap()) {
2019-12-22 17:42:04 -05:00
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();
}
2019-06-14 00:48:52 +03:00
pub fn find_entry_point(tcx: TyCtxt<'_>) -> Option<(DefId, EntryFnType)> {
2019-01-13 13:06:26 +01:00
tcx.entry_fn(LOCAL_CRATE)
}
pub fn provide(providers: &mut Providers<'_>) {
2019-12-22 17:42:04 -05:00
*providers = Providers { entry_fn, ..*providers };
2019-01-13 13:06:26 +01:00
}