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