399 lines
21 KiB
HTML
399 lines
21 KiB
HTML
<!DOCTYPE HTML>
|
|
<html lang="en" class="light sidebar-visible" dir="ltr">
|
|
<head>
|
|
<!-- Book generated using mdBook -->
|
|
<meta charset="UTF-8">
|
|
<title>Salsa - 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/queries/salsa.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="how-salsa-works"><a class="header" href="#how-salsa-works">How Salsa works</a></h1>
|
|
<ul>
|
|
<li><a href="#what-is-salsa">What is Salsa?</a></li>
|
|
<li><a href="#how-does-it-work">How does it work?</a></li>
|
|
<li><a href="#key-salsa-concepts">Key Salsa concepts</a>
|
|
<ul>
|
|
<li><a href="#query">Query</a></li>
|
|
<li><a href="#database">Database</a></li>
|
|
<li><a href="#query-groups">Query Groups</a></li>
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
<p>This chapter is based on the explanation given by Niko Matsakis in this
|
|
<a href="https://www.youtube.com/watch?v=_muY4HjSqVw">video</a> about
|
|
<a href="https://github.com/salsa-rs/salsa">Salsa</a>. To find out more you may
|
|
want to watch <a href="https://www.youtube.com/watch?v=i_IhACacPRY">Salsa In More
|
|
Depth</a>, also by Niko
|
|
Matsakis.</p>
|
|
<blockquote>
|
|
<p>As of <!-- date-check --> November 2022, although Salsa is inspired by (among
|
|
other things) rustc's query system, it is not used directly in rustc. It
|
|
<em>is</em> used in <a href="https://rust-lang.github.io/chalk/book/what_is_chalk.html">chalk</a>, an implementation of Rust's trait system, and
|
|
extensively in <a href="https://rust-analyzer.github.io/"><code>rust-analyzer</code></a>, the official implementation of the language
|
|
server protocol for Rust, but there are no medium or long-term concrete
|
|
plans to integrate it into the compiler.</p>
|
|
</blockquote>
|
|
<h2 id="what-is-salsa"><a class="header" href="#what-is-salsa">What is Salsa?</a></h2>
|
|
<p>Salsa is a library for incremental recomputation. This means it allows reusing
|
|
computations that were already done in the past to increase the efficiency
|
|
of future computations.</p>
|
|
<p>The objectives of Salsa are:</p>
|
|
<ul>
|
|
<li>Provide that functionality in an automatic way, so reusing old computations
|
|
is done automatically by the library.</li>
|
|
<li>Doing so in a "sound", or "correct", way, therefore leading to the same
|
|
results as if it had been done from scratch.</li>
|
|
</ul>
|
|
<p>Salsa's actual model is much richer, allowing many kinds of inputs and many different outputs.
|
|
For example, integrating Salsa with an IDE could mean that
|
|
the inputs could be manifests (<code>Cargo.toml</code>, <code>rust-toolchain.toml</code>), entire
|
|
source files (<code>foo.rs</code>), snippets and so on. The outputs of such an integration
|
|
could range from a binary executable, to lints, types (for example, if a user
|
|
selects a certain variable and wishes to see its type), completions, etc.</p>
|
|
<h2 id="how-does-it-work"><a class="header" href="#how-does-it-work">How does it work?</a></h2>
|
|
<p>The first thing that Salsa has to do is identify the "base inputs" that
|
|
are not something computed but given as input.</p>
|
|
<p>Then Salsa has to also identify intermediate, "derived" values, which are
|
|
something that the library produces, but, for each derived value there's a
|
|
"pure" function that computes the derived value.</p>
|
|
<p>For example, there might be a function <code>ast(x: Path) -> AST</code>. The produced
|
|
Abstract Syntax Tree (<code>AST</code>) isn't a final value, it's an intermediate value
|
|
that the library would use for the computation.</p>
|
|
<p>This means that when you try to compute with the library, Salsa is going to
|
|
compute various derived values, and eventually read the input and produce the
|
|
result for the asked computation.</p>
|
|
<p>In the course of computing, Salsa tracks which inputs were accessed and which
|
|
values are derived. This information is used to determine what's going to
|
|
happen when the inputs change: are the derived values still valid?</p>
|
|
<p>This doesn't necessarily mean that each computation downstream from the input
|
|
is going to be checked, which could be costly. Salsa only needs to check each
|
|
downstream computation until it finds one that isn't changed. At that point, it
|
|
won't check other derived computations since they wouldn't need to change.</p>
|
|
<p>It's helpful to think about this as a graph with nodes. Each derived value
|
|
has a dependency on other values, which could themselves be either base or
|
|
derived. Base values don't have a dependency.</p>
|
|
<pre><code class="language-ignore">I <- A <- C ...
|
|
|
|
|
J <- B <--+
|
|
</code></pre>
|
|
<p>When an input <code>I</code> changes, the derived value <code>A</code> could change. The derived
|
|
value <code>B</code>, which does not depend on <code>I</code>, <code>A</code>, or any value derived from <code>A</code> or
|
|
<code>I</code>, is not subject to change. Therefore, Salsa can reuse the computation done
|
|
for <code>B</code> in the past, without having to compute it again.</p>
|
|
<p>The computation could also terminate early. Keeping the same graph as before,
|
|
say that input <code>I</code> has changed in some way (and input <code>J</code> hasn't), but when
|
|
computing <code>A</code> again, it's found that <code>A</code> hasn't changed from the previous
|
|
computation. This leads to an "early termination", because there's no need to
|
|
check if <code>C</code> needs to change, since both <code>C</code> direct inputs, <code>A</code> and <code>B</code>,
|
|
haven't changed.</p>
|
|
<h2 id="key-salsa-concepts"><a class="header" href="#key-salsa-concepts">Key Salsa concepts</a></h2>
|
|
<h3 id="query"><a class="header" href="#query">Query</a></h3>
|
|
<p>A query is some value that Salsa can access in the course of computation. Each
|
|
query can have a number of keys (from 0 to many), and all queries have a
|
|
result, akin to functions. <code>0-key</code> queries are called "input" queries.</p>
|
|
<h3 id="database"><a class="header" href="#database">Database</a></h3>
|
|
<p>The database is basically the context for the entire computation, it's meant to
|
|
store Salsa's internal state, all intermediate values for each query, and
|
|
anything else that the computation might need. The database must know all the
|
|
queries the library is going to do before it can be built, but they don't need
|
|
to be specified in the same place.</p>
|
|
<p>After the database is formed, it can be accessed with queries that are very
|
|
similar to functions. Since each query's result is stored in the database, when
|
|
a query is invoked <code>N</code>-times, it will return <code>N</code>-<strong>cloned</strong> results, without having
|
|
to recompute the query (unless the input has changed in such a way that it
|
|
warrants recomputation).</p>
|
|
<p>For each input query (<code>0-key</code>), a "set" method is generated, allowing the user to
|
|
change the output of such query, and trigger previous memoized values to be
|
|
potentially invalidated.</p>
|
|
<h3 id="query-groups"><a class="header" href="#query-groups">Query Groups</a></h3>
|
|
<p>A query group is a set of queries which have been defined together as a unit.
|
|
The database is formed by combining query groups. Query groups are akin to
|
|
"Salsa modules".</p>
|
|
<p>A set of queries in a query group are just a set of methods in a trait.</p>
|
|
<p>To create a query group a trait annotated with a specific attribute
|
|
(<code>#[salsa::query_group(...)]</code>) has to be created.</p>
|
|
<p>An argument must also be provided to said attribute as it will be used by Salsa
|
|
to create a <code>struct</code> to be used later when the database is created.</p>
|
|
<p>Example input query group:</p>
|
|
<pre><code class="language-rust ignore">/// This attribute will process this tree, produce this tree as output, and produce
|
|
/// a bunch of intermediate stuff that Salsa also uses. One of these things is a
|
|
/// "StorageStruct", whose name we have specified in the attribute.
|
|
///
|
|
/// This query group is a bunch of **input** queries, that do not rely on any
|
|
/// derived input.
|
|
#[salsa::query_group(InputsStorage)]
|
|
pub trait Inputs {
|
|
/// This attribute (`#[salsa::input]`) indicates that this query is a base
|
|
/// input, therefore `set_manifest` is going to be auto-generated
|
|
#[salsa::input]
|
|
fn manifest(&self) -> Manifest;
|
|
|
|
#[salsa::input]
|
|
fn source_text(&self, name: String) -> String;
|
|
}</code></pre>
|
|
<p>To create a <strong>derived</strong> query group, one must specify which other query groups
|
|
this one depends on by specifying them as supertraits, as seen in the following
|
|
example:</p>
|
|
<pre><code class="language-rust ignore">/// This query group is going to contain queries that depend on derived values.
|
|
/// A query group can access another query group's queries by specifying the
|
|
/// dependency as a supertrait. Query groups can be stacked as much as needed using
|
|
/// that pattern.
|
|
#[salsa::query_group(ParserStorage)]
|
|
pub trait Parser: Inputs {
|
|
/// This query `ast` is not an input query, it's a derived query this means
|
|
/// that a definition is necessary.
|
|
fn ast(&self, name: String) -> String;
|
|
}</code></pre>
|
|
<p>When creating a derived query the implementation of said query must be defined
|
|
outside the trait. The definition must take a database parameter as an <code>impl Trait</code> (or <code>dyn Trait</code>), where trait is the query group that the definition
|
|
belongs to, in addition to the other keys.</p>
|
|
<pre><code class="language-rust ignore">/// This is going to be the definition of the `ast` query in the `Parser` trait.
|
|
/// So, when the query `ast` is invoked, and it needs to be recomputed, Salsa is
|
|
/// going to call this function and it's going to give it the database as `impl
|
|
/// Parser`. The function doesn't need to be aware of all the queries of all the
|
|
/// query groups
|
|
fn ast(db: &impl Parser, name: String) -> String {
|
|
//! Note, `impl Parser` is used here but `dyn Parser` works just as well
|
|
/* code */
|
|
///By passing an `impl Parser`, this is allowed
|
|
let source_text = db.input_file(name);
|
|
/* do the actual parsing */
|
|
return ast;
|
|
}</code></pre>
|
|
<p>Eventually, after all the query groups have been defined, the database can be
|
|
created by declaring a <code>struct</code>.</p>
|
|
<p>To specify which query groups are going to be part of the database an <code>attribute</code>
|
|
(<code>#[salsa::database(...)]</code>) must be added. The argument of said <code>attribute</code> is a
|
|
list of <code>identifiers</code>, specifying the query groups <strong>storages</strong>.</p>
|
|
<pre><code class="language-rust ignore">///This attribute specifies which query groups are going to be in the database
|
|
#[salsa::database(InputsStorage, ParserStorage)]
|
|
#[derive(Default)] //optional!
|
|
struct MyDatabase {
|
|
///You also need this one field
|
|
runtime : salsa::Runtime<MyDatabase>,
|
|
}
|
|
///And this trait has to be implemented
|
|
impl salsa::Database for MyDatabase {
|
|
fn salsa_runtime(&self) -> &salsa::Runtime<MyDatabase> {
|
|
&self.runtime
|
|
}
|
|
}</code></pre>
|
|
<p>Example usage:</p>
|
|
<pre><code class="language-rust ignore">fn main() {
|
|
let db = MyDatabase::default();
|
|
db.set_manifest(...);
|
|
db.set_source_text(...);
|
|
loop {
|
|
db.ast(...); //will reuse results
|
|
db.set_source_text(...);
|
|
}
|
|
}</code></pre>
|
|
|
|
</main>
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
<!-- Mobile navigation buttons -->
|
|
<a rel="prev" href="../incrcomp-debugging.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="../memory.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="../incrcomp-debugging.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="../memory.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>
|