1 use rustc_ast::entry::EntryPointType;
2 use rustc_errors::struct_span_err;
3 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
4 use rustc_hir::itemlikevisit::ItemLikeVisitor;
5 use rustc_hir::{ForeignItem, ImplItem, Item, ItemKind, Node, TraitItem, CRATE_HIR_ID};
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::parse::feature_err;
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 function that has attribute named `main`.
21 attr_main_fn: Option<(LocalDefId, Span)>,
23 /// The function that has the attribute 'start' on it.
24 start_fn: Option<(LocalDefId, Span)>,
26 /// The functions that one might think are `main` but aren't, e.g.
27 /// main functions not defined at the top level. For diagnostics.
28 non_main_fns: Vec<Span>,
31 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
32 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
33 let def_key = self.map.def_key(item.def_id);
34 let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
35 find_item(item, self, at_root);
38 fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
39 // Entry fn is never a trait item.
42 fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
43 // Entry fn is never a trait item.
46 fn visit_foreign_item(&mut self, _: &'tcx ForeignItem<'tcx>) {
47 // Entry fn is never a foreign item.
51 fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
52 let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
54 // No need to find a main function.
58 // If the user wants no main function at all, then stop here.
59 if tcx.sess.contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) {
63 let mut ctxt = EntryContext {
68 non_main_fns: Vec::new(),
71 tcx.hir().visit_all_item_likes(&mut ctxt);
73 configure_main(tcx, &ctxt)
76 // Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
77 // (with `ast::Item`), so make sure to keep them in sync.
78 fn entry_point_type(ctxt: &EntryContext<'_, '_>, item: &Item<'_>, at_root: bool) -> EntryPointType {
79 let attrs = ctxt.map.attrs(item.hir_id());
80 if ctxt.session.contains_name(attrs, sym::start) {
82 } else if ctxt.session.contains_name(attrs, sym::rustc_main) {
83 EntryPointType::MainAttr
84 } else if item.ident.name == sym::main {
86 // This is a top-level function so can be `main`.
87 EntryPointType::MainNamed
89 EntryPointType::OtherMain
96 fn throw_attr_err(sess: &Session, span: Span, attr: &str) {
97 sess.struct_span_err(span, &format!("`{}` attribute can only be used on functions", attr))
101 fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
102 match entry_point_type(ctxt, item, at_root) {
103 EntryPointType::None => (),
104 _ if !matches!(item.kind, ItemKind::Fn(..)) => {
105 let attrs = ctxt.map.attrs(item.hir_id());
106 if let Some(attr) = ctxt.session.find_by_name(attrs, sym::start) {
107 throw_attr_err(&ctxt.session, attr.span, "start");
109 if let Some(attr) = ctxt.session.find_by_name(attrs, sym::rustc_main) {
110 throw_attr_err(&ctxt.session, attr.span, "rustc_main");
113 EntryPointType::MainNamed => (),
114 EntryPointType::OtherMain => {
115 ctxt.non_main_fns.push(item.span);
117 EntryPointType::MainAttr => {
118 if ctxt.attr_main_fn.is_none() {
119 ctxt.attr_main_fn = Some((item.def_id, item.span));
125 "multiple functions with a `#[main]` attribute"
127 .span_label(item.span, "additional `#[main]` function")
128 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
132 EntryPointType::Start => {
133 if ctxt.start_fn.is_none() {
134 ctxt.start_fn = Some((item.def_id, item.span));
136 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
137 .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
138 .span_label(item.span, "multiple `start` functions")
145 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(DefId, EntryFnType)> {
146 if let Some((def_id, _)) = visitor.start_fn {
147 Some((def_id.to_def_id(), EntryFnType::Start))
148 } else if let Some((def_id, _)) = visitor.attr_main_fn {
149 Some((def_id.to_def_id(), EntryFnType::Main))
151 if let Some(main_def) = tcx.resolutions(()).main_def {
152 if let Some(def_id) = main_def.opt_fn_def_id() {
153 // non-local main imports are handled below
154 if let Some(def_id) = def_id.as_local() {
155 if matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
158 tcx.def_span(def_id),
159 "the `main` function cannot be declared in an `extern` block",
166 if main_def.is_import && !tcx.features().imported_main {
167 let span = main_def.span;
169 &tcx.sess.parse_sess,
172 "using an imported function as entry point `main` is experimental",
176 return Some((def_id, EntryFnType::Main));
179 no_main_err(tcx, visitor);
184 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
185 let sp = tcx.def_span(CRATE_DEF_ID);
186 if *tcx.sess.parse_sess.reached_eof.borrow() {
187 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
188 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
189 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
193 // There is no main function.
194 let mut err = struct_span_err!(
198 "`main` function not found in crate `{}`",
199 tcx.crate_name(LOCAL_CRATE)
201 let filename = &tcx.sess.local_crate_source_file;
202 let note = if !visitor.non_main_fns.is_empty() {
203 for &span in &visitor.non_main_fns {
204 err.span_note(span, "here is a function named `main`");
206 err.note("you have one or more functions named `main` not defined at the crate level");
207 err.help("consider moving the `main` function definitions");
208 // There were some functions named `main` though. Try to give the user a hint.
210 "the main function must be defined at the crate level{}",
211 filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
213 } else if let Some(filename) = filename {
214 format!("consider adding a `main` function to `{}`", filename.display())
216 String::from("consider adding a `main` function at the crate level")
218 // The file may be empty, which leads to the diagnostic machinery not emitting this
219 // note. This is a relatively simple way to detect that case and emit a span-less
221 if tcx.sess.source_map().lookup_line(sp.hi()).is_ok() {
222 err.set_span(sp.shrink_to_hi());
223 err.span_label(sp.shrink_to_hi(), ¬e);
228 if let Some(main_def) = tcx.resolutions(()).main_def {
229 if main_def.opt_fn_def_id().is_none() {
230 // There is something at `crate::main`, but it is not a function definition.
231 err.span_label(main_def.span, "non-function item at `crate::main` is found");
235 if tcx.sess.teach(&err.get_code().unwrap()) {
237 "If you don't know the basics of Rust, you can go look to the Rust Book \
238 to get started: https://doc.rust-lang.org/book/",
244 pub fn provide(providers: &mut Providers) {
245 *providers = Providers { entry_fn, ..*providers };