LCOV - code coverage report
Current view: top level - gcc/rust/resolve - rust-name-resolution-context.h (source / functions) Coverage Total Hit
Test: gcc.info Lines: 93.6 % 204 191
Test Date: 2026-11-14 16:39:50 Functions: 98.9 % 93 92
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              : #ifndef RUST_NAME_RESOLVER_2_0_CTX_H
      20              : #define RUST_NAME_RESOLVER_2_0_CTX_H
      21              : 
      22              : #include "optional.h"
      23              : #include "rust-forever-stack.h"
      24              : #include "rust-hir-map.h"
      25              : #include "rust-rib.h"
      26              : #include "rust-stacked-contexts.h"
      27              : #include "rust-item.h"
      28              : #include "rust-name-resolution.h"
      29              : 
      30              : namespace Rust {
      31              : namespace Resolver2_0 {
      32              : 
      33              : // TODO: Add missing mappings and data structures
      34              : 
      35              : /**
      36              : The data structures we need to develop need to fill in a few roles - like the
      37              : original name resolver, they need to be accessible at multiple points during the
      38              : pipeline to allow compiler passes such as macro expansion or typechecking to
      39              : benefit from them. Unlike the original name resolution, these data structures
      40              : need to be created by multiple compiler passes: Whereas the original name
      41              : resolution of gccrs tries to perform name resolution in a single pass, it fails
      42              : at properly handling more complex name resolution cases such as macro name
      43              : resolution, imports in general, and glob imports in particular. The goal of this
      44              : new name resolution algorithm is to split the name resolution in at least two
      45              : passes - `Early` name resolution, which takes care of macro name resolution and
      46              : import resolution, and `Late` name resolution - your typical name resolution,
      47              : for types, functions, variables...
      48              : 
      49              :   1. `Early`
      50              : 
      51              :   The Early name resolution is tied in snuggly with macro expansion: macro
      52              : expansion cannot happen without some form of name resolution (pointing an
      53              : invocation to its definition) but may also *depend* on name resolution (a macro
      54              : generating another macro... or importing items... and funny other cases like
      55              : these). It needs to work in a fixed-point fashion alongside macro expansion:
      56              : While there are imports to resolve, or macros to expand, we need to keep going
      57              : and resolve them. This is achieved, among other things, by a top-level name
      58              : resolution pass in charge of collection use statements and macro definitions (as
      59              : well as Items, which will be useful for later passes of the name resolution).
      60              : 
      61              :     This top-level pass exists because Rust enables you to call a function
      62              : before having declared it (at a lexical level, i.e calling `f(15)` at line 3
      63              : while the `f` function is declared at line 1499).
      64              : 
      65              :   This Early pass needs to build the first part of our "resolution map", which
      66              : will then be used in multiple contexts:
      67              : 
      68              :   1. The MacroExpander, in a read-only fashion: fetching macro definitions for
      69              : each invocation and performing the expansion.
      70              :   2. `Late`, which will write more data inside that resolution map, and use it
      71              : to perform its name resolution too.
      72              : 
      73              :   This is where the first challenge of this data structure lies: The existing
      74              : data structures and name resolution algorithm relies on the name resolution pass
      75              : happening just once. In typical name resolution fashion, when it sees a lexical
      76              : scope (a new module, a function's block, a block expression...), it "pushes" a
      77              : new "Scope" to a stack of these scopes, and "pops" it when exiting said lexical
      78              : scope. However, because we are splitting the name resolution into two passes, we
      79              : would like to avoid re-doing a bunch of work we've already done - which is why
      80              : this data structure needs to allow "re-entrancy", or to at least not keep as
      81              : much state as the existing one, and allow for viewing the same module multiple
      82              : times without throwing a fit.
      83              : 
      84              :   We will be implementing a "forever stack" of scopes, which allows the user the
      85              : pushing of new scopes onto the stack, but only simulates the popping of a scope:
      86              : When pushing new scopes, more space is allocated on our stack, and we keep
      87              : track of this scope as being the current one - however, when popping this scope,
      88              : we do not actually delete the memory associated with it: we simply mark the
      89              : previous scope (parent) as the current one.
      90              : 
      91              : In the example below, each number indicates the "state" of our resolution map,
      92              : and the carret is used to point to the current lexical scope.
      93              : 
      94              : ```rust
      95              :                 // []
      96              :                 //
      97              : fn main() {     // [ `main` scope: {} ]
      98              :                 //         ^
      99              :   let a = 15;   // [ `main` scope: { Decl(a) } ]
     100              :                 //         ^
     101              :   {  _PUSH_     // [ `main` scope: { Decl(a) }, anonymous scope: {} ]
     102              :                 //                                        ^
     103              :     let a = 16; // [ `main` scope: { Decl(a) }, anonymous scope: { Decl(a) } ]
     104              :                 //                                        ^
     105              :     f(a);       // [ `main` scope: { Decl(a) }, anonymous scope: { Decl(a) } ]
     106              :                 //                                        ^
     107              :   }   _POP_     // [ `main` scope: { Decl(a) }, anonymous scope: { Decl(a) } ]
     108              :                 //         ^
     109              :   f(a);         // [ `main` scope: { Decl(a) }, anonymous scope: { Decl(a) } ]
     110              :                 //         ^
     111              : }
     112              : ```
     113              : 
     114              : This allows us to revisit scopes previously visited in later phases of the name
     115              : resolution, and add more information if necessary.
     116              : 
     117              :   2. `Late`
     118              : 
     119              :   `Late` name resolution possesses some unique challenges since Rust's name
     120              : resolution rules are extremely complex - variable shadowing, variable capture in
     121              : closures (but not inner functions!)... You can have a look at a fucked up
     122              : example here:
     123              : 
     124              : https://rustc-dev-guide.rust-lang.org/name-resolution.html#scopes-and-ribs
     125              : 
     126              : This requires us to think about what exactly to put in our `Scope`s and what to
     127              : do with our `Rib`s - and how it affects our data structures. For example, in the
     128              : above example, `rustc` demonstrates how multiple `Rib`s can be created inside of
     129              : a single lexical scope for variables, as the Rust programming language allows
     130              : shadowing.
     131              : 
     132              :     TODO: Mention macro hygiene and that it is the same
     133              :     TODO: How does this affect our data structures?
     134              :     TODO: Last challenge - reuse the same APIs to allow the typechecker to not
     135              : change?
     136              :     TODO: Mention that ForeverStack is templated to make sure that behavior is
     137              : correct
     138              : */
     139              : 
     140              : struct IdentifierMode
     141              : {
     142              :   bool is_ref;
     143              :   bool is_mut;
     144              : 
     145       177741 :   IdentifierMode (bool is_ref, bool is_mut) : is_ref (is_ref), is_mut (is_mut)
     146              :   {}
     147              : 
     148           68 :   bool operator== (const IdentifierMode &other)
     149              :   {
     150           68 :     return other.is_ref == is_ref && other.is_mut == is_mut;
     151              :   }
     152              : 
     153          272 :   bool operator!= (const IdentifierMode &other) { return !(*this == other); }
     154              : };
     155              : 
     156      3395675 : struct Binding
     157              : {
     158              :   enum class Kind
     159              :   {
     160              :     Product,
     161              :     Or,
     162              :   } kind;
     163              : 
     164              :   // used to check the correctness of or-bindings
     165              :   bool has_expected_bindings;
     166              : 
     167              :   std::unordered_map<std::string, std::pair<location_t, IdentifierMode>> idents;
     168              : 
     169       566533 :   Binding (Binding::Kind kind) : kind (kind), has_expected_bindings (false) {}
     170              : };
     171              : 
     172              : /**
     173              :  * Used to identify the source of a binding, and emit the correct error message.
     174              :  */
     175              : enum class BindingSource
     176              : {
     177              :   Match,
     178              :   Let,
     179              :   IfLet,
     180              :   WhileLet,
     181              :   For,
     182              :   /* Closure param or function param */
     183              :   Param
     184              : };
     185              : 
     186      2259470 : class BindingLayer
     187              : {
     188              :   BindingSource source;
     189              :   std::vector<Binding> bindings;
     190              : 
     191              :   bool bind_test (Identifier ident, Binding::Kind kind);
     192              : 
     193              : public:
     194              :   void push (Binding::Kind kind);
     195              : 
     196              :   BindingLayer (BindingSource source);
     197              : 
     198              :   /**
     199              :    * Identifies if the identifier has been used in a product binding context.
     200              :    * eg. `let (a, a) = test();`
     201              :    */
     202              :   bool is_and_bound (Identifier ident);
     203              : 
     204              :   /**
     205              :    * Identifies if the identifier has been used in a or context.
     206              :    * eg. `let (a, 1) | (a, 2) = test()`
     207              :    */
     208              :   bool is_or_bound (Identifier ident);
     209              : 
     210              :   void insert_ident (std::string ident, location_t locus, bool is_ref,
     211              :                      bool is_mut);
     212              : 
     213              :   void merge ();
     214              : 
     215              :   BindingSource get_source () const;
     216              : };
     217              : 
     218              : class NameResolutionContext;
     219              : /*
     220              :  * Used to handle canonical paths
     221              :  * Similar to ForeverStack, but namespace independent and more specialized
     222              :  */
     223       244544 : class CanonicalPathRecord
     224              : {
     225              : public:
     226              :   virtual Resolver::CanonicalPath as_path (const NameResolutionContext &,
     227              :                                            Namespace ns)
     228              :     = 0;
     229              : 
     230              :   virtual bool is_root () const = 0;
     231              : 
     232              :   virtual ~CanonicalPathRecord () = default;
     233              : };
     234              : 
     235              : class CanonicalPathRecordWithParent : public CanonicalPathRecord
     236              : {
     237              : public:
     238       239141 :   CanonicalPathRecordWithParent (NodeId parent_node_id)
     239       239141 :     : parent_node_id (parent_node_id)
     240              :   {}
     241              : 
     242     13695819 :   NodeId get_parent () { return parent_node_id; }
     243              : 
     244     13481369 :   bool is_root () const override final { return false; }
     245              : 
     246              : private:
     247              :   NodeId parent_node_id;
     248              : };
     249              : 
     250              : class CanonicalPathRecordCrateRoot : public CanonicalPathRecord
     251              : {
     252              : public:
     253         5403 :   CanonicalPathRecordCrateRoot (NodeId node_id, std::string seg)
     254         5403 :     : node_id (node_id), seg (std::move (seg))
     255              :   {
     256         5403 :     rust_assert (Analysis::Mappings::get ().crate.node_is_crate (node_id));
     257         5403 :     crate_num
     258         5403 :       = Analysis::Mappings::get ().crate.lookup_crate_num (node_id).value ();
     259         5403 :   }
     260              : 
     261              :   Resolver::CanonicalPath as_path (const NameResolutionContext &,
     262              :                                    Namespace ns) override;
     263              : 
     264        35695 :   bool is_root () const override final { return true; }
     265              : 
     266              : private:
     267              :   NodeId node_id;
     268              :   CrateNum crate_num;
     269              :   std::string seg;
     270              : };
     271              : 
     272              : class CanonicalPathRecordNormal : public CanonicalPathRecordWithParent
     273              : {
     274              : public:
     275       173547 :   CanonicalPathRecordNormal (NodeId parent_node_id, NodeId node_id,
     276              :                              std::string seg)
     277       173547 :     : CanonicalPathRecordWithParent (parent_node_id), node_id (node_id),
     278       173547 :       seg (std::move (seg))
     279              :   {
     280       173547 :     rust_assert (!Analysis::Mappings::get ().crate.node_is_crate (node_id));
     281       173547 :   }
     282              : 
     283              :   Resolver::CanonicalPath as_path (const NameResolutionContext &,
     284              :                                    Namespace ns) override;
     285              : 
     286              : private:
     287              :   NodeId node_id;
     288              :   std::string seg;
     289              : };
     290              : 
     291              : class CanonicalPathRecordLookup : public CanonicalPathRecord
     292              : {
     293              : public:
     294        65594 :   CanonicalPathRecordLookup (NodeId lookup_id)
     295        65594 :     : lookup_id (lookup_id), cache (nullptr)
     296              :   {}
     297              : 
     298              :   Resolver::CanonicalPath as_path (const NameResolutionContext &,
     299              :                                    Namespace ns) override;
     300              : 
     301            0 :   bool is_root () const override final { return true; }
     302              : 
     303              : private:
     304              :   NodeId lookup_id;
     305              :   CanonicalPathRecord *cache;
     306              : };
     307              : 
     308              : class CanonicalPathRecordImpl : public CanonicalPathRecordWithParent
     309              : {
     310              : public:
     311         3577 :   CanonicalPathRecordImpl (NodeId parent_node_id, NodeId impl_id,
     312              :                            NodeId type_id)
     313         3577 :     : CanonicalPathRecordWithParent (parent_node_id), impl_id (impl_id),
     314         3577 :       type_record (type_id)
     315              :   {}
     316              : 
     317              :   Resolver::CanonicalPath as_path (const NameResolutionContext &,
     318              :                                    Namespace ns) override;
     319              : 
     320              : private:
     321              :   NodeId impl_id;
     322              :   CanonicalPathRecordLookup type_record;
     323              : };
     324              : 
     325              : class CanonicalPathRecordTraitImpl : public CanonicalPathRecordWithParent
     326              : {
     327              : public:
     328        62017 :   CanonicalPathRecordTraitImpl (NodeId parent_node_id, NodeId impl_id,
     329              :                                 NodeId type_id, NodeId trait_path_id)
     330        62017 :     : CanonicalPathRecordWithParent (parent_node_id), impl_id (impl_id),
     331        62017 :       type_record (type_id), trait_path_record (trait_path_id)
     332              :   {}
     333              : 
     334              :   Resolver::CanonicalPath as_path (const NameResolutionContext &,
     335              :                                    Namespace ns) override;
     336              : 
     337              : private:
     338              :   NodeId impl_id;
     339              :   CanonicalPathRecordLookup type_record;
     340              :   CanonicalPathRecordLookup trait_path_record;
     341              : };
     342              : 
     343              : class CanonicalPathCtx
     344              : {
     345              : public:
     346         5334 :   CanonicalPathCtx (const NameResolutionContext &ctx)
     347         5334 :     : current_record (UNKNOWN_NODEID), nr_ctx (&ctx)
     348              :   {}
     349              : 
     350        62251 :   Resolver::CanonicalPath get_path (NodeId id, Namespace ns) const
     351              :   {
     352        62251 :     return get_record (id).as_path (*nr_ctx, ns);
     353              :   }
     354              : 
     355       276701 :   CanonicalPathRecord &get_record (NodeId id) const
     356              :   {
     357       276701 :     auto it = records.find (id);
     358       276701 :     rust_assert (it != records.end ());
     359       276701 :     return *it->second;
     360              :   }
     361              : 
     362        32668 :   tl::optional<CanonicalPathRecord *> get_record_opt (NodeId id) const
     363              :   {
     364        32668 :     auto it = records.find (id);
     365        32668 :     if (it == records.end ())
     366        11194 :       return tl::nullopt;
     367              :     else
     368        21474 :       return it->second.get ();
     369              :   }
     370              : 
     371              :   void insert_record (NodeId id, const Identifier &ident)
     372              :   {
     373              :     insert_record (id, ident.as_string ());
     374              :   }
     375              : 
     376              :   void insert_record (NodeId id, std::string seg)
     377              :   {
     378              :     rust_assert (current_record != UNKNOWN_NODEID);
     379              : 
     380              :     auto it = records.find (id);
     381              :     if (it == records.end ())
     382              :       {
     383              :         auto record
     384              :           = new CanonicalPathRecordNormal (current_record, id, std::move (seg));
     385              :         bool ok
     386              :           = records.emplace (id, std::unique_ptr<CanonicalPathRecord> (record))
     387              :               .second;
     388              :         rust_assert (ok);
     389              :       }
     390              :   }
     391              : 
     392      9586516 :   template <typename F> void scope (NodeId id, const Identifier &ident, F &&f)
     393              :   {
     394     19173032 :     scope (id, ident.as_string (), std::forward<F> (f));
     395      9586514 :   }
     396              : 
     397      9586516 :   template <typename F> void scope (NodeId id, std::string seg, F &&f)
     398              :   {
     399      9586516 :     rust_assert (current_record != UNKNOWN_NODEID);
     400              : 
     401      9760063 :     scope_inner (id, std::forward<F> (f), [this, id, &seg] () {
     402       173547 :       return new CanonicalPathRecordNormal (current_record, id,
     403       173547 :                                             std::move (seg));
     404              :     });
     405      9586514 :   }
     406              : 
     407       174592 :   template <typename F> void scope_impl (AST::InherentImpl &impl, F &&f)
     408              :   {
     409       174592 :     rust_assert (current_record != UNKNOWN_NODEID);
     410              : 
     411       174592 :     NodeId id = impl.get_node_id ();
     412       174592 :     scope_inner (id, std::forward<F> (f), [this, id, &impl] () {
     413         3577 :       return new CanonicalPathRecordImpl (current_record, id,
     414         3577 :                                           impl.get_type ().get_node_id ());
     415              :     });
     416       174592 :   }
     417              : 
     418      3720261 :   template <typename F> void scope_impl (AST::TraitImpl &impl, F &&f)
     419              :   {
     420      3720261 :     rust_assert (current_record != UNKNOWN_NODEID);
     421              : 
     422      3720261 :     NodeId id = impl.get_node_id ();
     423      3720261 :     scope_inner (id, std::forward<F> (f), [this, id, &impl] () {
     424        62017 :       return new CanonicalPathRecordTraitImpl (
     425        62017 :         current_record, id, impl.get_type ().get_node_id (),
     426        62017 :         impl.get_trait_path ().get_node_id ());
     427              :     });
     428      3720261 :   }
     429              : 
     430              :   template <typename F>
     431        35695 :   void scope_crate (NodeId node_id, std::string crate_name, F &&f)
     432              :   {
     433        41098 :     scope_inner (node_id, std::forward<F> (f), [node_id, &crate_name] () {
     434         5403 :       return new CanonicalPathRecordCrateRoot (node_id, std::move (crate_name));
     435              :     });
     436              :   }
     437              : 
     438              :   /** Merge another CanonicalPathCtx within this one. Intended to be used when
     439              :    * merging crate name resolution context.
     440              :    */
     441           69 :   void merge (CanonicalPathCtx &&other)
     442              :   {
     443           69 :     records.insert (std::make_move_iterator (other.records.begin ()),
     444              :                     std::make_move_iterator (other.records.end ()));
     445           69 :   }
     446              : 
     447              : private:
     448              :   template <typename FCreate, typename FCallback>
     449     13517064 :   void scope_inner (NodeId id, FCallback &&f_callback, FCreate &&f_create)
     450              :   {
     451     13517064 :     auto it = records.find (id);
     452     13761608 :     if (it == records.end ())
     453              :       {
     454       244544 :         CanonicalPathRecord *record = std::forward<FCreate> (f_create) ();
     455       244544 :         it = records.emplace (id, std::unique_ptr<CanonicalPathRecord> (record))
     456              :                .first;
     457              :       }
     458              : 
     459     13517064 :     rust_assert (it->second->is_root ()
     460              :                  || static_cast<CanonicalPathRecordWithParent &> (*it->second)
     461              :                         .get_parent ()
     462              :                       == current_record);
     463              : 
     464     13517064 :     NodeId stash = it->first;
     465     13517064 :     std::swap (stash, current_record);
     466              : 
     467     13517062 :     std::forward<FCallback> (f_callback) ();
     468              : 
     469     13517060 :     std::swap (stash, current_record);
     470     13517060 :   }
     471              : 
     472              :   std::unordered_map<NodeId, std::unique_ptr<CanonicalPathRecord>> records;
     473              :   NodeId current_record;
     474              : 
     475              :   const NameResolutionContext *nr_ctx;
     476              : };
     477              : 
     478              : // Now our resolver, which keeps track of all the `ForeverStack`s we could want
     479              : class NameResolutionContext
     480              : {
     481              : public:
     482              :   NameResolutionContext ();
     483              : 
     484              :   /**
     485              :    * Insert a new value in the current rib.
     486              :    *
     487              :    * @param name Name of the value to insert.
     488              :    * @param id This value's ID, e.g the function definition's node ID.
     489              :    * @param ns Namespace in which to insert the value.
     490              :    */
     491              :   tl::expected<NodeId, DuplicateNameError> insert (Identifier name, NodeId id,
     492              :                                                    Namespace ns);
     493              : 
     494              :   tl::expected<NodeId, DuplicateNameError>
     495              :   insert_variant (Identifier name, NodeId id, bool is_also_value);
     496              : 
     497              :   tl::expected<NodeId, DuplicateNameError>
     498              :   insert_shadowable (Identifier name, NodeId id, Namespace ns);
     499              : 
     500              :   tl::expected<NodeId, DuplicateNameError>
     501              :   insert_globbed (Identifier name, NodeId id, Namespace ns);
     502              : 
     503              :   // Crate are supposed to be injected before any other module because we want
     504              :   // the name collision error to be reported on the offending module which has a
     505              :   // real source location, this function should therefore not fail.
     506              :   void insert_crate_in_prelude (Identifier name, NodeId id);
     507              : 
     508              :   /**
     509              :    * Run a lambda in a "scoped" context, meaning that a new `Rib` will be pushed
     510              :    * before executing the lambda and then popped. This is useful for all kinds
     511              :    * of scope in the language, such as a block expression or when entering a
     512              :    * function. This variant of the function enters a new scope in *all*
     513              :    * namespaces, while the second variant enters a scope in *one* namespace.
     514              :    *
     515              :    * @param rib_kind New `Rib` to create when entering this scope. A function
     516              :    *        `Rib`, or an item `Rib`... etc
     517              :    * @param scope_id node ID of the scope we are entering, e.g the block's
     518              :    *        `NodeId`.
     519              :    * @param lambda Function to run within that scope
     520              :    * @param path Optional path of the scope. This is useful for scopes which
     521              :    *        affect path resolution, such as modules. Defaults to an empty
     522              :    *        option.
     523              :    */
     524              :   // FIXME: Do we want to handle something in particular for expected within the
     525              :   // scoped lambda?
     526              :   void scoped (Rib::Kind rib_kind, NodeId scope_id,
     527              :                std::function<void (void)> lambda,
     528              :                tl::optional<Identifier> path = {});
     529              :   void scoped (Rib::Kind rib_kind, Namespace ns, NodeId scope_id,
     530              :                std::function<void (void)> lambda,
     531              :                tl::optional<Identifier> path = {});
     532              : 
     533              :   using Node = ForeverStackBase::Node;
     534              : 
     535              :   std::unique_ptr<Node> root;
     536              :   std::unique_ptr<Node> lang_prelude;
     537              :   std::unique_ptr<Node> extern_prelude;
     538              : 
     539              :   ForeverStack<Namespace::Values> values;
     540              :   ForeverStack<Namespace::Types> types;
     541              :   ForeverStack<Namespace::Macros> macros;
     542              :   ForeverStack<Namespace::Labels> labels;
     543              : 
     544              :   Analysis::Mappings &mappings;
     545              :   StackedContexts<BindingLayer> bindings;
     546              : 
     547              :   CanonicalPathCtx canonical_ctx;
     548              : 
     549              :   /**
     550              :    * The result type for a multi-namespace call to
     551              :    * NameResolutionContext::lookup()
     552              :    */
     553              :   struct NSLookup
     554              :   {
     555              :     NodeId id;
     556              :     Namespace ns;
     557              : 
     558       264600 :     NSLookup (NodeId id, Namespace ns) : id (id), ns (ns) {}
     559              :   };
     560              : 
     561              :   /**
     562              :    * These functions are mostly useful for the FinalizedNameResolutionContext
     563              :    * and used in later passes of the pipeline. They don't need to know as much
     564              :    * about a definition, hence why they don't use the NamespacedDefinition which
     565              :    * returns a Rib::Definition.
     566              :    */
     567              :   void map_usage (Usage usage, Definition definition, Namespace ns);
     568              :   tl::optional<NodeId> lookup (NodeId usage, Namespace ns) const;
     569              : 
     570              :   /**
     571              :    * The order of namespaces is important - if the usage resolves in the first
     572              :    * namespace, then it will be returned. Collisions are not guarded against and
     573              :    * should NOT happen. This is for looking up usages once name resolution is
     574              :    * done and we are in later stages of the pipeline.
     575              :    */
     576              :   tl::optional<NSLookup> lookup (NodeId usage, Namespace ns1,
     577              :                                  Namespace ns2) const;
     578              :   tl::optional<NSLookup> lookup (NodeId usage, Namespace ns1, Namespace ns2,
     579              :                                  Namespace ns3) const;
     580              : 
     581              :   Resolver::CanonicalPath to_canonical_path (NodeId id, Namespace ns) const
     582              :   {
     583              :     return canonical_ctx.get_path (id, ns);
     584              :   }
     585              : 
     586              :   /**
     587              :    * The return value when the namespace in which a definition was resolved
     588              :    * matters
     589              :    */
     590     10600496 :   struct NamespacedDefinition
     591              :   {
     592      1820130 :     explicit NamespacedDefinition (Rib::Definition definition, Namespace ns)
     593       425134 :       : definition (definition), ns (ns)
     594              :     {}
     595              : 
     596              :     static tl::optional<NamespacedDefinition>
     597      1819626 :     Maybe (tl::optional<Rib::Definition> definition, Namespace ns)
     598              :     {
     599      5034248 :       return definition.map ([ns] (Rib::Definition definition) {
     600      1394996 :         return NamespacedDefinition (definition, ns);
     601      1819626 :       });
     602              :     }
     603              : 
     604              :     Rib::Definition definition;
     605              :     Namespace ns;
     606              :   };
     607              : 
     608              :   tl::optional<NamespacedDefinition>
     609      1613194 :   resolve_path (const ResolutionPath &path, ResolutionMode mode,
     610              :                 std::vector<Error> &collect_errors, Namespace ns)
     611              :   {
     612      1613194 :     std::function<void (Usage, Definition, Namespace)> insert_segment_resolution
     613      1613194 :       = [this] (Usage seg_id, Definition id, Namespace ns) {
     614      2170395 :           map_usage (seg_id, id, ns);
     615      1613194 :         };
     616              : 
     617      1613194 :     tl::optional<NamespacedDefinition> resolved = tl::nullopt;
     618              : 
     619      1613194 :     switch (ns)
     620              :       {
     621       678436 :       case Namespace::Values:
     622      1356872 :         resolved = NamespacedDefinition::Maybe (
     623      1356872 :           resolve_path (values, path, mode, insert_segment_resolution,
     624              :                         collect_errors),
     625       678436 :           ns);
     626       678436 :         break;
     627       825538 :       case Namespace::Types:
     628      1651076 :         resolved = NamespacedDefinition::Maybe (
     629      1651076 :           resolve_path (types, path, mode, insert_segment_resolution,
     630              :                         collect_errors),
     631       825538 :           ns);
     632       825538 :         break;
     633       109220 :       case Namespace::Macros:
     634       218440 :         resolved = NamespacedDefinition::Maybe (
     635       218440 :           resolve_path (macros, path, mode, insert_segment_resolution,
     636              :                         collect_errors),
     637       109220 :           ns);
     638       109220 :         break;
     639            0 :       case Namespace::Labels:
     640            0 :         resolved = NamespacedDefinition::Maybe (
     641            0 :           resolve_path (labels, path, mode, insert_segment_resolution,
     642              :                         collect_errors),
     643            0 :           ns);
     644            0 :         break;
     645            0 :       default:
     646            0 :         rust_unreachable ();
     647              :       }
     648              : 
     649              :     // If it fails, switch to std prelude resolution if it exists
     650      1613194 :     if (prelude && !resolved)
     651              :       {
     652              :         // TODO: Factor this with the above
     653       206432 :         switch (ns)
     654              :           {
     655        63728 :           case Namespace::Values:
     656        63728 :             return NamespacedDefinition::Maybe (
     657       127456 :               resolve_path (values, path, mode, insert_segment_resolution,
     658        63728 :                             collect_errors, *prelude),
     659        63728 :               ns);
     660        98392 :           case Namespace::Types:
     661        98392 :             return NamespacedDefinition::Maybe (
     662       196784 :               resolve_path (types, path, mode, insert_segment_resolution,
     663        98392 :                             collect_errors, *prelude),
     664        98392 :               ns);
     665        44312 :           case Namespace::Macros:
     666        44312 :             return NamespacedDefinition::Maybe (
     667        88624 :               resolve_path (macros, path, mode, insert_segment_resolution,
     668        44312 :                             collect_errors, *prelude),
     669        44312 :               ns);
     670            0 :           case Namespace::Labels:
     671            0 :             return NamespacedDefinition::Maybe (
     672            0 :               resolve_path (labels, path, mode, insert_segment_resolution,
     673            0 :                             collect_errors, *prelude),
     674            0 :               ns);
     675              :           default:
     676              :             rust_unreachable ();
     677              :           }
     678              :       }
     679              : 
     680      1406762 :     return resolved;
     681      1613194 :   }
     682              : 
     683      1564548 :   class ResolutionBuilder
     684              :   {
     685              :   public:
     686      1564548 :     ResolutionBuilder (NameResolutionContext &ctx) : ctx (&ctx) {}
     687              : 
     688              :     template <typename S>
     689      1365297 :     void set_path (const RawPath<S> &new_path, NodeId node_id)
     690              :     {
     691      1365297 :       path = ResolutionPath (new_path, node_id);
     692      1365297 :       mode = ResolutionMode::Normal;
     693      1365297 :       if (new_path.has_opening_scope_resolution ())
     694              :         {
     695           49 :           if (get_rust_edition () == Edition::E2015)
     696           28 :             mode = ResolutionMode::FromRoot;
     697              :           else
     698           21 :             mode = ResolutionMode::FromExtern;
     699              :         }
     700      1365297 :       has_path_set = true;
     701      1365297 :     }
     702              : 
     703              :     template <typename S>
     704       199251 :     void set_path (const RawPath<S> &new_path, NodeId node_id,
     705              :                    ResolutionMode mode)
     706              :     {
     707       199251 :       path = ResolutionPath (new_path, node_id);
     708       199251 :       this->mode = mode;
     709       199251 :       has_path_set = true;
     710       199251 :     }
     711              : 
     712              :     void set_path (const AST::SimplePath &path)
     713              :     {
     714              :       set_path (path, path.get_node_id ());
     715              :     }
     716              : 
     717              :     void set_path (const AST::PathInExpression &path)
     718              :     {
     719              :       set_path (path, path.get_node_id ());
     720              :     }
     721              : 
     722              :     void set_path (const AST::TypePath &path)
     723              :     {
     724              :       set_path (path, path.get_node_id ());
     725              :     }
     726              : 
     727              :     void set_mode (ResolutionMode mode) { this->mode = mode; }
     728              : 
     729      2187603 :     void add_namespaces (Namespace ns) { namespace_list.push_back (ns); }
     730              : 
     731       623055 :     template <typename... Args> void add_namespaces (Namespace ns, Args... rest)
     732              :     {
     733       623055 :       add_namespaces (ns);
     734       623055 :       add_namespaces (rest...);
     735       623055 :     }
     736              : 
     737       166143 :     void set_collect_errors (tl::optional<std::vector<Error> &> collect_errors)
     738              :     {
     739       166143 :       this->collect_errors = collect_errors;
     740              :     }
     741              : 
     742      1564548 :     tl::optional<NamespacedDefinition> resolve ()
     743              :     {
     744      1564548 :       rust_assert (has_path_set);
     745              : 
     746      1782746 :       for (auto ns : namespace_list)
     747              :         {
     748      1613194 :           std::vector<Error> collect_errors_inner;
     749      1613194 :           if (auto ret
     750      1613194 :               = ctx->resolve_path (path, mode, collect_errors_inner, ns))
     751      1613194 :             return ret;
     752       218198 :           if (!collect_errors_inner.empty ())
     753              :             {
     754           18 :               if (collect_errors.has_value ())
     755              :                 {
     756           12 :                   std::move (collect_errors_inner.begin (),
     757              :                              collect_errors_inner.end (),
     758              :                              std::back_inserter (collect_errors.value ()));
     759              :                 }
     760              :               else
     761              :                 {
     762           12 :                   for (auto &e : collect_errors_inner)
     763            6 :                     e.emit ();
     764              :                 }
     765              :             }
     766      1613194 :         }
     767              : 
     768       169552 :       return tl::nullopt;
     769              :     }
     770              : 
     771              :   private:
     772              :     ResolutionPath path;
     773              :     ResolutionMode mode;
     774              :     bool has_path_set;
     775              : 
     776              :     std::vector<Namespace> namespace_list;
     777              : 
     778              :     tl::optional<std::vector<Error> &> collect_errors;
     779              : 
     780              :     NameResolutionContext *ctx;
     781              :   };
     782              : 
     783              :   template <typename S, typename... Args>
     784              :   tl::optional<NamespacedDefinition>
     785       166143 :   resolve_path (const RawPath<S> &path, ResolutionMode mode,
     786              :                 tl::optional<std::vector<Error> &> collect_errors,
     787              :                 Namespace ns_first, Args... ns_args)
     788              :   {
     789       166143 :     ResolutionBuilder builder (*this);
     790       166143 :     builder.set_path (path, UNKNOWN_NODEID, mode);
     791       166143 :     builder.add_namespaces (ns_first, ns_args...);
     792       166143 :     builder.set_collect_errors (collect_errors);
     793              : 
     794       166143 :     return builder.resolve ();
     795       166143 :   }
     796              : 
     797              :   template <typename S, typename... Args>
     798              :   tl::optional<NamespacedDefinition>
     799              :   resolve_path (const RawPath<S> &path,
     800              :                 tl::optional<std::vector<Error> &> collect_errors,
     801              :                 Namespace ns_first, Args... ns_args)
     802              :   {
     803              :     ResolutionBuilder builder (*this);
     804              :     builder.set_path (path.get_segments (), path.has_opening_scope (),
     805              :                       UNKNOWN_NODEID);
     806              :     builder.add_namespaces (ns_first, ns_args...);
     807              :     builder.set_collect_errors (collect_errors);
     808              : 
     809              :     return builder.resolve ();
     810              :   }
     811              : 
     812              :   template <typename S, typename... Args>
     813              :   tl::optional<NamespacedDefinition>
     814      1365297 :   resolve_path (const RawPath<S> &path, Namespace ns_first, Args... ns_args)
     815              :   {
     816      1365297 :     ResolutionBuilder builder (*this);
     817      1365297 :     builder.set_path (path, UNKNOWN_NODEID);
     818      1365297 :     builder.add_namespaces (ns_first, ns_args...);
     819              : 
     820      1365297 :     return builder.resolve ();
     821      1365297 :   }
     822              : 
     823              :   template <typename S, typename... Args>
     824              :   tl::optional<NamespacedDefinition>
     825        33108 :   resolve_path (const RawPath<S> &path, ResolutionMode mode, Namespace ns_first,
     826              :                 Args... ns_args)
     827              :   {
     828        33108 :     ResolutionBuilder builder (*this);
     829        33108 :     builder.set_path (path, UNKNOWN_NODEID, mode);
     830        33108 :     builder.add_namespaces (ns_first, ns_args...);
     831              : 
     832        33108 :     return builder.resolve ();
     833        33108 :   }
     834              : 
     835              :   /*
     836              :    * Merge a name resolution context within another one at a given location.
     837              :    *
     838              :    * @param other The other name resolution context to merge within the current
     839              :    * one.
     840              :    * @param at The node id of the container were the nr context should be
     841              :    * merged. Usually an extern crate node.
     842              :    */
     843              :   void merge (NameResolutionContext &other, NodeId at);
     844              : 
     845              : // We disable this function for now as it causes regressions, but I think it
     846              : // is important for a more proper final nameres context - need to investigate
     847              : #if 0
     848              :   /**
     849              :    * We've now collected every definition and import, and errored out when
     850              :    * necessary if multiple definitions are colliding. Do a final flattening of
     851              :    * the name resolution context to make it easier to digest for the late name
     852              :    * resolution and type-checker. This basically turns the `resolved_nodes`
     853              :    * map from a linked-list-like map to a regular, flat hashmap.
     854              :    *
     855              :    * FIXME: The documentation is wrong, this needs to also run after all
     856              :    * usages have been *resolved* so after Late as well!!!
     857              :    *
     858              :    * TODO: Should this return something like the FinalizedNameResolutionCtx?
     859              :    * Or set it up at least? And instead of mutating the `resolved_nodes` map,
     860              :    * create a new one for the FinalizedNameResolutionCtx?
     861              :    * Actually, since Late uses the NRCtx directly we should mutate this. Most
     862              :    * later passes don't look at this map. So let's go for side-effects in a
     863              :    * void function, yipee.
     864              :    */
     865              :   void flatten ();
     866              : #endif
     867              : 
     868              :   /* If declared with #[prelude_import], the current standard library module
     869              :    */
     870              :   tl::optional<NodeId> prelude;
     871              : 
     872              : private:
     873              :   template <Namespace N>
     874              :   bool
     875              :   should_search_prelude (const typename ForeverStack<N>::Node *current_node,
     876              :                          const typename ForeverStack<N>::SegIterator &iterator,
     877              :                          const std::vector<ResolutionPathSegment> &segments);
     878              : 
     879              :   /**
     880              :    * Resolve a path to its definition
     881              :    *
     882              :    * // TODO: Add documentation for `segments`
     883              :    *
     884              :    * @return a valid option with the Definition if the path is present in the
     885              :    *         current map, an empty one otherwise.
     886              :    */
     887              :   template <Namespace N>
     888              :   tl::optional<Rib::Definition>
     889              :   resolve_path (ForeverStack<N> &stack, const ResolutionPath &path,
     890              :                 ResolutionMode mode,
     891              :                 std::function<void (Usage, Definition, Namespace)>
     892              :                   insert_segment_resolution,
     893              :                 std::vector<Error> &collect_errors);
     894              : 
     895              :   template <Namespace N>
     896              :   tl::optional<Rib::Definition>
     897              :   resolve_path (ForeverStack<N> &stack, const ResolutionPath &path,
     898              :                 ResolutionMode mode,
     899              :                 std::function<void (Usage, Definition, Namespace)>
     900              :                   insert_segment_resolution,
     901              :                 std::vector<Error> &collect_errors, NodeId starting_point_id);
     902              : 
     903              :   template <Namespace N>
     904              :   tl::optional<Rib::Definition> resolve_path (
     905              :     ForeverStack<N> &stack, const ResolutionPath &path, ResolutionMode mode,
     906              :     std::function<void (Usage, Definition, Namespace)>
     907              :       insert_segment_resolution,
     908              :     std::vector<Error> &collect_errors,
     909              :     std::reference_wrapper<typename ForeverStack<N>::Node> starting_point);
     910              : 
     911              :   template <Namespace N>
     912              :   tl::optional<typename ForeverStack<N>::Node &>
     913              :   resolve_segments (ForeverStack<N> &stack,
     914              :                     typename ForeverStack<N>::Node &starting_point,
     915              :                     const RawPath<ResolutionPathSegment> &path,
     916              :                     typename ForeverStack<N>::SegIterator iterator,
     917              :                     std::function<void (Usage, Definition, Namespace)>
     918              :                       insert_segment_resolution,
     919              :                     std::vector<Error> &collect_errors);
     920              : 
     921              :   template <Namespace N>
     922              :   tl::optional<Rib::Definition>
     923              :   resolve_final_segment (ForeverStack<N> &stack,
     924              :                          typename ForeverStack<N>::Node &final_node,
     925              :                          std::string &seg_name, bool is_lower_self);
     926              : };
     927              : 
     928              : } // namespace Resolver2_0
     929              : } // namespace Rust
     930              : 
     931              : #include "rust-name-resolution-context.hxx"
     932              : 
     933              : #endif // ! RUST_NAME_RESOLVER_2_0_CTX_H
        

Generated by: LCOV version 2.5.0-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.