1 use rustc_ast::entry::EntryPointType;
2 use rustc_errors::error_code;
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};
14 AttrOnlyInFunctions, AttrOnlyOnMain, AttrOnlyOnRootMain, ExternMain, MultipleRustcMain,
15 MultipleStartFunctions, NoMainErr, UnixSigpipeValues,
18 struct EntryContext<'tcx> {
21 /// The function that has attribute named `main`.
22 attr_main_fn: Option<(LocalDefId, Span)>,
24 /// The function that has the attribute 'start' on it.
25 start_fn: Option<(LocalDefId, Span)>,
27 /// The functions that one might think are `main` but aren't, e.g.
28 /// main functions not defined at the top level. For diagnostics.
29 non_main_fns: Vec<Span>,
32 fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
33 let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
35 // No need to find a main function.
39 // If the user wants no main function at all, then stop here.
40 if tcx.sess.contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) {
45 EntryContext { tcx, attr_main_fn: None, start_fn: None, non_main_fns: Vec::new() };
47 for id in tcx.hir().items() {
48 find_item(id, &mut ctxt);
51 configure_main(tcx, &ctxt)
54 // Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
55 // (with `ast::Item`), so make sure to keep them in sync.
56 // A small optimization was added so that hir::Item is fetched only when needed.
57 // An equivalent optimization was not applied to the duplicated code in test_harness.rs.
58 fn entry_point_type(ctxt: &EntryContext<'_>, id: ItemId, at_root: bool) -> EntryPointType {
59 let attrs = ctxt.tcx.hir().attrs(id.hir_id());
60 if ctxt.tcx.sess.contains_name(attrs, sym::start) {
62 } else if ctxt.tcx.sess.contains_name(attrs, sym::rustc_main) {
63 EntryPointType::RustcMainAttr
65 if let Some(name) = ctxt.tcx.opt_item_name(id.owner_id.to_def_id())
66 && name == sym::main {
68 // This is a top-level function so can be `main`.
69 EntryPointType::MainNamed
71 EntryPointType::OtherMain
79 fn attr_span_by_symbol(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol) -> Option<Span> {
80 let attrs = ctxt.tcx.hir().attrs(id.hir_id());
81 ctxt.tcx.sess.find_by_name(attrs, sym).map(|attr| attr.span)
84 fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) {
85 let at_root = ctxt.tcx.opt_local_parent(id.owner_id.def_id) == Some(CRATE_DEF_ID);
87 match entry_point_type(ctxt, id, at_root) {
88 EntryPointType::None => {
89 if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) {
90 ctxt.tcx.sess.emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe });
93 _ if !matches!(ctxt.tcx.def_kind(id.owner_id), DefKind::Fn) => {
94 for attr in [sym::start, sym::rustc_main] {
95 if let Some(span) = attr_span_by_symbol(ctxt, id, attr) {
96 ctxt.tcx.sess.emit_err(AttrOnlyInFunctions { span, attr });
100 EntryPointType::MainNamed => (),
101 EntryPointType::OtherMain => {
102 if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) {
103 ctxt.tcx.sess.emit_err(AttrOnlyOnRootMain { span, attr: sym::unix_sigpipe });
105 ctxt.non_main_fns.push(ctxt.tcx.def_span(id.owner_id));
107 EntryPointType::RustcMainAttr => {
108 if ctxt.attr_main_fn.is_none() {
109 ctxt.attr_main_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id)));
111 ctxt.tcx.sess.emit_err(MultipleRustcMain {
112 span: ctxt.tcx.def_span(id.owner_id.to_def_id()),
113 first: ctxt.attr_main_fn.unwrap().1,
114 additional: ctxt.tcx.def_span(id.owner_id.to_def_id()),
118 EntryPointType::Start => {
119 if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) {
120 ctxt.tcx.sess.emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe });
122 if ctxt.start_fn.is_none() {
123 ctxt.start_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id)));
125 ctxt.tcx.sess.emit_err(MultipleStartFunctions {
126 span: ctxt.tcx.def_span(id.owner_id),
127 labeled: ctxt.tcx.def_span(id.owner_id.to_def_id()),
128 previous: ctxt.start_fn.unwrap().1,
135 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, EntryFnType)> {
136 if let Some((def_id, _)) = visitor.start_fn {
137 Some((def_id.to_def_id(), EntryFnType::Start))
138 } else if let Some((local_def_id, _)) = visitor.attr_main_fn {
139 let def_id = local_def_id.to_def_id();
140 Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) }))
142 if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() {
143 // non-local main imports are handled below
144 if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
145 tcx.sess.emit_err(ExternMain { span: tcx.def_span(def_id) });
149 if main_def.is_import && !tcx.features().imported_main {
150 let span = main_def.span;
152 &tcx.sess.parse_sess,
155 "using an imported function as entry point `main` is experimental",
159 return Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) }));
161 no_main_err(tcx, visitor);
166 fn sigpipe(tcx: TyCtxt<'_>, def_id: DefId) -> u8 {
167 if let Some(attr) = tcx.get_attr(def_id, sym::unix_sigpipe) {
168 match (attr.value_str(), attr.meta_item_list()) {
169 (Some(sym::inherit), None) => sigpipe::INHERIT,
170 (Some(sym::sig_ign), None) => sigpipe::SIG_IGN,
171 (Some(sym::sig_dfl), None) => sigpipe::SIG_DFL,
173 // Keep going so that `fn emit_malformed_attribute()` can print
174 // an excellent error message
178 tcx.sess.emit_err(UnixSigpipeValues { span: attr.span });
187 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) {
188 let sp = tcx.def_span(CRATE_DEF_ID);
189 if *tcx.sess.parse_sess.reached_eof.borrow() {
190 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
191 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
192 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
196 // There is no main function.
197 let mut has_filename = true;
198 let filename = tcx.sess.local_crate_source_file.clone().unwrap_or_else(|| {
199 has_filename = false;
202 let main_def_opt = tcx.resolutions(()).main_def;
203 let diagnostic_id = error_code!(E0601);
204 let add_teach_note = tcx.sess.teach(&diagnostic_id);
205 // The file may be empty, which leads to the diagnostic machinery not emitting this
206 // note. This is a relatively simple way to detect that case and emit a span-less
208 let file_empty = !tcx.sess.source_map().lookup_line(sp.hi()).is_ok();
210 tcx.sess.emit_err(NoMainErr {
212 crate_name: tcx.crate_name(LOCAL_CRATE),
216 non_main_fns: visitor.non_main_fns.clone(),
222 pub fn provide(providers: &mut Providers) {
223 *providers = Providers { entry_fn, ..*providers };