| <!DOCTYPE HTML> |
| <html lang="en" class="light sidebar-visible" dir="ltr"> |
| <head> |
| <!-- Book generated using mdBook --> |
| <meta charset="UTF-8"> |
| <title>Invariants of the type system - Rust Compiler Development Guide</title> |
| |
| |
| <!-- Custom HTML head --> |
| |
| <meta name="description" content="A guide to developing the Rust compiler (rustc)"> |
| <meta name="viewport" content="width=device-width, initial-scale=1"> |
| <meta name="theme-color" content="#ffffff"> |
| |
| <link rel="icon" href="../favicon.svg"> |
| <link rel="shortcut icon" href="../favicon.png"> |
| <link rel="stylesheet" href="../css/variables.css"> |
| <link rel="stylesheet" href="../css/general.css"> |
| <link rel="stylesheet" href="../css/chrome.css"> |
| <link rel="stylesheet" href="../css/print.css" media="print"> |
| |
| <!-- Fonts --> |
| <link rel="stylesheet" href="../FontAwesome/css/font-awesome.css"> |
| <link rel="stylesheet" href="../fonts/fonts.css"> |
| |
| <!-- Highlight.js Stylesheets --> |
| <link rel="stylesheet" id="highlight-css" href="../highlight.css"> |
| <link rel="stylesheet" id="tomorrow-night-css" href="../tomorrow-night.css"> |
| <link rel="stylesheet" id="ayu-highlight-css" href="../ayu-highlight.css"> |
| |
| <!-- Custom theme stylesheets --> |
| |
| |
| <!-- Provide site root and default themes to javascript --> |
| <script> |
| const path_to_root = "../"; |
| const default_light_theme = "light"; |
| const default_dark_theme = "navy"; |
| </script> |
| <!-- Start loading toc.js asap --> |
| <script src="../toc.js"></script> |
| </head> |
| <body> |
| <div id="body-container"> |
| <!-- Work around some values being stored in localStorage wrapped in quotes --> |
| <script> |
| try { |
| let theme = localStorage.getItem('mdbook-theme'); |
| let sidebar = localStorage.getItem('mdbook-sidebar'); |
| |
| if (theme.startsWith('"') && theme.endsWith('"')) { |
| localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1)); |
| } |
| |
| if (sidebar.startsWith('"') && sidebar.endsWith('"')) { |
| localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1)); |
| } |
| } catch (e) { } |
| </script> |
| |
| <!-- Set the theme before any content is loaded, prevents flash --> |
| <script> |
| const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme; |
| let theme; |
| try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } |
| if (theme === null || theme === undefined) { theme = default_theme; } |
| const html = document.documentElement; |
| html.classList.remove('light') |
| html.classList.add(theme); |
| html.classList.add("js"); |
| </script> |
| |
| <input type="checkbox" id="sidebar-toggle-anchor" class="hidden"> |
| |
| <!-- Hide / unhide sidebar before it is displayed --> |
| <script> |
| let sidebar = null; |
| const sidebar_toggle = document.getElementById("sidebar-toggle-anchor"); |
| if (document.body.clientWidth >= 1080) { |
| try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } |
| sidebar = sidebar || 'visible'; |
| } else { |
| sidebar = 'hidden'; |
| } |
| sidebar_toggle.checked = sidebar === 'visible'; |
| html.classList.remove('sidebar-visible'); |
| html.classList.add("sidebar-" + sidebar); |
| </script> |
| |
| <nav id="sidebar" class="sidebar" aria-label="Table of contents"> |
| <!-- populated by js --> |
| <mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox> |
| <noscript> |
| <iframe class="sidebar-iframe-outer" src="../toc.html"></iframe> |
| </noscript> |
| <div id="sidebar-resize-handle" class="sidebar-resize-handle"> |
| <div class="sidebar-resize-indicator"></div> |
| </div> |
| </nav> |
| |
| <div id="page-wrapper" class="page-wrapper"> |
| |
| <div class="page"> |
| <div id="menu-bar-hover-placeholder"></div> |
| <div id="menu-bar" class="menu-bar sticky"> |
| <div class="left-buttons"> |
| <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar"> |
| <i class="fa fa-bars"></i> |
| </label> |
| <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list"> |
| <i class="fa fa-paint-brush"></i> |
| </button> |
| <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu"> |
| <li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li> |
| </ul> |
| <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar"> |
| <i class="fa fa-search"></i> |
| </button> |
| </div> |
| |
| <h1 class="menu-title">Rust Compiler Development Guide</h1> |
| |
| <div class="right-buttons"> |
| <a href="../print.html" title="Print this book" aria-label="Print this book"> |
| <i id="print-button" class="fa fa-print"></i> |
| </a> |
| <a href="https://github.com/rust-lang/rustc-dev-guide" title="Git repository" aria-label="Git repository"> |
| <i id="git-repository-button" class="fa fa-github"></i> |
| </a> |
| <a href="https://github.com/rust-lang/rustc-dev-guide/edit/master/src/solve/invariants.md" title="Suggest an edit" aria-label="Suggest an edit"> |
| <i id="git-edit-button" class="fa fa-edit"></i> |
| </a> |
| |
| </div> |
| </div> |
| |
| <div id="search-wrapper" class="hidden"> |
| <form id="searchbar-outer" class="searchbar-outer"> |
| <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header"> |
| </form> |
| <div id="searchresults-outer" class="searchresults-outer hidden"> |
| <div id="searchresults-header" class="searchresults-header"></div> |
| <ul id="searchresults"> |
| </ul> |
| </div> |
| </div> |
| |
| <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM --> |
| <script> |
| document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible'); |
| document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible'); |
| Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) { |
| link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1); |
| }); |
| </script> |
| |
| <div id="content" class="content"> |
| <main> |
| <h1 id="invariants-of-the-type-system"><a class="header" href="#invariants-of-the-type-system">Invariants of the type system</a></h1> |
| <p>FIXME: This file talks about invariants of the type system as a whole, not only the solver</p> |
| <p>There are a lot of invariants - things the type system guarantees to be true at all times - |
| which are desirable or expected from other languages and type systems. Unfortunately, quite |
| a few of them do not hold in Rust right now. This is either a fundamental to its design or |
| caused by bugs and something that may change in the future.</p> |
| <p>It is important to know about the things you can assume while working on - and with - the |
| type system, so here's an incomplete and unofficial list of invariants of |
| the core type system:</p> |
| <ul> |
| <li>✅: this invariant mostly holds, with some weird exceptions, you can rely on it outside |
| of these cases</li> |
| <li>❌: this invariant does not hold, either due to bugs or by design, you must not rely on |
| it for soundness or have to be incredibly careful when doing so</li> |
| </ul> |
| <h3 id="wfx-implies-wfnormalizex-"><a class="header" href="#wfx-implies-wfnormalizex-"><code>wf(X)</code> implies <code>wf(normalize(X))</code> ✅</a></h3> |
| <p>If a type containing aliases is well-formed, it should also be |
| well-formed after normalizing said aliases. We rely on this as |
| otherwise we would have to re-check for well-formedness for these |
| types.</p> |
| <h3 id="structural-equality-modulo-regions-implies-semantic-equality-"><a class="header" href="#structural-equality-modulo-regions-implies-semantic-equality-">Structural equality modulo regions implies semantic equality ✅</a></h3> |
| <p>If you have a some type and equate it to itself after replacing any regions with unique |
| inference variables in both the lhs and rhs, the now potentially structurally different |
| types should still be equal to each other.</p> |
| <p>Needed to prevent goals from succeeding in HIR typeck and then failing in MIR borrowck. |
| If this invariant is broken MIR typeck ends up failing with an ICE.</p> |
| <h3 id="applying-inference-results-from-a-goal-does-not-change-its-result-"><a class="header" href="#applying-inference-results-from-a-goal-does-not-change-its-result-">Applying inference results from a goal does not change its result ❌</a></h3> |
| <p>TODO: this invariant is formulated in a weird way and needs to be elaborated. |
| Pretty much: I would like this check to only fail if there's a solver bug: |
| https://github.com/rust-lang/rust/blob/2ffeb4636b4ae376f716dc4378a7efb37632dc2d/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs#L391-L407</p> |
| <p>If we prove some goal/equate types/whatever, apply the resulting inference constraints, |
| and then redo the original action, the result should be the same.</p> |
| <p>This unfortunately does not hold - at least in the new solver - due to a few annoying reasons.</p> |
| <h3 id="the-trait-solver-has-to-be-locally-sound-"><a class="header" href="#the-trait-solver-has-to-be-locally-sound-">The trait solver has to be <em>locally sound</em> ✅</a></h3> |
| <p>This means that we must never return <em>success</em> for goals for which no <code>impl</code> exists. That would |
| mean we assume a trait is implemented even though it is not, which is very likely to result in |
| actual unsoundness. When using <code>where</code>-bounds to prove a goal, the <code>impl</code> will be provided by the |
| user of the item.</p> |
| <p>This invariant only holds if we check region constraints. As we do not check region constraints |
| during implicit negative overlap check in coherence, this invariant is broken there. As this check |
| relies on <em>completeness</em> of the trait solver, it is not able to use the current region constraints |
| check - <code>InferCtxt::resolve_regions</code> - as its handling of type outlives goals is incomplete.</p> |
| <h3 id="normalization-of-semantically-equal-aliases-in-empty-environments-results-in-a-unique-type-"><a class="header" href="#normalization-of-semantically-equal-aliases-in-empty-environments-results-in-a-unique-type-">Normalization of semantically equal aliases in empty environments results in a unique type ✅</a></h3> |
| <p>Normalization for alias types/consts has to have a unique result. Otherwise we can easily |
| implement transmute in safe code. Given the following function, we have to make sure that |
| the input and output types always get normalized to the same concrete type.</p> |
| <pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)] |
| </span><span class="boring">fn main() { |
| </span>fn foo<T: Trait>( |
| x: <T as Trait>::Assoc |
| ) -> <T as Trait>::Assoc { |
| x |
| } |
| <span class="boring">}</span></code></pre></pre> |
| <p>Many of the currently known unsound issues end up relying on this invariant being broken. |
| It is however very difficult to imagine a sound type system without this invariant, so |
| the issue is that the invariant is broken, not that we incorrectly rely on it.</p> |
| <h3 id="generic-goals-and-their-instantiations-have-the-same-result-"><a class="header" href="#generic-goals-and-their-instantiations-have-the-same-result-">Generic goals and their instantiations have the same result ✅</a></h3> |
| <p>Pretty much: If we successfully typecheck a generic function concrete instantiations |
| of that function should also typeck. We should not get errors post-monomorphization. |
| We can however get overflow errors at that point.</p> |
| <p>TODO: example for overflow error post-monomorphization</p> |
| <p>This invariant is relied on to allow the normalization of generic aliases. Breaking |
| it can easily result in unsoundness, e.g. <a href="https://github.com/rust-lang/rust/issues/57893">#57893</a></p> |
| <h3 id="trait-goals-in-empty-environments-are-proven-by-a-unique-impl-"><a class="header" href="#trait-goals-in-empty-environments-are-proven-by-a-unique-impl-">Trait goals in empty environments are proven by a unique impl ✅</a></h3> |
| <p>If a trait goal holds with an empty environment, there should be a unique <code>impl</code>, |
| either user-defined or builtin, which is used to prove that goal. This is |
| necessary to select a unique method.</p> |
| <p>We do however break this invariant in few cases, some of which are due to bugs, |
| some by design:</p> |
| <ul> |
| <li><em>marker traits</em> are allowed to overlap as they do not have associated items</li> |
| <li><em>specialization</em> allows specializing impls to overlap with their parent</li> |
| <li>the builtin trait object trait implementation can overlap with a user-defined impl: |
| <a href="https://github.com/rust-lang/rust/issues/57893">#57893</a></li> |
| </ul> |
| <h3 id="the-type-system-is-complete-"><a class="header" href="#the-type-system-is-complete-">The type system is complete ❌</a></h3> |
| <p>The type system is not complete, it often adds unnecessary inference constraints, and errors |
| even though the goal could hold.</p> |
| <ul> |
| <li>method selection</li> |
| <li>opaque type inference</li> |
| <li>handling type outlives constraints</li> |
| <li>preferring <code>ParamEnv</code> candidates over <code>Impl</code> candidates during candidate selection |
| in the trait solver</li> |
| </ul> |
| <h4 id="the-type-system-is-complete-during-the-implicit-negative-overlap-check-in-coherence-"><a class="header" href="#the-type-system-is-complete-during-the-implicit-negative-overlap-check-in-coherence-">The type system is complete during the implicit negative overlap check in coherence ✅</a></h4> |
| <p>For more on overlap checking: <a href="../coherence.html">coherence</a></p> |
| <p>During the implicit negative overlap check in coherence we must never return <em>error</em> for |
| goals which can be proven. This would allow for overlapping impls with potentially different |
| associated items, breaking a bunch of other invariants.</p> |
| <p>This invariant is currently broken in many different ways while actually something we rely on. |
| We have to be careful as it is quite easy to break:</p> |
| <ul> |
| <li>generalization of aliases</li> |
| <li>generalization during subtyping binders (luckily not exploitable in coherence)</li> |
| </ul> |
| <h3 id="trait-solving-must-be-free-lifetime-agnostic-"><a class="header" href="#trait-solving-must-be-free-lifetime-agnostic-">Trait solving must be (free) lifetime agnostic ✅</a></h3> |
| <p>Trait solving during codegen should have the same result as during typeck. As we erase |
| all free regions during codegen we must not rely on them during typeck. A noteworthy example |
| is special behavior for <code>'static</code>.</p> |
| <p>We also have to be careful with relying on equality of regions in the trait solver. |
| This is fine for codegen, as we treat all erased regions as equal. We can however |
| lose equality information from HIR to MIR typeck.</p> |
| <p>The new solver "uniquifies regions" during canonicalization, canonicalizing <code>u32: Trait<'x, 'x></code> |
| as <code>exists<'0, '1> u32: Trait<'0, '1></code>, to make it harder to rely on this property.</p> |
| <h3 id="removing-ambiguity-makes-strictly-more-things-compile-"><a class="header" href="#removing-ambiguity-makes-strictly-more-things-compile-">Removing ambiguity makes strictly more things compile ❌</a></h3> |
| <p>Ideally we <em>should</em> not rely on ambiguity for things to compile. |
| Not doing that will cause future improvements to be breaking changes.</p> |
| <p>Due to <em>incompleteness</em> this is not the case and improving inference can result in inference |
| changes, breaking existing projects.</p> |
| <h3 id="semantic-equality-implies-structural-equality-"><a class="header" href="#semantic-equality-implies-structural-equality-">Semantic equality implies structural equality ✅</a></h3> |
| <p>Two types being equal in the type system must mean that they have the |
| same <code>TypeId</code> after instantiating their generic parameters with concrete |
| arguments. This currently does not hold: <a href="https://github.com/rust-lang/rust/issues/97156">#97156</a>.</p> |
| |
| </main> |
| |
| <nav class="nav-wrapper" aria-label="Page navigation"> |
| <!-- Mobile navigation buttons --> |
| <a rel="prev" href="../solve/trait-solving.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> |
| <i class="fa fa-angle-left"></i> |
| </a> |
| |
| <a rel="next prefetch" href="../solve/the-solver.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> |
| <i class="fa fa-angle-right"></i> |
| </a> |
| |
| <div style="clear: both"></div> |
| </nav> |
| </div> |
| </div> |
| |
| <nav class="nav-wide-wrapper" aria-label="Page navigation"> |
| <a rel="prev" href="../solve/trait-solving.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> |
| <i class="fa fa-angle-left"></i> |
| </a> |
| |
| <a rel="next prefetch" href="../solve/the-solver.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> |
| <i class="fa fa-angle-right"></i> |
| </a> |
| </nav> |
| |
| </div> |
| |
| |
| |
| |
| <script> |
| window.playground_copyable = true; |
| </script> |
| |
| |
| <script src="../elasticlunr.min.js"></script> |
| <script src="../mark.min.js"></script> |
| <script src="../searcher.js"></script> |
| |
| <script src="../clipboard.min.js"></script> |
| <script src="../highlight.js"></script> |
| <script src="../book.js"></script> |
| |
| <!-- Custom JS scripts --> |
| <script src="../mermaid.min.js"></script> |
| <script src="../mermaid-init.js"></script> |
| |
| |
| </div> |
| </body> |
| </html> |