1 use rustc_ast::entry::EntryPointType;
2 use rustc_errors::struct_span_err;
3 use rustc_hir::def_id::{CrateNum, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
4 use rustc_hir::itemlikevisit::ItemLikeVisitor;
5 use rustc_hir::{HirId, ImplItem, Item, ItemKind, TraitItem};
6 use rustc_middle::hir::map::Map;
7 use rustc_middle::ty::query::Providers;
8 use rustc_middle::ty::TyCtxt;
9 use rustc_session::config::{CrateType, EntryFnType};
10 use rustc_session::Session;
11 use rustc_span::symbol::sym;
12 use rustc_span::{Span, DUMMY_SP};
14 struct EntryContext<'a, 'tcx> {
19 /// The top-level function called `main`.
20 main_fn: Option<(HirId, Span)>,
22 /// The function that has attribute named `main`.
23 attr_main_fn: Option<(HirId, Span)>,
25 /// The function that has the attribute 'start' on it.
26 start_fn: Option<(HirId, Span)>,
28 /// The functions that one might think are `main` but aren't, e.g.
29 /// main functions not defined at the top level. For diagnostics.
30 non_main_fns: Vec<(HirId, Span)>,
33 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
34 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
35 let def_id = self.map.local_def_id(item.hir_id);
36 let def_key = self.map.def_key(def_id);
37 let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
38 find_item(item, self, at_root);
41 fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
42 // Entry fn is never a trait item.
45 fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
46 // Entry fn is never a trait item.
50 fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(LocalDefId, EntryFnType)> {
51 assert_eq!(cnum, LOCAL_CRATE);
53 let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
55 // No need to find a main function.
59 // If the user wants no main function at all, then stop here.
60 if tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::no_main) {
64 let mut ctxt = EntryContext {
70 non_main_fns: Vec::new(),
73 tcx.hir().krate().visit_all_item_likes(&mut ctxt);
75 configure_main(tcx, &ctxt)
78 // Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
79 // (with `ast::Item`), so make sure to keep them in sync.
80 fn entry_point_type(sess: &Session, item: &Item<'_>, at_root: bool) -> EntryPointType {
83 if sess.contains_name(&item.attrs, sym::start) {
85 } else if sess.contains_name(&item.attrs, sym::main) {
86 EntryPointType::MainAttr
87 } else if item.ident.name == sym::main {
89 // This is a top-level function so can be `main`.
90 EntryPointType::MainNamed
92 EntryPointType::OtherMain
98 _ => EntryPointType::None,
102 fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
103 match entry_point_type(&ctxt.session, item, at_root) {
104 EntryPointType::MainNamed => {
105 if ctxt.main_fn.is_none() {
106 ctxt.main_fn = Some((item.hir_id, item.span));
108 struct_span_err!(ctxt.session, item.span, E0136, "multiple `main` functions")
112 EntryPointType::OtherMain => {
113 ctxt.non_main_fns.push((item.hir_id, item.span));
115 EntryPointType::MainAttr => {
116 if ctxt.attr_main_fn.is_none() {
117 ctxt.attr_main_fn = Some((item.hir_id, item.span));
123 "multiple functions with a `#[main]` attribute"
125 .span_label(item.span, "additional `#[main]` function")
126 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
130 EntryPointType::Start => {
131 if ctxt.start_fn.is_none() {
132 ctxt.start_fn = Some((item.hir_id, item.span));
134 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
135 .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
136 .span_label(item.span, "multiple `start` functions")
140 EntryPointType::None => (),
146 visitor: &EntryContext<'_, '_>,
147 ) -> Option<(LocalDefId, EntryFnType)> {
148 if let Some((hir_id, _)) = visitor.start_fn {
149 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start))
150 } else if let Some((hir_id, _)) = visitor.attr_main_fn {
151 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
152 } else if let Some((hir_id, _)) = visitor.main_fn {
153 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
155 no_main_err(tcx, visitor);
160 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
161 let sp = tcx.hir().krate().item.span;
162 if *tcx.sess.parse_sess.reached_eof.borrow() {
163 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
164 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
165 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
169 // There is no main function.
170 let mut err = struct_span_err!(
174 "`main` function not found in crate `{}`",
175 tcx.crate_name(LOCAL_CRATE)
177 let filename = &tcx.sess.local_crate_source_file;
178 let note = if !visitor.non_main_fns.is_empty() {
179 for &(_, span) in &visitor.non_main_fns {
180 err.span_note(span, "here is a function named `main`");
182 err.note("you have one or more functions named `main` not defined at the crate level");
184 "either move the `main` function definitions or attach the `#[main]` attribute \
187 // There were some functions named `main` though. Try to give the user a hint.
189 "the main function must be defined at the crate level{}",
190 filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
192 } else if let Some(filename) = filename {
193 format!("consider adding a `main` function to `{}`", filename.display())
195 String::from("consider adding a `main` function at the crate level")
197 // The file may be empty, which leads to the diagnostic machinery not emitting this
198 // note. This is a relatively simple way to detect that case and emit a span-less
200 if tcx.sess.source_map().lookup_line(sp.lo()).is_ok() {
202 err.span_label(sp, ¬e);
206 if tcx.sess.teach(&err.get_code().unwrap()) {
208 "If you don't know the basics of Rust, you can go look to the Rust Book \
209 to get started: https://doc.rust-lang.org/book/",
215 pub fn find_entry_point(tcx: TyCtxt<'_>) -> Option<(LocalDefId, EntryFnType)> {
216 tcx.entry_fn(LOCAL_CRATE)
219 pub fn provide(providers: &mut Providers) {
220 *providers = Providers { entry_fn, ..*providers };