SlideShare uma empresa Scribd logo
1 de 52
Baixar para ler offline
c 2014– Andrei Alexandrescu. 1 / 47
Three Cool Things About D
Andrei Alexandrescu, Ph.D.
Research Scientist, Facebook
aa@fb.com
NDC Oslo 2014
c 2014– Andrei Alexandrescu. 2 / 47
ThreeFour Cool Things About D
Andrei Alexandrescu, Ph.D.
Research Scientist, Facebook
aa@fb.com
NDC Oslo 2014
What’s the Deal??
c 2014– Andrei Alexandrescu. 3 / 47
D is. . .
c 2014– Andrei Alexandrescu. 4 / 47
• Efficient when it can
• Convenient when it should
• Safe when it must
Basics
c 2014– Andrei Alexandrescu. 5 / 47
• Statically typed
Use deduction wherever possible
• Sininimp-Mulinint object-oriented style
• Gray-box modularity:
◦ Python-inspired modules for “classic” entities
◦ White-box parameterized types and functions
• Heterogeneous translation of parameterized code
Turtles all the way down
c 2014– Andrei Alexandrescu. 6 / 47
Hello, World!
c 2014– Andrei Alexandrescu. 7 / 47
#!/usr/bin/rdmd
import std.stdio;
void main() {
writeln("Hello, world!");
}
• “Meh”worthy
• However:
◦ Simple
◦ Correct
◦ Scriptable
◦ Features turtles
Them turtles
c 2014– Andrei Alexandrescu. 8 / 47
#!/usr/bin/rdmd
void main() {
import std.stdio;
writeln("Hello, world!");
}
• Most everything can be scoped everywhere
• Better scoping, reasoning, dependency mgmt
• Functions
• Types (Voldermort types)
• Even generics
Segue into generics
c 2014– Andrei Alexandrescu. 9 / 47
void log(T)(T stuff) {
import std.datetime, std.stdio;
writeln(Clock.currTime(), ’ ’, stuff);
}
void main() {
log("hello");
}
• If not instantiated, no import
• imports cached once realized
• Generics faster to build, import
• Less pressure on linker
Approach to Safety
c 2014– Andrei Alexandrescu. 10 / 47
Memory Safety
c 2014– Andrei Alexandrescu. 11 / 47
• All data is read with the type it was written
• Eliminates unpleasant class of errors
• Makes bugs reproducible
• Preserves the integrity of the type system
Challenge
c 2014– Andrei Alexandrescu. 12 / 47
• System-level languages must:
◦ Forge pointers (linkers/loaders)
◦ Magically change type of memory (allocators/GCs)
◦ Recycle memory “early”
◦ Circumvent type system
Attack
c 2014– Andrei Alexandrescu. 13 / 47
• All of D can’t be safe
• Define a safe subset
• Safe subset usable for large portions or entire programs
• Tagged with @safe attribute
@safe double cube(double x) {
return x * x * x;
}
• Unsafe functions tagged with @system
@system void free(void*);
But wait
c 2014– Andrei Alexandrescu. 14 / 47
• Important case: safe functions with
unknown/unprovable implementation
◦ fopen, malloc, isAlpha
◦ Small buffer optimization
◦ Tagged union implementation
• Define attribute @trusted
Rules
c 2014– Andrei Alexandrescu. 15 / 47
• @safe functions cannot:
◦ call @system functions
◦ escape addresses of locals
◦ forge pointers
◦ cast pointers around
◦ do pointer arithmetic
• N.B. Not all rules completely implemented
◦ Some on the conservative side
◦ A few details in flux
Resulting setup
c 2014– Andrei Alexandrescu. 16 / 47
• Low notational overhead: entire modules or portions
thereof can be annotated
• Deduction for generics
• Application divided in:
◦ Safe part, uses GC, easy to write and debug
◦ Trusted part, encapsulated unsafe manipulation,
proven by means of code review
◦ System part, non-encapsulated unsafe
manipulation, only when solidly justified
Approach to Purity
c 2014– Andrei Alexandrescu. 17 / 47
Thesis
c 2014– Andrei Alexandrescu. 18 / 47
• Writing entire programs in pure style difficult
• Writing fragments of programs in pure style easy, useful
• + Easier to verify useful properties, debug
• + Better code generation
• − Challenge: interfacing pure and impure code
Functional Factorial (yawn)
c 2014– Andrei Alexandrescu. 19 / 47
ulong factorial(uint n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
• It’s PSPACE!
• Somebody should do hard time for this
However, it’s pure
c 2014– Andrei Alexandrescu. 20 / 47
pure ulong factorial(uint n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
• Pure is good
Functional Factorial, Fixed
c 2014– Andrei Alexandrescu. 21 / 47
pure ulong factorial(uint n) {
ulong crutch(uint n, ulong result) {
return n <= 1
? result
: crutch(n - 1, n * result);
}
return crutch(n, 1);
}
• Threads state through as parameters
• You know what? I don’t care for it
Honest Factorial
c 2014– Andrei Alexandrescu. 22 / 47
ulong factorial(uint n) {
ulong result = 1;
foreach (uint i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
• But no longer pure!
• Well allow me to retort
Pure is as pure does
c 2014– Andrei Alexandrescu. 24 / 47
• “Pure functions always return the same result for the
same arguments”
• No reading and writing of global variables
◦ (Global constants okay)
• No calling of impure functions
• Who said anything about local, transient state inside the
function?
Transitive State
c 2014– Andrei Alexandrescu. 25 / 47
pure void reverse(T)(T[] a) {
foreach (i; 0 .. data.length / 2) {
swap(data[i], data[$ - i - 1]);
}
}
• Possibility: disallow
• More useful: relaxed rule
• Operate with transitive closure of state reachable
through parameter
• Not functional pure, but an interesting superset
• No need for another annotation, it’s all in the signature!
User-defined types
c 2014– Andrei Alexandrescu. 26 / 47
pure BigInt factorial(uint n) {
BigInt result = 1;
for (; n > 1; --n) {
result *= n;
}
return result;
}
• Works, but not in released version
• Most of stdlib “purified”
Aftermath
c 2014– Andrei Alexandrescu. 27 / 47
• If parameters reach mutable state:
◦ Relaxed pure—no globals, no I/O, no impure calls
• If parameters can’t reach mutable state:
◦ “Haskell-grade” observed purity
◦ Yet imperative implementation possible
◦ As long as it’s local only
The Generative Connection:
mixin
c 2014– Andrei Alexandrescu. 28 / 47
Generative programming
c 2014– Andrei Alexandrescu. 29 / 47
• In brief: code that generates code
• Generic programming often requires algorithm
specialization
• Specification often present in a DSL
Embedded DSLs
c 2014– Andrei Alexandrescu. 30 / 47
Force into host language’s syntax?
Embedded DSLs
c 2014– Andrei Alexandrescu. 31 / 47
• Formatted printing?
Embedded DSLs
c 2014– Andrei Alexandrescu. 31 / 47
• Formatted printing?
• Regular expressions?
Embedded DSLs
c 2014– Andrei Alexandrescu. 31 / 47
• Formatted printing?
• Regular expressions?
• EBNF?
Embedded DSLs
c 2014– Andrei Alexandrescu. 31 / 47
• Formatted printing?
• Regular expressions?
• EBNF?
• PEG?
Embedded DSLs
c 2014– Andrei Alexandrescu. 31 / 47
• Formatted printing?
• Regular expressions?
• EBNF?
• PEG?
• SQL?
Embedded DSLs
c 2014– Andrei Alexandrescu. 31 / 47
• Formatted printing?
• Regular expressions?
• EBNF?
• PEG?
• SQL?
• . . . Pasta for everyone!
Embedded DSLs
c 2014– Andrei Alexandrescu. 32 / 47
Here: use with native grammar
Process during compilation
Generate D code accordingly
Compile-Time Evaluation
c 2014– Andrei Alexandrescu. 33 / 47
• A large subset of D available for compile-time evaluation
ulong factorial(uint n) {
ulong result = 1;
for (; n > 1; --n) result *= n;
return result;
}
...
auto f1 = factorial(10); // run-time
static f2 = factorial(10); // compile-time
Code injection with mixin
c 2014– Andrei Alexandrescu. 34 / 47
mixin("writeln("hello, world");");
mixin(generateSomeCode());
• Not as glamorous as AST manipulation but darn
effective
• Easy to understand and debug
• Now we have compile-time evaluation AND mixin. . .
c 2014– Andrei Alexandrescu. 35 / 47
Wait a minute!
Example: bitfields in library
c 2014– Andrei Alexandrescu. 36 / 47
struct A {
int a;
mixin(bitfields!(
uint, "x", 2,
int, "y", 3,
uint, "z", 2,
bool, "flag", 1));
}
A obj;
obj.x = 2;
obj.z = obj.x;
Example: boilerplate
c 2014– Andrei Alexandrescu. 37 / 47
string forward(string p, string[] names...)
{
string r;
foreach (n; names)
{
r ~= "static if (hasMember!(typeof("~p~
"), ‘"~n~"‘)"
~ ") auto ref "~n~
"(T_...)(T_ t_) { return "~
p~"."~n~"(t_); }n";
}
return r;
}
Example: boilerplate
c 2014– Andrei Alexandrescu. 38 / 47
struct A {
int fun(int, string) { ... }
int gun(int, string, double) { ... }
}
struct B {
A a;
//pragma(msg, forward("a", "fun", "gun"));
mixin(forward("a", "fun", "gun"));
}
Parser
c 2014– Andrei Alexandrescu. 39 / 47
import pegged.grammar; // by Philippe Sigaud
mixin(grammar("
Expr < Factor AddExpr*
AddExpr < (’+’/’-’) Factor
Factor < Primary MulExpr*
MulExpr < (’*’/’/’) Primary
Primary < Parens / Number / Variable
/ ’-’ Primary
Parens < ’(’ Expr ’)’
Number <~ [0-9]+
Variable <- Identifier
"));
Usage
c 2014– Andrei Alexandrescu. 40 / 47
// Parsing at compile-time:
static parseTree1 = Expr.parse(
"1 + 2 - (3*x-5)*6");
pragma(msg, parseTree1.capture);
// Parsing at run-time:
auto parseTree2 = Expr.parse(readln());
writeln(parseTree2.capture);
Scaling up
c 2014– Andrei Alexandrescu. 41 / 47
1000 lines of D grammar →
3000 lines D parser
c 2014– Andrei Alexandrescu. 42 / 47
Highly integrated lex+yacc
c 2014– Andrei Alexandrescu. 43 / 47
What about regexen?
Compile-time regular expressions
c 2014– Andrei Alexandrescu. 44 / 47
• GSoC project by Dmitry Olshansky, merged into std
• Fully UTF capable, no special casing for ASCII
• Two modes sharing the same backend:
auto r1 = regex("^.*/([^/]+)/?$");
static r2 = ctRegex!("^.*/([^/]+)/?$");
• Run-time version uses intrinsics in a few places
• Static version generates specialized automaton, then
compiles it
Summary
c 2014– Andrei Alexandrescu. 46 / 47
Summary
c 2014– Andrei Alexandrescu. 47 / 47
• Turtles
• Safe subset
• Pure functions
• Generative programming

Mais conteúdo relacionado

Mais procurados

EdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for JavaEdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for JavaLisa Hua
 
Introduction toc sharp
Introduction toc sharpIntroduction toc sharp
Introduction toc sharpSDFG5
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 
Design And Simulation of Electronic Circuits Lec_02
Design And Simulation of Electronic Circuits Lec_02Design And Simulation of Electronic Circuits Lec_02
Design And Simulation of Electronic Circuits Lec_02Mohamed Atef
 
Unifi
Unifi Unifi
Unifi hangal
 
Design And Simulation of Electronic Circuits Lec_01
Design And Simulation of Electronic Circuits Lec_01Design And Simulation of Electronic Circuits Lec_01
Design And Simulation of Electronic Circuits Lec_01Mohamed Atef
 
ENKI: Access Control for Encrypted Query Processing
ENKI: Access Control for Encrypted Query ProcessingENKI: Access Control for Encrypted Query Processing
ENKI: Access Control for Encrypted Query ProcessingMateus S. H. Cruz
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in CodeEamonn Boyle
 
Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...
Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...
Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...Mateus S. H. Cruz
 

Mais procurados (13)

C language
C languageC language
C language
 
College1
College1College1
College1
 
Introduction to HDLs
Introduction to HDLsIntroduction to HDLs
Introduction to HDLs
 
EdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for JavaEdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for Java
 
Introduction toc sharp
Introduction toc sharpIntroduction toc sharp
Introduction toc sharp
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Design And Simulation of Electronic Circuits Lec_02
Design And Simulation of Electronic Circuits Lec_02Design And Simulation of Electronic Circuits Lec_02
Design And Simulation of Electronic Circuits Lec_02
 
Unifi
Unifi Unifi
Unifi
 
Design And Simulation of Electronic Circuits Lec_01
Design And Simulation of Electronic Circuits Lec_01Design And Simulation of Electronic Circuits Lec_01
Design And Simulation of Electronic Circuits Lec_01
 
ENKI: Access Control for Encrypted Query Processing
ENKI: Access Control for Encrypted Query ProcessingENKI: Access Control for Encrypted Query Processing
ENKI: Access Control for Encrypted Query Processing
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
 
Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...
Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...
Fast, Private and Verifiable: Server-aided Approximate Similarity Computation...
 
Overview of CryptDB
Overview of CryptDBOverview of CryptDB
Overview of CryptDB
 

Destaque

Destaque (6)

DConf 2016: Bitpacking Like a Madman by Amaury Sechet
DConf 2016: Bitpacking Like a Madman by Amaury SechetDConf 2016: Bitpacking Like a Madman by Amaury Sechet
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
 
DaNode - A home made web server in D
DaNode - A home made web server in DDaNode - A home made web server in D
DaNode - A home made web server in D
 
Dconf2015 d2 t3
Dconf2015 d2 t3Dconf2015 d2 t3
Dconf2015 d2 t3
 
Dconf2015 d2 t4
Dconf2015 d2 t4Dconf2015 d2 t4
Dconf2015 d2 t4
 
Three Optimization Tips for C++
Three Optimization Tips for C++Three Optimization Tips for C++
Three Optimization Tips for C++
 
Three Optimization Tips for C++
Three Optimization Tips for C++Three Optimization Tips for C++
Three Optimization Tips for C++
 

Semelhante a Three, no, Four Cool Things About D

Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
10 declarative-control-flow.handouts
10 declarative-control-flow.handouts10 declarative-control-flow.handouts
10 declarative-control-flow.handoutsAndrei Alexandrescu
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming languageKumar Gaurav
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Windows Developer
 
Angular 2 On Production (IT Talk in Dnipro)
Angular 2 On Production (IT Talk in Dnipro)Angular 2 On Production (IT Talk in Dnipro)
Angular 2 On Production (IT Talk in Dnipro)Oleksandr Tryshchenko
 
Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I) Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I) Mobivery
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
Вредные советы .NET разработчикам, Сергей Калинец
Вредные советы .NET разработчикам, Сергей КалинецВредные советы .NET разработчикам, Сергей Калинец
Вредные советы .NET разработчикам, Сергей КалинецSigma Software
 
6 attributed grammars
6  attributed grammars6  attributed grammars
6 attributed grammarsSaeed Parsa
 
Craftsmanship in Computational Work
Craftsmanship in Computational WorkCraftsmanship in Computational Work
Craftsmanship in Computational WorkYung-Yu Chen
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#ANURAG SINGH
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015Igor Laborie
 
The Present and Future of the Web Platform
The Present and Future of the Web PlatformThe Present and Future of the Web Platform
The Present and Future of the Web PlatformC4Media
 

Semelhante a Three, no, Four Cool Things About D (20)

Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
C.ppt
C.pptC.ppt
C.ppt
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
10 declarative-control-flow.handouts
10 declarative-control-flow.handouts10 declarative-control-flow.handouts
10 declarative-control-flow.handouts
 
201801 CSE240 Lecture 13
201801 CSE240 Lecture 13201801 CSE240 Lecture 13
201801 CSE240 Lecture 13
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
 
Return of c++
Return of c++Return of c++
Return of c++
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
 
Angular 2 On Production (IT Talk in Dnipro)
Angular 2 On Production (IT Talk in Dnipro)Angular 2 On Production (IT Talk in Dnipro)
Angular 2 On Production (IT Talk in Dnipro)
 
Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I) Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I)
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Вредные советы .NET разработчикам, Сергей Калинец
Вредные советы .NET разработчикам, Сергей КалинецВредные советы .NET разработчикам, Сергей Калинец
Вредные советы .NET разработчикам, Сергей Калинец
 
6 attributed grammars
6  attributed grammars6  attributed grammars
6 attributed grammars
 
Craftsmanship in Computational Work
Craftsmanship in Computational WorkCraftsmanship in Computational Work
Craftsmanship in Computational Work
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
Lua Study Share
Lua Study ShareLua Study Share
Lua Study Share
 
The Present and Future of the Web Platform
The Present and Future of the Web PlatformThe Present and Future of the Web Platform
The Present and Future of the Web Platform
 

Último

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Último (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 

Three, no, Four Cool Things About D

  • 1. c 2014– Andrei Alexandrescu. 1 / 47 Three Cool Things About D Andrei Alexandrescu, Ph.D. Research Scientist, Facebook aa@fb.com NDC Oslo 2014
  • 2. c 2014– Andrei Alexandrescu. 2 / 47 ThreeFour Cool Things About D Andrei Alexandrescu, Ph.D. Research Scientist, Facebook aa@fb.com NDC Oslo 2014
  • 3. What’s the Deal?? c 2014– Andrei Alexandrescu. 3 / 47
  • 4. D is. . . c 2014– Andrei Alexandrescu. 4 / 47 • Efficient when it can • Convenient when it should • Safe when it must
  • 5. Basics c 2014– Andrei Alexandrescu. 5 / 47 • Statically typed Use deduction wherever possible • Sininimp-Mulinint object-oriented style • Gray-box modularity: ◦ Python-inspired modules for “classic” entities ◦ White-box parameterized types and functions • Heterogeneous translation of parameterized code
  • 6. Turtles all the way down c 2014– Andrei Alexandrescu. 6 / 47
  • 7. Hello, World! c 2014– Andrei Alexandrescu. 7 / 47 #!/usr/bin/rdmd import std.stdio; void main() { writeln("Hello, world!"); } • “Meh”worthy • However: ◦ Simple ◦ Correct ◦ Scriptable ◦ Features turtles
  • 8. Them turtles c 2014– Andrei Alexandrescu. 8 / 47 #!/usr/bin/rdmd void main() { import std.stdio; writeln("Hello, world!"); } • Most everything can be scoped everywhere • Better scoping, reasoning, dependency mgmt • Functions • Types (Voldermort types) • Even generics
  • 9. Segue into generics c 2014– Andrei Alexandrescu. 9 / 47 void log(T)(T stuff) { import std.datetime, std.stdio; writeln(Clock.currTime(), ’ ’, stuff); } void main() { log("hello"); } • If not instantiated, no import • imports cached once realized • Generics faster to build, import • Less pressure on linker
  • 10. Approach to Safety c 2014– Andrei Alexandrescu. 10 / 47
  • 11. Memory Safety c 2014– Andrei Alexandrescu. 11 / 47 • All data is read with the type it was written • Eliminates unpleasant class of errors • Makes bugs reproducible • Preserves the integrity of the type system
  • 12. Challenge c 2014– Andrei Alexandrescu. 12 / 47 • System-level languages must: ◦ Forge pointers (linkers/loaders) ◦ Magically change type of memory (allocators/GCs) ◦ Recycle memory “early” ◦ Circumvent type system
  • 13. Attack c 2014– Andrei Alexandrescu. 13 / 47 • All of D can’t be safe • Define a safe subset • Safe subset usable for large portions or entire programs • Tagged with @safe attribute @safe double cube(double x) { return x * x * x; } • Unsafe functions tagged with @system @system void free(void*);
  • 14. But wait c 2014– Andrei Alexandrescu. 14 / 47 • Important case: safe functions with unknown/unprovable implementation ◦ fopen, malloc, isAlpha ◦ Small buffer optimization ◦ Tagged union implementation • Define attribute @trusted
  • 15. Rules c 2014– Andrei Alexandrescu. 15 / 47 • @safe functions cannot: ◦ call @system functions ◦ escape addresses of locals ◦ forge pointers ◦ cast pointers around ◦ do pointer arithmetic • N.B. Not all rules completely implemented ◦ Some on the conservative side ◦ A few details in flux
  • 16. Resulting setup c 2014– Andrei Alexandrescu. 16 / 47 • Low notational overhead: entire modules or portions thereof can be annotated • Deduction for generics • Application divided in: ◦ Safe part, uses GC, easy to write and debug ◦ Trusted part, encapsulated unsafe manipulation, proven by means of code review ◦ System part, non-encapsulated unsafe manipulation, only when solidly justified
  • 17. Approach to Purity c 2014– Andrei Alexandrescu. 17 / 47
  • 18. Thesis c 2014– Andrei Alexandrescu. 18 / 47 • Writing entire programs in pure style difficult • Writing fragments of programs in pure style easy, useful • + Easier to verify useful properties, debug • + Better code generation • − Challenge: interfacing pure and impure code
  • 19. Functional Factorial (yawn) c 2014– Andrei Alexandrescu. 19 / 47 ulong factorial(uint n) { return n <= 1 ? 1 : n * factorial(n - 1); } • It’s PSPACE! • Somebody should do hard time for this
  • 20. However, it’s pure c 2014– Andrei Alexandrescu. 20 / 47 pure ulong factorial(uint n) { return n <= 1 ? 1 : n * factorial(n - 1); } • Pure is good
  • 21. Functional Factorial, Fixed c 2014– Andrei Alexandrescu. 21 / 47 pure ulong factorial(uint n) { ulong crutch(uint n, ulong result) { return n <= 1 ? result : crutch(n - 1, n * result); } return crutch(n, 1); } • Threads state through as parameters • You know what? I don’t care for it
  • 22. Honest Factorial c 2014– Andrei Alexandrescu. 22 / 47 ulong factorial(uint n) { ulong result = 1; foreach (uint i = 2; i <= n; ++i) { result *= i; } return result; } • But no longer pure! • Well allow me to retort
  • 23.
  • 24. Pure is as pure does c 2014– Andrei Alexandrescu. 24 / 47 • “Pure functions always return the same result for the same arguments” • No reading and writing of global variables ◦ (Global constants okay) • No calling of impure functions • Who said anything about local, transient state inside the function?
  • 25. Transitive State c 2014– Andrei Alexandrescu. 25 / 47 pure void reverse(T)(T[] a) { foreach (i; 0 .. data.length / 2) { swap(data[i], data[$ - i - 1]); } } • Possibility: disallow • More useful: relaxed rule • Operate with transitive closure of state reachable through parameter • Not functional pure, but an interesting superset • No need for another annotation, it’s all in the signature!
  • 26. User-defined types c 2014– Andrei Alexandrescu. 26 / 47 pure BigInt factorial(uint n) { BigInt result = 1; for (; n > 1; --n) { result *= n; } return result; } • Works, but not in released version • Most of stdlib “purified”
  • 27. Aftermath c 2014– Andrei Alexandrescu. 27 / 47 • If parameters reach mutable state: ◦ Relaxed pure—no globals, no I/O, no impure calls • If parameters can’t reach mutable state: ◦ “Haskell-grade” observed purity ◦ Yet imperative implementation possible ◦ As long as it’s local only
  • 28. The Generative Connection: mixin c 2014– Andrei Alexandrescu. 28 / 47
  • 29. Generative programming c 2014– Andrei Alexandrescu. 29 / 47 • In brief: code that generates code • Generic programming often requires algorithm specialization • Specification often present in a DSL
  • 30. Embedded DSLs c 2014– Andrei Alexandrescu. 30 / 47 Force into host language’s syntax?
  • 31. Embedded DSLs c 2014– Andrei Alexandrescu. 31 / 47 • Formatted printing?
  • 32. Embedded DSLs c 2014– Andrei Alexandrescu. 31 / 47 • Formatted printing? • Regular expressions?
  • 33. Embedded DSLs c 2014– Andrei Alexandrescu. 31 / 47 • Formatted printing? • Regular expressions? • EBNF?
  • 34. Embedded DSLs c 2014– Andrei Alexandrescu. 31 / 47 • Formatted printing? • Regular expressions? • EBNF? • PEG?
  • 35. Embedded DSLs c 2014– Andrei Alexandrescu. 31 / 47 • Formatted printing? • Regular expressions? • EBNF? • PEG? • SQL?
  • 36. Embedded DSLs c 2014– Andrei Alexandrescu. 31 / 47 • Formatted printing? • Regular expressions? • EBNF? • PEG? • SQL? • . . . Pasta for everyone!
  • 37. Embedded DSLs c 2014– Andrei Alexandrescu. 32 / 47 Here: use with native grammar Process during compilation Generate D code accordingly
  • 38. Compile-Time Evaluation c 2014– Andrei Alexandrescu. 33 / 47 • A large subset of D available for compile-time evaluation ulong factorial(uint n) { ulong result = 1; for (; n > 1; --n) result *= n; return result; } ... auto f1 = factorial(10); // run-time static f2 = factorial(10); // compile-time
  • 39. Code injection with mixin c 2014– Andrei Alexandrescu. 34 / 47 mixin("writeln("hello, world");"); mixin(generateSomeCode()); • Not as glamorous as AST manipulation but darn effective • Easy to understand and debug • Now we have compile-time evaluation AND mixin. . .
  • 40. c 2014– Andrei Alexandrescu. 35 / 47 Wait a minute!
  • 41. Example: bitfields in library c 2014– Andrei Alexandrescu. 36 / 47 struct A { int a; mixin(bitfields!( uint, "x", 2, int, "y", 3, uint, "z", 2, bool, "flag", 1)); } A obj; obj.x = 2; obj.z = obj.x;
  • 42. Example: boilerplate c 2014– Andrei Alexandrescu. 37 / 47 string forward(string p, string[] names...) { string r; foreach (n; names) { r ~= "static if (hasMember!(typeof("~p~ "), ‘"~n~"‘)" ~ ") auto ref "~n~ "(T_...)(T_ t_) { return "~ p~"."~n~"(t_); }n"; } return r; }
  • 43. Example: boilerplate c 2014– Andrei Alexandrescu. 38 / 47 struct A { int fun(int, string) { ... } int gun(int, string, double) { ... } } struct B { A a; //pragma(msg, forward("a", "fun", "gun")); mixin(forward("a", "fun", "gun")); }
  • 44. Parser c 2014– Andrei Alexandrescu. 39 / 47 import pegged.grammar; // by Philippe Sigaud mixin(grammar(" Expr < Factor AddExpr* AddExpr < (’+’/’-’) Factor Factor < Primary MulExpr* MulExpr < (’*’/’/’) Primary Primary < Parens / Number / Variable / ’-’ Primary Parens < ’(’ Expr ’)’ Number <~ [0-9]+ Variable <- Identifier "));
  • 45. Usage c 2014– Andrei Alexandrescu. 40 / 47 // Parsing at compile-time: static parseTree1 = Expr.parse( "1 + 2 - (3*x-5)*6"); pragma(msg, parseTree1.capture); // Parsing at run-time: auto parseTree2 = Expr.parse(readln()); writeln(parseTree2.capture);
  • 46. Scaling up c 2014– Andrei Alexandrescu. 41 / 47 1000 lines of D grammar → 3000 lines D parser
  • 47. c 2014– Andrei Alexandrescu. 42 / 47 Highly integrated lex+yacc
  • 48. c 2014– Andrei Alexandrescu. 43 / 47 What about regexen?
  • 49. Compile-time regular expressions c 2014– Andrei Alexandrescu. 44 / 47 • GSoC project by Dmitry Olshansky, merged into std • Fully UTF capable, no special casing for ASCII • Two modes sharing the same backend: auto r1 = regex("^.*/([^/]+)/?$"); static r2 = ctRegex!("^.*/([^/]+)/?$"); • Run-time version uses intrinsics in a few places • Static version generates specialized automaton, then compiles it
  • 50.
  • 51. Summary c 2014– Andrei Alexandrescu. 46 / 47
  • 52. Summary c 2014– Andrei Alexandrescu. 47 / 47 • Turtles • Safe subset • Pure functions • Generative programming