]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/entry.rs
Merge commit '598f0909568a51de8a2d1148f55a644fd8dffad0' into sync_cg_clif-2023-01-24
[rust.git] / compiler / rustc_passes / src / entry.rs
1 use rustc_ast::entry::EntryPointType;
2 use rustc_errors::error_code;
3 use rustc_hir::def::DefKind;
4 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
5 use rustc_hir::{ItemId, Node, CRATE_HIR_ID};
6 use rustc_middle::ty::query::Providers;
7 use rustc_middle::ty::{DefIdTree, TyCtxt};
8 use rustc_session::config::{sigpipe, CrateType, EntryFnType};
9 use rustc_session::parse::feature_err;
10 use rustc_span::symbol::sym;
11 use rustc_span::{Span, Symbol};
12
13 use crate::errors::{
14     AttrOnlyInFunctions, AttrOnlyOnMain, AttrOnlyOnRootMain, ExternMain, MultipleRustcMain,
15     MultipleStartFunctions, NoMainErr, UnixSigpipeValues,
16 };
17
18 struct EntryContext<'tcx> {
19     tcx: TyCtxt<'tcx>,
20
21     /// The function that has attribute named `main`.
22     attr_main_fn: Option<(LocalDefId, Span)>,
23
24     /// The function that has the attribute 'start' on it.
25     start_fn: Option<(LocalDefId, 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<Span>,
30 }
31
32 fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
33     let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
34     if !any_exe {
35         // No need to find a main function.
36         return None;
37     }
38
39     // If the user wants no main function at all, then stop here.
40     if tcx.sess.contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) {
41         return None;
42     }
43
44     let mut ctxt =
45         EntryContext { tcx, attr_main_fn: None, start_fn: None, non_main_fns: Vec::new() };
46
47     for id in tcx.hir().items() {
48         find_item(id, &mut ctxt);
49     }
50
51     configure_main(tcx, &ctxt)
52 }
53
54 // Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
55 // (with `ast::Item`), so make sure to keep them in sync.
56 // A small optimization was added so that hir::Item is fetched only when needed.
57 // An equivalent optimization was not applied to the duplicated code in test_harness.rs.
58 fn entry_point_type(ctxt: &EntryContext<'_>, id: ItemId, at_root: bool) -> EntryPointType {
59     let attrs = ctxt.tcx.hir().attrs(id.hir_id());
60     if ctxt.tcx.sess.contains_name(attrs, sym::start) {
61         EntryPointType::Start
62     } else if ctxt.tcx.sess.contains_name(attrs, sym::rustc_main) {
63         EntryPointType::RustcMainAttr
64     } else {
65         if let Some(name) = ctxt.tcx.opt_item_name(id.owner_id.to_def_id())
66             && name == sym::main {
67             if at_root {
68                 // This is a top-level function so can be `main`.
69                 EntryPointType::MainNamed
70             } else {
71                 EntryPointType::OtherMain
72             }
73         } else {
74             EntryPointType::None
75         }
76     }
77 }
78
79 fn attr_span_by_symbol(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol) -> Option<Span> {
80     let attrs = ctxt.tcx.hir().attrs(id.hir_id());
81     ctxt.tcx.sess.find_by_name(attrs, sym).map(|attr| attr.span)
82 }
83
84 fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) {
85     let at_root = ctxt.tcx.opt_local_parent(id.owner_id.def_id) == Some(CRATE_DEF_ID);
86
87     match entry_point_type(ctxt, id, at_root) {
88         EntryPointType::None => {
89             if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) {
90                 ctxt.tcx.sess.emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe });
91             }
92         }
93         _ if !matches!(ctxt.tcx.def_kind(id.owner_id), DefKind::Fn) => {
94             for attr in [sym::start, sym::rustc_main] {
95                 if let Some(span) = attr_span_by_symbol(ctxt, id, attr) {
96                     ctxt.tcx.sess.emit_err(AttrOnlyInFunctions { span, attr });
97                 }
98             }
99         }
100         EntryPointType::MainNamed => (),
101         EntryPointType::OtherMain => {
102             if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) {
103                 ctxt.tcx.sess.emit_err(AttrOnlyOnRootMain { span, attr: sym::unix_sigpipe });
104             }
105             ctxt.non_main_fns.push(ctxt.tcx.def_span(id.owner_id));
106         }
107         EntryPointType::RustcMainAttr => {
108             if ctxt.attr_main_fn.is_none() {
109                 ctxt.attr_main_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id)));
110             } else {
111                 ctxt.tcx.sess.emit_err(MultipleRustcMain {
112                     span: ctxt.tcx.def_span(id.owner_id.to_def_id()),
113                     first: ctxt.attr_main_fn.unwrap().1,
114                     additional: ctxt.tcx.def_span(id.owner_id.to_def_id()),
115                 });
116             }
117         }
118         EntryPointType::Start => {
119             if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) {
120                 ctxt.tcx.sess.emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe });
121             }
122             if ctxt.start_fn.is_none() {
123                 ctxt.start_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id)));
124             } else {
125                 ctxt.tcx.sess.emit_err(MultipleStartFunctions {
126                     span: ctxt.tcx.def_span(id.owner_id),
127                     labeled: ctxt.tcx.def_span(id.owner_id.to_def_id()),
128                     previous: ctxt.start_fn.unwrap().1,
129                 });
130             }
131         }
132     }
133 }
134
135 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, EntryFnType)> {
136     if let Some((def_id, _)) = visitor.start_fn {
137         Some((def_id.to_def_id(), EntryFnType::Start))
138     } else if let Some((local_def_id, _)) = visitor.attr_main_fn {
139         let def_id = local_def_id.to_def_id();
140         Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) }))
141     } else {
142         if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() {
143             // non-local main imports are handled below
144             if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
145                 tcx.sess.emit_err(ExternMain { span: tcx.def_span(def_id) });
146                 return None;
147             }
148
149             if main_def.is_import && !tcx.features().imported_main {
150                 let span = main_def.span;
151                 feature_err(
152                     &tcx.sess.parse_sess,
153                     sym::imported_main,
154                     span,
155                     "using an imported function as entry point `main` is experimental",
156                 )
157                 .emit();
158             }
159             return Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) }));
160         }
161         no_main_err(tcx, visitor);
162         None
163     }
164 }
165
166 fn sigpipe(tcx: TyCtxt<'_>, def_id: DefId) -> u8 {
167     if let Some(attr) = tcx.get_attr(def_id, sym::unix_sigpipe) {
168         match (attr.value_str(), attr.meta_item_list()) {
169             (Some(sym::inherit), None) => sigpipe::INHERIT,
170             (Some(sym::sig_ign), None) => sigpipe::SIG_IGN,
171             (Some(sym::sig_dfl), None) => sigpipe::SIG_DFL,
172             (_, Some(_)) => {
173                 // Keep going so that `fn emit_malformed_attribute()` can print
174                 // an excellent error message
175                 sigpipe::DEFAULT
176             }
177             _ => {
178                 tcx.sess.emit_err(UnixSigpipeValues { span: attr.span });
179                 sigpipe::DEFAULT
180             }
181         }
182     } else {
183         sigpipe::DEFAULT
184     }
185 }
186
187 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) {
188     let sp = tcx.def_span(CRATE_DEF_ID);
189     if *tcx.sess.parse_sess.reached_eof.borrow() {
190         // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
191         // the missing `fn main()` then as it might have been hidden inside an unclosed block.
192         tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
193         return;
194     }
195
196     // There is no main function.
197     let mut has_filename = true;
198     let filename = tcx.sess.local_crate_source_file().unwrap_or_else(|| {
199         has_filename = false;
200         Default::default()
201     });
202     let main_def_opt = tcx.resolutions(()).main_def;
203     let diagnostic_id = error_code!(E0601);
204     let add_teach_note = tcx.sess.teach(&diagnostic_id);
205     // The file may be empty, which leads to the diagnostic machinery not emitting this
206     // note. This is a relatively simple way to detect that case and emit a span-less
207     // note instead.
208     let file_empty = !tcx.sess.source_map().lookup_line(sp.hi()).is_ok();
209
210     tcx.sess.emit_err(NoMainErr {
211         sp,
212         crate_name: tcx.crate_name(LOCAL_CRATE),
213         has_filename,
214         filename,
215         file_empty,
216         non_main_fns: visitor.non_main_fns.clone(),
217         main_def_opt,
218         add_teach_note,
219     });
220 }
221
222 pub fn provide(providers: &mut Providers) {
223     *providers = Providers { entry_fn, ..*providers };
224 }