callsite-tostring.js (2229B)
1 /*! 2 * depd 3 * Copyright(c) 2014 Douglas Christopher Wilson 4 * MIT Licensed 5 */ 6 7 'use strict' 8 9 /** 10 * Module exports. 11 */ 12 13 module.exports = callSiteToString 14 15 /** 16 * Format a CallSite file location to a string. 17 */ 18 19 function callSiteFileLocation (callSite) { 20 var fileName 21 var fileLocation = '' 22 23 if (callSite.isNative()) { 24 fileLocation = 'native' 25 } else if (callSite.isEval()) { 26 fileName = callSite.getScriptNameOrSourceURL() 27 if (!fileName) { 28 fileLocation = callSite.getEvalOrigin() 29 } 30 } else { 31 fileName = callSite.getFileName() 32 } 33 34 if (fileName) { 35 fileLocation += fileName 36 37 var lineNumber = callSite.getLineNumber() 38 if (lineNumber != null) { 39 fileLocation += ':' + lineNumber 40 41 var columnNumber = callSite.getColumnNumber() 42 if (columnNumber) { 43 fileLocation += ':' + columnNumber 44 } 45 } 46 } 47 48 return fileLocation || 'unknown source' 49 } 50 51 /** 52 * Format a CallSite to a string. 53 */ 54 55 function callSiteToString (callSite) { 56 var addSuffix = true 57 var fileLocation = callSiteFileLocation(callSite) 58 var functionName = callSite.getFunctionName() 59 var isConstructor = callSite.isConstructor() 60 var isMethodCall = !(callSite.isToplevel() || isConstructor) 61 var line = '' 62 63 if (isMethodCall) { 64 var methodName = callSite.getMethodName() 65 var typeName = getConstructorName(callSite) 66 67 if (functionName) { 68 if (typeName && functionName.indexOf(typeName) !== 0) { 69 line += typeName + '.' 70 } 71 72 line += functionName 73 74 if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { 75 line += ' [as ' + methodName + ']' 76 } 77 } else { 78 line += typeName + '.' + (methodName || '<anonymous>') 79 } 80 } else if (isConstructor) { 81 line += 'new ' + (functionName || '<anonymous>') 82 } else if (functionName) { 83 line += functionName 84 } else { 85 addSuffix = false 86 line += fileLocation 87 } 88 89 if (addSuffix) { 90 line += ' (' + fileLocation + ')' 91 } 92 93 return line 94 } 95 96 /** 97 * Get constructor name of reviver. 98 */ 99 100 function getConstructorName (obj) { 101 var receiver = obj.receiver 102 return (receiver.constructor && receiver.constructor.name) || null 103 }