SlideShare a Scribd company logo
1 of 151
Download to read offline
The Rust Borrow Checker
A Deep Dive
Nell Shamrell-Harrington, Mozilla
@nellshamrell
Is the Borrow Checker a friend or a foe?
The Borrow Checker becomes your
friend through experience...
...understanding how it works also helps.
Nell Shamrell-Harrington
● Sr. Staff Research Engineer at Mozilla
● Lead Editor of This Week in Rust
● Host of the This Week in Rust podcast on the
Rustacean Station
● @nellshamrell
Agenda
● Rust Compiler Overview
● Borrow Checker Deep Dive
Overview of the Rust Compiler
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
src/main.rs
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
src/main.rs
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
src/main.rs
$ cargo run
$ cargo run
1
2
3
4
5
Stages of Compilation
● Lexical Analysis
Source: "The Imposter's Handbook" by Rob Conery
Stages of Compilation
● Lexical Analysis
● Parsing
Source: "The Imposter's Handbook" by Rob Conery
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
Source: "The Imposter's Handbook" by Rob Conery
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
● Optimization
Source: "The Imposter's Handbook" by Rob Conery
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
● Optimization
● Code Generation
Source: "The Imposter's Handbook" by Rob Conery
Wait a minute - isn't the Rust
compiler query based?
Yes...but that is out of
the scope of this talk.
Check out the "Guide
to Rustc Development"
for more info!
https://rustc-dev-guide.rust-lang.org/
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
● Optimization
● Code Generation
Source: "The Imposter's Handbook" by Rob Conery
Lexical Analysis
Lexer
Program
Source: "The Imposter's Handbook" by Rob Conery
A program called a lexer
fn main() {
let numbers =
vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
Lexer
Program
Source: "The Imposter's Handbook" by Rob Conery
Lexeme
Lexical Analysis
A program called a lexer takes the raw source code (called a lexeme)
fn main() {
let numbers =
vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
Lexer
Program
Tokens
Source: "The Imposter's Handbook" by Rob Conery
Lexeme
Lexical Analysis
A program called a lexer takes the raw source code (called a lexeme)
and splits it into tokens
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
● Optimization
● Code Generation
Source: "The Imposter's Handbook" by Rob Conery
Parser
Program
Source: "The Imposter's Handbook" by Rob Conery
Parsing
A program called a parser
Parser
ProgramTokens
Source: "The Imposter's Handbook" by Rob Conery
Parsing
A program called a parser analyzes the tokens
Parser
ProgramTokens
Source: "The Imposter's Handbook" by Rob Conery
Parsing
A program called a parser analyzes the tokens and translates them into
an abstract syntax tree (AST)
Abstract
Syntax
Tree
Source: "Guide to Rustc Development"
Lowering to HIR
The Rust compiler
Rust
Compiler
Source: "Guide to Rustc Development"
The Rust compiler takes the AST
Rust
Compiler
Abstract
Syntax
Tree
Lowering to HIR
And...
● Expands any macros included in the code
Source: "Guide to Rustc Development"
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
src/main.rs
println!("{}", n);
src/main.rs
::std::io::_print(::core::fmt::Arguments::new_v1(
&["", "n"],
&match (&n,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
src/main.rs
And...
● Expands any macros included in the code
● Desugars certain constructs
Source: "Guide to Rustc Development"
for n in numbers {
}
src/main.rs
let result = match IntoIterator::into_iter(numbers) {
mut iter => loop {
let next;
match iter.next() {
Some(val) => next = val,
None => break,
};
(...)
},
};
src/main.rs
And...
● Expands any macros included in the code
● Desugars certain constructs
● Resolves any imports in the code
Source: "Guide to Rustc Development"
Source: "Guide to Rustc Development"
The Rust compiler takes the AST
Rust
Compiler
Abstract
Syntax
Tree
Lowering to HIR
Source: "Guide to Rustc Development"
The Rust compiler takes the AST and converts it into a Higher-level
Intermediate Representation (HIR)
Rust
Compiler
Abstract
Syntax
Tree HIR
Lowering to HIR
Source: "Guide to Rustc Development"
HIR Data Structures
Node (HirId)
Source: "Guide to Rustc Development"
HIR Data Structures
Definition (DefId)
Node (HirId)
Source: "Guide to Rustc Development"
HIR Data Structures
Crate (CrateNum)
Definition (DefId)
Node (HirId)
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers {
println!("{}", n);
}
}
src/main.rs
for n in numbers {
}
src/main.rs
let result = match IntoIterator::into_iter(numbers) {
mut iter => loop {
let next;
match iter.next() {
Some(val) => next = val,
None => break,
};
(...)
},
};
src/main.rs
Arm {
hir_id: HirId {
owner: DefId(0:3 ~
sample_code_1[24c3]::main[0]),
local_id: 107,
},
span: src/main.rs:4:5: 6:6,
higher_level_intermediate_representation
Arm {
hir_id: HirId {
owner: DefId(0:3 ~
sample_code_1[24c3]::main[0]),
local_id: 107,
},
span: src/main.rs:4:5: 6:6,
higher_level_intermediate_representation
Represents an arm of
the match expression
Arm {
hir_id: HirId {
owner: DefId(0:3 ~
sample_code_1[24c3]::main[0]),
local_id: 107,
},
span: src/main.rs:4:5: 6:6,
higher_level_intermediate_representation
Node
Arm {
hir_id: HirId {
owner: DefId(0:3 ~
sample_code_1[24c3]::main[0]),
local_id: 107,
},
span: src/main.rs:4:5: 6:6,
higher_level_intermediate_representation
Owned
by a
definition
Arm {
hir_id: HirId {
owner: DefId(0:3 ~
sample_code_1[24c3]::main[0]),
local_id: 107,
},
span: src/main.rs:4:5: 6:6,
higher_level_intermediate_representation
Owned by
a crate
Arm {
hir_id: HirId {
owner: DefId(0:3 ~
sample_code_1[24c3]::main[0]),
local_id: 107,
},
span: src/main.rs:4:5: 6:6,
higher_level_intermediate_representation
Rust
Compiler
Source: "Guide to Rustc Development"
Lowering to MIR
Rust
Compiler
HIR
Compiler then lowers the HIR
Source: "Guide to Rustc Development"
Lowering to MIR
Rust
Compiler
HIR MIR
Compiler then lowers the HIR into Mid-level Intermediate
Representation (MIR)
Source: "Guide to Rustc Development"
Lowering to MIR
Source: "Guide to Rustc Development"
MIR Data Structures
Control Flow Graph
Source: "Guide to Rustc Development"
MIR Data Structures
Definition (DefId)
Basic Block (bb1)Basic Block (bb0)
Control Flow Graph
MIR Data Structures
Definition (DefId)
Basic Block (bb0) Basic Block (bb1)
Statement
Terminator
Statement
Statement Terminator
Source: "Guide to Rustc Development"
Control Flow Graph
if condition {
do_one_thing
} else {
do_something_else
}
example.rs
MIR Data Structures
Definition (DefId)
Basic Block (bb0)
Statement
Terminator
Definition (DefId)
Basic Block (bb1)
Statement
Terminator
Definition (DefId)
Basic Block (bb2)
Statement
Terminator
Source: "Guide to Rustc Development"
Control Flow Graph
Are there more MIR data structures?
Check out the "Guide
to Rustc Development"
for more info!
https://rustc-dev-guide.rust-lang.org/
let result = match IntoIterator::into_iter(numbers) {
mut iter => loop {
let next;
match iter.next() {
Some(val) => next = val,
None => break,
};
(...)
},
};
src/main.rs
let result = match IntoIterator::into_iter(numbers) {
};
src/main.rs
bb2: {
_5 = const <std::vec::Vec<i32> as
std::iter::IntoIterator>::into_iter(move _6)
span: src/main.rs:4:14: 4:21
mid_level_intermediate_representation
bb2: {
_5 = const <std::vec::Vec<i32> as
std::iter::IntoIterator>::into_iter(move _6)
span: src/main.rs:4:14: 4:21
mid_level_intermediate_representation
Basic Block
bb2: {
_5 = const <std::vec::Vec<i32> as
std::iter::IntoIterator>::into_iter(move _6)
span: src/main.rs:4:14: 4:21
mid_level_intermediate_representation
Local
(result)
bb2: {
_5 = const <std::vec::Vec<i32> as
std::iter::IntoIterator>::into_iter(move _6)
span: src/main.rs:4:14: 4:21
mid_level_intermediate_representation
Span
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
● Optimization
● Code Generation
Source: "The Imposter's Handbook" by Rob Conery
Source: "The Imposter's Handbook" by Rob Conery
Semantic Analysis
Compiler tries to figure out what the programmer is trying to do in a way
the compiler can understand it
Semantic Analysis
At this point the Rust compiler will run several checks - including the
borrow checker
Source: "Guide to Rustc Development"
We'll come back to the borrow
checker shortly...
Stages of Compilation
● Lexical Analysis
● Parsing
● Semantic Analysis
● Optimization
● Code Generation
Source: "Guide to Rustc Development"
Optimization & Code Generation
Source: "Guide to Rustc Development"
This is where the code is transformed into an executable binary
Source: https://llvm.org
LLVM is a collection of modular and re-usable compiler and toolchain
technologies
LLVM
Rust
Compiler
Source: "Guide to Rustc Development"
Optimization & Code Generation
Rust
Compiler
MIR
Compiler lowers the MIR
Source: "Guide to Rustc Development"
Optimization & Code Generation
Rust
Compiler
Compiler lowers the MIR into LLVM Intermediate Representation
Source: "Guide to Rustc Development"
LLVM IR
Optimization & Code Generation
MIR
bb2:
; preds = %bb1
ret i32 %1, !dbg !194
}
llvm_intermediate_representation
bb2:
; preds = %bb1
ret i32 %1, !dbg !194
}
llvm_intermediate_representation
Basic Block
LLVM
Source: "Guide to Rustc Development"
Optimization & Code Generation
LLVM
And LLVM takes the LLVM IR
Source: "Guide to Rustc Development"
LLVM IR
Optimization & Code Generation
LLVM
And LLVM takes the LLVM IR, which runs more optimizations on it and
emits machine code
Source: "Guide to Rustc Development"
LLVM IR
Machine
Code
Optimization & Code Generation
LLVM then links the machine code files together to produce the final
binary
Source: "Guide to Rustc Development"
Machine
Code
Optimization & Code Generation
$ cargo run
$ cargo run
1
2
3
4
5
Yay!!!
$ cargo run
1
2
3
4
5
Back to the borrow checker!
src/main.rs
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
$ cargo build
$ cargo build
error[E0382]: borrow of moved value: `x`
--> src/main.rs:7:20
5 | let y = x;
| - value moved here
6 |
7 | println!("{}", x);
| ^ value borrowed here after move
error: aborting due to previous error
For more information about this error, try `rustc --explain
E0382`.
Borrow Checker
Does several things including:
● Tracking initializations and moves
Source: "Guide to Rustc Development"
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
let x: String; // x is not initialized here
src/main.rs
let x: String; // x is not initialized here
src/main.rs
mid_level_intermediate_representation
debug x => _1;
let _1: std::string::String
let x: String; // x is not initialized here
src/main.rs
mid_level_intermediate_representation
debug x => _1;
let _1: std::string::String
x
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
x = String::from("Hi Rusty Days!"); // x is initialized here
src/main.rs
x = String::from("Hi Rusty Days!"); // x is initialized here
src/main.rs
mid_level_intermediate_representation
_2 = const <String as
From<&str>>::from(const "Hi Rusty Days!")
_1 = move _2;
x = String::from("Hi Rusty Days!"); // x is initialized here
src/main.rs
mid_level_intermediate_representation
_2 = const <String as
From<&str>>::from(const "Hi Rusty Days!")
_1 = move _2;
x
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
let y = x; // x is moved here
src/main.rs
let y = x; // x is moved here
src/main.rs
mid_level_intermediate_representation
debug y => _3;
let _3: &std::string::String;
_3 = move _1;
let y = x; // x is moved here
src/main.rs
mid_level_intermediate_representation
debug y => _3;
let _3: &std::string::String;
_3 = move _1;
let y = x; // x is moved here
src/main.rs
mid_level_intermediate_representation
debug y => _3;
let _3: &std::string::String;
_3 = move _1;
xy
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
println!("{}", x); // x is NOT initialized here
src/main.rs
$ cargo build
error[E0382]: borrow of moved value: `x`
--> src/main.rs:7:20
5 | let y = x;
| - value moved here
6 |
7 | println!("{}", x);
| ^ value borrowed here after move
error: aborting due to previous error
For more information about this error,
try `rustc --explain E0382`.
$ cargo build
error[E0382]: borrow of moved value: `x`
--> src/main.rs:7:20
5 | let y = x;
| - value moved here
6 |
7 | println!("{}", x);
| ^ value borrowed here after move
error: aborting due to previous error
For more information about this error,
try `rustc --explain E0382`.
Span
$ cargo build
error[E0382]: borrow of moved value: `x`
--> src/main.rs:7:20
5 | let y = x;
| - value moved here
6 |
7 | println!("{}", x);
| ^ value borrowed here after move
error: aborting due to previous error
For more information about this error,
try `rustc --explain E0382`.
$ rustc --explain E0382
A variable was used after its contents have been moved elsewhere.
fn main() {
let mut x = MyStruct{ s: 5u32 };
let y = x;
x.s = 6;
println!("{}", x.s);
}
Since `MyStruct` is a type that is not marked `Copy`, the data gets moved
out
of `x` when we set `y`.
$ rustc --explain E0382
Sometimes we don't need to move the value. Using a reference, we can
let another function borrow the value without changing its ownership.
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
$ cargo run
$ cargo run
Hi Rusty Days!
Hi Rusty Days!
Borrow Checker
Does several things including:
● Tracking initializations and moves
● Lifetime inference
Source: "Guide to Rustc Development"
Rust uses "lifetime" in two distinct ways
● Lifetime of a variable
○ Span of time before the value of the variable gets freed
○ Also known as "scope"
Source: "Rust RFC #2094: NLL"
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
x is initialized
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
x is moved
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
x is not
initialized here
Rust uses "lifetime" in two distinct ways
● Lifetime of a variable
○ Span of time before the value of the variable gets freed
○ Also known as "scope"
● Lifetime of a reference
○ Span of time in which the reference can be used
Source: "Rust RFC #2094: NLL"
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
let y = &x;
src/main.rs
let y = &x;
src/main.rs
mid_level_intermediate_representation
debug x => _1;
debug y => _3;
_3 = &_1;
let y = &x;
src/main.rs
mid_level_intermediate_representation
debug x => _1;
debug y => _3;
_3 = &_1;
let y = &x;
src/main.rs
mid_level_intermediate_representation
debug x => _1;
debug y => _3;
_3 = &_1;
xy
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
println!("{}", x);
println!("{}", y);
}
src/main.rs
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
drop(x);
println!("{}", y);
}
src/main.rs
$ cargo build
$ cargo build
error[E0505]: cannot move out of `x` because it is borrowed
--> src/main.rs:7:10
|
5 | let y = &x;
| -- borrow of `x` occurs here
6 |
7 | drop(x);
| ^ move out of `x` occurs here
8 |
9 | println!("{}", y);
| - borrow later used here
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
drop(x);
println!("{}", y);
}
src/main.rs
Lifetime
of x
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
drop(x);
println!("{}", y);
}
src/main.rs
Needed
lifetime
of y
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
drop(x);
println!("{}", y);
}
src/main.rs
y can no
longer
reference x
fn main() {
let x: String;
x = String::from("Hi Rusty Days!");
let y = &x;
drop(x);
println!("{}", y);
}
src/main.rs
y is dead
here
Rust uses "lifetime" in two distinct ways
● Lifetime of a variable
○ Span of time before the value of the variable gets freed
○ Also known as "scope"
● Lifetime of a reference
○ Span of time in which the reference can be used
● If you make a reference to a value, the lifetime of that reference
cannot outlive the scope of the value
Source: "Rust RFC #2094: NLL"
There is SO much more to both
the compiler and the borrow checker!
Check out the "Guide
to Rustc Development"
for more info!
https://rustc-dev-guide.rust-lang.org/
Is the Borrow Checker a friend or a foe?
It is a friend...though a strict one
but one that will not only tell you when
something is wrong...
...it will also tell you how to fix it.
Nell Shamrell-Harrington
● Sr. Staff Research Engineer at Mozilla
● Lead Editor of This Week in Rust
● Host of the This Week in Rust podcast on the
Rustacean Station
● @nellshamrell

More Related Content

What's hot

Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)Youssef Dirani
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software ValidationJames Pascoe
 
Secure Programming
Secure ProgrammingSecure Programming
Secure Programmingalpha0
 
2016年のPerl (Long version)
2016年のPerl (Long version)2016年のPerl (Long version)
2016年のPerl (Long version)charsbar
 
2015 07-30-sysetm t.short.no.animation
2015 07-30-sysetm t.short.no.animation2015 07-30-sysetm t.short.no.animation
2015 07-30-sysetm t.short.no.animationdiannepatricia
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developersJosé Paumard
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
NOSQL and Cassandra
NOSQL and CassandraNOSQL and Cassandra
NOSQL and Cassandrarantav
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Php questions and answers
Php questions and answersPhp questions and answers
Php questions and answersDeepika joshi
 
An Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAn Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAndrey Karpov
 
JFokus 50 new things with java 8
JFokus 50 new things with java 8JFokus 50 new things with java 8
JFokus 50 new things with java 8José Paumard
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developersJosé Paumard
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConfJaroslaw Palka
 

What's hot (19)

Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software Validation
 
Python build your security tools.pdf
Python build your security tools.pdfPython build your security tools.pdf
Python build your security tools.pdf
 
Secure Programming
Secure ProgrammingSecure Programming
Secure Programming
 
2016年のPerl (Long version)
2016年のPerl (Long version)2016年のPerl (Long version)
2016年のPerl (Long version)
 
Pycon Sec
Pycon SecPycon Sec
Pycon Sec
 
2015 07-30-sysetm t.short.no.animation
2015 07-30-sysetm t.short.no.animation2015 07-30-sysetm t.short.no.animation
2015 07-30-sysetm t.short.no.animation
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
NOSQL and Cassandra
NOSQL and CassandraNOSQL and Cassandra
NOSQL and Cassandra
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Php questions and answers
Php questions and answersPhp questions and answers
Php questions and answers
 
An Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAn Experiment with Checking the glibc Library
An Experiment with Checking the glibc Library
 
JFokus 50 new things with java 8
JFokus 50 new things with java 8JFokus 50 new things with java 8
JFokus 50 new things with java 8
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
 

Similar to Rust Borrow Checker Deep Dive

Impala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopImpala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopAll Things Open
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?lichtkind
 
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]RootedCON
 
Tips And Tricks For Bioinformatics Software Engineering
Tips And Tricks For Bioinformatics Software EngineeringTips And Tricks For Bioinformatics Software Engineering
Tips And Tricks For Bioinformatics Software Engineeringjtdudley
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesJamund Ferguson
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programmingYanchang Zhao
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Data Con LA
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8Giovanni Bassi
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression LanguageDzmitry Naskou
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
Language-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchLanguage-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchAndrew Lowe
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?osfameron
 
The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)jaxLondonConference
 
Recursive descent parsing
Recursive descent parsingRecursive descent parsing
Recursive descent parsingBoy Baukema
 
Driver Debugging Basics
Driver Debugging BasicsDriver Debugging Basics
Driver Debugging BasicsBala Subra
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Vitaly Baum
 
Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for RSeth Falcon
 
I need help building a dictionary for the unique packets tha.pdf
I need help building a dictionary for the unique packets tha.pdfI need help building a dictionary for the unique packets tha.pdf
I need help building a dictionary for the unique packets tha.pdfsukhvir71
 

Similar to Rust Borrow Checker Deep Dive (20)

Impala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopImpala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for Hadoop
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
 
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
 
Tips And Tricks For Bioinformatics Software Engineering
Tips And Tricks For Bioinformatics Software EngineeringTips And Tricks For Bioinformatics Software Engineering
Tips And Tricks For Bioinformatics Software Engineering
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Language-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchLanguage-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible research
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)
 
Recursive descent parsing
Recursive descent parsingRecursive descent parsing
Recursive descent parsing
 
Driver Debugging Basics
Driver Debugging BasicsDriver Debugging Basics
Driver Debugging Basics
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
 
Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for R
 
I need help building a dictionary for the unique packets tha.pdf
I need help building a dictionary for the unique packets tha.pdfI need help building a dictionary for the unique packets tha.pdf
I need help building a dictionary for the unique packets tha.pdf
 

More from Nell Shamrell-Harrington

This Week in Rust: 400 Issues and Counting!
This Week in Rust: 400 Issues and Counting!This Week in Rust: 400 Issues and Counting!
This Week in Rust: 400 Issues and Counting!Nell Shamrell-Harrington
 
Higher. Faster. Stronger. Your Applications with Habitat
Higher. Faster. Stronger. Your Applications with HabitatHigher. Faster. Stronger. Your Applications with Habitat
Higher. Faster. Stronger. Your Applications with HabitatNell Shamrell-Harrington
 
Containers, Virtual Machines, and Bare Metal, Oh My!
Containers, Virtual Machines, and Bare Metal, Oh My!Containers, Virtual Machines, and Bare Metal, Oh My!
Containers, Virtual Machines, and Bare Metal, Oh My!Nell Shamrell-Harrington
 
Creating Packages that Run Anywhere with Chef Habitat
Creating Packages that Run Anywhere with Chef HabitatCreating Packages that Run Anywhere with Chef Habitat
Creating Packages that Run Anywhere with Chef HabitatNell Shamrell-Harrington
 
First Do No Harm: Surgical Refactoring (extended edition)
First Do No Harm: Surgical Refactoring (extended edition)First Do No Harm: Surgical Refactoring (extended edition)
First Do No Harm: Surgical Refactoring (extended edition)Nell Shamrell-Harrington
 
A Supermarket of Your Own: Running a Private Chef Supermarket
A Supermarket of Your Own: Running a Private Chef SupermarketA Supermarket of Your Own: Running a Private Chef Supermarket
A Supermarket of Your Own: Running a Private Chef SupermarketNell Shamrell-Harrington
 

More from Nell Shamrell-Harrington (20)

This Week in Rust: 400 Issues and Counting!
This Week in Rust: 400 Issues and Counting!This Week in Rust: 400 Issues and Counting!
This Week in Rust: 400 Issues and Counting!
 
Higher. Faster. Stronger. Your Applications with Habitat
Higher. Faster. Stronger. Your Applications with HabitatHigher. Faster. Stronger. Your Applications with Habitat
Higher. Faster. Stronger. Your Applications with Habitat
 
Habitat Service Discovery
Habitat Service DiscoveryHabitat Service Discovery
Habitat Service Discovery
 
Web Operations101
Web Operations101Web Operations101
Web Operations101
 
Rust Traits And You: A Deep Dive
Rust Traits And You: A Deep DiveRust Traits And You: A Deep Dive
Rust Traits And You: A Deep Dive
 
Rust, Redis, and Protobuf - Oh My!
Rust, Redis, and Protobuf - Oh My!Rust, Redis, and Protobuf - Oh My!
Rust, Redis, and Protobuf - Oh My!
 
Containers, Virtual Machines, and Bare Metal, Oh My!
Containers, Virtual Machines, and Bare Metal, Oh My!Containers, Virtual Machines, and Bare Metal, Oh My!
Containers, Virtual Machines, and Bare Metal, Oh My!
 
Chef Vault: A Deep Dive
Chef Vault: A Deep DiveChef Vault: A Deep Dive
Chef Vault: A Deep Dive
 
Open Source Governance 101
Open Source Governance 101Open Source Governance 101
Open Source Governance 101
 
DevOps in Politics
DevOps in PoliticsDevOps in Politics
DevOps in Politics
 
Open Source Governance - The Hard Parts
Open Source Governance - The Hard PartsOpen Source Governance - The Hard Parts
Open Source Governance - The Hard Parts
 
Creating Packages that Run Anywhere with Chef Habitat
Creating Packages that Run Anywhere with Chef HabitatCreating Packages that Run Anywhere with Chef Habitat
Creating Packages that Run Anywhere with Chef Habitat
 
Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
 
Refactoring Infrastructure Code
Refactoring Infrastructure CodeRefactoring Infrastructure Code
Refactoring Infrastructure Code
 
Devops: A History
Devops: A HistoryDevops: A History
Devops: A History
 
First Do No Harm: Surgical Refactoring (extended edition)
First Do No Harm: Surgical Refactoring (extended edition)First Do No Harm: Surgical Refactoring (extended edition)
First Do No Harm: Surgical Refactoring (extended edition)
 
First Do No Harm: Surgical Refactoring
First Do No Harm: Surgical RefactoringFirst Do No Harm: Surgical Refactoring
First Do No Harm: Surgical Refactoring
 
A Supermarket of Your Own: Running a Private Chef Supermarket
A Supermarket of Your Own: Running a Private Chef SupermarketA Supermarket of Your Own: Running a Private Chef Supermarket
A Supermarket of Your Own: Running a Private Chef Supermarket
 
Public Supermarket: The Insider's Tour
Public Supermarket: The Insider's TourPublic Supermarket: The Insider's Tour
Public Supermarket: The Insider's Tour
 
Beneath the Surface - Rubyconf 2013
Beneath the Surface - Rubyconf 2013Beneath the Surface - Rubyconf 2013
Beneath the Surface - Rubyconf 2013
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Rust Borrow Checker Deep Dive

  • 1. The Rust Borrow Checker A Deep Dive Nell Shamrell-Harrington, Mozilla @nellshamrell
  • 2. Is the Borrow Checker a friend or a foe?
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. The Borrow Checker becomes your friend through experience...
  • 9. ...understanding how it works also helps.
  • 10. Nell Shamrell-Harrington ● Sr. Staff Research Engineer at Mozilla ● Lead Editor of This Week in Rust ● Host of the This Week in Rust podcast on the Rustacean Station ● @nellshamrell
  • 11. Agenda ● Rust Compiler Overview ● Borrow Checker Deep Dive
  • 12. Overview of the Rust Compiler
  • 13. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } src/main.rs
  • 14. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } src/main.rs
  • 15. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } src/main.rs
  • 18. Stages of Compilation ● Lexical Analysis Source: "The Imposter's Handbook" by Rob Conery
  • 19. Stages of Compilation ● Lexical Analysis ● Parsing Source: "The Imposter's Handbook" by Rob Conery
  • 20. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis Source: "The Imposter's Handbook" by Rob Conery
  • 21. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis ● Optimization Source: "The Imposter's Handbook" by Rob Conery
  • 22. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis ● Optimization ● Code Generation Source: "The Imposter's Handbook" by Rob Conery
  • 23. Wait a minute - isn't the Rust compiler query based?
  • 24. Yes...but that is out of the scope of this talk.
  • 25. Check out the "Guide to Rustc Development" for more info! https://rustc-dev-guide.rust-lang.org/
  • 26. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis ● Optimization ● Code Generation Source: "The Imposter's Handbook" by Rob Conery
  • 27. Lexical Analysis Lexer Program Source: "The Imposter's Handbook" by Rob Conery A program called a lexer
  • 28. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } Lexer Program Source: "The Imposter's Handbook" by Rob Conery Lexeme Lexical Analysis A program called a lexer takes the raw source code (called a lexeme)
  • 29. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } Lexer Program Tokens Source: "The Imposter's Handbook" by Rob Conery Lexeme Lexical Analysis A program called a lexer takes the raw source code (called a lexeme) and splits it into tokens
  • 30. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis ● Optimization ● Code Generation Source: "The Imposter's Handbook" by Rob Conery
  • 31. Parser Program Source: "The Imposter's Handbook" by Rob Conery Parsing A program called a parser
  • 32. Parser ProgramTokens Source: "The Imposter's Handbook" by Rob Conery Parsing A program called a parser analyzes the tokens
  • 33. Parser ProgramTokens Source: "The Imposter's Handbook" by Rob Conery Parsing A program called a parser analyzes the tokens and translates them into an abstract syntax tree (AST) Abstract Syntax Tree
  • 34. Source: "Guide to Rustc Development" Lowering to HIR The Rust compiler Rust Compiler
  • 35. Source: "Guide to Rustc Development" The Rust compiler takes the AST Rust Compiler Abstract Syntax Tree Lowering to HIR
  • 36. And... ● Expands any macros included in the code Source: "Guide to Rustc Development"
  • 37. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } src/main.rs
  • 39. ::std::io::_print(::core::fmt::Arguments::new_v1( &["", "n"], &match (&n,) { (arg0,) => [::core::fmt::ArgumentV1::new( arg0, ::core::fmt::Display::fmt, )], }, )); src/main.rs
  • 40. And... ● Expands any macros included in the code ● Desugars certain constructs Source: "Guide to Rustc Development"
  • 41. for n in numbers { } src/main.rs
  • 42. let result = match IntoIterator::into_iter(numbers) { mut iter => loop { let next; match iter.next() { Some(val) => next = val, None => break, }; (...) }, }; src/main.rs
  • 43. And... ● Expands any macros included in the code ● Desugars certain constructs ● Resolves any imports in the code Source: "Guide to Rustc Development"
  • 44. Source: "Guide to Rustc Development" The Rust compiler takes the AST Rust Compiler Abstract Syntax Tree Lowering to HIR
  • 45. Source: "Guide to Rustc Development" The Rust compiler takes the AST and converts it into a Higher-level Intermediate Representation (HIR) Rust Compiler Abstract Syntax Tree HIR Lowering to HIR
  • 46. Source: "Guide to Rustc Development" HIR Data Structures Node (HirId)
  • 47. Source: "Guide to Rustc Development" HIR Data Structures Definition (DefId) Node (HirId)
  • 48. Source: "Guide to Rustc Development" HIR Data Structures Crate (CrateNum) Definition (DefId) Node (HirId)
  • 49. fn main() { let numbers = vec![1, 2, 3, 4, 5]; for n in numbers { println!("{}", n); } } src/main.rs
  • 50. for n in numbers { } src/main.rs
  • 51. let result = match IntoIterator::into_iter(numbers) { mut iter => loop { let next; match iter.next() { Some(val) => next = val, None => break, }; (...) }, }; src/main.rs
  • 52. Arm { hir_id: HirId { owner: DefId(0:3 ~ sample_code_1[24c3]::main[0]), local_id: 107, }, span: src/main.rs:4:5: 6:6, higher_level_intermediate_representation
  • 53. Arm { hir_id: HirId { owner: DefId(0:3 ~ sample_code_1[24c3]::main[0]), local_id: 107, }, span: src/main.rs:4:5: 6:6, higher_level_intermediate_representation Represents an arm of the match expression
  • 54. Arm { hir_id: HirId { owner: DefId(0:3 ~ sample_code_1[24c3]::main[0]), local_id: 107, }, span: src/main.rs:4:5: 6:6, higher_level_intermediate_representation Node
  • 55. Arm { hir_id: HirId { owner: DefId(0:3 ~ sample_code_1[24c3]::main[0]), local_id: 107, }, span: src/main.rs:4:5: 6:6, higher_level_intermediate_representation Owned by a definition
  • 56. Arm { hir_id: HirId { owner: DefId(0:3 ~ sample_code_1[24c3]::main[0]), local_id: 107, }, span: src/main.rs:4:5: 6:6, higher_level_intermediate_representation Owned by a crate
  • 57. Arm { hir_id: HirId { owner: DefId(0:3 ~ sample_code_1[24c3]::main[0]), local_id: 107, }, span: src/main.rs:4:5: 6:6, higher_level_intermediate_representation
  • 58. Rust Compiler Source: "Guide to Rustc Development" Lowering to MIR
  • 59. Rust Compiler HIR Compiler then lowers the HIR Source: "Guide to Rustc Development" Lowering to MIR
  • 60. Rust Compiler HIR MIR Compiler then lowers the HIR into Mid-level Intermediate Representation (MIR) Source: "Guide to Rustc Development" Lowering to MIR
  • 61. Source: "Guide to Rustc Development" MIR Data Structures Control Flow Graph
  • 62. Source: "Guide to Rustc Development" MIR Data Structures Definition (DefId) Basic Block (bb1)Basic Block (bb0) Control Flow Graph
  • 63. MIR Data Structures Definition (DefId) Basic Block (bb0) Basic Block (bb1) Statement Terminator Statement Statement Terminator Source: "Guide to Rustc Development" Control Flow Graph
  • 64. if condition { do_one_thing } else { do_something_else } example.rs
  • 65. MIR Data Structures Definition (DefId) Basic Block (bb0) Statement Terminator Definition (DefId) Basic Block (bb1) Statement Terminator Definition (DefId) Basic Block (bb2) Statement Terminator Source: "Guide to Rustc Development" Control Flow Graph
  • 66. Are there more MIR data structures?
  • 67. Check out the "Guide to Rustc Development" for more info! https://rustc-dev-guide.rust-lang.org/
  • 68. let result = match IntoIterator::into_iter(numbers) { mut iter => loop { let next; match iter.next() { Some(val) => next = val, None => break, }; (...) }, }; src/main.rs
  • 69. let result = match IntoIterator::into_iter(numbers) { }; src/main.rs
  • 70. bb2: { _5 = const <std::vec::Vec<i32> as std::iter::IntoIterator>::into_iter(move _6) span: src/main.rs:4:14: 4:21 mid_level_intermediate_representation
  • 71. bb2: { _5 = const <std::vec::Vec<i32> as std::iter::IntoIterator>::into_iter(move _6) span: src/main.rs:4:14: 4:21 mid_level_intermediate_representation Basic Block
  • 72. bb2: { _5 = const <std::vec::Vec<i32> as std::iter::IntoIterator>::into_iter(move _6) span: src/main.rs:4:14: 4:21 mid_level_intermediate_representation Local (result)
  • 73. bb2: { _5 = const <std::vec::Vec<i32> as std::iter::IntoIterator>::into_iter(move _6) span: src/main.rs:4:14: 4:21 mid_level_intermediate_representation Span
  • 74. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis ● Optimization ● Code Generation Source: "The Imposter's Handbook" by Rob Conery
  • 75. Source: "The Imposter's Handbook" by Rob Conery Semantic Analysis Compiler tries to figure out what the programmer is trying to do in a way the compiler can understand it
  • 76. Semantic Analysis At this point the Rust compiler will run several checks - including the borrow checker Source: "Guide to Rustc Development"
  • 77. We'll come back to the borrow checker shortly...
  • 78. Stages of Compilation ● Lexical Analysis ● Parsing ● Semantic Analysis ● Optimization ● Code Generation Source: "Guide to Rustc Development"
  • 79. Optimization & Code Generation Source: "Guide to Rustc Development" This is where the code is transformed into an executable binary
  • 80. Source: https://llvm.org LLVM is a collection of modular and re-usable compiler and toolchain technologies LLVM
  • 81. Rust Compiler Source: "Guide to Rustc Development" Optimization & Code Generation
  • 82. Rust Compiler MIR Compiler lowers the MIR Source: "Guide to Rustc Development" Optimization & Code Generation
  • 83. Rust Compiler Compiler lowers the MIR into LLVM Intermediate Representation Source: "Guide to Rustc Development" LLVM IR Optimization & Code Generation MIR
  • 84. bb2: ; preds = %bb1 ret i32 %1, !dbg !194 } llvm_intermediate_representation
  • 85. bb2: ; preds = %bb1 ret i32 %1, !dbg !194 } llvm_intermediate_representation Basic Block
  • 86. LLVM Source: "Guide to Rustc Development" Optimization & Code Generation
  • 87. LLVM And LLVM takes the LLVM IR Source: "Guide to Rustc Development" LLVM IR Optimization & Code Generation
  • 88. LLVM And LLVM takes the LLVM IR, which runs more optimizations on it and emits machine code Source: "Guide to Rustc Development" LLVM IR Machine Code Optimization & Code Generation
  • 89. LLVM then links the machine code files together to produce the final binary Source: "Guide to Rustc Development" Machine Code Optimization & Code Generation
  • 93. Back to the borrow checker!
  • 94. src/main.rs fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); }
  • 95. src/main.rs fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); }
  • 96. src/main.rs fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); }
  • 97. src/main.rs fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); }
  • 98. src/main.rs fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); }
  • 100. $ cargo build error[E0382]: borrow of moved value: `x` --> src/main.rs:7:20 5 | let y = x; | - value moved here 6 | 7 | println!("{}", x); | ^ value borrowed here after move error: aborting due to previous error For more information about this error, try `rustc --explain E0382`.
  • 101. Borrow Checker Does several things including: ● Tracking initializations and moves Source: "Guide to Rustc Development"
  • 102. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs
  • 103. let x: String; // x is not initialized here src/main.rs
  • 104. let x: String; // x is not initialized here src/main.rs mid_level_intermediate_representation debug x => _1; let _1: std::string::String
  • 105. let x: String; // x is not initialized here src/main.rs mid_level_intermediate_representation debug x => _1; let _1: std::string::String x
  • 106. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs
  • 107. x = String::from("Hi Rusty Days!"); // x is initialized here src/main.rs
  • 108. x = String::from("Hi Rusty Days!"); // x is initialized here src/main.rs mid_level_intermediate_representation _2 = const <String as From<&str>>::from(const "Hi Rusty Days!") _1 = move _2;
  • 109. x = String::from("Hi Rusty Days!"); // x is initialized here src/main.rs mid_level_intermediate_representation _2 = const <String as From<&str>>::from(const "Hi Rusty Days!") _1 = move _2; x
  • 110. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs
  • 111. let y = x; // x is moved here src/main.rs
  • 112. let y = x; // x is moved here src/main.rs mid_level_intermediate_representation debug y => _3; let _3: &std::string::String; _3 = move _1;
  • 113. let y = x; // x is moved here src/main.rs mid_level_intermediate_representation debug y => _3; let _3: &std::string::String; _3 = move _1;
  • 114. let y = x; // x is moved here src/main.rs mid_level_intermediate_representation debug y => _3; let _3: &std::string::String; _3 = move _1; xy
  • 115. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs
  • 116. println!("{}", x); // x is NOT initialized here src/main.rs
  • 117. $ cargo build error[E0382]: borrow of moved value: `x` --> src/main.rs:7:20 5 | let y = x; | - value moved here 6 | 7 | println!("{}", x); | ^ value borrowed here after move error: aborting due to previous error For more information about this error, try `rustc --explain E0382`.
  • 118. $ cargo build error[E0382]: borrow of moved value: `x` --> src/main.rs:7:20 5 | let y = x; | - value moved here 6 | 7 | println!("{}", x); | ^ value borrowed here after move error: aborting due to previous error For more information about this error, try `rustc --explain E0382`. Span
  • 119. $ cargo build error[E0382]: borrow of moved value: `x` --> src/main.rs:7:20 5 | let y = x; | - value moved here 6 | 7 | println!("{}", x); | ^ value borrowed here after move error: aborting due to previous error For more information about this error, try `rustc --explain E0382`.
  • 120. $ rustc --explain E0382 A variable was used after its contents have been moved elsewhere. fn main() { let mut x = MyStruct{ s: 5u32 }; let y = x; x.s = 6; println!("{}", x.s); } Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out of `x` when we set `y`.
  • 121. $ rustc --explain E0382 Sometimes we don't need to move the value. Using a reference, we can let another function borrow the value without changing its ownership.
  • 122. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; println!("{}", x); println!("{}", y); } src/main.rs
  • 124. $ cargo run Hi Rusty Days! Hi Rusty Days!
  • 125. Borrow Checker Does several things including: ● Tracking initializations and moves ● Lifetime inference Source: "Guide to Rustc Development"
  • 126. Rust uses "lifetime" in two distinct ways ● Lifetime of a variable ○ Span of time before the value of the variable gets freed ○ Also known as "scope" Source: "Rust RFC #2094: NLL"
  • 127. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs x is initialized
  • 128. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs x is moved
  • 129. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = x; println!("{}", x); println!("{}", y); } src/main.rs x is not initialized here
  • 130. Rust uses "lifetime" in two distinct ways ● Lifetime of a variable ○ Span of time before the value of the variable gets freed ○ Also known as "scope" ● Lifetime of a reference ○ Span of time in which the reference can be used Source: "Rust RFC #2094: NLL"
  • 131. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; println!("{}", x); println!("{}", y); } src/main.rs
  • 132. let y = &x; src/main.rs
  • 133. let y = &x; src/main.rs mid_level_intermediate_representation debug x => _1; debug y => _3; _3 = &_1;
  • 134. let y = &x; src/main.rs mid_level_intermediate_representation debug x => _1; debug y => _3; _3 = &_1;
  • 135. let y = &x; src/main.rs mid_level_intermediate_representation debug x => _1; debug y => _3; _3 = &_1; xy
  • 136. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; println!("{}", x); println!("{}", y); } src/main.rs
  • 137. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; drop(x); println!("{}", y); } src/main.rs
  • 139. $ cargo build error[E0505]: cannot move out of `x` because it is borrowed --> src/main.rs:7:10 | 5 | let y = &x; | -- borrow of `x` occurs here 6 | 7 | drop(x); | ^ move out of `x` occurs here 8 | 9 | println!("{}", y); | - borrow later used here
  • 140. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; drop(x); println!("{}", y); } src/main.rs Lifetime of x
  • 141. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; drop(x); println!("{}", y); } src/main.rs Needed lifetime of y
  • 142. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; drop(x); println!("{}", y); } src/main.rs y can no longer reference x
  • 143. fn main() { let x: String; x = String::from("Hi Rusty Days!"); let y = &x; drop(x); println!("{}", y); } src/main.rs y is dead here
  • 144. Rust uses "lifetime" in two distinct ways ● Lifetime of a variable ○ Span of time before the value of the variable gets freed ○ Also known as "scope" ● Lifetime of a reference ○ Span of time in which the reference can be used ● If you make a reference to a value, the lifetime of that reference cannot outlive the scope of the value Source: "Rust RFC #2094: NLL"
  • 145. There is SO much more to both the compiler and the borrow checker!
  • 146. Check out the "Guide to Rustc Development" for more info! https://rustc-dev-guide.rust-lang.org/
  • 147. Is the Borrow Checker a friend or a foe?
  • 148. It is a friend...though a strict one
  • 149. but one that will not only tell you when something is wrong...
  • 150. ...it will also tell you how to fix it.
  • 151. Nell Shamrell-Harrington ● Sr. Staff Research Engineer at Mozilla ● Lead Editor of This Week in Rust ● Host of the This Week in Rust podcast on the Rustacean Station ● @nellshamrell