]> git.proxmox.com Git - rustc.git/blame - src/librustc_passes/entry.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_passes / entry.rs
CommitLineData
74b04a01
XL
1use rustc_ast::attr;
2use rustc_ast::entry::EntryPointType;
dfeec247
XL
3use rustc_errors::struct_span_err;
4use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5use rustc_hir::itemlikevisit::ItemLikeVisitor;
6use rustc_hir::{HirId, ImplItem, Item, ItemKind, TraitItem};
ba9703b0
XL
7use rustc_middle::hir::map::Map;
8use rustc_middle::ty::query::Providers;
9use rustc_middle::ty::TyCtxt;
10use rustc_session::config::EntryFnType;
11use rustc_session::{config, Session};
dfeec247
XL
12use rustc_span::symbol::sym;
13use rustc_span::{Span, DUMMY_SP};
60c5eb7d 14
dc9dc135 15struct EntryContext<'a, 'tcx> {
1a4d82fc 16 session: &'a Session,
970d7e83 17
ba9703b0 18 map: Map<'tcx>,
970d7e83 19
e1599b0c 20 /// The top-level function called `main`.
532ac7d7 21 main_fn: Option<(HirId, Span)>,
970d7e83 22
e1599b0c 23 /// The function that has attribute named `main`.
532ac7d7 24 attr_main_fn: Option<(HirId, Span)>,
970d7e83 25
e1599b0c 26 /// The function that has the attribute 'start' on it.
532ac7d7 27 start_fn: Option<(HirId, Span)>,
970d7e83 28
e1599b0c
XL
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.
dfeec247 31 non_main_fns: Vec<(HirId, Span)>,
970d7e83
LB
32}
33
476ff2be 34impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
dfeec247 35 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
416331ca 36 let def_id = self.map.local_def_id(item.hir_id);
ba9703b0 37 let def_key = self.map.def_key(def_id.expect_local());
92a42be0
SL
38 let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
39 find_item(item, self, at_root);
1a4d82fc 40 }
476ff2be 41
dfeec247 42 fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
e1599b0c 43 // Entry fn is never a trait item.
32a655c1 44 }
476ff2be 45
dfeec247 46 fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
e1599b0c 47 // Entry fn is never a trait item.
476ff2be 48 }
1a4d82fc 49}
970d7e83 50
dc9dc135 51fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
9fa01778
XL
52 assert_eq!(cnum, LOCAL_CRATE);
53
dfeec247
XL
54 let any_exe =
55 tcx.sess.crate_types.borrow().iter().any(|ty| *ty == config::CrateType::Executable);
1a4d82fc 56 if !any_exe {
e1599b0c 57 // No need to find a main function.
9fa01778 58 return None;
970d7e83
LB
59 }
60
1a4d82fc 61 // If the user wants no main function at all, then stop here.
ba9703b0 62 if attr::contains_name(&tcx.hir().krate().item.attrs, sym::no_main) {
9fa01778 63 return None;
1a4d82fc
JJ
64 }
65
66 let mut ctxt = EntryContext {
9fa01778
XL
67 session: tcx.sess,
68 map: tcx.hir(),
970d7e83
LB
69 main_fn: None,
70 attr_main_fn: None,
71 start_fn: None,
1a4d82fc 72 non_main_fns: Vec::new(),
970d7e83
LB
73 };
74
9fa01778 75 tcx.hir().krate().visit_all_item_likes(&mut ctxt);
970d7e83 76
9fa01778 77 configure_main(tcx, &ctxt)
970d7e83
LB
78}
79
74b04a01 80// Beware, this is duplicated in `librustc_ast/entry.rs`, so make sure to keep
e9174d1e 81// them in sync.
dfeec247 82fn entry_point_type(item: &Item<'_>, at_root: bool) -> EntryPointType {
e74abb32 83 match item.kind {
8faf50e0 84 ItemKind::Fn(..) => {
48663c56 85 if attr::contains_name(&item.attrs, sym::start) {
e9174d1e 86 EntryPointType::Start
48663c56 87 } else if attr::contains_name(&item.attrs, sym::main) {
e9174d1e 88 EntryPointType::MainAttr
48663c56 89 } else if item.ident.name == sym::main {
92a42be0 90 if at_root {
e1599b0c 91 // This is a top-level function so can be `main`.
e9174d1e 92 EntryPointType::MainNamed
970d7e83 93 } else {
e9174d1e 94 EntryPointType::OtherMain
970d7e83 95 }
e9174d1e
SL
96 } else {
97 EntryPointType::None
970d7e83
LB
98 }
99 }
e9174d1e
SL
100 _ => EntryPointType::None,
101 }
102}
103
dfeec247 104fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
92a42be0 105 match entry_point_type(item, at_root) {
e9174d1e
SL
106 EntryPointType::MainNamed => {
107 if ctxt.main_fn.is_none() {
532ac7d7 108 ctxt.main_fn = Some((item.hir_id, item.span));
e9174d1e 109 } else {
dfeec247
XL
110 struct_span_err!(ctxt.session, item.span, E0136, "multiple `main` functions")
111 .emit();
e9174d1e 112 }
dfeec247 113 }
e9174d1e 114 EntryPointType::OtherMain => {
532ac7d7 115 ctxt.non_main_fns.push((item.hir_id, item.span));
dfeec247 116 }
e9174d1e
SL
117 EntryPointType::MainAttr => {
118 if ctxt.attr_main_fn.is_none() {
532ac7d7 119 ctxt.attr_main_fn = Some((item.hir_id, item.span));
e9174d1e 120 } else {
dfeec247
XL
121 struct_span_err!(
122 ctxt.session,
123 item.span,
124 E0137,
125 "multiple functions with a `#[main]` attribute"
126 )
416331ca
XL
127 .span_label(item.span, "additional `#[main]` function")
128 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
5bcae85e 129 .emit();
e9174d1e 130 }
dfeec247 131 }
e9174d1e
SL
132 EntryPointType::Start => {
133 if ctxt.start_fn.is_none() {
532ac7d7 134 ctxt.start_fn = Some((item.hir_id, item.span));
e9174d1e 135 } else {
e1599b0c 136 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
dfeec247 137 .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
7cac9316 138 .span_label(item.span, "multiple `start` functions")
5bcae85e 139 .emit();
e9174d1e 140 }
9fa01778
XL
141 }
142 EntryPointType::None => (),
970d7e83 143 }
970d7e83
LB
144}
145
dc9dc135 146fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(DefId, EntryFnType)> {
532ac7d7 147 if let Some((hir_id, _)) = visitor.start_fn {
416331ca 148 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start))
532ac7d7 149 } else if let Some((hir_id, _)) = visitor.attr_main_fn {
416331ca 150 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
532ac7d7 151 } else if let Some((hir_id, _)) = visitor.main_fn {
416331ca 152 Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
970d7e83 153 } else {
e1599b0c 154 no_main_err(tcx, visitor);
9fa01778 155 None
970d7e83
LB
156 }
157}
9fa01778 158
e1599b0c 159fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
ba9703b0 160 let sp = tcx.hir().krate().item.span;
e74abb32
XL
161 if *tcx.sess.parse_sess.reached_eof.borrow() {
162 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
163 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
164 tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
165 return;
166 }
167
e1599b0c 168 // There is no main function.
dfeec247
XL
169 let mut err = struct_span_err!(
170 tcx.sess,
171 DUMMY_SP,
172 E0601,
173 "`main` function not found in crate `{}`",
174 tcx.crate_name(LOCAL_CRATE)
175 );
e1599b0c
XL
176 let filename = &tcx.sess.local_crate_source_file;
177 let note = if !visitor.non_main_fns.is_empty() {
178 for &(_, span) in &visitor.non_main_fns {
179 err.span_note(span, "here is a function named `main`");
180 }
181 err.note("you have one or more functions named `main` not defined at the crate level");
dfeec247
XL
182 err.help(
183 "either move the `main` function definitions or attach the `#[main]` attribute \
184 to one of them",
185 );
e1599b0c 186 // There were some functions named `main` though. Try to give the user a hint.
dfeec247
XL
187 format!(
188 "the main function must be defined at the crate level{}",
189 filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
190 )
e1599b0c
XL
191 } else if let Some(filename) = filename {
192 format!("consider adding a `main` function to `{}`", filename.display())
193 } else {
194 String::from("consider adding a `main` function at the crate level")
195 };
e1599b0c
XL
196 // The file may be empty, which leads to the diagnostic machinery not emitting this
197 // note. This is a relatively simple way to detect that case and emit a span-less
198 // note instead.
74b04a01 199 if tcx.sess.source_map().lookup_line(sp.lo()).is_ok() {
e1599b0c
XL
200 err.set_span(sp);
201 err.span_label(sp, &note);
202 } else {
203 err.note(&note);
204 }
205 if tcx.sess.teach(&err.get_code().unwrap()) {
dfeec247
XL
206 err.note(
207 "If you don't know the basics of Rust, you can go look to the Rust Book \
208 to get started: https://doc.rust-lang.org/book/",
209 );
e1599b0c
XL
210 }
211 err.emit();
212}
213
dc9dc135 214pub fn find_entry_point(tcx: TyCtxt<'_>) -> Option<(DefId, EntryFnType)> {
9fa01778
XL
215 tcx.entry_fn(LOCAL_CRATE)
216}
217
218pub fn provide(providers: &mut Providers<'_>) {
dfeec247 219 *providers = Providers { entry_fn, ..*providers };
9fa01778 220}