1 use rustc::hir::map as hir_map;
2 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
3 use rustc::session::{config, Session};
4 use rustc::session::config::EntryFnType;
6 use syntax::entry::EntryPointType;
7 use syntax::symbol::sym;
9 use rustc::hir::{HirId, Item, ItemKind, ImplItem, TraitItem};
10 use rustc::hir::itemlikevisit::ItemLikeVisitor;
11 use rustc::ty::TyCtxt;
12 use rustc::ty::query::Providers;
14 struct EntryContext<'a, 'tcx> {
17 map: &'a hir_map::Map<'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) {
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) {
42 // Entry fn is never a trait item.
45 fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem) {
46 // Entry fn is never a trait item.
50 fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
51 assert_eq!(cnum, LOCAL_CRATE);
53 let any_exe = tcx.sess.crate_types.borrow().iter().any(|ty| {
54 *ty == config::CrateType::Executable
57 // No need to find a main function.
61 // If the user wants no main function at all, then stop here.
62 if attr::contains_name(&tcx.hir().krate().attrs, sym::no_main) {
66 let mut ctxt = EntryContext {
72 non_main_fns: Vec::new(),
75 tcx.hir().krate().visit_all_item_likes(&mut ctxt);
77 configure_main(tcx, &ctxt)
80 // Beware, this is duplicated in `libsyntax/entry.rs`, so make sure to keep
82 fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType {
85 if attr::contains_name(&item.attrs, sym::start) {
87 } else if attr::contains_name(&item.attrs, sym::main) {
88 EntryPointType::MainAttr
89 } else if item.ident.name == sym::main {
91 // This is a top-level function so can be `main`.
92 EntryPointType::MainNamed
94 EntryPointType::OtherMain
100 _ => EntryPointType::None,
105 fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
106 match entry_point_type(item, at_root) {
107 EntryPointType::MainNamed => {
108 if ctxt.main_fn.is_none() {
109 ctxt.main_fn = Some((item.hir_id, item.span));
111 span_err!(ctxt.session, item.span, E0136,
112 "multiple `main` functions");
115 EntryPointType::OtherMain => {
116 ctxt.non_main_fns.push((item.hir_id, item.span));
118 EntryPointType::MainAttr => {
119 if ctxt.attr_main_fn.is_none() {
120 ctxt.attr_main_fn = Some((item.hir_id, item.span));
122 struct_span_err!(ctxt.session, item.span, E0137,
123 "multiple functions with a `#[main]` attribute")
124 .span_label(item.span, "additional `#[main]` function")
125 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
129 EntryPointType::Start => {
130 if ctxt.start_fn.is_none() {
131 ctxt.start_fn = Some((item.hir_id, item.span));
133 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
134 .span_label(ctxt.start_fn.unwrap().1, "previous `start` function here")
135 .span_label(item.span, "multiple `start` functions")
139 EntryPointType::None => (),
143 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(DefId, EntryFnType)> {
144 if let Some((hir_id, _)) = visitor.start_fn {
145 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start))
146 } else if let Some((hir_id, _)) = visitor.attr_main_fn {
147 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
148 } else if let Some((hir_id, _)) = visitor.main_fn {
149 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
151 no_main_err(tcx, visitor);
156 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
157 let sp = tcx.hir().krate().span;
158 if *tcx.sess.parse_sess.reached_eof.borrow() {
159 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
160 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
161 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
165 // There is no main function.
166 let mut err = struct_err!(tcx.sess, E0601,
167 "`main` function not found in crate `{}`", tcx.crate_name(LOCAL_CRATE));
168 let filename = &tcx.sess.local_crate_source_file;
169 let note = if !visitor.non_main_fns.is_empty() {
170 for &(_, span) in &visitor.non_main_fns {
171 err.span_note(span, "here is a function named `main`");
173 err.note("you have one or more functions named `main` not defined at the crate level");
174 err.help("either move the `main` function definitions or attach the `#[main]` attribute \
176 // There were some functions named `main` though. Try to give the user a hint.
177 format!("the main function must be defined at the crate level{}",
178 filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default())
179 } else if let Some(filename) = filename {
180 format!("consider adding a `main` function to `{}`", filename.display())
182 String::from("consider adding a `main` function at the crate level")
184 // The file may be empty, which leads to the diagnostic machinery not emitting this
185 // note. This is a relatively simple way to detect that case and emit a span-less
187 if let Ok(_) = tcx.sess.source_map().lookup_line(sp.lo()) {
189 err.span_label(sp, ¬e);
193 if tcx.sess.teach(&err.get_code().unwrap()) {
194 err.note("If you don't know the basics of Rust, you can go look to the Rust Book \
195 to get started: https://doc.rust-lang.org/book/");
200 pub fn find_entry_point(tcx: TyCtxt<'_>) -> Option<(DefId, EntryFnType)> {
201 tcx.entry_fn(LOCAL_CRATE)
204 pub fn provide(providers: &mut Providers<'_>) {
205 *providers = Providers {