Line data Source code
1 : // Copyright (C) 2020-2026 Free Software Foundation, Inc.
2 :
3 : // This file is part of GCC.
4 :
5 : // GCC is free software; you can redistribute it and/or modify it under
6 : // the terms of the GNU General Public License as published by the Free
7 : // Software Foundation; either version 3, or (at your option) any later
8 : // version.
9 :
10 : // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 : // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 : // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 : // for more details.
14 :
15 : // You should have received a copy of the GNU General Public License
16 : // along with GCC; see the file COPYING3. If not see
17 : // <http://www.gnu.org/licenses/>.
18 :
19 : #include "rust-session-manager.h"
20 : #include "rust-collect-lang-items.h"
21 : #include "rust-desugar-for-loops.h"
22 : #include "rust-desugar-question-mark.h"
23 : #include "rust-desugar-apit.h"
24 : #include "rust-diagnostics.h"
25 : #include "rust-expression-yeast.h"
26 : #include "rust-hir-pattern-analysis.h"
27 : #include "rust-finalized-name-resolution-context.h"
28 : #include "rust-location.h"
29 : #include "rust-unsafe-checker.h"
30 : #include "rust-lex.h"
31 : #include "rust-parse.h"
32 : #include "rust-macro-expand.h"
33 : #include "rust-ast-lower.h"
34 : #include "rust-hir-type-check.h"
35 : #include "rust-privacy-check.h"
36 : #include "rust-const-checker.h"
37 : #include "rust-feature-collector.h"
38 : #include "rust-feature-gate.h"
39 : #include "rust-compile.h"
40 : #include "rust-cfg-parser.h"
41 : #include "rust-lint-scan-deadcode.h"
42 : #include "rust-lint-unused-var.h"
43 : #include "rust-unused-checker.h"
44 : #include "rust-readonly-check.h"
45 : #include "rust-hir-dump.h"
46 : #include "rust-ast-dump.h"
47 : #include "rust-export-metadata.h"
48 : #include "rust-imports.h"
49 : #include "rust-extern-crate.h"
50 : #include "rust-attributes.h"
51 : #include "rust-name-resolution-context.h"
52 : #include "rust-early-name-resolver-2.0.h"
53 : #include "rust-late-name-resolver-2.0.h"
54 : #include "rust-resolve-builtins.h"
55 : #include "rust-early-cfg-strip.h"
56 : #include "rust-cfg-strip.h"
57 : #include "rust-expand-visitor.h"
58 : #include "rust-unicode.h"
59 : #include "rust-attribute-values.h"
60 : #include "rust-borrow-checker.h"
61 : #include "rust-ast-validation.h"
62 : #include "rust-tyty-variance-analysis.h"
63 : #include "rust-attribute-checker.h"
64 : #include "rust-builtin-attribute-checker.h"
65 : #include "rust-extern-crate-loader.h"
66 :
67 : #include "input.h"
68 : #include "selftest.h"
69 : #include "tm.h"
70 : #include "rust-target.h"
71 : #include "rust-system.h"
72 :
73 : extern bool saw_errors (void);
74 :
75 : extern Linemap *rust_get_linemap ();
76 :
77 : namespace Rust {
78 :
79 : const char *kLexDumpFile = "gccrs.lex.dump";
80 : const char *kASTDumpFile = "gccrs.ast.dump";
81 : const char *kASTPrettyDumpFile = "gccrs.ast-pretty.dump";
82 : const char *kASTPrettyInternalDumpFile = "gccrs.ast-pretty-internal.dump";
83 : const char *kASTPrettyDumpFileExpanded = "gccrs.ast-pretty-expanded.dump";
84 : const char *kASTExpandedDumpFile = "gccrs.ast-expanded.dump";
85 : const char *kASTmacroResolutionDumpFile = "gccrs.ast-macro-resolution.dump";
86 : const char *kASTlabelResolutionDumpFile = "gccrs.ast-label-resolution.dump";
87 : const char *kASTtypeResolutionDumpFile = "gccrs.ast-type-resolution.dump";
88 : const char *kASTvalueResolutionDumpFile = "gccrs.ast-value-resolution.dump";
89 : const char *kHIRDumpFile = "gccrs.hir.dump";
90 : const char *kHIRPrettyDumpFile = "gccrs.hir-pretty.dump";
91 : const char *kHIRTypeResolutionDumpFile = "gccrs.type-resolution.dump";
92 : const char *kTargetOptionsDumpFile = "gccrs.target-options.dump";
93 :
94 : const std::string kDefaultCrateName = "rust_out";
95 : const size_t kMaxNameLength = 64;
96 :
97 : Session &
98 136342416 : Session::get_instance ()
99 : {
100 136347534 : static Session instance{};
101 136342416 : return instance;
102 : }
103 :
104 : static std::string
105 5100 : infer_crate_name (const std::string &filename)
106 :
107 : {
108 5100 : if (filename == "-")
109 0 : return kDefaultCrateName;
110 :
111 5100 : std::string crate = std::string (filename);
112 5100 : size_t path_sep = crate.find_last_of (file_separator);
113 :
114 : // find the base filename
115 5100 : if (path_sep != std::string::npos)
116 5096 : crate.erase (0, path_sep + 1);
117 :
118 : // find the file stem name (remove file extension)
119 5100 : size_t ext_position = crate.find_last_of ('.');
120 5100 : if (ext_position != std::string::npos)
121 5099 : crate.erase (ext_position);
122 :
123 : // Replace all the '-' symbols with '_' per Rust rules
124 65295 : for (auto &c : crate)
125 : {
126 60195 : if (c == '-')
127 1655 : c = '_';
128 : }
129 5100 : return crate;
130 5100 : }
131 :
132 : /* Validate the crate name using the ASCII rules */
133 :
134 : static bool
135 5130 : validate_crate_name (const std::string &crate_name, Error &error)
136 : {
137 5130 : tl::optional<Utf8String> utf8_name_opt
138 5130 : = Utf8String::make_utf8_string (crate_name);
139 5130 : if (!utf8_name_opt.has_value ())
140 : {
141 0 : error = Error (UNDEF_LOCATION, "crate name is not a valid UTF-8 string");
142 0 : return false;
143 : }
144 :
145 5130 : std::vector<Codepoint> uchars = utf8_name_opt->get_chars ();
146 5130 : if (uchars.empty ())
147 : {
148 0 : error = Error (UNDEF_LOCATION, "crate name cannot be empty");
149 0 : return false;
150 : }
151 5130 : if (uchars.size () > kMaxNameLength)
152 : {
153 0 : error = Error (UNDEF_LOCATION, "crate name cannot exceed %lu characters",
154 0 : (unsigned long) kMaxNameLength);
155 0 : return false;
156 : }
157 65506 : for (Codepoint &c : uchars)
158 : {
159 60384 : if (!(is_alphabetic (c.value) || is_numeric (c.value) || c.value == '_'))
160 : {
161 8 : error
162 8 : = Error (UNDEF_LOCATION, "invalid character %qs in crate name: %qs",
163 8 : c.as_string ().c_str (), crate_name.c_str ());
164 8 : return false;
165 : }
166 : }
167 : return true;
168 5130 : }
169 :
170 : static bool
171 4961 : has_attribute (AST::Crate crate, std::string attribute)
172 : {
173 4961 : auto &crate_attrs = crate.get_inner_attrs ();
174 15044 : auto has_attr = [&attribute] (AST::Attribute &attr) {
175 10083 : return attr.as_string () == attribute;
176 4961 : };
177 4961 : return std::any_of (crate_attrs.begin (), crate_attrs.end (), has_attr);
178 : }
179 :
180 : void
181 5117 : Session::init ()
182 : {
183 : // initialize target hooks
184 5117 : targetrustm.rust_cpu_info ();
185 5117 : targetrustm.rust_os_info ();
186 :
187 : // target-independent values that should exist in all targets
188 5117 : options.target_data.insert_key_value_pair ("target_pointer_width",
189 5117 : std::to_string (POINTER_SIZE));
190 5117 : options.target_data.insert_key_value_pair ("target_endian", BYTES_BIG_ENDIAN
191 5117 : ? "big"
192 : : "little");
193 :
194 : // setup singleton linemap
195 5117 : linemap = rust_get_linemap ();
196 :
197 : // setup backend to GCC GIMPLE
198 5117 : Backend::init ();
199 :
200 : // setup mappings class
201 5117 : mappings = Analysis::Mappings::get ();
202 5117 : }
203 :
204 : /* Initialise default options. Actually called before handle_option, unlike init
205 : * itself. */
206 : void
207 5118 : Session::init_options ()
208 5118 : {}
209 :
210 : // Handle option selection.
211 : bool
212 46351 : Session::handle_option (
213 : enum opt_code code, const char *arg, HOST_WIDE_INT value ATTRIBUTE_UNUSED,
214 : int kind ATTRIBUTE_UNUSED, location_t loc,
215 : const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED)
216 : {
217 : // used to store whether results of various stuff are successful
218 46351 : bool ret = true;
219 :
220 : // Handles options as listed in lang.opt.
221 46351 : switch (code)
222 : {
223 35824 : case OPT_I:
224 35824 : case OPT_L:
225 35824 : {
226 : // TODO: add search path
227 35824 : const std::string p = std::string (arg);
228 35824 : add_search_path (p);
229 35824 : }
230 35824 : break;
231 :
232 0 : case OPT_frust_extern_:
233 0 : {
234 0 : std::string input (arg);
235 0 : ret = handle_extern_option (input);
236 0 : }
237 0 : break;
238 14 : case OPT_frust_crate_:
239 : // set the crate name
240 14 : if (arg != nullptr)
241 : {
242 14 : auto error = Error (UNDEF_LOCATION, std::string ());
243 14 : if ((ret = validate_crate_name (arg, error)))
244 : {
245 13 : options.set_crate_name (arg);
246 13 : options.crate_name_set_manually = true;
247 : }
248 : else
249 : {
250 1 : rust_assert (!error.message.empty ());
251 1 : error.emit ();
252 : }
253 14 : }
254 : else
255 : ret = false;
256 : break;
257 :
258 1 : case OPT_frust_crate_attr_:
259 1 : if (arg != nullptr)
260 : {
261 1 : options.addional_attributes.emplace_back (arg, loc);
262 : }
263 : break;
264 3 : case OPT_frust_dump_:
265 : // enable dump and return whether this was successful
266 3 : if (arg != nullptr)
267 : {
268 3 : ret = enable_dump (std::string (arg));
269 : }
270 : else
271 : {
272 : ret = false;
273 : }
274 : break;
275 :
276 2 : case OPT_frust_mangling_:
277 2 : Compile::Mangler::set_mangling (flag_rust_mangling);
278 2 : break;
279 :
280 83 : case OPT_frust_cfg_:
281 83 : {
282 83 : auto string_arg = std::string (arg);
283 83 : ret = handle_cfg_option (string_arg);
284 83 : break;
285 83 : }
286 21 : case OPT_frust_crate_type_:
287 21 : options.set_crate_type (flag_rust_crate_type);
288 21 : break;
289 13 : case OPT_frust_edition_:
290 13 : options.set_edition (flag_rust_edition);
291 13 : break;
292 40 : case OPT_frust_compat_version_:
293 40 : options.set_compat_version (flag_rust_compat_version);
294 40 : break;
295 53 : case OPT_frust_compile_until_:
296 53 : options.set_compile_step (flag_rust_compile_until);
297 53 : break;
298 0 : case OPT_frust_metadata_output_:
299 0 : options.set_metadata_output (arg);
300 0 : break;
301 0 : case OPT_frust_panic_:
302 0 : options.set_panic_strategy (flag_rust_panic);
303 0 : break;
304 :
305 : default:
306 : break;
307 : }
308 :
309 46351 : return ret;
310 : }
311 :
312 : bool
313 0 : Session::handle_extern_option (std::string &input)
314 : {
315 0 : auto pos = input.find ('=');
316 0 : if (std::string::npos == pos)
317 : return false;
318 :
319 0 : std::string libname = input.substr (0, pos);
320 0 : std::string path = input.substr (pos + 1);
321 :
322 0 : extern_crates.insert ({libname, path});
323 0 : return true;
324 0 : }
325 :
326 : bool
327 83 : Session::handle_cfg_option (std::string &input)
328 : {
329 83 : std::string key;
330 83 : std::string value;
331 :
332 : // Refactor this if needed
333 83 : if (!parse_cfg_option (input, key, value))
334 : {
335 0 : rust_error_at (
336 : UNDEF_LOCATION,
337 : "invalid argument to %<-frust-cfg%>: Accepted formats are "
338 : "%<-frust-cfg=key%> or %<-frust-cfg=key=\"value\"%> (quoted)");
339 0 : return false;
340 : }
341 :
342 83 : if (value.empty ())
343 : // rustc does not seem to error on dup key
344 132 : options.target_data.insert_key (key);
345 : else
346 51 : options.target_data.insert_key_value_pair (key, value);
347 :
348 : return true;
349 83 : }
350 :
351 : /* Enables a certain dump depending on the name passed in. Returns true if
352 : * name is valid, false otherwise. */
353 : bool
354 3 : Session::enable_dump (std::string arg)
355 : {
356 3 : const std::string INTERNAL_DUMP_OPTION_TEXT = "internal";
357 :
358 3 : if (arg.empty ())
359 : {
360 0 : rust_error_at (
361 : UNDEF_LOCATION,
362 : "dump option was not given a name. choose %<lex%>, %<ast-pretty%>, "
363 : "%<register_plugins%>, %<injection%>, "
364 : "%<expansion%>, %<resolution%>, %<target_options%>, %<hir%>, "
365 : "%<hir-pretty%>, %<bir%> or %<all%>");
366 0 : return false;
367 : }
368 :
369 3 : if (arg == "all")
370 : {
371 0 : options.enable_all_dump_options ();
372 : }
373 3 : else if (arg == "lex")
374 : {
375 1 : options.enable_dump_option (CompileOptions::LEXER_DUMP);
376 : }
377 2 : else if (arg == "ast-pretty")
378 : {
379 0 : options.enable_dump_option (CompileOptions::AST_DUMP_PRETTY);
380 : }
381 2 : else if (arg == "register_plugins")
382 : {
383 0 : options.enable_dump_option (CompileOptions::REGISTER_PLUGINS_DUMP);
384 : }
385 2 : else if (arg == "injection")
386 : {
387 0 : options.enable_dump_option (CompileOptions::INJECTION_DUMP);
388 : }
389 2 : else if (arg == "expansion")
390 : {
391 0 : options.enable_dump_option (CompileOptions::EXPANSION_DUMP);
392 : }
393 2 : else if (arg == "resolution")
394 : {
395 0 : options.enable_dump_option (CompileOptions::RESOLUTION_DUMP);
396 : }
397 2 : else if (arg == "target_options")
398 : {
399 0 : options.enable_dump_option (CompileOptions::TARGET_OPTION_DUMP);
400 : }
401 2 : else if (arg == "hir")
402 : {
403 0 : options.enable_dump_option (CompileOptions::HIR_DUMP);
404 : }
405 2 : else if (arg == "hir-pretty")
406 : {
407 0 : options.enable_dump_option (CompileOptions::HIR_DUMP_PRETTY);
408 : }
409 2 : else if (arg == "bir")
410 : {
411 2 : options.enable_dump_option (CompileOptions::BIR_DUMP);
412 : }
413 0 : else if (!arg.compare (0, INTERNAL_DUMP_OPTION_TEXT.size (),
414 : INTERNAL_DUMP_OPTION_TEXT))
415 : {
416 0 : if (arg.size () == INTERNAL_DUMP_OPTION_TEXT.size ())
417 : {
418 0 : options.enable_dump_option (CompileOptions::INTERNAL_DUMP);
419 : }
420 : else
421 : {
422 0 : if (arg[INTERNAL_DUMP_OPTION_TEXT.size ()] != ':')
423 : {
424 0 : rust_error_at (UNDEF_LOCATION, "bad format for %qs",
425 : arg.c_str ());
426 0 : rust_inform (UNDEF_LOCATION,
427 : "to specify the nodes to ignore when "
428 : "dumping their description put a "
429 : "%<:%> then all the Nodes separated by comma");
430 0 : return false;
431 : }
432 0 : handle_excluded_node (arg);
433 0 : options.enable_dump_option (CompileOptions::INTERNAL_DUMP);
434 : }
435 : }
436 : else
437 : {
438 0 : rust_error_at (
439 : UNDEF_LOCATION,
440 : "dump option %qs was unrecognised. choose %<lex%>, %<ast-pretty%>, "
441 : "%<internal[:ignore1,ignore2,...]%>, %<register_plugins%>, "
442 : "%<injection%>, %<expansion%>, %<resolution%>, %<target_options%>, "
443 : "%<hir%>, %<hir-pretty%>, or %<all%>",
444 : arg.c_str ());
445 0 : return false;
446 : }
447 : return true;
448 3 : }
449 :
450 : /* Helper function to parse a string when dump internal to get node to blacklist
451 : */
452 :
453 : void
454 0 : Session::handle_excluded_node (std::string arg)
455 : {
456 0 : size_t colon = arg.find (":");
457 0 : size_t suffix_size = arg.size () - colon;
458 0 : std::istringstream blist_str (arg.substr (colon + 1, suffix_size));
459 0 : std::string token;
460 0 : while (std::getline (blist_str, token, ','))
461 : {
462 0 : options.add_excluded (token);
463 : }
464 0 : }
465 :
466 : /* Actual main entry point for front-end. Called from langhook to parse files.
467 : */
468 : void
469 5117 : Session::handle_input_files (int num_files, const char **files)
470 : {
471 5117 : if (num_files != 1)
472 0 : rust_fatal_error (UNDEF_LOCATION,
473 : "only one file may be specified on the command line");
474 :
475 5117 : const auto &file = files[0];
476 :
477 5117 : rust_debug ("Attempting to parse file: %s", file);
478 5117 : compile_crate (file);
479 5099 : }
480 :
481 : void
482 5116 : Session::handle_crate_name (const char *filename,
483 : const AST::Crate &parsed_crate)
484 : {
485 5116 : auto &mappings = Analysis::Mappings::get ();
486 5116 : auto crate_name_found = false;
487 5116 : auto error = Error (UNDEF_LOCATION, std::string ());
488 :
489 18176 : for (const auto &attr : parsed_crate.inner_attrs)
490 : {
491 13060 : if (attr.get_path () != Values::Attributes::CRATE_NAME)
492 13050 : continue;
493 :
494 10 : auto msg_str = Analysis::Attributes::extract_string_literal (attr);
495 10 : if (!msg_str.has_value ())
496 : {
497 0 : rust_error_at (attr.get_locus (),
498 : "malformed %<crate_name%> attribute input");
499 0 : continue;
500 : }
501 :
502 10 : if (!validate_crate_name (*msg_str, error))
503 : {
504 1 : error.locus = attr.get_locus ();
505 1 : error.emit ();
506 1 : continue;
507 : }
508 :
509 9 : if (options.crate_name_set_manually && (options.crate_name != *msg_str))
510 : {
511 1 : rust_error_at (attr.get_locus (),
512 : "%<-frust-crate-name%> and %<#[crate_name]%> are "
513 : "required to match, but %qs does not match %qs",
514 : options.crate_name.c_str (), msg_str->c_str ());
515 : }
516 9 : crate_name_found = true;
517 18 : options.set_crate_name (*msg_str);
518 13060 : }
519 :
520 5116 : options.crate_name_set_manually |= crate_name_found;
521 5116 : if (!options.crate_name_set_manually)
522 : {
523 5095 : auto crate_name = infer_crate_name (filename);
524 5095 : if (crate_name.empty ())
525 : {
526 0 : rust_error_at (UNDEF_LOCATION, "crate name is empty");
527 0 : rust_inform (linemap_position_for_column (line_table, 0),
528 : "crate name inferred from this file");
529 0 : return;
530 : }
531 :
532 5095 : rust_debug ("inferred crate name: %s", crate_name.c_str ());
533 10190 : options.set_crate_name (crate_name);
534 :
535 5095 : if (!validate_crate_name (options.get_crate_name (), error))
536 : {
537 1 : error.emit ();
538 1 : rust_inform (linemap_position_for_column (line_table, 0),
539 : "crate name inferred from this file");
540 1 : return;
541 : }
542 5095 : }
543 :
544 5115 : if (saw_errors ())
545 : return;
546 :
547 5001 : CrateNum crate_num = mappings.get_next_crate_num (options.get_crate_name ());
548 5001 : mappings.set_current_crate (crate_num);
549 5116 : }
550 :
551 : /** Parse additional attributes injected from the command line
552 : *
553 : */
554 : AST::AttrVec
555 5117 : parse_cli_attributes (
556 : std::vector<CompileOptions::CliAttributeContent> attributes)
557 : {
558 5117 : AST::AttrVec result;
559 5117 : result.reserve (attributes.size ());
560 :
561 5118 : for (auto attribute : attributes)
562 : {
563 1 : Session::get_instance ().linemap->start_file ("cli", 1);
564 1 : Lexer lex (attribute.content, Session::get_instance ().linemap);
565 1 : Parser<Lexer> parser (lex);
566 :
567 1 : if (auto attr_body = parser.parse_attribute_body ())
568 : {
569 1 : auto body = std::move (attr_body.value ());
570 1 : result.push_back (AST::Attribute (std::move (body.path),
571 : std::move (body.input), body.locus,
572 2 : true));
573 1 : }
574 :
575 1 : for (auto error : parser.get_errors ())
576 0 : error.emit ();
577 1 : }
578 5117 : return result;
579 : }
580 :
581 : // Parses a single file with filename filename.
582 : void
583 5117 : Session::compile_crate (const char *filename)
584 : {
585 5117 : if (!flag_rust_experimental
586 5117 : && !std::getenv ("GCCRS_INCOMPLETE_AND_EXPERIMENTAL_COMPILER_DO_NOT_USE"))
587 0 : rust_fatal_error (
588 : UNDEF_LOCATION, "%s",
589 : "gccrs is not yet able to compile Rust code "
590 : "properly. Most of the errors produced will be the fault of gccrs and "
591 : "not the crate you are trying to compile. Because of this, please report "
592 : "errors directly to us instead of opening issues on said crate's "
593 : "repository.\n\n"
594 : "Our github repository: "
595 : "https://github.com/rust-gcc/gccrs\nOur bugzilla tracker: "
596 : "https://gcc.gnu.org/bugzilla/"
597 : "buglist.cgi?bug_status=__open__&component=rust&product=gcc\n\n"
598 : "If you understand this, and understand that the binaries produced might "
599 : "not behave accordingly, you may attempt to use gccrs in an experimental "
600 : "manner by passing the following flag:\n\n"
601 : "`-frust-incomplete-and-experimental-compiler-do-not-use`\n\nor by "
602 : "defining the following environment variable (any value will "
603 : "do)\n\nGCCRS_INCOMPLETE_AND_EXPERIMENTAL_COMPILER_DO_NOT_USE\n\nFor "
604 : "cargo-gccrs, this means passing\n\n"
605 : "GCCRS_EXTRA_ARGS=\"-frust-incomplete-and-experimental-compiler-do-not-"
606 : "use\"\n\nas an environment variable.");
607 :
608 5117 : RAIIFile file_wrap (filename);
609 5117 : if (!file_wrap.ok ())
610 : {
611 0 : rust_error_at (UNDEF_LOCATION, "cannot open filename %s: %m", filename);
612 0 : return;
613 : }
614 :
615 5117 : auto last_step = options.get_compile_until ();
616 :
617 : // parse file here
618 : /* create lexer and parser - these are file-specific and so aren't instance
619 : * variables */
620 5117 : tl::optional<std::ofstream &> dump_lex_opt = tl::nullopt;
621 5117 : std::ofstream dump_lex_stream;
622 5117 : if (options.dump_option_enabled (CompileOptions::LEXER_DUMP))
623 : {
624 1 : dump_lex_stream.open (kLexDumpFile);
625 1 : if (dump_lex_stream.fail ())
626 0 : rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
627 : kLexDumpFile);
628 :
629 1 : dump_lex_opt = dump_lex_stream;
630 : }
631 :
632 5117 : auto cli_attributes = parse_cli_attributes (options.addional_attributes);
633 :
634 5117 : Lexer lex (filename, std::move (file_wrap), linemap, dump_lex_opt);
635 :
636 5117 : if (!lex.input_source_is_valid_utf8 ())
637 : {
638 1 : rust_error_at (UNKNOWN_LOCATION,
639 : "cannot read %s; stream did not contain valid UTF-8",
640 : filename);
641 1 : return;
642 : }
643 :
644 5116 : Parser<Lexer> parser (lex);
645 :
646 : // generate crate from parser
647 5116 : std::unique_ptr<AST::Crate> ast_crate = parser.parse_crate ();
648 :
649 : // handle crate name
650 5116 : handle_crate_name (filename, *ast_crate.get ());
651 :
652 : // dump options except lexer dump
653 5116 : if (options.dump_option_enabled (CompileOptions::TARGET_OPTION_DUMP))
654 : {
655 0 : options.target_data.dump_target_options ();
656 : }
657 5116 : if (saw_errors ())
658 : return;
659 :
660 5001 : if (options.dump_option_enabled (CompileOptions::AST_DUMP_PRETTY))
661 : {
662 0 : dump_ast_pretty (*ast_crate.get ());
663 : }
664 5001 : if (options.dump_option_enabled (CompileOptions::INTERNAL_DUMP))
665 : {
666 0 : dump_ast_pretty_internal (*ast_crate.get ());
667 : }
668 :
669 : // setup the mappings for this AST
670 5001 : CrateNum current_crate = mappings.get_current_crate ();
671 5001 : AST::Crate &parsed_crate
672 5001 : = mappings.insert_ast_crate (std::move (ast_crate), current_crate);
673 :
674 : /* basic pipeline:
675 : * - lex
676 : * - parse
677 : * - register plugins (dummy stage for now) - attribute injection? what is
678 : * this? (attribute injection is injecting attributes specified in command
679 : * line into crate root)
680 : * - injection (some lint checks or dummy, register builtin macros, crate
681 : * injection)
682 : * - expansion (expands all macros, maybe build test harness, AST
683 : * validation, maybe macro crate)
684 : * - resolution (name resolution, type resolution, maybe feature checking,
685 : * maybe buffered lints)
686 : * TODO not done */
687 :
688 5001 : rust_debug ("\033[0;31mSUCCESSFULLY PARSED CRATE \033[0m");
689 :
690 : // If -fsyntax-only was passed, we can just skip the remaining passes.
691 : // Parsing errors are already emitted in `parse_crate()`
692 5001 : if (flag_syntax_only || last_step == CompileOptions::CompileStep::Ast)
693 : return;
694 :
695 : // register plugins pipeline stage
696 4976 : register_plugins (parsed_crate);
697 4976 : rust_debug ("\033[0;31mSUCCESSFULLY REGISTERED PLUGINS \033[0m");
698 4976 : if (options.dump_option_enabled (CompileOptions::REGISTER_PLUGINS_DUMP))
699 : {
700 : // TODO: what do I dump here?
701 : }
702 :
703 : // injection pipeline stage
704 4976 : injection (parsed_crate, cli_attributes);
705 4976 : rust_debug ("\033[0;31mSUCCESSFULLY FINISHED INJECTION \033[0m");
706 4976 : if (options.dump_option_enabled (CompileOptions::INJECTION_DUMP))
707 : {
708 : // TODO: what do I dump here? injected crate names?
709 : }
710 :
711 4976 : if (last_step == CompileOptions::CompileStep::AttributeCheck)
712 : return;
713 :
714 4976 : Analysis::AttributeChecker ().go (parsed_crate);
715 :
716 4976 : EarlyCfgStrip ().go (parsed_crate);
717 :
718 4976 : auto parsed_crate_features
719 4976 : = Features::FeatureCollector{}.collect (parsed_crate);
720 :
721 : // Do not inject core if some errors were emitted
722 9952 : if (!saw_errors ()
723 9937 : && !has_attribute (parsed_crate,
724 14898 : std::string (Values::Attributes::NO_CORE)))
725 : {
726 0 : parsed_crate.inject_extern_crate ("core");
727 : // #![no_core] implies #![no_std]
728 0 : if (!has_attribute (parsed_crate,
729 0 : std::string (Values::Attributes::NO_STD)))
730 : {
731 0 : parsed_crate.inject_extern_crate ("std");
732 : }
733 : }
734 :
735 4976 : if (last_step == CompileOptions::CompileStep::Expansion)
736 : return;
737 :
738 4976 : auto name_resolution_ctx = Resolver2_0::NameResolutionContext ();
739 : // expansion pipeline stage
740 :
741 4976 : expansion (parsed_crate, name_resolution_ctx);
742 :
743 4976 : Analysis::BuiltinAttributeChecker ().go (parsed_crate);
744 :
745 4976 : AST::CollectLangItems ().go (parsed_crate);
746 :
747 4976 : rust_debug ("\033[0;31mSUCCESSFULLY FINISHED EXPANSION \033[0m");
748 4976 : if (options.dump_option_enabled (CompileOptions::EXPANSION_DUMP))
749 : {
750 : // dump AST with expanded stuff
751 0 : rust_debug ("BEGIN POST-EXPANSION AST DUMP");
752 0 : dump_ast_pretty (parsed_crate, true);
753 0 : rust_debug ("END POST-EXPANSION AST DUMP");
754 : }
755 :
756 : // AST Validation pass
757 4976 : if (last_step == CompileOptions::CompileStep::ASTValidation)
758 : return;
759 :
760 4975 : ASTValidation ().check (parsed_crate);
761 :
762 : // feature gating
763 4975 : if (last_step == CompileOptions::CompileStep::FeatureGating)
764 : return;
765 :
766 4975 : FeatureGate (parsed_crate_features).check (parsed_crate);
767 :
768 4975 : if (last_step == CompileOptions::CompileStep::NameResolution)
769 : return;
770 :
771 : // resolution pipeline stage
772 4971 : Resolver2_0::Late (name_resolution_ctx).go (parsed_crate);
773 :
774 4969 : if (options.dump_option_enabled (CompileOptions::RESOLUTION_DUMP))
775 0 : dump_name_resolution (name_resolution_ctx);
776 :
777 4969 : if (saw_errors ())
778 : return;
779 :
780 4745 : if (last_step == CompileOptions::CompileStep::Lowering)
781 : return;
782 :
783 : // Name resolution is complete. Freeze its context before lowering so HIR
784 : // construction can register information keyed by resolved definitions.
785 4733 : Resolver2_0::FinalizedNameResolutionContext::init (name_resolution_ctx);
786 :
787 : // lower AST to HIR
788 4733 : std::unique_ptr<HIR::Crate> lowered
789 4733 : = HIR::ASTLowering::Resolve (parsed_crate);
790 4725 : if (saw_errors ())
791 : return;
792 :
793 : // add the mappings to it
794 4715 : HIR::Crate &hir = mappings.insert_hir_crate (std::move (lowered));
795 4715 : mappings.build_impl_indexes ();
796 4715 : if (options.dump_option_enabled (CompileOptions::HIR_DUMP))
797 : {
798 0 : dump_hir (hir);
799 : }
800 4715 : if (options.dump_option_enabled (CompileOptions::HIR_DUMP_PRETTY))
801 : {
802 0 : dump_hir_pretty (hir);
803 : }
804 :
805 4715 : if (last_step == CompileOptions::CompileStep::TypeCheck)
806 : return;
807 :
808 : // type resolve
809 4707 : Compile::Context *ctx = Compile::Context::get ();
810 4707 : Resolver::TypeResolution::Resolve (hir);
811 :
812 4706 : Resolver::TypeCheckContext::get ()->get_variance_analysis_ctx ().solve ();
813 :
814 4706 : if (saw_errors ())
815 : return;
816 :
817 4501 : Analysis::PatternChecker ().go (hir);
818 :
819 4496 : if (saw_errors ())
820 : return;
821 :
822 4488 : if (last_step == CompileOptions::CompileStep::Privacy)
823 : return;
824 :
825 : // Various HIR error passes. The privacy pass happens before the unsafe checks
826 4488 : Privacy::Resolver::resolve (hir);
827 4488 : if (saw_errors ())
828 : return;
829 :
830 4478 : if (last_step == CompileOptions::CompileStep::Unsafety)
831 : return;
832 :
833 4477 : HIR::UnsafeChecker ().go (hir);
834 :
835 4477 : if (last_step == CompileOptions::CompileStep::Const)
836 : return;
837 :
838 4477 : HIR::ConstChecker ().go (hir);
839 :
840 4477 : if (last_step == CompileOptions::CompileStep::BorrowCheck)
841 : return;
842 :
843 4477 : if (flag_borrowcheck)
844 : {
845 17 : const bool dump_bir
846 17 : = options.dump_option_enabled (CompileOptions::DumpOption::BIR_DUMP);
847 17 : HIR::BorrowChecker (dump_bir).go (hir);
848 : }
849 :
850 4477 : if (saw_errors ())
851 : return;
852 :
853 4448 : if (last_step == CompileOptions::CompileStep::Compilation)
854 : return;
855 :
856 : // do compile to gcc generic
857 4443 : Compile::CompileCrate::Compile (hir, ctx);
858 :
859 : // we can't do static analysis if there are errors to worry about
860 4441 : if (!saw_errors ())
861 : {
862 : // lints
863 4394 : Analysis::ScanDeadcode::Scan (hir);
864 :
865 4394 : if (flag_unused_check_2_0)
866 26 : Analysis::UnusedChecker ().go (hir);
867 : else
868 4368 : Analysis::UnusedVariables::Lint (*ctx);
869 :
870 4394 : HIR::ReadonlyChecker ().go (hir);
871 :
872 : // metadata
873 4394 : bool specified_emit_metadata
874 4394 : = flag_rust_embed_metadata || options.metadata_output_path_set ();
875 4394 : if (!specified_emit_metadata)
876 : {
877 4394 : Metadata::PublicInterface::ExportTo (
878 8788 : hir, Metadata::PublicInterface::expected_metadata_filename ());
879 : }
880 : else
881 : {
882 0 : if (flag_rust_embed_metadata)
883 0 : Metadata::PublicInterface::Export (hir);
884 0 : if (options.metadata_output_path_set ())
885 0 : Metadata::PublicInterface::ExportTo (
886 : hir, options.get_metadata_output ());
887 : }
888 : }
889 :
890 4441 : if (saw_errors ())
891 : return;
892 :
893 : // pass to GCC middle-end
894 4390 : ctx->write_to_backend ();
895 5808 : }
896 :
897 : void
898 4976 : Session::register_plugins (AST::Crate &crate ATTRIBUTE_UNUSED)
899 : {
900 4976 : rust_debug ("ran register_plugins (with no body)");
901 4976 : }
902 :
903 : // TODO: move somewhere else
904 : bool
905 4976 : contains_name (const AST::AttrVec &attrs, std::string name)
906 : {
907 10113 : for (const auto &attr : attrs)
908 : {
909 10113 : if (attr.get_path () == name)
910 4976 : return true;
911 : }
912 :
913 : return false;
914 : }
915 :
916 : void
917 4976 : Session::injection (AST::Crate &crate, AST::AttrVec cli_attributes)
918 : {
919 4976 : rust_debug ("started injection");
920 :
921 : // lint checks in future maybe?
922 :
923 : // register builtin macros
924 : /* In rustc, builtin macros are divided into 3 categories depending on use -
925 : * "bang" macros, "attr" macros, and "derive" macros. I think the meanings
926 : * of these categories should be fairly obvious to anyone who has used rust.
927 : * Builtin macro list by category: Bang
928 : * - asm
929 : * - assert
930 : * - cfg
931 : * - column
932 : * - compile_error
933 : * - concat_idents
934 : * - concat
935 : * - env
936 : * - file
937 : * - format_args_nl
938 : * - format_args
939 : * - global_asm
940 : * - include_bytes
941 : * - include_str
942 : * - include
943 : * - line
944 : * - log_syntax
945 : * - module_path
946 : * - option_env
947 : * - stringify
948 : * - trace_macros
949 : * Attr
950 : * - bench
951 : * - global_allocator
952 : * - test
953 : * - test_case
954 : * Derive
955 : * - Clone
956 : * - Copy
957 : * - Debug
958 : * - Default
959 : * - Eq
960 : * - Hash
961 : * - Ord
962 : * - PartialEq
963 : * - PartialOrd
964 : * - RustcDecodable
965 : * - RustcEncodable
966 : * rustc also has a "quote" macro that is defined differently and is
967 : * supposedly not stable so eh. */
968 : /* TODO: actually implement injection of these macros. In particular, derive
969 : * macros, cfg, and test should be prioritised since they seem to be used
970 : * the most. */
971 :
972 4977 : for (auto attribute : cli_attributes)
973 1 : crate.inject_inner_attribute (attribute);
974 :
975 : // crate injection
976 4976 : std::vector<std::string> names;
977 4976 : if (contains_name (crate.inner_attrs, "no_core"))
978 : {
979 : // no prelude
980 4976 : injected_crate_name = "";
981 : }
982 0 : else if (contains_name (crate.inner_attrs, "no_std"))
983 : {
984 0 : names.push_back ("core");
985 :
986 0 : if (!contains_name (crate.inner_attrs, "compiler_builtins"))
987 : {
988 0 : names.push_back ("compiler_builtins");
989 : }
990 :
991 0 : injected_crate_name = "core";
992 : }
993 : else
994 : {
995 0 : names.push_back ("std");
996 :
997 0 : injected_crate_name = "std";
998 : }
999 :
1000 : // reverse iterate through names to insert crate items in "forward" order at
1001 : // beginning of crate
1002 4976 : for (auto it = names.rbegin (); it != names.rend (); ++it)
1003 : {
1004 : // create "macro use" attribute for use on extern crate item to enable
1005 : // loading macros from it
1006 0 : AST::Attribute attr (AST::SimplePath::from_str (
1007 0 : Values::Attributes::MACRO_USE, UNDEF_LOCATION),
1008 0 : nullptr);
1009 :
1010 : // create "extern crate" item with the name
1011 0 : std::unique_ptr<AST::ExternCrate> extern_crate (
1012 0 : new AST::ExternCrate (*it, AST::Visibility::create_private (),
1013 0 : {std::move (attr)}, UNKNOWN_LOCATION));
1014 :
1015 : // insert at beginning
1016 : // crate.items.insert (crate.items.begin (), std::move (extern_crate));
1017 0 : }
1018 :
1019 : // create use tree path
1020 : // prelude is injected_crate_name
1021 : // FIXME: Once we do want to include the standard library, add the prelude
1022 : // use item
1023 : // std::vector<AST::SimplePathSegment> segments
1024 : // = {AST::SimplePathSegment (injected_crate_name, UNDEF_LOCATION),
1025 : // AST::SimplePathSegment ("prelude", UNDEF_LOCATION),
1026 : // AST::SimplePathSegment ("v1", UNDEF_LOCATION)};
1027 : // // create use tree and decl
1028 : // std::unique_ptr<AST::UseTreeGlob> use_tree (
1029 : // new AST::UseTreeGlob (AST::UseTreeGlob::PATH_PREFIXED,
1030 : // AST::SimplePath (std::move (segments)),
1031 : // UNDEF_LOCATION));
1032 : // AST::Attribute prelude_attr (AST::SimplePath::from_str ("prelude_import",
1033 : // UNDEF_LOCATION),
1034 : // nullptr);
1035 : // std::unique_ptr<AST::UseDeclaration> use_decl (
1036 : // new AST::UseDeclaration (std::move (use_tree),
1037 : // AST::Visibility::create_error (),
1038 : // {std::move (prelude_attr)}, UNDEF_LOCATION));
1039 :
1040 : // crate.items.insert (crate.items.begin (), std::move (use_decl));
1041 :
1042 : /* TODO: potentially add checking attribute crate type? I can't figure out
1043 : * what this does currently comment says "Unconditionally collect crate
1044 : * types from attributes to make them used", which presumably refers to
1045 : * checking the linkage info by "crate_type". It also seems to ensure that
1046 : * an invalid crate type is not specified, so maybe just do that. Valid
1047 : * crate types: bin lib dylib staticlib cdylib rlib proc-macro */
1048 :
1049 : // this crate type will have options affecting the metadata ouput
1050 :
1051 4976 : rust_debug ("finished injection");
1052 4976 : }
1053 :
1054 : void
1055 4976 : Session::expansion (AST::Crate &crate, Resolver2_0::NameResolutionContext &ctx)
1056 : {
1057 4976 : rust_debug ("started expansion");
1058 :
1059 : /* rustc has a modification to windows PATH temporarily here, which may end
1060 : * up being required */
1061 :
1062 : // create macro expansion config?
1063 : // if not, would at least have to configure recursion_limit
1064 4976 : ExpansionCfg cfg;
1065 :
1066 4976 : auto fixed_point_reached = false;
1067 4976 : unsigned iterations = 0;
1068 :
1069 : // create extctxt? from parse session, cfg, and resolver?
1070 : /* expand by calling cxtctxt object's monotonic_expander's expand_crate
1071 : * method. */
1072 4976 : MacroExpander expander (crate, cfg, *this);
1073 4976 : std::vector<Error> macro_errors;
1074 :
1075 4976 : Resolver2_0::Builtins::setup_lang_prelude (ctx);
1076 :
1077 21298 : while (!fixed_point_reached && iterations < cfg.recursion_limit)
1078 : {
1079 11447 : std::vector<Session::LoadedCrate> loaded_crates;
1080 11447 : CfgStrip (cfg).go (crate);
1081 : // Errors might happen during cfg strip pass
1082 :
1083 11447 : ExternCrateLoaderVisitor (loaded_crates).go (crate);
1084 :
1085 11447 : Resolver2_0::Early early (ctx);
1086 11447 : early.go (crate);
1087 11495 : for (auto &loaded_crate : loaded_crates)
1088 48 : ctx.merge (loaded_crate.ctx, loaded_crate.node_id);
1089 11447 : macro_errors = early.get_macro_resolve_errors ();
1090 :
1091 11447 : if (saw_errors ())
1092 : break;
1093 :
1094 11388 : ExpandVisitor (expander).go (crate);
1095 :
1096 11388 : fixed_point_reached = !expander.has_changed () && !early.is_dirty ();
1097 11388 : expander.reset_changed_state ();
1098 11388 : iterations++;
1099 :
1100 11388 : if (saw_errors ())
1101 : break;
1102 11447 : }
1103 :
1104 : // Fixed point reached: Emit unresolved macros error
1105 5021 : for (auto &error : macro_errors)
1106 45 : error.emit ();
1107 :
1108 4976 : if (iterations == cfg.recursion_limit)
1109 : {
1110 1 : auto &last_invoc = expander.get_last_invocation ();
1111 1 : auto &last_def = expander.get_last_definition ();
1112 :
1113 1 : rust_assert (last_def.has_value () && last_invoc.has_value ());
1114 :
1115 1 : rich_location range (line_table, last_invoc->get_locus ());
1116 1 : range.add_range (last_def->get_locus ());
1117 :
1118 1 : rust_error_at (range, "reached recursion limit");
1119 1 : }
1120 :
1121 : // handle AST desugaring
1122 4976 : if (!saw_errors ())
1123 : {
1124 4860 : AST::ExpressionYeast ().go (crate);
1125 :
1126 4860 : AST::DesugarApit ().go (crate);
1127 :
1128 : // HACK: we may need a final TopLevel pass
1129 : // however, this should not count towards the recursion limit
1130 : // and we don't need a full Early pass
1131 4860 : Resolver2_0::TopLevel (ctx).go (crate);
1132 : }
1133 :
1134 : // error reporting - check unused macros, get missing fragment specifiers
1135 :
1136 : // build test harness
1137 :
1138 : // ast validation (also with proc macro decls)
1139 :
1140 : // maybe create macro crate if not rustdoc
1141 :
1142 4976 : rust_debug ("finished expansion");
1143 4976 : }
1144 :
1145 : void
1146 0 : Session::dump_ast_pretty (AST::Crate &crate, bool expanded) const
1147 : {
1148 0 : std::ofstream out;
1149 0 : if (expanded)
1150 0 : out.open (kASTPrettyDumpFileExpanded);
1151 : else
1152 0 : out.open (kASTPrettyDumpFile);
1153 :
1154 0 : if (out.fail ())
1155 : {
1156 0 : rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
1157 : kASTDumpFile);
1158 0 : return;
1159 : }
1160 :
1161 0 : AST::Dump (out).go (crate);
1162 :
1163 0 : out.close ();
1164 0 : }
1165 :
1166 : void
1167 0 : Session::dump_ast_pretty_internal (AST::Crate &crate) const
1168 : {
1169 0 : std::ofstream out;
1170 0 : out.open (kASTPrettyInternalDumpFile);
1171 :
1172 0 : if (out.fail ())
1173 : {
1174 0 : rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
1175 : kASTDumpFile);
1176 0 : return;
1177 : }
1178 :
1179 0 : std::set<std::string> str_tmp = options.get_excluded ();
1180 :
1181 0 : AST::Dump (out,
1182 : AST::Dump::Configuration{
1183 : AST::Dump::Configuration::InternalComment::Dump,
1184 : AST::Dump::Configuration::NodeDescription::Dump,
1185 : AST::Dump::Configuration::Comment::Dump,
1186 : AST::Dump::Configuration::Newline::Dump,
1187 : AST::Dump::Configuration::Indentation::Space4,
1188 : },
1189 0 : str_tmp)
1190 0 : .go (crate);
1191 :
1192 0 : out.close ();
1193 0 : }
1194 :
1195 : void
1196 0 : Session::dump_name_resolution (Resolver2_0::NameResolutionContext &ctx) const
1197 : {
1198 : // YES this is ugly but NO GCC 4.8 does not allow us to make it fancier :(
1199 0 : std::string types_content = ctx.types.as_debug_string ();
1200 0 : std::ofstream types_stream{kASTtypeResolutionDumpFile};
1201 0 : types_stream << types_content;
1202 :
1203 0 : std::string macros_content = ctx.macros.as_debug_string ();
1204 0 : std::ofstream macros_stream{kASTmacroResolutionDumpFile};
1205 0 : macros_stream << macros_content;
1206 :
1207 0 : std::string labels_content = ctx.labels.as_debug_string ();
1208 0 : std::ofstream labels_stream{kASTlabelResolutionDumpFile};
1209 0 : labels_stream << labels_content;
1210 :
1211 0 : std::string values_content = ctx.values.as_debug_string ();
1212 0 : std::ofstream values_stream{kASTvalueResolutionDumpFile};
1213 0 : values_stream << values_content;
1214 0 : }
1215 :
1216 : void
1217 0 : Session::dump_hir (HIR::Crate &crate) const
1218 : {
1219 0 : std::ofstream out;
1220 0 : out.open (kHIRDumpFile);
1221 0 : if (out.fail ())
1222 : {
1223 0 : rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
1224 : kHIRDumpFile);
1225 0 : return;
1226 : }
1227 :
1228 0 : out << crate.to_string ();
1229 0 : out.close ();
1230 0 : }
1231 :
1232 : void
1233 0 : Session::dump_hir_pretty (HIR::Crate &crate) const
1234 : {
1235 0 : std::ofstream out;
1236 0 : out.open (kHIRPrettyDumpFile);
1237 0 : if (out.fail ())
1238 : {
1239 0 : rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
1240 : kHIRPrettyDumpFile);
1241 0 : return;
1242 : }
1243 :
1244 0 : HIR::Dump (out).go (crate);
1245 0 : out.close ();
1246 0 : }
1247 :
1248 : // imports
1249 :
1250 : tl::expected<Session::LoadedCrate, Session::LoadingError>
1251 131 : Session::load_extern_crate (const std::string &crate_name, location_t locus)
1252 : {
1253 : // has it already been loaded?
1254 131 : if (auto crate_num = mappings.lookup_crate_name (crate_name))
1255 : {
1256 80 : auto resolved_node_id = mappings.crate_num_to_nodeid (*crate_num);
1257 80 : rust_assert (resolved_node_id);
1258 :
1259 80 : return tl::make_unexpected (
1260 80 : LoadingError::make_already_loaded (*resolved_node_id));
1261 : }
1262 :
1263 51 : std::string relative_import_path = "";
1264 51 : std::string import_name = crate_name;
1265 :
1266 : // The path to the extern crate might have been specified by the user using
1267 : // -frust-extern
1268 51 : auto cli_extern_crate = extern_crates.find (crate_name);
1269 :
1270 51 : std::pair<std::unique_ptr<Import::Stream>, std::vector<ProcMacro::Procmacro>>
1271 51 : package_result;
1272 51 : if (cli_extern_crate != extern_crates.end ())
1273 : {
1274 0 : auto path = cli_extern_crate->second;
1275 0 : package_result = Import::try_package_in_directory (path, locus);
1276 0 : }
1277 : else
1278 : {
1279 51 : package_result
1280 102 : = Import::open_package (import_name, locus, relative_import_path);
1281 : }
1282 :
1283 51 : auto stream = std::move (package_result.first);
1284 51 : auto proc_macros = std::move (package_result.second);
1285 :
1286 51 : if (stream == NULL // No stream and
1287 51 : && proc_macros.empty ()) // no proc macros
1288 : {
1289 3 : rust_error_at (locus, "failed to locate crate %qs", import_name.c_str ());
1290 3 : return tl::make_unexpected (LoadingError::make_failed_to_locate ());
1291 : }
1292 :
1293 48 : auto extern_crate
1294 48 : = stream == nullptr
1295 48 : ? Imports::ExternCrate (crate_name,
1296 0 : proc_macros) // Import proc macros
1297 48 : : Imports::ExternCrate (*stream); // Import from stream
1298 48 : if (stream != nullptr)
1299 : {
1300 48 : bool ok = extern_crate.load (locus);
1301 48 : if (!ok)
1302 : {
1303 0 : rust_error_at (locus, "failed to load crate metadata");
1304 0 : return tl::make_unexpected (LoadingError::make_failed_to_locate ());
1305 : }
1306 : }
1307 :
1308 : // ensure the current vs this crate name don't collide
1309 48 : const std::string current_crate_name = mappings.get_current_crate_name ();
1310 48 : if (current_crate_name.compare (extern_crate.get_crate_name ()) == 0)
1311 : {
1312 0 : rust_error_at (locus, "current crate name %qs collides with this",
1313 : current_crate_name.c_str ());
1314 0 : return tl::make_unexpected (LoadingError::make_collision ());
1315 : }
1316 :
1317 : // setup mappings
1318 48 : CrateNum saved_crate_num = mappings.get_current_crate ();
1319 48 : CrateNum crate_num
1320 48 : = mappings.get_next_crate_num (extern_crate.get_crate_name ());
1321 48 : mappings.set_current_crate (crate_num);
1322 :
1323 : // then lets parse this as a 2nd crate
1324 48 : Lexer lex (extern_crate.get_metadata (), linemap);
1325 48 : Parser<Lexer> parser (lex);
1326 48 : std::unique_ptr<AST::Crate> metadata_crate = parser.parse_crate ();
1327 :
1328 48 : AST::Crate &parsed_crate
1329 48 : = mappings.insert_ast_crate (std::move (metadata_crate), crate_num);
1330 :
1331 48 : auto ctx = Resolver2_0::NameResolutionContext ();
1332 48 : Resolver2_0::Builtins::setup_lang_prelude (ctx);
1333 :
1334 48 : Resolver2_0::Early early (ctx);
1335 48 : early.go (parsed_crate);
1336 48 : Resolver2_0::Late (ctx).go (parsed_crate);
1337 :
1338 48 : std::vector<AttributeProcMacro> attribute_macros;
1339 48 : std::vector<CustomDeriveProcMacro> derive_macros;
1340 48 : std::vector<BangProcMacro> bang_macros;
1341 :
1342 48 : for (auto ¯o : extern_crate.get_proc_macros ())
1343 : {
1344 0 : switch (macro.tag)
1345 : {
1346 0 : case ProcMacro::CUSTOM_DERIVE:
1347 0 : derive_macros.push_back (macro.payload.custom_derive);
1348 0 : break;
1349 0 : case ProcMacro::ATTR:
1350 0 : attribute_macros.push_back (macro.payload.attribute);
1351 0 : break;
1352 0 : case ProcMacro::BANG:
1353 0 : bang_macros.push_back (macro.payload.bang);
1354 0 : break;
1355 0 : default:
1356 0 : gcc_unreachable ();
1357 : }
1358 : }
1359 :
1360 48 : mappings.insert_attribute_proc_macros (crate_num, attribute_macros);
1361 48 : mappings.insert_bang_proc_macros (crate_num, bang_macros);
1362 48 : mappings.insert_derive_proc_macros (crate_num, derive_macros);
1363 :
1364 : // always restore the crate_num
1365 48 : mappings.set_current_crate (saved_crate_num);
1366 :
1367 192 : return LoadedCrate{crate_name, parsed_crate.get_node_id (), std::move (ctx)};
1368 198 : }
1369 : //
1370 :
1371 : void
1372 0 : TargetOptions::dump_target_options () const
1373 : {
1374 0 : std::ofstream out;
1375 0 : out.open (kTargetOptionsDumpFile);
1376 0 : if (out.fail ())
1377 : {
1378 0 : rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
1379 : kTargetOptionsDumpFile);
1380 0 : return;
1381 : }
1382 :
1383 0 : if (features.empty ())
1384 : {
1385 0 : out << "No target options available!\n";
1386 : }
1387 :
1388 0 : for (const auto &pairs : features)
1389 : {
1390 0 : for (const auto &value : pairs.second)
1391 : {
1392 0 : if (value.has_value ())
1393 0 : out << pairs.first + ": \"" + value.value () + "\"\n";
1394 : else
1395 0 : out << pairs.first + "\n";
1396 : }
1397 : }
1398 :
1399 0 : out.close ();
1400 0 : }
1401 :
1402 : void
1403 0 : TargetOptions::init_derived_values ()
1404 : {
1405 : // enable derived values based on target families
1406 0 : if (has_key_value_pair ("target_family", "unix"))
1407 0 : insert_key ("unix");
1408 0 : if (has_key_value_pair ("target_family", "windows"))
1409 0 : insert_key ("windows");
1410 :
1411 : // implicitly enable features - this should not be required in general
1412 0 : if (has_key_value_pair ("target_feature", "aes"))
1413 0 : enable_implicit_feature_reqs ("aes");
1414 0 : if (has_key_value_pair ("target_feature", "avx"))
1415 0 : enable_implicit_feature_reqs ("sse4.2");
1416 0 : if (has_key_value_pair ("target_feature", "avx2"))
1417 0 : enable_implicit_feature_reqs ("avx");
1418 0 : if (has_key_value_pair ("target_feature", "pclmulqdq"))
1419 0 : enable_implicit_feature_reqs ("sse2");
1420 0 : if (has_key_value_pair ("target_feature", "sha"))
1421 0 : enable_implicit_feature_reqs ("sse2");
1422 0 : if (has_key_value_pair ("target_feature", "sse2"))
1423 0 : enable_implicit_feature_reqs ("sse");
1424 0 : if (has_key_value_pair ("target_feature", "sse3"))
1425 0 : enable_implicit_feature_reqs ("sse2");
1426 0 : if (has_key_value_pair ("target_feature", "sse4.1"))
1427 0 : enable_implicit_feature_reqs ("sse3");
1428 0 : if (has_key_value_pair ("target_feature", "sse4.2"))
1429 0 : enable_implicit_feature_reqs ("sse4.1");
1430 0 : if (has_key_value_pair ("target_feature", "ssse3"))
1431 0 : enable_implicit_feature_reqs ("sse3");
1432 0 : }
1433 :
1434 : void
1435 0 : TargetOptions::enable_implicit_feature_reqs (std::string feature)
1436 : {
1437 0 : if (feature == "aes")
1438 0 : enable_implicit_feature_reqs ("sse2");
1439 0 : else if (feature == "avx")
1440 0 : enable_implicit_feature_reqs ("sse4.2");
1441 0 : else if (feature == "avx2")
1442 0 : enable_implicit_feature_reqs ("avx");
1443 0 : else if (feature == "fma")
1444 0 : enable_implicit_feature_reqs ("avx");
1445 0 : else if (feature == "pclmulqdq")
1446 0 : enable_implicit_feature_reqs ("sse2");
1447 0 : else if (feature == "sha")
1448 0 : enable_implicit_feature_reqs ("sse2");
1449 0 : else if (feature == "sse2")
1450 0 : enable_implicit_feature_reqs ("sse");
1451 0 : else if (feature == "sse3")
1452 0 : enable_implicit_feature_reqs ("sse2");
1453 0 : else if (feature == "sse4.1")
1454 0 : enable_implicit_feature_reqs ("sse3");
1455 0 : else if (feature == "sse4.2")
1456 0 : enable_implicit_feature_reqs ("sse4.1");
1457 0 : else if (feature == "ssse3")
1458 0 : enable_implicit_feature_reqs ("sse3");
1459 :
1460 0 : if (!has_key_value_pair ("target_feature", feature))
1461 : {
1462 0 : insert_key_value_pair ("target_feature", feature);
1463 :
1464 0 : rust_debug ("had to implicitly enable feature '%s'!", feature.c_str ());
1465 : }
1466 0 : }
1467 :
1468 : // NOTEs:
1469 : /* mrustc compile pipeline:
1470 : * - target load (pass target spec to parser?)
1471 : * - parse (convert source to AST)
1472 : * - load crates (load any explicitly mentioned extern crates [not all of
1473 : * them])
1474 : * - expand (AST transformations from attributes and macros, loads remaining
1475 : * extern crates [std/core and any triggered by macro expansion])
1476 : * - implicit crates (test harness, allocator crate, panic crate)
1477 : * - resolve use (annotate every 'use' item with source [supposedly handles
1478 : * nasty recursion])
1479 : * - resolve index (generate index of visible items for every module [avoids
1480 : * recursion in next pass])
1481 : * - resolve absolute (resolve all paths into either variable names
1482 : * [types/values] or absolute paths)
1483 : * - HIR lower (convert modified AST to simpler HIR [both expressions and
1484 : * module tree])
1485 : * - resolve type aliases (replace any usages of type aliases with actual
1486 : * type [except associated types])
1487 : * - resolve bind (iterate HIR tree and set binding annotations on all
1488 : * concrete types [avoids path lookups later])
1489 : * - resolve HIR markings (generate "markings" [e.g. for Copy/Send/Sync/...]
1490 : * for all types
1491 : * - sort impls (small pass - sort impls into groups)
1492 : * - resolve UFCS outer (determine source trait for all top-level <T>::Type
1493 : * [qualified] paths)
1494 : * - resolve UFCS paths (do the same, but include for exprs this time. also
1495 : * normalises results of previous pass [expanding known associated types])
1496 : * - constant evaluate (evaluate all constants)
1497 : * - typecheck outer (checks impls are sane)
1498 : * - typecheck expressions (resolve and check types for all exprs)
1499 : * - expand HIR annotate (annotate how exprs are used - used for closure
1500 : * extractions and reborrows)
1501 : * - expand HIR closures (extract closures into structs implementing Fn*
1502 : * traits)
1503 : * - expand HIR vtables (generate vtables for types with dyn dispatch)
1504 : * - expand HIR calls (converts method and callable calls into explicit
1505 : * function calls)
1506 : * - expand HIR reborrows (apply reborrow rules [taking '&mut *v' instead of
1507 : * 'v'])
1508 : * - expand HIR erasedtype (replace all erased types 'impl Trait' with the
1509 : * true type)
1510 : * - typecheck expressions (validate - double check that previous passes
1511 : * haven't broke type system rules)
1512 : * - lower MIR (convert HIR exprs into a control-flow graph [MIR])
1513 : * - MIR validate (check that the generated MIR is consistent)
1514 : * - MIR cleanup (perform various transformations on MIR - replace reads of
1515 : * const items with the item itself; convert casts to unsized types into
1516 : * 'MakeDst' operations)
1517 : * - MIR optimise (perform various simple optimisations on the MIR - constant
1518 : * propagation, dead code elimination, borrow elimination, some inlining)
1519 : * - MIR validate PO (re-validate the MIR)
1520 : * - MIR validate full (optionally: perform expensive state-tracking
1521 : * validation on MIR)
1522 : * - trans enumerate (enumerate all items needed for code generation,
1523 : * primarily types used for generics)
1524 : * - trans auto impls (create magic trait impls as enumerated in previous
1525 : * pass)
1526 : * - trans monomorph (generate monomorphised copies of all functions [with
1527 : * generics replaced with real types])
1528 : * - MIR optimise inline (run optimisation again, this time with full type
1529 : * info [primarily for inlining])
1530 : * - HIR serialise (write out HIR dump [module tree and generic/inline MIR])
1531 : * - trans codegen (generate final output file: emit C source file and call C
1532 : * compiler) */
1533 :
1534 : /* rustc compile pipeline (basic, in way less detail):
1535 : * - parse input (parse .rs to AST)
1536 : * - name resolution, macro expansion, and configuration (process AST
1537 : * recursively, resolving paths, expanding macros, processing #[cfg] nodes
1538 : * [i.e. maybe stripping stuff from AST])
1539 : * - lower to HIR
1540 : * - type check and other analyses (e.g. privacy checking)
1541 : * - lower to MIR and post-processing (and do stuff like borrow checking)
1542 : * - translation to LLVM IR and LLVM optimisations (produce the .o files)
1543 : * - linking (link together .o files) */
1544 :
1545 : /* Pierced-together rustc compile pipeline (from source):
1546 : * - parse input (parse file to crate)
1547 : * - register plugins (attributes injection, set various options, register
1548 : * lints, load plugins)
1549 : * - expansion/configure and expand (initial 'cfg' processing, 'loading
1550 : * compiler plugins', syntax expansion, secondary 'cfg' expansion, synthesis
1551 : * of a test harness if required, injection of any std lib dependency and
1552 : * prelude, and name resolution) - actually documented inline
1553 : * - seeming pierced-together order: pre-AST expansion lint checks,
1554 : * registering builtin macros, crate injection, then expand all macros, then
1555 : * maybe build test harness, AST validation, maybe create a macro crate (if
1556 : * not rustdoc), name resolution, complete gated feature checking, add all
1557 : * buffered lints
1558 : * - create global context (lower to HIR)
1559 : * - analysis on global context (HIR optimisations? create MIR?)
1560 : * - code generation
1561 : * - link */
1562 : } // namespace Rust
1563 :
1564 : #if CHECKING_P
1565 : namespace selftest {
1566 : void
1567 1 : rust_crate_name_validation_test (void)
1568 : {
1569 1 : auto error = Rust::Error (UNDEF_LOCATION, std::string ());
1570 1 : ASSERT_TRUE (Rust::validate_crate_name ("example", error));
1571 1 : ASSERT_TRUE (Rust::validate_crate_name ("abcdefg_1234", error));
1572 1 : ASSERT_TRUE (Rust::validate_crate_name ("1", error));
1573 1 : ASSERT_TRUE (Rust::validate_crate_name ("クレート", error));
1574 1 : ASSERT_TRUE (Rust::validate_crate_name ("Sōkrátēs", error));
1575 1 : ASSERT_TRUE (Rust::validate_crate_name ("惊吓", error));
1576 :
1577 : // NOTE: - is not allowed in the crate name ...
1578 :
1579 1 : ASSERT_FALSE (Rust::validate_crate_name ("abcdefg-1234", error));
1580 1 : ASSERT_FALSE (Rust::validate_crate_name ("a+b", error));
1581 1 : ASSERT_FALSE (Rust::validate_crate_name ("/a+b/", error));
1582 1 : ASSERT_FALSE (Rust::validate_crate_name ("😸++", error));
1583 1 : ASSERT_FALSE (Rust::validate_crate_name ("∀", error));
1584 :
1585 : /* Tests for crate name inference */
1586 1 : ASSERT_EQ (Rust::infer_crate_name (".rs"), "");
1587 1 : ASSERT_EQ (Rust::infer_crate_name ("c.rs"), "c");
1588 : // NOTE: ... but - is allowed when in the filename
1589 1 : ASSERT_EQ (Rust::infer_crate_name ("a-b.rs"), "a_b");
1590 1 : ASSERT_EQ (Rust::infer_crate_name ("book.rs.txt"), "book.rs");
1591 : #if defined(HAVE_DOS_BASED_FILE_SYSTEM)
1592 : ASSERT_EQ (Rust::infer_crate_name ("a\\c\\a-b.rs"), "a_b");
1593 : #else
1594 1 : ASSERT_EQ (Rust::infer_crate_name ("a/c/a-b.rs"), "a_b");
1595 : #endif
1596 1 : }
1597 : } // namespace selftest
1598 : #endif // CHECKING_P
|