Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

events: refactor to use more primordials #36304

Closed
wants to merge 13 commits into from
Closed
50 changes: 31 additions & 19 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,19 @@
'use strict';

const {
ArrayPrototypeForEach,
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
ArrayPrototypePush,
ArrayPrototypeShift,
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
ArrayPrototypeSlice,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
Boolean,
Error,
ErrorCaptureStackTrace,
FunctionPrototypeBind,
FunctionPrototypeCall,
MathMin,
NumberIsNaN,
ObjectCreate,
Expand All @@ -39,6 +48,7 @@ const {
ReflectApply,
ReflectOwnKeys,
String,
StringPrototypeSplit,
Symbol,
SymbolFor,
SymbolAsyncIterator
Expand Down Expand Up @@ -81,7 +91,7 @@ const lazyDOMException = hideStackFrames((message, name) => {


function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
FunctionPrototypeCall(EventEmitter.init, this, opts);
}
module.exports = EventEmitter;
module.exports.once = once;
Expand Down Expand Up @@ -173,7 +183,7 @@ EventEmitter.setMaxListeners =
isEventTarget = require('internal/event_target').isEventTarget;

// Performance for forEach is now comparable with regular for-loop
eventTargets.forEach((target) => {
ArrayPrototypeForEach(eventTargets, (target) => {
if (isEventTarget(target)) {
target[kMaxEventTargetListeners] = n;
target[kMaxEventTargetListenersWarned] = false;
Expand Down Expand Up @@ -224,7 +234,7 @@ function addCatch(that, promise, type, args) {
const then = promise.then;

if (typeof then === 'function') {
then.call(promise, undefined, function(err) {
FunctionPrototypeCall(then, promise, undefined, function(err) {
// The callback is called with nextTick to avoid a follow-up
// rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, that, err, type, args);
Expand Down Expand Up @@ -281,7 +291,7 @@ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
function identicalSequenceRange(a, b) {
for (let i = 0; i < a.length - 3; i++) {
// Find the first entry of b that matches the current entry of a.
const pos = b.indexOf(a[i]);
const pos = ArrayPrototypeIndexOf(b, a[i]);
if (pos !== -1) {
const rest = b.length - pos;
if (rest > 3) {
Expand Down Expand Up @@ -310,16 +320,18 @@ function enhanceStackTrace(err, own) {
} catch {}
const sep = `\nEmitted 'error' event${ctorInfo} at:\n`;

const errStack = err.stack.split('\n').slice(1);
const ownStack = own.stack.split('\n').slice(1);
const errStack =
ArrayPrototypeSlice(StringPrototypeSplit(err.stack, '\n'), 1);
const ownStack =
ArrayPrototypeSlice(StringPrototypeSplit(own.stack, '\n'), 1);

const [ len, off ] = identicalSequenceRange(ownStack, errStack);
if (len > 0) {
ownStack.splice(off + 1, len - 2,
' [... lines matching original stack trace ...]');
ArrayPrototypeSplice(ownStack, off + 1, len - 2,
' [... lines matching original stack trace ...]');
}

return err.stack + sep + ownStack.join('\n');
return err.stack + sep + ArrayPrototypeJoin(ownStack, '\n');
}

EventEmitter.prototype.emit = function emit(type, ...args) {
Expand All @@ -343,7 +355,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
const capture = {};
ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit);
ObjectDefineProperty(er, kEnhanceStackBeforeInspector, {
value: enhanceStackTrace.bind(this, er, capture),
value: FunctionPrototypeBind(enhanceStackTrace, this, er, capture),
configurable: true
});
} catch {}
Expand Down Expand Up @@ -437,9 +449,9 @@ function _addListener(target, type, listener, prepend) {
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
ArrayPrototypeUnshift(existing, listener);
} else {
existing.push(listener);
ArrayPrototypePush(existing, listener);
}

// Check for listener leak
Expand Down Expand Up @@ -479,14 +491,14 @@ function onceWrapper() {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
return FunctionPrototypeCall(this.listener, this.target);
return ReflectApply(this.listener, this.target, arguments);
}
}

function _onceWrap(target, type, listener) {
const state = { fired: false, wrapFn: undefined, target, type, listener };
const wrapped = onceWrapper.bind(state);
const wrapped = FunctionPrototypeBind(onceWrapper, state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
Expand Down Expand Up @@ -636,7 +648,7 @@ EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
}
return listenerCount.call(emitter, type);
return FunctionPrototypeCall(listenerCount, emitter, type);
};

EventEmitter.prototype.listenerCount = listenerCount;
Expand Down Expand Up @@ -670,7 +682,7 @@ function arrayClone(arr) {
case 5: return [arr[0], arr[1], arr[2], arr[3], arr[4]];
case 6: return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]];
}
return arr.slice();
return ArrayPrototypeSlice(arr);
}

function unwrapListeners(arr) {
Expand Down Expand Up @@ -813,7 +825,7 @@ function on(emitter, event, options) {

// Wait until an event happens
return new Promise(function(resolve, reject) {
unconsumedPromises.push({ resolve, reject });
ArrayPrototypePush(unconsumedPromises, { resolve, reject });
});
},

Expand Down Expand Up @@ -877,7 +889,7 @@ function on(emitter, event, options) {
if (promise) {
promise.resolve(createIterResult(args, false));
} else {
unconsumedEvents.push(args);
ArrayPrototypePush(unconsumedEvents, args);
}
}

Expand Down
7 changes: 4 additions & 3 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {
ArrayFrom,
Boolean,
Error,
FunctionPrototypeBind,
FunctionPrototypeCall,
NumberIsInteger,
ObjectAssign,
Expand Down Expand Up @@ -212,7 +213,7 @@ class Listener {
this.callback =
typeof listener === 'function' ?
listener :
listener.handleEvent.bind(listener);
FunctionPrototypeBind(listener.handleEvent, listener);
}

same(listener, capture) {
Expand Down Expand Up @@ -419,7 +420,7 @@ class EventTarget {
} else {
arg = createEvent();
}
const result = handler.callback.call(this, arg);
const result = FunctionPrototypeCall(handler.callback, this, arg);
if (result !== undefined && result !== null)
addCatch(this, result, createEvent());
} catch (err) {
Expand Down Expand Up @@ -590,7 +591,7 @@ function isEventTarget(obj) {
function addCatch(that, promise, event) {
const then = promise.then;
if (typeof then === 'function') {
then.call(promise, undefined, function(err) {
FunctionPrototypeCall(then, promise, undefined, function(err) {
// The callback is called with nextTick to avoid a follow-up
// rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, that, err, event);
Expand Down
7 changes: 4 additions & 3 deletions lib/trace_events.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

const {
ArrayIsArray,
Set,
ArrayPrototypeJoin,
SafeSet,
Symbol,
} = primordials;

Expand All @@ -27,7 +28,7 @@ const { CategorySet, getEnabledCategories } = internalBinding('trace_events');
const { customInspectSymbol } = require('internal/util');
const { format } = require('internal/util/inspect');

const enabledTracingObjects = new Set();
const enabledTracingObjects = new SafeSet();

class Tracing {
constructor(categories) {
Expand Down Expand Up @@ -63,7 +64,7 @@ class Tracing {
}

get categories() {
return this[kCategories].join(',');
return ArrayPrototypeJoin(this[kCategories], ',');
}

[customInspectSymbol](depth, opts) {
Expand Down