]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/entry.rs
Auto merge of #58710 - EdorianDark:master, r=sfackler
[rust.git] / src / librustc / middle / entry.rs
1 use crate::hir::map as hir_map;
2 use crate::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
3 use crate::session::{config, Session};
4 use crate::session::config::EntryFnType;
5 use syntax::attr;
6 use syntax::entry::EntryPointType;
7 use syntax_pos::Span;
8 use crate::hir::{HirId, Item, ItemKind, ImplItem, TraitItem};
9 use crate::hir::itemlikevisit::ItemLikeVisitor;
10 use crate::ty::TyCtxt;
11 use crate::ty::query::Providers;
12
13 struct EntryContext<'a, 'tcx: 'a> {
14     session: &'a Session,
15
16     map: &'a hir_map::Map<'tcx>,
17
18     // The top-level function called 'main'
19     main_fn: Option<(HirId, Span)>,
20
21     // The function that has attribute named 'main'
22     attr_main_fn: Option<(HirId, Span)>,
23
24     // The function that has the attribute 'start' on it
25     start_fn: Option<(HirId, Span)>,
26
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<(HirId, Span)> ,
30 }
31
32 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
33     fn visit_item(&mut self, item: &'tcx Item) {
34         let def_id = self.map.local_def_id_from_hir_id(item.hir_id);
35         let def_key = self.map.def_key(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) {
41         // entry fn is never a trait item
42     }
43
44     fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem) {
45         // entry fn is never an impl item
46     }
47 }
48
49 fn entry_fn(tcx: TyCtxt<'_, '_, '_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
50     assert_eq!(cnum, LOCAL_CRATE);
51
52     let any_exe = tcx.sess.crate_types.borrow().iter().any(|ty| {
53         *ty == config::CrateType::Executable
54     });
55     if !any_exe {
56         // No need to find a main function
57         return None;
58     }
59
60     // If the user wants no main function at all, then stop here.
61     if attr::contains_name(&tcx.hir().krate().attrs, "no_main") {
62         return None;
63     }
64
65     let mut ctxt = EntryContext {
66         session: tcx.sess,
67         map: tcx.hir(),
68         main_fn: None,
69         attr_main_fn: None,
70         start_fn: None,
71         non_main_fns: Vec::new(),
72     };
73
74     tcx.hir().krate().visit_all_item_likes(&mut ctxt);
75
76     configure_main(tcx, &ctxt)
77 }
78
79 // Beware, this is duplicated in `libsyntax/entry.rs`, so make sure to keep
80 // them in sync.
81 fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType {
82     match item.node {
83         ItemKind::Fn(..) => {
84             if attr::contains_name(&item.attrs, "start") {
85                 EntryPointType::Start
86             } else if attr::contains_name(&item.attrs, "main") {
87                 EntryPointType::MainAttr
88             } else if item.ident.name == "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         _ => EntryPointType::None,
100     }
101 }
102
103
104 fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
105     match entry_point_type(item, at_root) {
106         EntryPointType::MainNamed => {
107             if ctxt.main_fn.is_none() {
108                 ctxt.main_fn = Some((item.hir_id, item.span));
109             } else {
110                 span_err!(ctxt.session, item.span, E0136,
111                           "multiple 'main' functions");
112             }
113         },
114         EntryPointType::OtherMain => {
115             ctxt.non_main_fns.push((item.hir_id, item.span));
116         },
117         EntryPointType::MainAttr => {
118             if ctxt.attr_main_fn.is_none() {
119                 ctxt.attr_main_fn = Some((item.hir_id, item.span));
120             } else {
121                 struct_span_err!(ctxt.session, item.span, E0137,
122                                  "multiple functions with a #[main] attribute")
123                 .span_label(item.span, "additional #[main] function")
124                 .span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function")
125                 .emit();
126             }
127         },
128         EntryPointType::Start => {
129             if ctxt.start_fn.is_none() {
130                 ctxt.start_fn = Some((item.hir_id, item.span));
131             } else {
132                 struct_span_err!(ctxt.session, item.span, E0138, "multiple 'start' functions")
133                     .span_label(ctxt.start_fn.unwrap().1, "previous `start` function here")
134                     .span_label(item.span, "multiple `start` functions")
135                     .emit();
136             }
137         }
138         EntryPointType::None => (),
139     }
140 }
141
142 fn configure_main(
143     tcx: TyCtxt<'_, '_, '_>,
144     visitor: &EntryContext<'_, '_>,
145 ) -> Option<(DefId, EntryFnType)> {
146     if let Some((hir_id, _)) = visitor.start_fn {
147         Some((tcx.hir().local_def_id_from_hir_id(hir_id), EntryFnType::Start))
148     } else if let Some((hir_id, _)) = visitor.attr_main_fn {
149         Some((tcx.hir().local_def_id_from_hir_id(hir_id), EntryFnType::Main))
150     } else if let Some((hir_id, _)) = visitor.main_fn {
151         Some((tcx.hir().local_def_id_from_hir_id(hir_id), EntryFnType::Main))
152     } else {
153         // No main function
154         let mut err = struct_err!(tcx.sess, E0601,
155             "`main` function not found in crate `{}`", tcx.crate_name(LOCAL_CRATE));
156         if !visitor.non_main_fns.is_empty() {
157             // There were some functions named 'main' though. Try to give the user a hint.
158             err.note("the main function must be defined at the crate level \
159                       but you have one or more functions named 'main' that are not \
160                       defined at the crate level. Either move the definition or \
161                       attach the `#[main]` attribute to override this behavior.");
162             for &(_, span) in &visitor.non_main_fns {
163                 err.span_note(span, "here is a function named 'main'");
164             }
165             err.emit();
166             tcx.sess.abort_if_errors();
167         } else {
168             if let Some(ref filename) = tcx.sess.local_crate_source_file {
169                 err.note(&format!("consider adding a `main` function to `{}`", filename.display()));
170             }
171             if tcx.sess.teach(&err.get_code().unwrap()) {
172                 err.note("If you don't know the basics of Rust, you can go look to the Rust Book \
173                           to get started: https://doc.rust-lang.org/book/");
174             }
175             err.emit();
176         }
177
178         None
179     }
180 }
181
182 pub fn find_entry_point(tcx: TyCtxt<'_, '_, '_>) -> Option<(DefId, EntryFnType)> {
183     tcx.entry_fn(LOCAL_CRATE)
184 }
185
186 pub fn provide(providers: &mut Providers<'_>) {
187     *providers = Providers {
188         entry_fn,
189         ..*providers
190     };
191 }