Extensible Operators and Literals for JavaScript

Brendan Eich
Brendan EichCEO/President, Brave Software, Inc. at Brave Software, Inc.
Operators and Literals
Brendan Eich
brendan.eich@gmail.com
@BrendanEich
Ecma TC39 May 2015
Value Types Review
• Int64, Uint64 (note capitalized names)
• Int32x4, Int32x8, etc. (SIMD)
• Float32 (to/from Float32Array today)
• Float32x4, Float32x8 (SIMD)
• Bignum
• Decimal (long-time TC39 goal for IBM: self-hosted)
• Complex
• Rational
Value Types Review, 2
var ColorType =
ValueType(Symbol(“Color"), // or Symbol.for?
{r: Uint8, g: Uint8, b: Uint8, a: Uint8});
ColorType.prototype.average = function() {
return (this.r + this.g + this.b) / 3;
};
var color = ColorType({r: 22, g: 44, b: 66, a: 88});
color.average() // yields 44
assert(typeof color == “color”); // un-capitalized!
// ISSUE: some web JS hardcodes known typeof results
Literal Syntax
• Int64(0) ==> 0L // as in C#
• Uint64(0) ==> 0UL // as in C#
• Float32(0) ==> 0f // as in C#
• Bignum(0) ==> 0n // avoid i/I
• Decimal(0) ==> 0m // or M, C/F#
• Lexically transpose, e.g., 0L into L(0)
• Sanity: map short suffix to constructor name
• Reflect.defineSuffix(‘L’, Int64)
• or literalSuffixTable.L(‘0’) h/t @littledan
• or use imported names only? h/t @sebmarkbåge
Overloadable Operators
•| ^ &
•==
•< <=
•<< >> >>>
•+ -
•* / %
•unary- unary+ boolean-test!! ~
• ISSUES: lost invariants in spite of overloadable subset
Preserving Boolean Algebra
• != and ! are not overloadable, to preserve
identities including
• X ? A : B <=> !X ? B : A
• !(X && Y) <=> !X || !Y
• !(X || Y) <=> !X && !Y
• X != Y <=> !(X == Y)
• ISSUE: implicit-!!(x) vs. !(!x)
Preserving Relational Relations
• > and >= are derived from < and <= as follows:
• A > B <=> B < A
• A >= B <=> B <= A
• We provide <= in addition to < rather than derive
A <= B from !(B < A) in order to allow the <=
overloading to match the same value object’s ==
semantics
• And for unordered values (NaNs)
Strict Equality Operators
• The strict equality operators, === and !==,
cannot be overloaded
• They work on frozen-by-definition value
objects via a structural recursive strict
equality test (beware, NaN !== NaN)
• Same-object-reference remains a fast-path
optimization
Why Not Double Dispatch?
• Left-first asymmetry (v value, n number):
• v + n ==> v.add(n)
• n + v ==> v.radd(n)
• Anti-modular: exhaustive other-operand type
enumeration required in operator method
bodies
• Consequent loss of compositionality:
Complex and Rational cannot be
composed to make Ratplex without
modifying source or wrapping in proxies
Cacheable Multimethods
• Proposed in 2009 by Christian Plesner Hansen
(Google) in es-discuss
• Avoids double-dispatch drawbacks from last slide:
binary operators implemented by 2-ary functions
for each pair of types
• Supports Polymorphic Inline Cache (PIC)
optimizations (Christian was on theV8 team)
• Background reading: [Chambers 1992]
Binary Operator Example
• For v + u with either a value type instance:
• Let p = v.[[Get]](@@ADD)
• If p is not an OperatorSet, throw a TypeError
• Let q = u.[[Get]](@@ADD_R)
• If q is not an OperatorSet, throw a TypeError
• Let r = p.join(q) (r an Array)
• If r.length != 1 throw a TypeError
• Let f = r[0]; if f is not a function, throw
• Evaluate f(v, u) and return the result
Reflect API Example
function addPointAndNumber(a, b) {
return Point(a.x + b, a.y + b);
}
Reflect.defineOperator('+', addPointAndNumber, Point, Number);
function addNumberAndPoint(a, b) {
return Point(a + b.x, a + b.y);
}
Reflect.defineOperator('+', addNumberAndPoint, Number, Point);
function addPoints(a, b) {
return Point(a.x + b.x, a.y + b.y);
}
Reflect.defineOperator('+', addPoints, Point, Point);
// NB: Calling defineOperator with 3 args defines unary operator
Subclassing Problem
• Given class A and class B extends A,
• Reflect.defineOperator(‘+’, addAA, A, A);
• Reflect.defineOperator(‘+', addBB, B, B);
• a1 + a2 must select addAA
• a1 + b2 and b1 + a2 must select addAA
• b1 + b2 must select addBB not addAA
• How should OperatorSet implement this?
Subclassing Solution
• OperatorSet stores (depth, method) pairs
• Reflect.defineOperator(‘+', addBB, B, B);
copies B’s initial @@ADD and @@ADD_R operator-
sets from A’s @@ADD and @@ADD_R sets
• OperatorSet.join, on finding intersection not a
singleton, breaks tie by maximum prototype depth:
(2, addBB) > (1, addAA)
1 of 14

Recommended

JS Responsibilities by
JS ResponsibilitiesJS Responsibilities
JS ResponsibilitiesBrendan Eich
34.9K views34 slides
Value objects in JS - an ES7 work in progress by
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressBrendan Eich
22.7K views14 slides
Value Objects, Full Throttle (to be updated for spring TC39 meetings) by
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
16K views20 slides
Web futures by
Web futuresWeb futures
Web futuresBrendan Eich
8.7K views40 slides
Int64 by
Int64Int64
Int64Brendan Eich
12.8K views17 slides
Fluent14 by
Fluent14Fluent14
Fluent14Brendan Eich
8.9K views40 slides

More Related Content

What's hot

Railroading into Scala by
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
511 views35 slides
Overview of c (2) by
Overview of c (2)Overview of c (2)
Overview of c (2)Aayush Patel
352 views41 slides
Aspdot by
AspdotAspdot
AspdotNishad Nizarudeen
17 views94 slides
Algebraic Thinking for Evolution of Pure Functional Domain Models by
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
966 views67 slides
Yin Yangs of Software Development by
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software DevelopmentNaveenkumar Muguda
32 views137 slides
Deriving Scalaz by
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
2.4K views19 slides

What's hot(20)

Railroading into Scala by Nehal Shah
Railroading into ScalaRailroading into Scala
Railroading into Scala
Nehal Shah511 views
Algebraic Thinking for Evolution of Pure Functional Domain Models by Debasish Ghosh
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain Models
Debasish Ghosh966 views
Deriving Scalaz by nkpart
Deriving ScalazDeriving Scalaz
Deriving Scalaz
nkpart2.4K views
Basic Operator, String and Characters in Swift. by HSIEH CHING-FAN
Basic Operator, String and Characters in Swift.Basic Operator, String and Characters in Swift.
Basic Operator, String and Characters in Swift.
HSIEH CHING-FAN540 views
Functional Programming by Yuan Wang
Functional ProgrammingFunctional Programming
Functional Programming
Yuan Wang609 views
First-Class Patterns by John De Goes
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes3.3K views
Refinement Types for Haskell by Martin Ockajak
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
Martin Ockajak100 views
Architectural Patterns in Building Modular Domain Models by Debasish Ghosh
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain Models
Debasish Ghosh1.3K views
Power of functions in a typed world by Debasish Ghosh
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh909 views

Viewers also liked

Mozilla Research Party Talk by
Mozilla Research Party TalkMozilla Research Party Talk
Mozilla Research Party TalkBrendan Eich
3.1K views33 slides
Containers in a File by
Containers in a FileContainers in a File
Containers in a FileOpenVZ
766 views19 slides
PFcache - LinuxCon 2015 by
PFcache - LinuxCon 2015PFcache - LinuxCon 2015
PFcache - LinuxCon 2015OpenVZ
846 views23 slides
Capitol js by
Capitol jsCapitol js
Capitol jsBrendan Eich
4.8K views118 slides
Paren free by
Paren freeParen free
Paren freeBrendan Eich
2.3K views25 slides
Fluent15 by
Fluent15Fluent15
Fluent15Brendan Eich
8.1K views15 slides

Viewers also liked(16)

Mozilla Research Party Talk by Brendan Eich
Mozilla Research Party TalkMozilla Research Party Talk
Mozilla Research Party Talk
Brendan Eich3.1K views
Containers in a File by OpenVZ
Containers in a FileContainers in a File
Containers in a File
OpenVZ766 views
PFcache - LinuxCon 2015 by OpenVZ
PFcache - LinuxCon 2015PFcache - LinuxCon 2015
PFcache - LinuxCon 2015
OpenVZ846 views
Mozilla's NodeConf talk by Brendan Eich
Mozilla's NodeConf talkMozilla's NodeConf talk
Mozilla's NodeConf talk
Brendan Eich3.1K views
Always bet on JS - Finjs.io NYC 2016 by Brendan Eich
Always bet on JS - Finjs.io NYC 2016Always bet on JS - Finjs.io NYC 2016
Always bet on JS - Finjs.io NYC 2016
Brendan Eich1.9K views
The Same-Origin Saga by Brendan Eich
The Same-Origin SagaThe Same-Origin Saga
The Same-Origin Saga
Brendan Eich2.9K views
3日時間をもらったのでTypeScriptを触ってみた by Yasushi Kato
3日時間をもらったのでTypeScriptを触ってみた3日時間をもらったのでTypeScriptを触ってみた
3日時間をもらったのでTypeScriptを触ってみた
Yasushi Kato28K views

Similar to Extensible Operators and Literals for JavaScript

An introduction to functional programming with Swift by
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
836 views37 slides
Categories for the Working C++ Programmer by
Categories for the Working C++ ProgrammerCategories for the Working C++ Programmer
Categories for the Working C++ ProgrammerPlatonov Sergey
1.1K views28 slides
Structure on a freeform world by
Structure on a freeform worldStructure on a freeform world
Structure on a freeform worldIkai (藍奕凱) Lan
327 views58 slides
Python basics by
Python basicsPython basics
Python basicsTIB Academy
102 views30 slides
Java introduction by
Java introductionJava introduction
Java introductionSamsung Electronics Egypt
746 views61 slides
Αλγόριθμοι by
Αλγόριθμοι Αλγόριθμοι
Αλγόριθμοι Ρεβέκα Θεοδωροπούλου
524 views19 slides

Similar to Extensible Operators and Literals for JavaScript(20)

An introduction to functional programming with Swift by Fatih Nayebi, Ph.D.
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
Categories for the Working C++ Programmer by Platonov Sergey
Categories for the Working C++ ProgrammerCategories for the Working C++ Programmer
Categories for the Working C++ Programmer
Platonov Sergey1.1K views
Introduction to web programming for java and c# programmers by @drpicox by David Rodenas
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
David Rodenas475 views
JavaScript Foundations Day1 by Troy Miles
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1
Troy Miles677 views
Transferring Software Testing Tools to Practice (AST 2017 Keynote) by Tao Xie
Transferring Software Testing Tools to Practice (AST 2017 Keynote)Transferring Software Testing Tools to Practice (AST 2017 Keynote)
Transferring Software Testing Tools to Practice (AST 2017 Keynote)
Tao Xie390 views
Programming in java basics by LovelitJose
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose90 views
Functional Programming in Swift by Saugat Gautam
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam1.2K views
C sharp part 001 by Ralph Weber
C sharp part 001C sharp part 001
C sharp part 001
Ralph Weber746 views
Data Analysis and Programming in R by Eshwar Sai
Data Analysis and Programming in RData Analysis and Programming in R
Data Analysis and Programming in R
Eshwar Sai986 views
Chapter 2&3 (java fundamentals and Control Structures).ppt by henokmetaferia1
Chapter 2&3 (java fundamentals and Control Structures).pptChapter 2&3 (java fundamentals and Control Structures).ppt
Chapter 2&3 (java fundamentals and Control Structures).ppt
henokmetaferia13 views
TypeScript Presentation - Jason Haffey by Ralph Johnson
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
Ralph Johnson193 views
OSCON Presentation: Developing High Performance Websites and Modern Apps with... by Doris Chen
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Doris Chen4.1K views

Recently uploaded

ShortStory_qlora.pptx by
ShortStory_qlora.pptxShortStory_qlora.pptx
ShortStory_qlora.pptxpranathikrishna22
5 views10 slides
Agile 101 by
Agile 101Agile 101
Agile 101John Valentino
9 views20 slides
Sprint 226 by
Sprint 226Sprint 226
Sprint 226ManageIQ
10 views18 slides
HarshithAkkapelli_Presentation.pdf by
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
12 views16 slides
Using Qt under LGPL-3.0 by
Using Qt under LGPL-3.0Using Qt under LGPL-3.0
Using Qt under LGPL-3.0Burkhard Stubert
13 views11 slides
Software evolution understanding: Automatic extraction of software identifier... by
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...Ra'Fat Al-Msie'deen
10 views33 slides

Recently uploaded(20)

Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ10 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana16 views
Myths and Facts About Hospice Care: Busting Common Misconceptions by Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller42 views
Understanding HTML terminology by artembondar5
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminology
artembondar56 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok15 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254556 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan6 views

Extensible Operators and Literals for JavaScript

  • 1. Operators and Literals Brendan Eich brendan.eich@gmail.com @BrendanEich Ecma TC39 May 2015
  • 2. Value Types Review • Int64, Uint64 (note capitalized names) • Int32x4, Int32x8, etc. (SIMD) • Float32 (to/from Float32Array today) • Float32x4, Float32x8 (SIMD) • Bignum • Decimal (long-time TC39 goal for IBM: self-hosted) • Complex • Rational
  • 3. Value Types Review, 2 var ColorType = ValueType(Symbol(“Color"), // or Symbol.for? {r: Uint8, g: Uint8, b: Uint8, a: Uint8}); ColorType.prototype.average = function() { return (this.r + this.g + this.b) / 3; }; var color = ColorType({r: 22, g: 44, b: 66, a: 88}); color.average() // yields 44 assert(typeof color == “color”); // un-capitalized! // ISSUE: some web JS hardcodes known typeof results
  • 4. Literal Syntax • Int64(0) ==> 0L // as in C# • Uint64(0) ==> 0UL // as in C# • Float32(0) ==> 0f // as in C# • Bignum(0) ==> 0n // avoid i/I • Decimal(0) ==> 0m // or M, C/F# • Lexically transpose, e.g., 0L into L(0) • Sanity: map short suffix to constructor name • Reflect.defineSuffix(‘L’, Int64) • or literalSuffixTable.L(‘0’) h/t @littledan • or use imported names only? h/t @sebmarkbåge
  • 5. Overloadable Operators •| ^ & •== •< <= •<< >> >>> •+ - •* / % •unary- unary+ boolean-test!! ~ • ISSUES: lost invariants in spite of overloadable subset
  • 6. Preserving Boolean Algebra • != and ! are not overloadable, to preserve identities including • X ? A : B <=> !X ? B : A • !(X && Y) <=> !X || !Y • !(X || Y) <=> !X && !Y • X != Y <=> !(X == Y) • ISSUE: implicit-!!(x) vs. !(!x)
  • 7. Preserving Relational Relations • > and >= are derived from < and <= as follows: • A > B <=> B < A • A >= B <=> B <= A • We provide <= in addition to < rather than derive A <= B from !(B < A) in order to allow the <= overloading to match the same value object’s == semantics • And for unordered values (NaNs)
  • 8. Strict Equality Operators • The strict equality operators, === and !==, cannot be overloaded • They work on frozen-by-definition value objects via a structural recursive strict equality test (beware, NaN !== NaN) • Same-object-reference remains a fast-path optimization
  • 9. Why Not Double Dispatch? • Left-first asymmetry (v value, n number): • v + n ==> v.add(n) • n + v ==> v.radd(n) • Anti-modular: exhaustive other-operand type enumeration required in operator method bodies • Consequent loss of compositionality: Complex and Rational cannot be composed to make Ratplex without modifying source or wrapping in proxies
  • 10. Cacheable Multimethods • Proposed in 2009 by Christian Plesner Hansen (Google) in es-discuss • Avoids double-dispatch drawbacks from last slide: binary operators implemented by 2-ary functions for each pair of types • Supports Polymorphic Inline Cache (PIC) optimizations (Christian was on theV8 team) • Background reading: [Chambers 1992]
  • 11. Binary Operator Example • For v + u with either a value type instance: • Let p = v.[[Get]](@@ADD) • If p is not an OperatorSet, throw a TypeError • Let q = u.[[Get]](@@ADD_R) • If q is not an OperatorSet, throw a TypeError • Let r = p.join(q) (r an Array) • If r.length != 1 throw a TypeError • Let f = r[0]; if f is not a function, throw • Evaluate f(v, u) and return the result
  • 12. Reflect API Example function addPointAndNumber(a, b) { return Point(a.x + b, a.y + b); } Reflect.defineOperator('+', addPointAndNumber, Point, Number); function addNumberAndPoint(a, b) { return Point(a + b.x, a + b.y); } Reflect.defineOperator('+', addNumberAndPoint, Number, Point); function addPoints(a, b) { return Point(a.x + b.x, a.y + b.y); } Reflect.defineOperator('+', addPoints, Point, Point); // NB: Calling defineOperator with 3 args defines unary operator
  • 13. Subclassing Problem • Given class A and class B extends A, • Reflect.defineOperator(‘+’, addAA, A, A); • Reflect.defineOperator(‘+', addBB, B, B); • a1 + a2 must select addAA • a1 + b2 and b1 + a2 must select addAA • b1 + b2 must select addBB not addAA • How should OperatorSet implement this?
  • 14. Subclassing Solution • OperatorSet stores (depth, method) pairs • Reflect.defineOperator(‘+', addBB, B, B); copies B’s initial @@ADD and @@ADD_R operator- sets from A’s @@ADD and @@ADD_R sets • OperatorSet.join, on finding intersection not a singleton, breaks tie by maximum prototype depth: (2, addBB) > (1, addAA)