LCOV - code coverage report
Current view: top level - gcc/rust - rust-session-manager.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 60.9 % 652 397
Test Date: 2026-08-22 16:33:35 Functions: 66.7 % 30 20
Legend: Lines:     hit not hit

            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    134734434 : Session::get_instance ()
      99              : {
     100    134739418 :   static Session instance{};
     101    134734434 :   return instance;
     102              : }
     103              : 
     104              : static std::string
     105         4967 : infer_crate_name (const std::string &filename)
     106              : 
     107              : {
     108         4967 :   if (filename == "-")
     109            0 :     return kDefaultCrateName;
     110              : 
     111         4967 :   std::string crate = std::string (filename);
     112         4967 :   size_t path_sep = crate.find_last_of (file_separator);
     113              : 
     114              :   // find the base filename
     115         4967 :   if (path_sep != std::string::npos)
     116         4963 :     crate.erase (0, path_sep + 1);
     117              : 
     118              :   // find the file stem name (remove file extension)
     119         4967 :   size_t ext_position = crate.find_last_of ('.');
     120         4967 :   if (ext_position != std::string::npos)
     121         4966 :     crate.erase (ext_position);
     122              : 
     123              :   // Replace all the '-' symbols with '_' per Rust rules
     124        65755 :   for (auto &c : crate)
     125              :     {
     126        60788 :       if (c == '-')
     127         1956 :         c = '_';
     128              :     }
     129         4967 :   return crate;
     130         4967 : }
     131              : 
     132              : /* Validate the crate name using the ASCII rules */
     133              : 
     134              : static bool
     135         4996 : validate_crate_name (const std::string &crate_name, Error &error)
     136              : {
     137         4996 :   tl::optional<Utf8String> utf8_name_opt
     138         4996 :     = Utf8String::make_utf8_string (crate_name);
     139         4996 :   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         4996 :   std::vector<Codepoint> uchars = utf8_name_opt->get_chars ();
     146         4996 :   if (uchars.empty ())
     147              :     {
     148            0 :       error = Error (UNDEF_LOCATION, "crate name cannot be empty");
     149            0 :       return false;
     150              :     }
     151         4996 :   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        65960 :   for (Codepoint &c : uchars)
     158              :     {
     159        60972 :       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         4996 : }
     169              : 
     170              : static bool
     171         4830 : has_attribute (AST::Crate crate, std::string attribute)
     172              : {
     173         4830 :   auto &crate_attrs = crate.get_inner_attrs ();
     174        14575 :   auto has_attr = [&attribute] (AST::Attribute &attr) {
     175         9745 :     return attr.as_string () == attribute;
     176         4830 :   };
     177         4830 :   return std::any_of (crate_attrs.begin (), crate_attrs.end (), has_attr);
     178              : }
     179              : 
     180              : void
     181         4983 : Session::init ()
     182              : {
     183              :   // initialize target hooks
     184         4983 :   targetrustm.rust_cpu_info ();
     185         4983 :   targetrustm.rust_os_info ();
     186              : 
     187              :   // target-independent values that should exist in all targets
     188         4983 :   options.target_data.insert_key_value_pair ("target_pointer_width",
     189         4983 :                                              std::to_string (POINTER_SIZE));
     190         4983 :   options.target_data.insert_key_value_pair ("target_endian", BYTES_BIG_ENDIAN
     191         4983 :                                                                 ? "big"
     192              :                                                                 : "little");
     193              : 
     194              :   // setup singleton linemap
     195         4983 :   linemap = rust_get_linemap ();
     196              : 
     197              :   // setup backend to GCC GIMPLE
     198         4983 :   Backend::init ();
     199              : 
     200              :   // setup mappings class
     201         4983 :   mappings = Analysis::Mappings::get ();
     202         4983 : }
     203              : 
     204              : /* Initialise default options. Actually called before handle_option, unlike init
     205              :  * itself. */
     206              : void
     207         4984 : Session::init_options ()
     208         4984 : {}
     209              : 
     210              : // Handle option selection.
     211              : bool
     212        45124 : 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        45124 :   bool ret = true;
     219              : 
     220              :   // Handles options as listed in lang.opt.
     221        45124 :   switch (code)
     222              :     {
     223        34886 :     case OPT_I:
     224        34886 :     case OPT_L:
     225        34886 :       {
     226              :         // TODO: add search path
     227        34886 :         const std::string p = std::string (arg);
     228        34886 :         add_search_path (p);
     229        34886 :       }
     230        34886 :       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           13 :     case OPT_frust_crate_:
     239              :       // set the crate name
     240           13 :       if (arg != nullptr)
     241              :         {
     242           13 :           auto error = Error (UNDEF_LOCATION, std::string ());
     243           13 :           if ((ret = validate_crate_name (arg, error)))
     244              :             {
     245           12 :               options.set_crate_name (arg);
     246           12 :               options.crate_name_set_manually = true;
     247              :             }
     248              :           else
     249              :             {
     250            1 :               rust_assert (!error.message.empty ());
     251            1 :               error.emit ();
     252              :             }
     253           13 :         }
     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            1 :     case OPT_frust_dump_:
     265              :       // enable dump and return whether this was successful
     266            1 :       if (arg != nullptr)
     267              :         {
     268            1 :           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           82 :     case OPT_frust_cfg_:
     281           82 :       {
     282           82 :         auto string_arg = std::string (arg);
     283           82 :         ret = handle_cfg_option (string_arg);
     284           82 :         break;
     285           82 :       }
     286           21 :     case OPT_frust_crate_type_:
     287           21 :       options.set_crate_type (flag_rust_crate_type);
     288           21 :       break;
     289           11 :     case OPT_frust_edition_:
     290           11 :       options.set_edition (flag_rust_edition);
     291           11 :       break;
     292           40 :     case OPT_frust_compat_version_:
     293           40 :       options.set_compat_version (flag_rust_compat_version);
     294           40 :       break;
     295           49 :     case OPT_frust_compile_until_:
     296           49 :       options.set_compile_step (flag_rust_compile_until);
     297           49 :       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        45124 :   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           82 : Session::handle_cfg_option (std::string &input)
     328              : {
     329           82 :   std::string key;
     330           82 :   std::string value;
     331              : 
     332              :   // Refactor this if needed
     333           82 :   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           82 :   if (value.empty ())
     343              :     // rustc does not seem to error on dup key
     344          132 :     options.target_data.insert_key (key);
     345              :   else
     346           48 :     options.target_data.insert_key_value_pair (key, value);
     347              : 
     348              :   return true;
     349           82 : }
     350              : 
     351              : /* Enables a certain dump depending on the name passed in. Returns true if
     352              :  * name is valid, false otherwise. */
     353              : bool
     354            1 : Session::enable_dump (std::string arg)
     355              : {
     356            1 :   const std::string INTERNAL_DUMP_OPTION_TEXT = "internal";
     357              : 
     358            1 :   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            1 :   if (arg == "all")
     370              :     {
     371            0 :       options.enable_all_dump_options ();
     372              :     }
     373            1 :   else if (arg == "lex")
     374              :     {
     375            1 :       options.enable_dump_option (CompileOptions::LEXER_DUMP);
     376              :     }
     377            0 :   else if (arg == "ast-pretty")
     378              :     {
     379            0 :       options.enable_dump_option (CompileOptions::AST_DUMP_PRETTY);
     380              :     }
     381            0 :   else if (arg == "register_plugins")
     382              :     {
     383            0 :       options.enable_dump_option (CompileOptions::REGISTER_PLUGINS_DUMP);
     384              :     }
     385            0 :   else if (arg == "injection")
     386              :     {
     387            0 :       options.enable_dump_option (CompileOptions::INJECTION_DUMP);
     388              :     }
     389            0 :   else if (arg == "expansion")
     390              :     {
     391            0 :       options.enable_dump_option (CompileOptions::EXPANSION_DUMP);
     392              :     }
     393            0 :   else if (arg == "resolution")
     394              :     {
     395            0 :       options.enable_dump_option (CompileOptions::RESOLUTION_DUMP);
     396              :     }
     397            0 :   else if (arg == "target_options")
     398              :     {
     399            0 :       options.enable_dump_option (CompileOptions::TARGET_OPTION_DUMP);
     400              :     }
     401            0 :   else if (arg == "hir")
     402              :     {
     403            0 :       options.enable_dump_option (CompileOptions::HIR_DUMP);
     404              :     }
     405            0 :   else if (arg == "hir-pretty")
     406              :     {
     407            0 :       options.enable_dump_option (CompileOptions::HIR_DUMP_PRETTY);
     408              :     }
     409            0 :   else if (arg == "bir")
     410              :     {
     411            0 :       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            1 : }
     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         4983 : Session::handle_input_files (int num_files, const char **files)
     470              : {
     471         4983 :   if (num_files != 1)
     472            0 :     rust_fatal_error (UNDEF_LOCATION,
     473              :                       "only one file may be specified on the command line");
     474              : 
     475         4983 :   const auto &file = files[0];
     476              : 
     477         4983 :   rust_debug ("Attempting to parse file: %s", file);
     478         4983 :   compile_crate (file);
     479         4974 : }
     480              : 
     481              : void
     482         4982 : Session::handle_crate_name (const char *filename,
     483              :                             const AST::Crate &parsed_crate)
     484              : {
     485         4982 :   auto &mappings = Analysis::Mappings::get ();
     486         4982 :   auto crate_name_found = false;
     487         4982 :   auto error = Error (UNDEF_LOCATION, std::string ());
     488              : 
     489        17618 :   for (const auto &attr : parsed_crate.inner_attrs)
     490              :     {
     491        12636 :       if (attr.get_path () != Values::Attributes::CRATE_NAME)
     492        12626 :         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        12636 :     }
     519              : 
     520         4982 :   options.crate_name_set_manually |= crate_name_found;
     521         4982 :   if (!options.crate_name_set_manually)
     522              :     {
     523         4962 :       auto crate_name = infer_crate_name (filename);
     524         4962 :       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         4962 :       rust_debug ("inferred crate name: %s", crate_name.c_str ());
     533         9924 :       options.set_crate_name (crate_name);
     534              : 
     535         4962 :       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         4962 :     }
     543              : 
     544         4981 :   if (saw_errors ())
     545              :     return;
     546              : 
     547         4870 :   CrateNum crate_num = mappings.get_next_crate_num (options.get_crate_name ());
     548         4870 :   mappings.set_current_crate (crate_num);
     549         4982 : }
     550              : 
     551              : /** Parse additional attributes injected from the command line
     552              :  *
     553              :  */
     554              : AST::AttrVec
     555         4983 : parse_cli_attributes (
     556              :   std::vector<CompileOptions::CliAttributeContent> attributes)
     557              : {
     558         4983 :   AST::AttrVec result;
     559         4983 :   result.reserve (attributes.size ());
     560              : 
     561         4984 :   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         4983 :   return result;
     579              : }
     580              : 
     581              : // Parses a single file with filename filename.
     582              : void
     583         4983 : Session::compile_crate (const char *filename)
     584              : {
     585         4983 :   if (!flag_rust_experimental
     586         4983 :       && !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         4983 :   RAIIFile file_wrap (filename);
     609         4983 :   if (!file_wrap.ok ())
     610              :     {
     611            0 :       rust_error_at (UNDEF_LOCATION, "cannot open filename %s: %m", filename);
     612            0 :       return;
     613              :     }
     614              : 
     615         4983 :   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         4983 :   tl::optional<std::ofstream &> dump_lex_opt = tl::nullopt;
     621         4983 :   std::ofstream dump_lex_stream;
     622         4983 :   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         4983 :   auto cli_attributes = parse_cli_attributes (options.addional_attributes);
     633              : 
     634         4983 :   Lexer lex (filename, std::move (file_wrap), linemap, dump_lex_opt);
     635              : 
     636         4983 :   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         4982 :   Parser<Lexer> parser (lex);
     645              : 
     646              :   // generate crate from parser
     647         4982 :   std::unique_ptr<AST::Crate> ast_crate = parser.parse_crate ();
     648              : 
     649              :   // handle crate name
     650         4982 :   handle_crate_name (filename, *ast_crate.get ());
     651              : 
     652              :   // dump options except lexer dump
     653         4982 :   if (options.dump_option_enabled (CompileOptions::TARGET_OPTION_DUMP))
     654              :     {
     655            0 :       options.target_data.dump_target_options ();
     656              :     }
     657         4982 :   if (saw_errors ())
     658              :     return;
     659              : 
     660         4870 :   if (options.dump_option_enabled (CompileOptions::AST_DUMP_PRETTY))
     661              :     {
     662            0 :       dump_ast_pretty (*ast_crate.get ());
     663              :     }
     664         4870 :   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         4870 :   CrateNum current_crate = mappings.get_current_crate ();
     671         4870 :   AST::Crate &parsed_crate
     672         4870 :     = 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         4870 :   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         4870 :   if (flag_syntax_only || last_step == CompileOptions::CompileStep::Ast)
     693              :     return;
     694              : 
     695              :   // register plugins pipeline stage
     696         4845 :   register_plugins (parsed_crate);
     697         4845 :   rust_debug ("\033[0;31mSUCCESSFULLY REGISTERED PLUGINS \033[0m");
     698         4845 :   if (options.dump_option_enabled (CompileOptions::REGISTER_PLUGINS_DUMP))
     699              :     {
     700              :       // TODO: what do I dump here?
     701              :     }
     702              : 
     703              :   // injection pipeline stage
     704         4845 :   injection (parsed_crate, cli_attributes);
     705         4845 :   rust_debug ("\033[0;31mSUCCESSFULLY FINISHED INJECTION \033[0m");
     706         4845 :   if (options.dump_option_enabled (CompileOptions::INJECTION_DUMP))
     707              :     {
     708              :       // TODO: what do I dump here? injected crate names?
     709              :     }
     710              : 
     711         4845 :   if (last_step == CompileOptions::CompileStep::AttributeCheck)
     712              :     return;
     713              : 
     714         4845 :   Analysis::AttributeChecker ().go (parsed_crate);
     715              : 
     716         4845 :   EarlyCfgStrip ().go (parsed_crate);
     717              : 
     718         4845 :   auto parsed_crate_features
     719         4845 :     = Features::FeatureCollector{}.collect (parsed_crate);
     720              : 
     721              :   // Do not inject core if some errors were emitted
     722         9690 :   if (!saw_errors ()
     723         9675 :       && !has_attribute (parsed_crate,
     724        14505 :                          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         4845 :   if (last_step == CompileOptions::CompileStep::Expansion)
     736              :     return;
     737              : 
     738         4845 :   auto name_resolution_ctx = Resolver2_0::NameResolutionContext ();
     739              :   // expansion pipeline stage
     740              : 
     741         4845 :   expansion (parsed_crate, name_resolution_ctx);
     742              : 
     743         4845 :   Analysis::BuiltinAttributeChecker ().go (parsed_crate);
     744              : 
     745         4845 :   AST::CollectLangItems ().go (parsed_crate);
     746              : 
     747         4845 :   rust_debug ("\033[0;31mSUCCESSFULLY FINISHED EXPANSION \033[0m");
     748         4845 :   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         4845 :   if (last_step == CompileOptions::CompileStep::ASTValidation)
     758              :     return;
     759              : 
     760         4844 :   ASTValidation ().check (parsed_crate);
     761              : 
     762              :   // feature gating
     763         4844 :   if (last_step == CompileOptions::CompileStep::FeatureGating)
     764              :     return;
     765              : 
     766         4844 :   FeatureGate (parsed_crate_features).check (parsed_crate);
     767              : 
     768         4844 :   if (last_step == CompileOptions::CompileStep::NameResolution)
     769              :     return;
     770              : 
     771              :   // resolution pipeline stage
     772         4841 :   Resolver2_0::Late (name_resolution_ctx).go (parsed_crate);
     773              : 
     774         4839 :   if (options.dump_option_enabled (CompileOptions::RESOLUTION_DUMP))
     775            0 :     dump_name_resolution (name_resolution_ctx);
     776              : 
     777         4839 :   if (saw_errors ())
     778              :     return;
     779              : 
     780         4637 :   if (last_step == CompileOptions::CompileStep::Lowering)
     781              :     return;
     782              : 
     783              :   // lower AST to HIR
     784         4625 :   std::unique_ptr<HIR::Crate> lowered
     785         4625 :     = HIR::ASTLowering::Resolve (parsed_crate);
     786         4625 :   if (saw_errors ())
     787              :     return;
     788              : 
     789              :   // add the mappings to it
     790         4614 :   HIR::Crate &hir = mappings.insert_hir_crate (std::move (lowered));
     791         4614 :   if (options.dump_option_enabled (CompileOptions::HIR_DUMP))
     792              :     {
     793            0 :       dump_hir (hir);
     794              :     }
     795         4614 :   if (options.dump_option_enabled (CompileOptions::HIR_DUMP_PRETTY))
     796              :     {
     797            0 :       dump_hir_pretty (hir);
     798              :     }
     799              : 
     800         4614 :   if (last_step == CompileOptions::CompileStep::TypeCheck)
     801              :     return;
     802              : 
     803              :   // name resolution is done, we now freeze the name resolver for type checking
     804         4606 :   Resolver2_0::FinalizedNameResolutionContext::init (name_resolution_ctx);
     805              : 
     806              :   // type resolve
     807         4606 :   Compile::Context *ctx = Compile::Context::get ();
     808         4606 :   Resolver::TypeResolution::Resolve (hir);
     809              : 
     810         4606 :   Resolver::TypeCheckContext::get ()->get_variance_analysis_ctx ().solve ();
     811              : 
     812         4606 :   if (saw_errors ())
     813              :     return;
     814              : 
     815         4408 :   Analysis::PatternChecker ().go (hir);
     816              : 
     817         4403 :   if (saw_errors ())
     818              :     return;
     819              : 
     820         4395 :   if (last_step == CompileOptions::CompileStep::Privacy)
     821              :     return;
     822              : 
     823              :   // Various HIR error passes. The privacy pass happens before the unsafe checks
     824         4395 :   Privacy::Resolver::resolve (hir);
     825         4395 :   if (saw_errors ())
     826              :     return;
     827              : 
     828         4385 :   if (last_step == CompileOptions::CompileStep::Unsafety)
     829              :     return;
     830              : 
     831         4384 :   HIR::UnsafeChecker ().go (hir);
     832              : 
     833         4384 :   if (last_step == CompileOptions::CompileStep::Const)
     834              :     return;
     835              : 
     836         4384 :   HIR::ConstChecker ().go (hir);
     837              : 
     838         4384 :   if (last_step == CompileOptions::CompileStep::BorrowCheck)
     839              :     return;
     840              : 
     841         4384 :   if (flag_borrowcheck)
     842              :     {
     843           11 :       const bool dump_bir
     844           11 :         = options.dump_option_enabled (CompileOptions::DumpOption::BIR_DUMP);
     845           11 :       HIR::BorrowChecker (dump_bir).go (hir);
     846              :     }
     847              : 
     848         4384 :   if (saw_errors ())
     849              :     return;
     850              : 
     851         4356 :   if (last_step == CompileOptions::CompileStep::Compilation)
     852              :     return;
     853              : 
     854              :   // do compile to gcc generic
     855         4354 :   Compile::CompileCrate::Compile (hir, ctx);
     856              : 
     857              :   // we can't do static analysis if there are errors to worry about
     858         4352 :   if (!saw_errors ())
     859              :     {
     860              :       // lints
     861         4305 :       Analysis::ScanDeadcode::Scan (hir);
     862              : 
     863         4305 :       if (flag_unused_check_2_0)
     864           21 :         Analysis::UnusedChecker ().go (hir);
     865              :       else
     866         4284 :         Analysis::UnusedVariables::Lint (*ctx);
     867              : 
     868         4305 :       HIR::ReadonlyChecker ().go (hir);
     869              : 
     870              :       // metadata
     871         4305 :       bool specified_emit_metadata
     872         4305 :         = flag_rust_embed_metadata || options.metadata_output_path_set ();
     873         4305 :       if (!specified_emit_metadata)
     874              :         {
     875         4305 :           Metadata::PublicInterface::ExportTo (
     876         8610 :             hir, Metadata::PublicInterface::expected_metadata_filename ());
     877              :         }
     878              :       else
     879              :         {
     880            0 :           if (flag_rust_embed_metadata)
     881            0 :             Metadata::PublicInterface::Export (hir);
     882            0 :           if (options.metadata_output_path_set ())
     883            0 :             Metadata::PublicInterface::ExportTo (
     884              :               hir, options.get_metadata_output ());
     885              :         }
     886              :     }
     887              : 
     888         4352 :   if (saw_errors ())
     889              :     return;
     890              : 
     891              :   // pass to GCC middle-end
     892         4301 :   ctx->write_to_backend ();
     893         5647 : }
     894              : 
     895              : void
     896         4845 : Session::register_plugins (AST::Crate &crate ATTRIBUTE_UNUSED)
     897              : {
     898         4845 :   rust_debug ("ran register_plugins (with no body)");
     899         4845 : }
     900              : 
     901              : // TODO: move somewhere else
     902              : bool
     903         4845 : contains_name (const AST::AttrVec &attrs, std::string name)
     904              : {
     905         9775 :   for (const auto &attr : attrs)
     906              :     {
     907         9775 :       if (attr.get_path () == name)
     908         4845 :         return true;
     909              :     }
     910              : 
     911              :   return false;
     912              : }
     913              : 
     914              : void
     915         4845 : Session::injection (AST::Crate &crate, AST::AttrVec cli_attributes)
     916              : {
     917         4845 :   rust_debug ("started injection");
     918              : 
     919              :   // lint checks in future maybe?
     920              : 
     921              :   // register builtin macros
     922              :   /* In rustc, builtin macros are divided into 3 categories depending on use -
     923              :    * "bang" macros, "attr" macros, and "derive" macros. I think the meanings
     924              :    * of these categories should be fairly obvious to anyone who has used rust.
     925              :    * Builtin macro list by category: Bang
     926              :    *      - asm
     927              :    *      - assert
     928              :    *      - cfg
     929              :    *      - column
     930              :    *      - compile_error
     931              :    *      - concat_idents
     932              :    *      - concat
     933              :    *      - env
     934              :    *      - file
     935              :    *      - format_args_nl
     936              :    *      - format_args
     937              :    *      - global_asm
     938              :    *      - include_bytes
     939              :    *      - include_str
     940              :    *      - include
     941              :    *      - line
     942              :    *      - log_syntax
     943              :    *      - module_path
     944              :    *      - option_env
     945              :    *      - stringify
     946              :    *      - trace_macros
     947              :    *  Attr
     948              :    *      - bench
     949              :    *      - global_allocator
     950              :    *      - test
     951              :    *      - test_case
     952              :    *  Derive
     953              :    *      - Clone
     954              :    *      - Copy
     955              :    *      - Debug
     956              :    *      - Default
     957              :    *      - Eq
     958              :    *      - Hash
     959              :    *      - Ord
     960              :    *      - PartialEq
     961              :    *      - PartialOrd
     962              :    *      - RustcDecodable
     963              :    *      - RustcEncodable
     964              :    * rustc also has a "quote" macro that is defined differently and is
     965              :    * supposedly not stable so eh. */
     966              :   /* TODO: actually implement injection of these macros. In particular, derive
     967              :    * macros, cfg, and test should be prioritised since they seem to be used
     968              :    * the most. */
     969              : 
     970         4846 :   for (auto attribute : cli_attributes)
     971            1 :     crate.inject_inner_attribute (attribute);
     972              : 
     973              :   // crate injection
     974         4845 :   std::vector<std::string> names;
     975         4845 :   if (contains_name (crate.inner_attrs, "no_core"))
     976              :     {
     977              :       // no prelude
     978         4845 :       injected_crate_name = "";
     979              :     }
     980            0 :   else if (contains_name (crate.inner_attrs, "no_std"))
     981              :     {
     982            0 :       names.push_back ("core");
     983              : 
     984            0 :       if (!contains_name (crate.inner_attrs, "compiler_builtins"))
     985              :         {
     986            0 :           names.push_back ("compiler_builtins");
     987              :         }
     988              : 
     989            0 :       injected_crate_name = "core";
     990              :     }
     991              :   else
     992              :     {
     993            0 :       names.push_back ("std");
     994              : 
     995            0 :       injected_crate_name = "std";
     996              :     }
     997              : 
     998              :   // reverse iterate through names to insert crate items in "forward" order at
     999              :   // beginning of crate
    1000         4845 :   for (auto it = names.rbegin (); it != names.rend (); ++it)
    1001              :     {
    1002              :       // create "macro use" attribute for use on extern crate item to enable
    1003              :       // loading macros from it
    1004            0 :       AST::Attribute attr (AST::SimplePath::from_str (
    1005            0 :                              Values::Attributes::MACRO_USE, UNDEF_LOCATION),
    1006            0 :                            nullptr);
    1007              : 
    1008              :       // create "extern crate" item with the name
    1009            0 :       std::unique_ptr<AST::ExternCrate> extern_crate (
    1010            0 :         new AST::ExternCrate (*it, AST::Visibility::create_private (),
    1011            0 :                               {std::move (attr)}, UNKNOWN_LOCATION));
    1012              : 
    1013              :       // insert at beginning
    1014              :       // crate.items.insert (crate.items.begin (), std::move (extern_crate));
    1015            0 :     }
    1016              : 
    1017              :   // create use tree path
    1018              :   // prelude is injected_crate_name
    1019              :   // FIXME: Once we do want to include the standard library, add the prelude
    1020              :   // use item
    1021              :   // std::vector<AST::SimplePathSegment> segments
    1022              :   //   = {AST::SimplePathSegment (injected_crate_name, UNDEF_LOCATION),
    1023              :   //      AST::SimplePathSegment ("prelude", UNDEF_LOCATION),
    1024              :   //      AST::SimplePathSegment ("v1", UNDEF_LOCATION)};
    1025              :   // // create use tree and decl
    1026              :   // std::unique_ptr<AST::UseTreeGlob> use_tree (
    1027              :   //   new AST::UseTreeGlob (AST::UseTreeGlob::PATH_PREFIXED,
    1028              :   //                      AST::SimplePath (std::move (segments)),
    1029              :   //     UNDEF_LOCATION));
    1030              :   // AST::Attribute prelude_attr (AST::SimplePath::from_str ("prelude_import",
    1031              :   //                                                      UNDEF_LOCATION),
    1032              :   //                           nullptr);
    1033              :   // std::unique_ptr<AST::UseDeclaration> use_decl (
    1034              :   //   new AST::UseDeclaration (std::move (use_tree),
    1035              :   //                         AST::Visibility::create_error (),
    1036              :   //                         {std::move (prelude_attr)}, UNDEF_LOCATION));
    1037              : 
    1038              :   // crate.items.insert (crate.items.begin (), std::move (use_decl));
    1039              : 
    1040              :   /* TODO: potentially add checking attribute crate type? I can't figure out
    1041              :    * what this does currently comment says "Unconditionally collect crate
    1042              :    * types from attributes to make them used", which presumably refers to
    1043              :    * checking the linkage info by "crate_type". It also seems to ensure that
    1044              :    * an invalid crate type is not specified, so maybe just do that. Valid
    1045              :    * crate types: bin lib dylib staticlib cdylib rlib proc-macro */
    1046              : 
    1047              :   // this crate type will have options affecting the metadata ouput
    1048              : 
    1049         4845 :   rust_debug ("finished injection");
    1050         4845 : }
    1051              : 
    1052              : void
    1053         4845 : Session::expansion (AST::Crate &crate, Resolver2_0::NameResolutionContext &ctx)
    1054              : {
    1055         4845 :   rust_debug ("started expansion");
    1056              : 
    1057              :   /* rustc has a modification to windows PATH temporarily here, which may end
    1058              :    * up being required */
    1059              : 
    1060              :   // create macro expansion config?
    1061              :   // if not, would at least have to configure recursion_limit
    1062         4845 :   ExpansionCfg cfg;
    1063              : 
    1064         4845 :   auto fixed_point_reached = false;
    1065         4845 :   unsigned iterations = 0;
    1066              : 
    1067              :   // create extctxt? from parse session, cfg, and resolver?
    1068              :   /* expand by calling cxtctxt object's monotonic_expander's expand_crate
    1069              :    * method. */
    1070         4845 :   MacroExpander expander (crate, cfg, *this);
    1071         4845 :   std::vector<Error> macro_errors;
    1072              : 
    1073         4845 :   Resolver2_0::Builtins::setup_lang_prelude (ctx);
    1074              : 
    1075        20782 :   while (!fixed_point_reached && iterations < cfg.recursion_limit)
    1076              :     {
    1077        11176 :       std::vector<Session::LoadedCrate> loaded_crates;
    1078        11176 :       CfgStrip (cfg).go (crate);
    1079              :       // Errors might happen during cfg strip pass
    1080              : 
    1081        11176 :       ExternCrateLoaderVisitor (loaded_crates).go (crate);
    1082              : 
    1083        11176 :       Resolver2_0::Early early (ctx);
    1084        11176 :       early.go (crate);
    1085        11200 :       for (auto &loaded_crate : loaded_crates)
    1086           24 :         ctx.merge (loaded_crate.ctx, loaded_crate.node_id);
    1087        11176 :       macro_errors = early.get_macro_resolve_errors ();
    1088              : 
    1089        11176 :       if (saw_errors ())
    1090              :         break;
    1091              : 
    1092        11133 :       ExpandVisitor (expander).go (crate);
    1093              : 
    1094        11133 :       fixed_point_reached = !expander.has_changed () && !early.is_dirty ();
    1095        11133 :       expander.reset_changed_state ();
    1096        11133 :       iterations++;
    1097              : 
    1098        11133 :       if (saw_errors ())
    1099              :         break;
    1100        11176 :     }
    1101              : 
    1102              :   // Fixed point reached: Emit unresolved macros error
    1103         4888 :   for (auto &error : macro_errors)
    1104           43 :     error.emit ();
    1105              : 
    1106         4845 :   if (iterations == cfg.recursion_limit)
    1107              :     {
    1108            1 :       auto &last_invoc = expander.get_last_invocation ();
    1109            1 :       auto &last_def = expander.get_last_definition ();
    1110              : 
    1111            1 :       rust_assert (last_def.has_value () && last_invoc.has_value ());
    1112              : 
    1113            1 :       rich_location range (line_table, last_invoc->get_locus ());
    1114            1 :       range.add_range (last_def->get_locus ());
    1115              : 
    1116            1 :       rust_error_at (range, "reached recursion limit");
    1117            1 :     }
    1118              : 
    1119              :   // handle AST desugaring
    1120         4845 :   if (!saw_errors ())
    1121              :     {
    1122         4747 :       AST::ExpressionYeast ().go (crate);
    1123              : 
    1124         4747 :       AST::DesugarApit ().go (crate);
    1125              : 
    1126              :       // HACK: we may need a final TopLevel pass
    1127              :       // however, this should not count towards the recursion limit
    1128              :       // and we don't need a full Early pass
    1129         4747 :       Resolver2_0::TopLevel (ctx).go (crate);
    1130              :     }
    1131              : 
    1132              :   // error reporting - check unused macros, get missing fragment specifiers
    1133              : 
    1134              :   // build test harness
    1135              : 
    1136              :   // ast validation (also with proc macro decls)
    1137              : 
    1138              :   // maybe create macro crate if not rustdoc
    1139              : 
    1140         4845 :   rust_debug ("finished expansion");
    1141         4845 : }
    1142              : 
    1143              : void
    1144            0 : Session::dump_ast_pretty (AST::Crate &crate, bool expanded) const
    1145              : {
    1146            0 :   std::ofstream out;
    1147            0 :   if (expanded)
    1148            0 :     out.open (kASTPrettyDumpFileExpanded);
    1149              :   else
    1150            0 :     out.open (kASTPrettyDumpFile);
    1151              : 
    1152            0 :   if (out.fail ())
    1153              :     {
    1154            0 :       rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
    1155              :                      kASTDumpFile);
    1156            0 :       return;
    1157              :     }
    1158              : 
    1159            0 :   AST::Dump (out).go (crate);
    1160              : 
    1161            0 :   out.close ();
    1162            0 : }
    1163              : 
    1164              : void
    1165            0 : Session::dump_ast_pretty_internal (AST::Crate &crate) const
    1166              : {
    1167            0 :   std::ofstream out;
    1168            0 :   out.open (kASTPrettyInternalDumpFile);
    1169              : 
    1170            0 :   if (out.fail ())
    1171              :     {
    1172            0 :       rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
    1173              :                      kASTDumpFile);
    1174            0 :       return;
    1175              :     }
    1176              : 
    1177            0 :   std::set<std::string> str_tmp = options.get_excluded ();
    1178              : 
    1179            0 :   AST::Dump (out,
    1180              :              AST::Dump::Configuration{
    1181              :                AST::Dump::Configuration::InternalComment::Dump,
    1182              :                AST::Dump::Configuration::NodeDescription::Dump,
    1183              :                AST::Dump::Configuration::Comment::Dump,
    1184              :                AST::Dump::Configuration::Newline::Dump,
    1185              :                AST::Dump::Configuration::Indentation::Space4,
    1186              :              },
    1187            0 :              str_tmp)
    1188            0 :     .go (crate);
    1189              : 
    1190            0 :   out.close ();
    1191            0 : }
    1192              : 
    1193              : void
    1194            0 : Session::dump_name_resolution (Resolver2_0::NameResolutionContext &ctx) const
    1195              : {
    1196              :   // YES this is ugly but NO GCC 4.8 does not allow us to make it fancier :(
    1197            0 :   std::string types_content = ctx.types.as_debug_string ();
    1198            0 :   std::ofstream types_stream{kASTtypeResolutionDumpFile};
    1199            0 :   types_stream << types_content;
    1200              : 
    1201            0 :   std::string macros_content = ctx.macros.as_debug_string ();
    1202            0 :   std::ofstream macros_stream{kASTmacroResolutionDumpFile};
    1203            0 :   macros_stream << macros_content;
    1204              : 
    1205            0 :   std::string labels_content = ctx.labels.as_debug_string ();
    1206            0 :   std::ofstream labels_stream{kASTlabelResolutionDumpFile};
    1207            0 :   labels_stream << labels_content;
    1208              : 
    1209            0 :   std::string values_content = ctx.values.as_debug_string ();
    1210            0 :   std::ofstream values_stream{kASTvalueResolutionDumpFile};
    1211            0 :   values_stream << values_content;
    1212            0 : }
    1213              : 
    1214              : void
    1215            0 : Session::dump_hir (HIR::Crate &crate) const
    1216              : {
    1217            0 :   std::ofstream out;
    1218            0 :   out.open (kHIRDumpFile);
    1219            0 :   if (out.fail ())
    1220              :     {
    1221            0 :       rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
    1222              :                      kHIRDumpFile);
    1223            0 :       return;
    1224              :     }
    1225              : 
    1226            0 :   out << crate.to_string ();
    1227            0 :   out.close ();
    1228            0 : }
    1229              : 
    1230              : void
    1231            0 : Session::dump_hir_pretty (HIR::Crate &crate) const
    1232              : {
    1233            0 :   std::ofstream out;
    1234            0 :   out.open (kHIRPrettyDumpFile);
    1235            0 :   if (out.fail ())
    1236              :     {
    1237            0 :       rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
    1238              :                      kHIRPrettyDumpFile);
    1239            0 :       return;
    1240              :     }
    1241              : 
    1242            0 :   HIR::Dump (out).go (crate);
    1243            0 :   out.close ();
    1244            0 : }
    1245              : 
    1246              : // imports
    1247              : 
    1248              : tl::expected<Session::LoadedCrate, Session::LoadingError>
    1249           75 : Session::load_extern_crate (const std::string &crate_name, location_t locus)
    1250              : {
    1251              :   // has it already been loaded?
    1252           75 :   if (auto crate_num = mappings.lookup_crate_name (crate_name))
    1253              :     {
    1254           48 :       auto resolved_node_id = mappings.crate_num_to_nodeid (*crate_num);
    1255           48 :       rust_assert (resolved_node_id);
    1256              : 
    1257           48 :       return tl::make_unexpected (
    1258           48 :         LoadingError::make_already_loaded (*resolved_node_id));
    1259              :     }
    1260              : 
    1261           27 :   std::string relative_import_path = "";
    1262           27 :   std::string import_name = crate_name;
    1263              : 
    1264              :   // The path to the extern crate might have been specified by the user using
    1265              :   // -frust-extern
    1266           27 :   auto cli_extern_crate = extern_crates.find (crate_name);
    1267              : 
    1268           27 :   std::pair<std::unique_ptr<Import::Stream>, std::vector<ProcMacro::Procmacro>>
    1269           27 :     package_result;
    1270           27 :   if (cli_extern_crate != extern_crates.end ())
    1271              :     {
    1272            0 :       auto path = cli_extern_crate->second;
    1273            0 :       package_result = Import::try_package_in_directory (path, locus);
    1274            0 :     }
    1275              :   else
    1276              :     {
    1277           27 :       package_result
    1278           54 :         = Import::open_package (import_name, locus, relative_import_path);
    1279              :     }
    1280              : 
    1281           27 :   auto stream = std::move (package_result.first);
    1282           27 :   auto proc_macros = std::move (package_result.second);
    1283              : 
    1284           27 :   if (stream == NULL           // No stream and
    1285           27 :       && proc_macros.empty ()) // no proc macros
    1286              :     {
    1287            3 :       rust_error_at (locus, "failed to locate crate %qs", import_name.c_str ());
    1288            3 :       return tl::make_unexpected (LoadingError::make_failed_to_locate ());
    1289              :     }
    1290              : 
    1291           24 :   auto extern_crate
    1292           24 :     = stream == nullptr
    1293           24 :         ? Imports::ExternCrate (crate_name,
    1294            0 :                                 proc_macros) // Import proc macros
    1295           24 :         : Imports::ExternCrate (*stream);    // Import from stream
    1296           24 :   if (stream != nullptr)
    1297              :     {
    1298           24 :       bool ok = extern_crate.load (locus);
    1299           24 :       if (!ok)
    1300              :         {
    1301            0 :           rust_error_at (locus, "failed to load crate metadata");
    1302            0 :           return tl::make_unexpected (LoadingError::make_failed_to_locate ());
    1303              :         }
    1304              :     }
    1305              : 
    1306              :   // ensure the current vs this crate name don't collide
    1307           24 :   const std::string current_crate_name = mappings.get_current_crate_name ();
    1308           24 :   if (current_crate_name.compare (extern_crate.get_crate_name ()) == 0)
    1309              :     {
    1310            0 :       rust_error_at (locus, "current crate name %qs collides with this",
    1311              :                      current_crate_name.c_str ());
    1312            0 :       return tl::make_unexpected (LoadingError::make_collision ());
    1313              :     }
    1314              : 
    1315              :   // setup mappings
    1316           24 :   CrateNum saved_crate_num = mappings.get_current_crate ();
    1317           24 :   CrateNum crate_num
    1318           24 :     = mappings.get_next_crate_num (extern_crate.get_crate_name ());
    1319           24 :   mappings.set_current_crate (crate_num);
    1320              : 
    1321              :   // then lets parse this as a 2nd crate
    1322           24 :   Lexer lex (extern_crate.get_metadata (), linemap);
    1323           24 :   Parser<Lexer> parser (lex);
    1324           24 :   std::unique_ptr<AST::Crate> metadata_crate = parser.parse_crate ();
    1325              : 
    1326           24 :   AST::Crate &parsed_crate
    1327           24 :     = mappings.insert_ast_crate (std::move (metadata_crate), crate_num);
    1328              : 
    1329           24 :   auto ctx = Resolver2_0::NameResolutionContext ();
    1330           24 :   Resolver2_0::Builtins::setup_lang_prelude (ctx);
    1331              : 
    1332           24 :   Resolver2_0::Early early (ctx);
    1333           24 :   early.go (parsed_crate);
    1334           24 :   Resolver2_0::Late (ctx).go (parsed_crate);
    1335              : 
    1336           24 :   std::vector<AttributeProcMacro> attribute_macros;
    1337           24 :   std::vector<CustomDeriveProcMacro> derive_macros;
    1338           24 :   std::vector<BangProcMacro> bang_macros;
    1339              : 
    1340           24 :   for (auto &macro : extern_crate.get_proc_macros ())
    1341              :     {
    1342            0 :       switch (macro.tag)
    1343              :         {
    1344            0 :         case ProcMacro::CUSTOM_DERIVE:
    1345            0 :           derive_macros.push_back (macro.payload.custom_derive);
    1346            0 :           break;
    1347            0 :         case ProcMacro::ATTR:
    1348            0 :           attribute_macros.push_back (macro.payload.attribute);
    1349            0 :           break;
    1350            0 :         case ProcMacro::BANG:
    1351            0 :           bang_macros.push_back (macro.payload.bang);
    1352            0 :           break;
    1353            0 :         default:
    1354            0 :           gcc_unreachable ();
    1355              :         }
    1356              :     }
    1357              : 
    1358           24 :   mappings.insert_attribute_proc_macros (crate_num, attribute_macros);
    1359           24 :   mappings.insert_bang_proc_macros (crate_num, bang_macros);
    1360           24 :   mappings.insert_derive_proc_macros (crate_num, derive_macros);
    1361              : 
    1362              :   // always restore the crate_num
    1363           24 :   mappings.set_current_crate (saved_crate_num);
    1364              : 
    1365           96 :   return LoadedCrate{crate_name, parsed_crate.get_node_id (), std::move (ctx)};
    1366          102 : }
    1367              : //
    1368              : 
    1369              : void
    1370            0 : TargetOptions::dump_target_options () const
    1371              : {
    1372            0 :   std::ofstream out;
    1373            0 :   out.open (kTargetOptionsDumpFile);
    1374            0 :   if (out.fail ())
    1375              :     {
    1376            0 :       rust_error_at (UNKNOWN_LOCATION, "cannot open %s:%m; ignored",
    1377              :                      kTargetOptionsDumpFile);
    1378            0 :       return;
    1379              :     }
    1380              : 
    1381            0 :   if (features.empty ())
    1382              :     {
    1383            0 :       out << "No target options available!\n";
    1384              :     }
    1385              : 
    1386            0 :   for (const auto &pairs : features)
    1387              :     {
    1388            0 :       for (const auto &value : pairs.second)
    1389              :         {
    1390            0 :           if (value.has_value ())
    1391            0 :             out << pairs.first + ": \"" + value.value () + "\"\n";
    1392              :           else
    1393            0 :             out << pairs.first + "\n";
    1394              :         }
    1395              :     }
    1396              : 
    1397            0 :   out.close ();
    1398            0 : }
    1399              : 
    1400              : void
    1401            0 : TargetOptions::init_derived_values ()
    1402              : {
    1403              :   // enable derived values based on target families
    1404            0 :   if (has_key_value_pair ("target_family", "unix"))
    1405            0 :     insert_key ("unix");
    1406            0 :   if (has_key_value_pair ("target_family", "windows"))
    1407            0 :     insert_key ("windows");
    1408              : 
    1409              :   // implicitly enable features - this should not be required in general
    1410            0 :   if (has_key_value_pair ("target_feature", "aes"))
    1411            0 :     enable_implicit_feature_reqs ("aes");
    1412            0 :   if (has_key_value_pair ("target_feature", "avx"))
    1413            0 :     enable_implicit_feature_reqs ("sse4.2");
    1414            0 :   if (has_key_value_pair ("target_feature", "avx2"))
    1415            0 :     enable_implicit_feature_reqs ("avx");
    1416            0 :   if (has_key_value_pair ("target_feature", "pclmulqdq"))
    1417            0 :     enable_implicit_feature_reqs ("sse2");
    1418            0 :   if (has_key_value_pair ("target_feature", "sha"))
    1419            0 :     enable_implicit_feature_reqs ("sse2");
    1420            0 :   if (has_key_value_pair ("target_feature", "sse2"))
    1421            0 :     enable_implicit_feature_reqs ("sse");
    1422            0 :   if (has_key_value_pair ("target_feature", "sse3"))
    1423            0 :     enable_implicit_feature_reqs ("sse2");
    1424            0 :   if (has_key_value_pair ("target_feature", "sse4.1"))
    1425            0 :     enable_implicit_feature_reqs ("sse3");
    1426            0 :   if (has_key_value_pair ("target_feature", "sse4.2"))
    1427            0 :     enable_implicit_feature_reqs ("sse4.1");
    1428            0 :   if (has_key_value_pair ("target_feature", "ssse3"))
    1429            0 :     enable_implicit_feature_reqs ("sse3");
    1430            0 : }
    1431              : 
    1432              : void
    1433            0 : TargetOptions::enable_implicit_feature_reqs (std::string feature)
    1434              : {
    1435            0 :   if (feature == "aes")
    1436            0 :     enable_implicit_feature_reqs ("sse2");
    1437            0 :   else if (feature == "avx")
    1438            0 :     enable_implicit_feature_reqs ("sse4.2");
    1439            0 :   else if (feature == "avx2")
    1440            0 :     enable_implicit_feature_reqs ("avx");
    1441            0 :   else if (feature == "fma")
    1442            0 :     enable_implicit_feature_reqs ("avx");
    1443            0 :   else if (feature == "pclmulqdq")
    1444            0 :     enable_implicit_feature_reqs ("sse2");
    1445            0 :   else if (feature == "sha")
    1446            0 :     enable_implicit_feature_reqs ("sse2");
    1447            0 :   else if (feature == "sse2")
    1448            0 :     enable_implicit_feature_reqs ("sse");
    1449            0 :   else if (feature == "sse3")
    1450            0 :     enable_implicit_feature_reqs ("sse2");
    1451            0 :   else if (feature == "sse4.1")
    1452            0 :     enable_implicit_feature_reqs ("sse3");
    1453            0 :   else if (feature == "sse4.2")
    1454            0 :     enable_implicit_feature_reqs ("sse4.1");
    1455            0 :   else if (feature == "ssse3")
    1456            0 :     enable_implicit_feature_reqs ("sse3");
    1457              : 
    1458            0 :   if (!has_key_value_pair ("target_feature", feature))
    1459              :     {
    1460            0 :       insert_key_value_pair ("target_feature", feature);
    1461              : 
    1462            0 :       rust_debug ("had to implicitly enable feature '%s'!", feature.c_str ());
    1463              :     }
    1464            0 : }
    1465              : 
    1466              : // NOTEs:
    1467              : /* mrustc compile pipeline:
    1468              :  *  - target load (pass target spec to parser?)
    1469              :  *  - parse (convert source to AST)
    1470              :  *  - load crates (load any explicitly mentioned extern crates [not all of
    1471              :  * them])
    1472              :  *  - expand (AST transformations from attributes and macros, loads remaining
    1473              :  * extern crates [std/core and any triggered by macro expansion])
    1474              :  *  - implicit crates (test harness, allocator crate, panic crate)
    1475              :  *  - resolve use (annotate every 'use' item with source [supposedly handles
    1476              :  * nasty recursion])
    1477              :  *  - resolve index (generate index of visible items for every module [avoids
    1478              :  * recursion in next pass])
    1479              :  *  - resolve absolute (resolve all paths into either variable names
    1480              :  * [types/values] or absolute paths)
    1481              :  *  - HIR lower (convert modified AST to simpler HIR [both expressions and
    1482              :  * module tree])
    1483              :  *  - resolve type aliases (replace any usages of type aliases with actual
    1484              :  * type [except associated types])
    1485              :  *  - resolve bind (iterate HIR tree and set binding annotations on all
    1486              :  * concrete types [avoids path lookups later])
    1487              :  *  - resolve HIR markings (generate "markings" [e.g. for Copy/Send/Sync/...]
    1488              :  * for all types
    1489              :  *  - sort impls (small pass - sort impls into groups)
    1490              :  *  - resolve UFCS outer (determine source trait for all top-level <T>::Type
    1491              :  * [qualified] paths)
    1492              :  *  - resolve UFCS paths (do the same, but include for exprs this time. also
    1493              :  * normalises results of previous pass [expanding known associated types])
    1494              :  *  - constant evaluate (evaluate all constants)
    1495              :  *  - typecheck outer (checks impls are sane)
    1496              :  *  - typecheck expressions (resolve and check types for all exprs)
    1497              :  *  - expand HIR annotate (annotate how exprs are used - used for closure
    1498              :  * extractions and reborrows)
    1499              :  *  - expand HIR closures (extract closures into structs implementing Fn*
    1500              :  * traits)
    1501              :  *  - expand HIR vtables (generate vtables for types with dyn dispatch)
    1502              :  *  - expand HIR calls (converts method and callable calls into explicit
    1503              :  * function calls)
    1504              :  *  - expand HIR reborrows (apply reborrow rules [taking '&mut *v' instead of
    1505              :  * 'v'])
    1506              :  *  - expand HIR erasedtype (replace all erased types 'impl Trait' with the
    1507              :  * true type)
    1508              :  *  - typecheck expressions (validate - double check that previous passes
    1509              :  * haven't broke type system rules)
    1510              :  *  - lower MIR (convert HIR exprs into a control-flow graph [MIR])
    1511              :  *  - MIR validate (check that the generated MIR is consistent)
    1512              :  *  - MIR cleanup (perform various transformations on MIR - replace reads of
    1513              :  * const items with the item itself; convert casts to unsized types into
    1514              :  * 'MakeDst' operations)
    1515              :  *  - MIR optimise (perform various simple optimisations on the MIR - constant
    1516              :  * propagation, dead code elimination, borrow elimination, some inlining)
    1517              :  *  - MIR validate PO (re-validate the MIR)
    1518              :  *  - MIR validate full (optionally: perform expensive state-tracking
    1519              :  * validation on MIR)
    1520              :  *  - trans enumerate (enumerate all items needed for code generation,
    1521              :  * primarily types used for generics)
    1522              :  *  - trans auto impls (create magic trait impls as enumerated in previous
    1523              :  * pass)
    1524              :  *  - trans monomorph (generate monomorphised copies of all functions [with
    1525              :  * generics replaced with real types])
    1526              :  *  - MIR optimise inline (run optimisation again, this time with full type
    1527              :  * info [primarily for inlining])
    1528              :  *  - HIR serialise (write out HIR dump [module tree and generic/inline MIR])
    1529              :  *  - trans codegen (generate final output file: emit C source file and call C
    1530              :  * compiler) */
    1531              : 
    1532              : /* rustc compile pipeline (basic, in way less detail):
    1533              :  *  - parse input (parse .rs to AST)
    1534              :  *  - name resolution, macro expansion, and configuration (process AST
    1535              :  * recursively, resolving paths, expanding macros, processing #[cfg] nodes
    1536              :  * [i.e. maybe stripping stuff from AST])
    1537              :  *  - lower to HIR
    1538              :  *  - type check and other analyses (e.g. privacy checking)
    1539              :  *  - lower to MIR and post-processing (and do stuff like borrow checking)
    1540              :  *  - translation to LLVM IR and LLVM optimisations (produce the .o files)
    1541              :  *  - linking (link together .o files) */
    1542              : 
    1543              : /* Pierced-together rustc compile pipeline (from source):
    1544              :  *  - parse input (parse file to crate)
    1545              :  *  - register plugins (attributes injection, set various options, register
    1546              :  * lints, load plugins)
    1547              :  *  - expansion/configure and expand (initial 'cfg' processing, 'loading
    1548              :  * compiler plugins', syntax expansion, secondary 'cfg' expansion, synthesis
    1549              :  * of a test harness if required, injection of any std lib dependency and
    1550              :  * prelude, and name resolution) - actually documented inline
    1551              :  *      - seeming pierced-together order: pre-AST expansion lint checks,
    1552              :  * registering builtin macros, crate injection, then expand all macros, then
    1553              :  * maybe build test harness, AST validation, maybe create a macro crate (if
    1554              :  * not rustdoc), name resolution, complete gated feature checking, add all
    1555              :  * buffered lints
    1556              :  *  - create global context (lower to HIR)
    1557              :  *  - analysis on global context (HIR optimisations? create MIR?)
    1558              :  *  - code generation
    1559              :  *  - link */
    1560              : } // namespace Rust
    1561              : 
    1562              : #if CHECKING_P
    1563              : namespace selftest {
    1564              : void
    1565            1 : rust_crate_name_validation_test (void)
    1566              : {
    1567            1 :   auto error = Rust::Error (UNDEF_LOCATION, std::string ());
    1568            1 :   ASSERT_TRUE (Rust::validate_crate_name ("example", error));
    1569            1 :   ASSERT_TRUE (Rust::validate_crate_name ("abcdefg_1234", error));
    1570            1 :   ASSERT_TRUE (Rust::validate_crate_name ("1", error));
    1571            1 :   ASSERT_TRUE (Rust::validate_crate_name ("クレート", error));
    1572            1 :   ASSERT_TRUE (Rust::validate_crate_name ("Sōkrátēs", error));
    1573            1 :   ASSERT_TRUE (Rust::validate_crate_name ("惊吓", error));
    1574              : 
    1575              :   // NOTE: - is not allowed in the crate name ...
    1576              : 
    1577            1 :   ASSERT_FALSE (Rust::validate_crate_name ("abcdefg-1234", error));
    1578            1 :   ASSERT_FALSE (Rust::validate_crate_name ("a+b", error));
    1579            1 :   ASSERT_FALSE (Rust::validate_crate_name ("/a+b/", error));
    1580            1 :   ASSERT_FALSE (Rust::validate_crate_name ("😸++", error));
    1581            1 :   ASSERT_FALSE (Rust::validate_crate_name ("∀", error));
    1582              : 
    1583              :   /* Tests for crate name inference */
    1584            1 :   ASSERT_EQ (Rust::infer_crate_name (".rs"), "");
    1585            1 :   ASSERT_EQ (Rust::infer_crate_name ("c.rs"), "c");
    1586              :   // NOTE: ... but - is allowed when in the filename
    1587            1 :   ASSERT_EQ (Rust::infer_crate_name ("a-b.rs"), "a_b");
    1588            1 :   ASSERT_EQ (Rust::infer_crate_name ("book.rs.txt"), "book.rs");
    1589              : #if defined(HAVE_DOS_BASED_FILE_SYSTEM)
    1590              :   ASSERT_EQ (Rust::infer_crate_name ("a\\c\\a-b.rs"), "a_b");
    1591              : #else
    1592            1 :   ASSERT_EQ (Rust::infer_crate_name ("a/c/a-b.rs"), "a_b");
    1593              : #endif
    1594            1 : }
    1595              : } // namespace selftest
    1596              : #endif // CHECKING_P
        

Generated by: LCOV version 2.4-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.