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