getFunctionName.js (2532B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ 4 5 import * as t from "@babel/types"; 6 7 // Perform ES6's anonymous function name inference for all 8 // locations where static analysis is possible. 9 // eslint-disable-next-line complexity 10 export default function getFunctionName(node, parent) { 11 if (t.isIdentifier(node.id)) { 12 return node.id.name; 13 } 14 15 if ( 16 t.isObjectMethod(node, { computed: false }) || 17 t.isClassMethod(node, { computed: false }) || 18 t.isClassPrivateMethod(node) 19 ) { 20 const { key } = node; 21 22 if (t.isIdentifier(key)) { 23 return key.name; 24 } 25 if (t.isStringLiteral(key)) { 26 return key.value; 27 } 28 if (t.isNumericLiteral(key)) { 29 return `${key.value}`; 30 } 31 32 if (t.isPrivateName(key)) { 33 return `#${key.id.name}`; 34 } 35 } 36 37 if ( 38 t.isObjectProperty(parent, { computed: false, value: node }) || 39 // TODO: Babylon 6 doesn't support computed class props. It is included 40 // here so that it is most flexible. Once Babylon 7 is used, this 41 // can change to use computed: false like ObjectProperty. 42 (t.isClassProperty(parent, { value: node }) && !parent.computed) || 43 (t.isClassPrivateProperty(parent, { value: node }) && !parent.computed) 44 ) { 45 const { key } = parent; 46 47 if (t.isIdentifier(key)) { 48 return key.name; 49 } 50 if (t.isStringLiteral(key)) { 51 return key.value; 52 } 53 if (t.isNumericLiteral(key)) { 54 return `${key.value}`; 55 } 56 57 if (t.isPrivateName(key)) { 58 return `#${key.id.name}`; 59 } 60 } 61 62 if (t.isAssignmentExpression(parent, { operator: "=", right: node })) { 63 if (t.isIdentifier(parent.left)) { 64 return parent.left.name; 65 } 66 67 // This case is not supported in standard ES6 name inference, but it 68 // is included here since it is still a helpful case during debugging. 69 if (t.isMemberExpression(parent.left, { computed: false })) { 70 return parent.left.property.name; 71 } 72 } 73 74 if ( 75 t.isAssignmentPattern(parent, { right: node }) && 76 t.isIdentifier(parent.left) 77 ) { 78 return parent.left.name; 79 } 80 81 if ( 82 t.isVariableDeclarator(parent, { init: node }) && 83 t.isIdentifier(parent.id) 84 ) { 85 return parent.id.name; 86 } 87 88 if ( 89 t.isExportDefaultDeclaration(parent, { declaration: node }) && 90 t.isFunctionDeclaration(node) 91 ) { 92 return "default"; 93 } 94 95 return "anonymous"; 96 }