1、JavaScript WeakRefs andTC39 我 Daniel Ehrenberg littledan Delegate in TC39家Les Roquetes del Garraf, Europe工作Embedded WebKit and Chromium developmentMesa and GStreamer driversCSS, ARIA, WebAssembly, MathML, JavaScriptstandards+implementation in web WeakRefs:Motivation anduse In-memory cache Remote res
2、ources with identifiers Cache locally to avoid repeat lookups Tradeoff: Cache hit rate vs memory usage Idea: Hold things in the cache if the resource is being used Remove from cache when its garbage collected? (May be combined with LRU)WebAssembly memory management WebAssembly is based on a big Type
3、dArray: malloc and free inside How can allocations in WebAssembly be exposed to JavaScript? Object wrapping a range in the TypedArray Expect user to explicitly call obj.free() method? Too hard. Automatically free when no longer referenced?Avoiding stranded resources File handles, sockets, etc When n
4、o one references them:Resource leak until end of process Possible solution:Trigger error/log warning when a resource is Common capability: connecting to GC These examples require tying into GC:weak references and finalizers JavaScript doesnt give that access! Why? Interoperability/stability New trad
5、eoffs with new information Eventually, committee was convinced that we should add WeakRefs WebAssembly use case was especially persuasive JS devs have been telling us this is needed for decades Now, the proposal is at Stage 3 in TC39!Who is TC39? A committee of Ecma, with JS developers JavaScript en
6、gines Transpilers Frameworks, libraries Academics Major websites/app platforms Now, some Chinese companies! etcMeetings Every two months For three days Discuss language changes Seek consensus on proposalStage advancementTC39 stages Stage 1: An idea under discussion Stage 2: We want to do this, and w
7、e have a first draft.On the roadmap Stage 3: Basically final draft; ready to go Stage 4: 2+ implementations, tests Consensus-based decision-making TC39 doesnt vote on what the language will be (rarely vote on technicalities/procedural matters) TC39 is consensus-seeking We work together to meet every
8、ones goals Does anyone object to stage advancement? Objections must have rationale, appropriate to stage Technical concerns should be raised Consensus-based decision-making Consensus is established at some point,but could always be revisited with new consensus. Established consensus cannot be vetoed
9、/outvoted later Technical concerns should be raised as early as possible We assume good faith:True motivations are given for objectionsWorking together with trust All TC39 delegates are considered Stage 4 features2+ implementations, tests BigInt: Stage 4!const x = 2 * 53; x = 9007199254740992const y
10、 = x + 1; y = const x = 2n * 53n; x = 9007199254740992nconst y = x + 1n; y = const x = 2n * 53n; x = 9007199254740992nconst y = x + 1n; y = 9007199254740993nnstands for BigIDynamic import():Stage 4Domenic DlittledanIntl.RelativeTimeFormat:Stage 4Zibi BIntl.RelativeTimeFormat Shipped in Chrome and Fi
11、refoxlet rtf = new Intl.RelativeTimeFormat(en);rtf.format(100, day);/ in 100 daysnew Intl.RelativeTimeFormat(zh).format(100, day)/ 100天后Optional chaining:Stage 4Daniel RosenwasserClaude PacheGabriel IsenbergDustin Slet x = foo?.bar;/ Equivalent to.OptionalPropertyAccesslet x = (foo != null & foo !=
12、undefined) ?foo.bar :undefined;Collaboration with TypeScript in TC39 TypeScript saw many feature requests for ?. TC39s effort was going slowly TypeScript aligns with JavaScript runtime semantics TypeScript type system erased at compile time JS defines runtime semantics Daniel Rosenwasser, TypeScript
13、 PM, came in push it forward Based on TC39 success, ?. shipping in TS 3.7 Now, ?. will be part of ESNullish coalescing:Stage 4Daniel RosenwasserGabriel Ilet x = foo() ? bar();/ Equivalent to.NullishCoalescinglet tmp = foo();let x = (tmp != null & tmp != undefined) ?tmp :bar();Stage 3 featuresBasical
14、ly final draft; ready to WeakRefs:Stage 3Sathya GunasekaranTill SchneidereitMark MillerDean TRead consistencyconst w = new WeakRef(someObject);.if (w.deref() w.deref().foo(); / w.deref() here can not failPrivate fields andmethods:Stage Why? Private methods encapsulate behavior You can access private
15、 fields insideprivate methodsclass Counter extends HTMLElement #x = 0;connectedCallback() this.#render();#render() this.textContent =this.#x.toString();# is the new _for strong encapsulationWhy strong encapsulation? Not all code needs this, but Library/framework authors may want to provide a stable
16、API Common techniques can be hacked into_properties TypeScript private In practice, users depend on these internals, and then library authors cannotevolve beyond their old details Node.js and Moment.js hit these issues Library users benefit from good class PublicCounter class PrivateCounter _x = 0;#
17、x = 0;let c = new PublicCounter();let p = new PrivateCounter();console.log(c._x);/ 0console.log(p.#x);/ SyntaxErrorStage Why not private keyword? In languages with types:obj.x can check whether x is private by looking at the type of obj JavaScript is dynamically typed private vs public distinction n
18、eeded at access point,not just definition # as part of the name was the cleanest, simplest solution we found We thought about many alternatives over 20 years; ask me later about anyfurther Stage 2 featuresWe want to do this, and we have a first Decorators: Stage 2Yehuda KatzRon BSyntax abstraction f
19、or attrs/props in Web Components/ Salesforce abstraction/ Polymer abstractionimport api from salesforce;class XCustom extends PolymerElement property( type: String, reflect: trueclass InputAddress extends HTMLElement )api address = ;address = ;Example of using decorators to improve ergonomics.Tempor
20、al: Stage 2Maggie PintPhilipp DWhat time did this presentation start in Berlin?let startDateTime =/ Temporal.DateTimeTemporal.now.dateTime().with( hour: 14, minute: 00 );let startAbsolute =/ Temporal.AbsolutestartDateTime.inTimeZone(Temporal.now.timeZone();let localizedToBerlin =/ Temporal.DateTimes
21、tartAbsolute.inTimeZone(Europe/Berlin);Intl.DateTimeFormat(zh, hour: numeric, minute: numeric ).format(localizedToBerlin);/ 上午7:Stage 1 featuresAn idea under Pipeline operator:Stage 1Gilbert GarzaJ.S. ChoiJames DiGordinary.jsimport doubleSay, capitalize, exclaim from ./library.js;library.jslet resul
22、t =exclaim(capitalize(doubleSay(hello);/ = Hello, hello!export function doubleSay(str) return str + , + str;with-pipeline.jsexport function capitalize(str) import doubleSay, capitalize, exclaim from ./library.js;let result = hello| doubleSayreturn str0.toUpperCase() +str.substring(1);export function
23、 exclaim(str) return str + !;| capitalize| exclaim; = Hello, hello!Records and Tuples:Stage 1Robin RicardRichard Bconst marketData = # ticker: AAPL, lastPrice: 195.855 ,# ticker: SPY, lastPrice: 286.53 ,;Operator overloading:Stage Vector overloading: Usage/ Usage exampleimport Vector from ./vector.m
24、js;with operators from Vector;new Vector(1, 2, 3) + new Vector(4, 5, 6)3 * new Vector(1, 2, 3)/ = new Vector(5, 7, 9)/ = new Vector(3, 6, 9)new Vector(1, 2, 3) = new Vector(1, 2, 3) / = true(new Vector(1, 2, 3)1 / = 2Stage 0 featuresNot even really at a stage!BigDecimal: Stage 0Andrew P“Why are Numb
25、ers brokenin JS?”Problem and solution (?)/ Number (binary 64-bit floating point)js 0.1 + 0.2=0.30000000000000004/ BigDecimal (?)js 0.1d + 0.2d=WeakRef andFinalizationGroup APIWeakRef let weakRef = new WeakRef(obj) weakRef.deref()/ obj or In-memory FinalizationGroup function cleanupCallback(holdingsI
26、terator) /* */ let group = new FinalizationGroup(cleanupCallback) group.register(obj, holdings, unregisterToken) group.unregister(unregisterToken) /* implicitly */cleanupCallback(holdingsSymbol.iterator()Post-mortem finalization The FinalizerGroups callback iterator has holdings, not objectgroup.reg
27、ister(obj, holdings) API doesnt provide access to object after it is collected No resurrection/bringing-back-from-the-dead Bringing an object back alive is causes problems;this API avoids In-memory cache withtombstone cleanupStranded resource WebAssembly memory My suggestions forcontributing to TC39
28、 atdifferent Contributing to existing proposals The thing that you want to do may already be a proposal Proposal list https:/ Contributions welcome! Proposals often stalled/slow because more work Stage 0/1 Document use cases Begin seeking feedback, and keep doing it the whole time! Discuss the probl
29、em space/big-picture questions Prototype implementations:unstable, rough, maybe Stage 2 Nail down the proposal details, from discussion and prototyping Draft documentation and tests in the proposal repo Prototype implementations:Ideally nearing completion, but still considered unstable Distribute th
30、e prototype more broadly to gather more solid Stage 3 Upstream tests into test262 and fill in any gaps. Place documentation in MDN and fill in the gaps Implement in engines and consider shipping Integrate usage into environments (e.g., the Web, Node.js) Distribute high-level explanations more broadl
31、y to Stage 4 Ideally nothing! Tie up any loose ends in the spec language Implement in trailing engines if needed Further changes: separate PRs/WeakRefs history anddevelopment in TCA proposal for ES6 in Progression in TC39 stage process Stage 1: March 2016 However, there was strong resistance More pe
32、ople are convinced about WebAssembly use case Stage 2: March 2018 Stage 3: June 2019 As the proposal progressed, more co-champions/WeakRef behavior WeakRef behavior invariants Problem: Different JS implementations have different GCs. WeakRefs will go undefined at different times; FinalizationGroup c
33、leanup will happen at different times How can one program works across different JS engines? Non-answer: Require everyone to use the same GC Answer: Define certain common properties among GCConsistency of multiple .deref() calls In a straight line of code,.deref() either returns theconst w = new Wea
34、kRef(obj);object, or undefined, not a mix Objects may be collected onlywhen yielding to the event loop/ .if (w.deref() w.deref().foo();/ w.deref() here can not Definition of Further invariants All the WeakRefs pointing to the same object turn to undefined at the sametime, but the FinalizationGroup c
35、allback may be delayed until later. The unregisterToken is treated as a weak reference, not strong. If a strongly connected component of the object graph dies all at once, thenno finalizer callbacks are called. See GitHub issues for Participating in TCParticipating internationally Many TC39 members
36、are facing similar issues: English is a second language You can participate with mostly written communication Live outside the US Many delegates live in Europe Unable to attend most TC39 meetings in person Instead, join by video call TC39s code of conduct prohibits discrimination on nationality Many
37、 TC39 members want to increase international participation TC39 participants represent ideas and organizations, not Joining TC39 Join TC39 as a member by joining Ecma Joining Ecma requires: Signing IPR forms Typical Ecma RAND policy TC39-specific royalty-free agreement Paying membership fee TC39 del
38、egates represent member organizations Companies considering joining can provisionally attend TC39 asprospective Participating asynchronously on GitHub Most tasks dont take place in meetings:Most important technical work happens on GitHub Work on GitHub: Some of the discussion about design Specificat
39、ion text Documentation Tests Implementations Non-members can contribute on GitHub! We encourage it. Just sign non-member IPR form Meeting notes are published to GitHub Only members can take part in meetings and consensus TC39 changes over Older TC39 mode Specification: Big MS Word doc Communication:
40、 Meetings and es-discuss list Large, occasional specification; no Invited expertsIntegrating the traditional and the new values First-principles reasoning Practicality The future is bigger than the past Integration into the existing ecosystem Long, complete design cycles Rigorous debate Quick, incremental iteration Letting points be made without interruption Actively seeking out feedback Welcoming participants who join Language specialists/theorists More JS/frontend dev participationAll of these are useful,complementary perspectives