1 use rustc_ast::entry::EntryPointType;
2 use rustc_errors::struct_span_err;
3 use rustc_hir::def::DefKind;
4 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
5 use rustc_hir::{ItemId, Node, CRATE_HIR_ID};
6 use rustc_middle::ty::query::Providers;
7 use rustc_middle::ty::{DefIdTree, TyCtxt};
8 use rustc_session::config::{sigpipe, CrateType, EntryFnType};
9 use rustc_session::parse::feature_err;
10 use rustc_span::symbol::sym;
11 use rustc_span::{Span, Symbol, DUMMY_SP};
13 struct EntryContext<'tcx> {
16 /// The function that has attribute named `main`.
17 attr_main_fn: Option<(LocalDefId, Span)>,
19 /// The function that has the attribute 'start' on it.
20 start_fn: Option<(LocalDefId, Span)>,
22 /// The functions that one might think are `main` but aren't, e.g.
23 /// main functions not defined at the top level. For diagnostics.
24 non_main_fns: Vec<Span>,
27 fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
28 let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
30 // No need to find a main function.
34 // If the user wants no main function at all, then stop here.
35 if tcx.sess.contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) {
40 EntryContext { tcx, attr_main_fn: None, start_fn: None, non_main_fns: Vec::new() };
42 for id in tcx.hir().items() {
43 find_item(id, &mut ctxt);
46 configure_main(tcx, &ctxt)
49 // Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
50 // (with `ast::Item`), so make sure to keep them in sync.
51 // A small optimization was added so that hir::Item is fetched only when needed.
52 // An equivalent optimization was not applied to the duplicated code in test_harness.rs.
53 fn entry_point_type(ctxt: &EntryContext<'_>, id: ItemId, at_root: bool) -> EntryPointType {
54 let attrs = ctxt.tcx.hir().attrs(id.hir_id());
55 if ctxt.tcx.sess.contains_name(attrs, sym::start) {
57 } else if ctxt.tcx.sess.contains_name(attrs, sym::rustc_main) {
58 EntryPointType::RustcMainAttr
60 if let Some(name) = ctxt.tcx.opt_item_name(id.def_id.to_def_id())
61 && name == sym::main {
63 // This is a top-level function so can be `main`.
64 EntryPointType::MainNamed
66 EntryPointType::OtherMain
74 fn err_if_attr_found(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol, details: &str) {
75 let attrs = ctxt.tcx.hir().attrs(id.hir_id());
76 if let Some(attr) = ctxt.tcx.sess.find_by_name(attrs, sym) {
79 .struct_span_err(attr.span, &format!("`{}` attribute {}", sym, details))
84 fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) {
85 let at_root = ctxt.tcx.opt_local_parent(id.def_id) == Some(CRATE_DEF_ID);
87 match entry_point_type(ctxt, id, at_root) {
88 EntryPointType::None => {
89 err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on `fn main()`");
91 _ if !matches!(ctxt.tcx.def_kind(id.def_id), DefKind::Fn) => {
92 err_if_attr_found(ctxt, id, sym::start, "can only be used on functions");
93 err_if_attr_found(ctxt, id, sym::rustc_main, "can only be used on functions");
95 EntryPointType::MainNamed => (),
96 EntryPointType::OtherMain => {
97 err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on root `fn main()`");
98 ctxt.non_main_fns.push(ctxt.tcx.def_span(id.def_id));
100 EntryPointType::RustcMainAttr => {
101 if ctxt.attr_main_fn.is_none() {
102 ctxt.attr_main_fn = Some((id.def_id, ctxt.tcx.def_span(id.def_id.to_def_id())));
106 ctxt.tcx.def_span(id.def_id.to_def_id()),
108 "multiple functions with a `#[rustc_main]` attribute"
111 ctxt.tcx.def_span(id.def_id.to_def_id()),
112 "additional `#[rustc_main]` function",
114 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[rustc_main]` function")
118 EntryPointType::Start => {
119 err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on `fn main()`");
120 if ctxt.start_fn.is_none() {
121 ctxt.start_fn = Some((id.def_id, ctxt.tcx.def_span(id.def_id.to_def_id())));
125 ctxt.tcx.def_span(id.def_id.to_def_id()),
127 "multiple `start` functions"
129 .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
130 .span_label(ctxt.tcx.def_span(id.def_id.to_def_id()), "multiple `start` functions")
137 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, EntryFnType)> {
138 if let Some((def_id, _)) = visitor.start_fn {
139 Some((def_id.to_def_id(), EntryFnType::Start))
140 } else if let Some((local_def_id, _)) = visitor.attr_main_fn {
141 let def_id = local_def_id.to_def_id();
142 Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) }))
144 if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() {
145 // non-local main imports are handled below
146 if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
149 tcx.def_span(def_id),
150 "the `main` function cannot be declared in an `extern` block",
156 if main_def.is_import && !tcx.features().imported_main {
157 let span = main_def.span;
159 &tcx.sess.parse_sess,
162 "using an imported function as entry point `main` is experimental",
166 return Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) }));
168 no_main_err(tcx, visitor);
173 fn sigpipe(tcx: TyCtxt<'_>, def_id: DefId) -> u8 {
174 if let Some(attr) = tcx.get_attr(def_id, sym::unix_sigpipe) {
175 match (attr.value_str(), attr.meta_item_list()) {
176 (Some(sym::inherit), None) => sigpipe::INHERIT,
177 (Some(sym::sig_ign), None) => sigpipe::SIG_IGN,
178 (Some(sym::sig_dfl), None) => sigpipe::SIG_DFL,
180 // Keep going so that `fn emit_malformed_attribute()` can print
181 // an excellent error message
188 "valid values for `#[unix_sigpipe = \"...\"]` are `inherit`, `sig_ign`, or `sig_dfl`",
199 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) {
200 let sp = tcx.def_span(CRATE_DEF_ID);
201 if *tcx.sess.parse_sess.reached_eof.borrow() {
202 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
203 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
204 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
208 // There is no main function.
209 let mut err = struct_span_err!(
213 "`main` function not found in crate `{}`",
214 tcx.crate_name(LOCAL_CRATE)
216 let filename = &tcx.sess.local_crate_source_file;
217 let note = if !visitor.non_main_fns.is_empty() {
218 for &span in &visitor.non_main_fns {
219 err.span_note(span, "here is a function named `main`");
221 err.note("you have one or more functions named `main` not defined at the crate level");
222 err.help("consider moving the `main` function definitions");
223 // There were some functions named `main` though. Try to give the user a hint.
225 "the main function must be defined at the crate level{}",
226 filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
228 } else if let Some(filename) = filename {
229 format!("consider adding a `main` function to `{}`", filename.display())
231 String::from("consider adding a `main` function at the crate level")
233 // The file may be empty, which leads to the diagnostic machinery not emitting this
234 // note. This is a relatively simple way to detect that case and emit a span-less
236 if tcx.sess.source_map().lookup_line(sp.hi()).is_ok() {
237 err.set_span(sp.shrink_to_hi());
238 err.span_label(sp.shrink_to_hi(), ¬e);
243 if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none(){
244 // There is something at `crate::main`, but it is not a function definition.
245 err.span_label(main_def.span, "non-function item at `crate::main` is found");
248 if tcx.sess.teach(&err.get_code().unwrap()) {
250 "If you don't know the basics of Rust, you can go look to the Rust Book \
251 to get started: https://doc.rust-lang.org/book/",
257 pub fn provide(providers: &mut Providers) {
258 *providers = Providers { entry_fn, ..*providers };