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