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