2 use rustc_ast::entry::EntryPointType;
3 use rustc_errors::struct_span_err;
4 use rustc_hir::def_id::{CrateNum, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5 use rustc_hir::itemlikevisit::ItemLikeVisitor;
6 use rustc_hir::{HirId, ImplItem, Item, ItemKind, TraitItem};
7 use rustc_middle::hir::map::Map;
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::TyCtxt;
10 use rustc_session::config::{CrateType, EntryFnType};
11 use rustc_session::Session;
12 use rustc_span::symbol::sym;
13 use rustc_span::{Span, DUMMY_SP};
15 struct EntryContext<'a, 'tcx> {
20 /// The top-level function called `main`.
21 main_fn: Option<(HirId, Span)>,
23 /// The function that has attribute named `main`.
24 attr_main_fn: Option<(HirId, Span)>,
26 /// The function that has the attribute 'start' on it.
27 start_fn: Option<(HirId, Span)>,
29 /// The functions that one might think are `main` but aren't, e.g.
30 /// main functions not defined at the top level. For diagnostics.
31 non_main_fns: Vec<(HirId, Span)>,
34 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
35 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
36 let def_id = self.map.local_def_id(item.hir_id);
37 let def_key = self.map.def_key(def_id);
38 let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
39 find_item(item, self, at_root);
42 fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
43 // Entry fn is never a trait item.
46 fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
47 // Entry fn is never a trait item.
51 fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(LocalDefId, EntryFnType)> {
52 assert_eq!(cnum, LOCAL_CRATE);
54 let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
56 // No need to find a main function.
60 // If the user wants no main function at all, then stop here.
61 if attr::contains_name(&tcx.hir().krate().item.attrs, sym::no_main) {
65 let mut ctxt = EntryContext {
71 non_main_fns: Vec::new(),
74 tcx.hir().krate().visit_all_item_likes(&mut ctxt);
76 configure_main(tcx, &ctxt)
79 // Beware, this is duplicated in `librustc_ast/entry.rs`, so make sure to keep
81 fn entry_point_type(item: &Item<'_>, at_root: bool) -> EntryPointType {
84 if attr::contains_name(&item.attrs, sym::start) {
86 } else if attr::contains_name(&item.attrs, sym::main) {
87 EntryPointType::MainAttr
88 } else if item.ident.name == sym::main {
90 // This is a top-level function so can be `main`.
91 EntryPointType::MainNamed
93 EntryPointType::OtherMain
99 _ => EntryPointType::None,
103 fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
104 match entry_point_type(item, at_root) {
105 EntryPointType::MainNamed => {
106 if ctxt.main_fn.is_none() {
107 ctxt.main_fn = Some((item.hir_id, item.span));
109 struct_span_err!(ctxt.session, item.span, E0136, "multiple `main` functions")
113 EntryPointType::OtherMain => {
114 ctxt.non_main_fns.push((item.hir_id, item.span));
116 EntryPointType::MainAttr => {
117 if ctxt.attr_main_fn.is_none() {
118 ctxt.attr_main_fn = Some((item.hir_id, item.span));
124 "multiple functions with a `#[main]` attribute"
126 .span_label(item.span, "additional `#[main]` function")
127 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
131 EntryPointType::Start => {
132 if ctxt.start_fn.is_none() {
133 ctxt.start_fn = Some((item.hir_id, item.span));
135 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
136 .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
137 .span_label(item.span, "multiple `start` functions")
141 EntryPointType::None => (),
147 visitor: &EntryContext<'_, '_>,
148 ) -> Option<(LocalDefId, EntryFnType)> {
149 if let Some((hir_id, _)) = visitor.start_fn {
150 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start))
151 } else if let Some((hir_id, _)) = visitor.attr_main_fn {
152 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
153 } else if let Some((hir_id, _)) = visitor.main_fn {
154 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
156 no_main_err(tcx, visitor);
161 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
162 let sp = tcx.hir().krate().item.span;
163 if *tcx.sess.parse_sess.reached_eof.borrow() {
164 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
165 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
166 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
170 // There is no main function.
171 let mut err = struct_span_err!(
175 "`main` function not found in crate `{}`",
176 tcx.crate_name(LOCAL_CRATE)
178 let filename = &tcx.sess.local_crate_source_file;
179 let note = if !visitor.non_main_fns.is_empty() {
180 for &(_, span) in &visitor.non_main_fns {
181 err.span_note(span, "here is a function named `main`");
183 err.note("you have one or more functions named `main` not defined at the crate level");
185 "either move the `main` function definitions or attach the `#[main]` attribute \
188 // There were some functions named `main` though. Try to give the user a hint.
190 "the main function must be defined at the crate level{}",
191 filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
193 } else if let Some(filename) = filename {
194 format!("consider adding a `main` function to `{}`", filename.display())
196 String::from("consider adding a `main` function at the crate level")
198 // The file may be empty, which leads to the diagnostic machinery not emitting this
199 // note. This is a relatively simple way to detect that case and emit a span-less
201 if tcx.sess.source_map().lookup_line(sp.lo()).is_ok() {
203 err.span_label(sp, ¬e);
207 if tcx.sess.teach(&err.get_code().unwrap()) {
209 "If you don't know the basics of Rust, you can go look to the Rust Book \
210 to get started: https://doc.rust-lang.org/book/",
216 pub fn find_entry_point(tcx: TyCtxt<'_>) -> Option<(LocalDefId, EntryFnType)> {
217 tcx.entry_fn(LOCAL_CRATE)
220 pub fn provide(providers: &mut Providers) {
221 *providers = Providers { entry_fn, ..*providers };