From d0667e814e8be53d329a9c7f4849996c192395c9 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sun, 14 Apr 2019 21:37:03 +0200 Subject: util: improve function inspection This commit contains the following changes: 1) Add null prototype support for functions. 2) Safely detect async and generator functions. 3) Mark anonymous functions as such instead of just leaving out the name. PR-URL: https://github.com/nodejs/node/pull/27227 Reviewed-By: Joyee Cheung Reviewed-By: John-David Dalton Reviewed-By: Anto Aravinth Reviewed-By: Rich Trott --- lib/internal/util/inspect.js | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) (limited to 'lib/internal/util/inspect.js') diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index fccb46085d..8ffa303268 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -49,6 +49,8 @@ const { } = require('internal/errors'); const { + isAsyncFunction, + isGeneratorFunction, isAnyArrayBuffer, isArrayBuffer, isArgumentsObject, @@ -642,14 +644,9 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { return `${braces[0]}}`; } } else if (typeof value === 'function') { - const type = constructor || tag || 'Function'; - let name = `${type}`; - if (value.name && typeof value.name === 'string') { - name += `: ${value.name}`; - } + base = getFunctionBase(value, constructor, tag); if (keys.length === 0) - return ctx.stylize(`[${name}]`, 'special'); - base = `[${name}]`; + return ctx.stylize(base, 'special'); } else if (isRegExp(value)) { // Make RegExps say that they are RegExps base = RegExpPrototype.toString( @@ -834,6 +831,32 @@ function getBoxedBase(value, ctx, keys, constructor, tag) { return ctx.stylize(base, type.toLowerCase()); } +function getFunctionBase(value, constructor, tag) { + let type = 'Function'; + if (isAsyncFunction(value)) { + type = 'AsyncFunction'; + } else if (isGeneratorFunction(value)) { + type = 'GeneratorFunction'; + } + let base = `[${type}`; + if (constructor === null) { + base += ' (null prototype)'; + } + if (value.name === '') { + base += ' (anonymous)'; + } else { + base += `: ${value.name}`; + } + base += ']'; + if (constructor !== type && constructor !== null) { + base += ` ${constructor}`; + } + if (tag !== '' && constructor !== tag) { + base += ` [${tag}]`; + } + return base; +} + function formatError(err, constructor, tag, ctx) { // TODO(BridgeAR): Always show the error code if present. let stack = err.stack || ErrorPrototype.toString(err); -- cgit v1.2.3