code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
moveBinding(binding, toScope) { this.bindings.get(binding.scope).delete(binding.identifier.name); this.bindings.get(toScope).set(binding.identifier.name, binding); }
Moves Binding from it's own Scope to {@param toScope} required for fixup-var-scope @param {Binding} binding @param {Scope} toScope
moveBinding
javascript
babel/minify
packages/babel-plugin-minify-mangle-names/src/scope-tracker.js
https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js
MIT
hasBinding(scope, name) { return this.bindings.get(scope).has(name); }
has a Binding in the current {Scope} @param {Scope} scope @param {String} name
hasBinding
javascript
babel/minify
packages/babel-plugin-minify-mangle-names/src/scope-tracker.js
https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js
MIT
renameBinding(scope, oldName, newName) { const bindings = this.bindings.get(scope); bindings.set(newName, bindings.get(oldName)); bindings.delete(oldName); }
Update the ScopeTracker on rename @param {Scope} scope @param {String} oldName @param {String} newName
renameBinding
javascript
babel/minify
packages/babel-plugin-minify-mangle-names/src/scope-tracker.js
https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-mangle-names/src/scope-tracker.js
MIT
function pathJoin(...parts) { if (path.isAbsolute(parts[0])) { return path.join(...parts); } return "." + path.sep + path.join(...parts); }
Jest changes __dirname to relative path and the require of relative path that doesn't start with "." will be a module require - require("./packages/babel-plugin...") vs require("packages/babel-plugin.."); So we start the path with a "./"
pathJoin
javascript
babel/minify
utils/test-runner/src/index.js
https://github.com/babel/minify/blob/master/utils/test-runner/src/index.js
MIT
function inArray(o, arr) { return arr.indexOf(o) > -1; }
Check in array @param {*} o @param {Array} arr @returns {Boolean}
inArray
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]'; }
Check is array @param {*} o @returns {Boolean}
isArray
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function isObject(o) { return Object.prototype.toString.call(o) === '[object Object]'; }
Check is object @param {*} o @returns {Boolean}
isObject
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function hasClass(el, cls) { return el.className.match(new RegExp('(\\s|^)(' + cls + ')(\\s|$)')); }
@param {HTMLElement} el @param {String} cls @returns {Array|{index: number, input: string}}
hasClass
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function addClass(el, cls) { if (!hasClass(el, cls)) { el.className += ' ' + cls; } }
@param {HTMLElement} el @param {String} cls
addClass
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function isUrl(url) { if (/<\/?[^>]*>/.test(url)) return false; return /^(?:(https|http|ftp|rtsp|mms):)?(\/\/)?(\w+:{0,1}\w*@)?([^\?#:\/]+\.[a-z]+|\d+\.\d+\.\d+\.\d+)?(:[0-9]+)?((?:\.?\/)?([^\?#]*)?(\?[^#]+)?(#.+)?)?$/.test(url); }
Check is url @param {String} url @returns {Boolean}
isUrl
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function isDom(obj) { try { return obj instanceof HTMLElement; } catch (e) { return (typeof obj === "object") && (obj.nodeType === 1) && (typeof obj.style === "object") && (typeof obj.ownerDocument === "object"); } }
Check is dom object @param {object} dom @returns {Boolean}
isDom
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function _A(a) { return Array.prototype.slice.apply(a, Array.prototype.slice.call(arguments, 1)); }
Parse arguments to array @param {Arguments} a @param {Number|null} start @param {Number|null} end @returns {Array}
_A
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
iSlider = function () { var args = _A(arguments, 0, 3); if (!args.length) { throw new Error('Parameters required!'); } var opts = isObject(args.slice(-1)[0]) ? args.pop() : {}; switch (args.length) { case 2: opts.data = opts.data || args[1]; case 1: opts.dom = opts.dom || args[0]; } if (!opts.dom) { throw new Error('Container can not be empty!'); } else if (!isDom(opts.dom)) { throw new Error('Container must be a HTMLElement instance!'); } if (!opts.data || !opts.data.length) { throw new Error('Data must be an array and must have more than one element!'); } /** * Options * @private */ this._opts = opts; opts = null, args = null; this._setting(); this.fire('initialize'); this._renderWrapper(); this._initPlugins(); this._bindHandler(); this.fire('initialized'); // Autoplay mode this._autoPlay(); }
@constructor iSlider([[{HTMLElement} container,] {Array} datalist,] {Object} options) @param {HTMLElement} container @param {Array} datalist @param {Object} options @description options.dom > container options.data > datalist
iSlider
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function normal(dom, axis, scale, i, offset) { iSlider.setStyle(dom, 'transform', 'translateZ(0) translate' + axis + '(' + (offset + scale * (i - 1)) + 'px)'); }
@type {Object} @param {HTMLElement} dom The wrapper <li> element @param {String} axis Animate direction @param {Number} scale Outer wrapper @param {Number} i Wrapper's index @param {Number} offset Move distance @protected
normal
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
insertImg = function renderItemInsertImg() { var simg = ' src="' + item.content + '"'; // auto scale to full screen if (item.height / item.width > self.ratio) { simg += ' height="100%"'; } else { simg += ' width="100%"'; } if (self.isOverspread) { el.style.cssText += 'background-image:url(' + item.content + ');background-repeat:no-repeat;background-position:50% 50%;background-size:cover'; simg += ' style="display:block;opacity:0;height:100%;width:100%;"'; } // for right button, save picture el.innerHTML = '<img' + simg + ' />'; }
render single item html by idx @param {HTMLElement} el .. @param {Number} dataIndex .. @private
insertImg
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
loadImg = function (index) { var item = data[index]; if (self._itemType(item) === 'pic' && !item.load) { var preloadImg = new Image(); preloadImg.src = item.content; preloadImg.onload = function () { item.width = preloadImg.width; item.height = preloadImg.height; item.load = 2; }; preloadImg.onerror = function () { item.load = -1; } item.load = 1; } }
Preload img when slideChange From current index +2, -2 scene @param {Number} dataIndex means which image will be load @private
loadImg
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function dispatchLink(el) { if (el != null) { if (el.tagName === 'A') { if (el.href) { if (el.getAttribute('target') === '_blank') { global.open(el.href); } else { global.location.href = el.href; } evt.preventDefault(); return false; } } else if (el.tagName === 'LI' && el.className.search(/^islider\-/) > -1) { return false; } else { dispatchLink(el.parentNode); } } }
touchend callback @param {Object} evt event object @public
dispatchLink
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function delegatedEventCallbackHandle(e) { var evt = global.event ? global.event : e; var target = evt.target; var eleArr = document.querySelectorAll(selector); for (var i = 0; i < eleArr.length; i++) { if (target === eleArr[i]) { callback.call(target); break; } } }
simple event delegate method @param {String} evtType event name @param {String} selector the simple css selector like jQuery @param {Function} callback event callback @public @alias iSliderPrototype.bind
delegatedEventCallbackHandle
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function rotate(dom, axis, scale, i, offset, direct) { var rotateDirect = (axis === 'X') ? 'Y' : 'X'; if (this.isVertical) { offset = -offset; if (Math.abs(direct) > 1) { direct = -direct; } } var outer = dom.parentElement; iSlider.setStyle(outer, 'perspective', scale * 4); dom.style.visibility = 'visible'; if (direct > 0 && i === 2) { dom.style.visibility = 'hidden'; } if (direct < 0 && i === 0) { dom.style.visibility = 'hidden'; } dom.style.zIndex = i === 1 ? 1 : 0; dom.style.cssText += iSlider.styleProp('backface-visibility') + ':hidden;' + iSlider.styleProp('transform-style') + ':preserve-3d;' + 'position:absolute;'; // TODO: overflow... I dont understand why there are many differences between ios and desktop. Maybe they have different interpretations of Perspective iSlider.setStyle(dom, 'transform', 'rotate' + rotateDirect + '(' + 90 * (offset / scale + i - 1) + 'deg) translateZ(' + (0.889 * scale / 2) + 'px) scale(0.889)'); }
More animations @file animate.js @author BE-FE Team xieyu33333 [email protected] shinate [email protected]
rotate
javascript
be-fe/iSlider
build/index.bundle.js
https://github.com/be-fe/iSlider/blob/master/build/index.bundle.js
MIT
function parseZone(sizes) { if (typeof sizes === 'number') { if (sizes < 0) { sizes = 0; } return [sizes, sizes, sizes, sizes]; } else if (sizes instanceof Array) { switch (sizes.length) { case 4: return sizes; case 3: return [sizes[0], sizes[1], sizes[2], sizes[1]]; case 2: return [sizes[0], sizes[1], sizes[0], sizes[1]]; case 1: return [sizes[0], sizes[0], sizes[0], sizes[0]]; } } return [0, 0, 0, 0]; }
Boundary Identification Zone @file BIZone.js @author BE-FE Team shinate [email protected]
parseZone
javascript
be-fe/iSlider
build/iSlider.plugin.BIZone.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.BIZone.js
MIT
function renderDots() { var fragment = document.createDocumentFragment(); dots.forEach(function (el, i) { el.removeEventListener(endEvt, evtHandle[i], false); }); dots = [], evtHandle = []; dotWrap.innerHTML = ''; for (var i = 0; i < data.length; i++) { dots[i] = document.createElement('li'); dots[i].className = 'islider-dot'; dots[i].setAttribute('index', i); if (i === HANDLE.slideIndex) { dots[i].className += ' active'; } evtHandle[i] = function () { HANDLE.slideTo(parseInt(this.getAttribute('index'), 10)); }; dots[i].addEventListener(endEvt, evtHandle[i], false); fragment.appendChild(dots[i]); } dotWrap.appendChild(fragment); }
To create dots index on iSlider @file dot.js @author BE-FE Team xieyu33333 [email protected] shinate [email protected] @Instructions activation: new iSlider({ ... plugins: ['dot'] ... }); more options: new iSlider({ ... plugins: [['dot', {locate:'absoulute'}]] ... }); @options locate {string|HTML Element} the warpper of dots value: 'absolute', 'relative' or Specified dom, default: 'absolute'
renderDots
javascript
be-fe/iSlider
build/iSlider.plugin.dot.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.dot.js
MIT
function generateTranslate(x, y, z, scale) { return 'translate' + (has3d ? '3d(' : '(') + x + 'px,' + y + (has3d ? 'px,' + z + 'px)' : 'px)') + 'scale(' + scale + ')'; }
Generate translate @param x @param y @param z @param scale @returns {string}
generateTranslate
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function getDistance(a, b) { var x, y; x = a.left - b.left; y = a.top - b.top; return Math.sqrt(x * x + y * y); }
Get distance @param a @param b @returns {number}
getDistance
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function generateTransformOrigin(x, y) { return x + 'px ' + y + 'px'; }
Transform to string @param x @param y @returns {string}
generateTransformOrigin
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function getTouches(touches) { return Array.prototype.slice.call(touches).map(function (touch) { return { left: touch.pageX, top: touch.pageY }; }); }
Get touch pointer @param touches @returns {Array}
getTouches
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function calculateScale(start, end) { var startDistance = getDistance(start[0], start[1]); var endDistance = getDistance(end[0], end[1]); return endDistance / startDistance; }
Get scale @param start @param end @returns {number}
calculateScale
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function getComputedTranslate(obj) { var result = { translateX: 0, translateY: 0, translateZ: 0, scaleX: 1, scaleY: 1, offsetX: 0, offsetY: 0 }; var offsetX = 0, offsetY = 0; if (!global.getComputedStyle || !obj) return result; var style = global.getComputedStyle(obj), transform, origin; transform = style.webkitTransform || style.mozTransform; origin = style.webkitTransformOrigin || style.mozTransformOrigin; var par = origin.match(/(.*)px\s+(.*)px/); if (par.length > 1) { offsetX = par[1] - 0; offsetY = par[2] - 0; } if (transform === 'none') return result; var mat3d = transform.match(/^matrix3d\((.+)\)$/); var mat2d = transform.match(/^matrix\((.+)\)$/); var str; if (mat3d) { str = mat3d[1].split(', '); result = { translateX: str[12] - 0, translateY: str[13] - 0, translateZ: str[14] - 0, offsetX: offsetX - 0, offsetY: offsetY - 0, scaleX: str[0] - 0, scaleY: str[5] - 0, scaleZ: str[10] - 0 }; } else if (mat2d) { str = mat2d[1].split(', '); result = { translateX: str[4] - 0, translateY: str[5] - 0, offsetX: offsetX - 0, offsetY: offsetY - 0, scaleX: str[0] - 0, scaleY: str[3] - 0 }; } return result; }
Get computed translate @param obj @returns {{translateX: number, translateY: number, translateZ: number, scaleX: number, scaleY: number, offsetX: number, offsetY: number}}
getComputedTranslate
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function getCenter(a, b) { return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; }
Get center point @param a @param b @returns {{x: number, y: number}}
getCenter
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function startHandler(evt) { startHandlerOriginal.call(this, evt); // must be a picture, only one picture!! var node = this.els[1].querySelector('img:first-child'); var device = this.deviceEvents; if (device.hasTouch && node !== null) { IN_SCALE_MODE = true; var transform = getComputedTranslate(node); startTouches = getTouches(evt.targetTouches); startX = transform.translateX - 0; startY = transform.translateY - 0; currentScale = transform.scaleX; zoomNode = node; var pos = getPosition(node); if (evt.targetTouches.length == 2) { lastTouchStart = null; var touches = evt.touches; var touchCenter = getCenter({ x: touches[0].pageX, y: touches[0].pageY }, { x: touches[1].pageX, y: touches[1].pageY }); node.style.webkitTransformOrigin = generateTransformOrigin(touchCenter.x - pos.left, touchCenter.y - pos.top); } else if (evt.targetTouches.length === 1) { var time = (new Date()).getTime(); gesture = 0; if (time - lastTouchStart < 300) { evt.preventDefault(); gesture = 3; } lastTouchStart = time; } } }
Start event handle @param {object} evt
startHandler
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function moveHandler(evt) { if (IN_SCALE_MODE) { var result = 0; var node = zoomNode; var device = this.deviceEvents; if (device.hasTouch) { if (evt.targetTouches.length === 2) { node.style.webkitTransitionDuration = '0'; evt.preventDefault(); scaleImage(evt); result = 2; } else if (evt.targetTouches.length === 1 && currentScale > 1) { node.style.webkitTransitionDuration = '0'; evt.preventDefault(); moveImage.call(this, evt); result = 1; } gesture = result; if (result > 0) { return; } } } moveHandlerOriginal.call(this, evt); }
Move event handle @param {object} evt @returns {number}
moveHandler
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function handleDoubleTap(evt) { var zoomFactor = zoomFactor || 2; var node = zoomNode; var pos = getPosition(node); currentScale = currentScale == 1 ? zoomFactor : 1; node.style.webkitTransform = generateTranslate(0, 0, 0, currentScale); if (currentScale != 1) node.style.webkitTransformOrigin = generateTransformOrigin(evt.touches[0].pageX - pos.left, evt.touches[0].pageY - pos.top); }
Double tao handle @param {object} evt
handleDoubleTap
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function getPosition(element) { var pos = {'left': 0, 'top': 0}; do { pos.top += element.offsetTop || 0; pos.left += element.offsetLeft || 0; element = element.offsetParent; } while (element); return pos; }
Get position @param element @returns {{left: number, top: number}}
getPosition
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function valueInViewScope(node, value, tag) { var min, max; var pos = getPosition(node); viewScope = { start: {left: pos.left, top: pos.top}, end: {left: pos.left + node.clientWidth, top: pos.top + node.clientHeight} }; var str = tag == 1 ? 'left' : 'top'; min = viewScope.start[str]; max = viewScope.end[str]; return (value >= min && value <= max); }
Check target is in range @param node @param value @param tag @returns {boolean}
valueInViewScope
javascript
be-fe/iSlider
build/iSlider.plugin.zoompic.js
https://github.com/be-fe/iSlider/blob/master/build/iSlider.plugin.zoompic.js
MIT
function error(type) { throw new RangeError(errors[type]); }
A generic error utility function. @private @param {String} type The error type. @returns {Error} Throws a `RangeError` with the applicable error message.
error
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
function map(array, fn) { var result = []; var length = array.length; while (length--) { result[length] = fn(array[length]); } return result; }
A generic `Array#map` utility function. @private @param {Array} array The array to iterate over. @param {Function} callback The function that gets called for every array item. @returns {Array} A new array of values returned by the callback function.
map
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; }
A simple `Array#map`-like wrapper to work with domain name strings or email addresses. @private @param {String} domain The domain name or email address. @param {Function} callback The function that gets called for every character. @returns {Array} A new string of characters returned by the callback function.
mapDomain
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; while (counter < length) { var value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an unmatched surrogate; only append this code unit, in case the // next code unit is the high surrogate of a surrogate pair. output.push(value); counter--; } } else { output.push(value); } } return output; }
Creates an array containing the numeric code points of each Unicode character in the string. While JavaScript uses UCS-2 internally, this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. @see `punycode.ucs2.encode` @see <https://mathiasbynens.be/notes/javascript-encoding> @memberOf punycode.ucs2 @name decode @param {String} string The Unicode input string (UCS-2). @returns {Array} The new array of code points.
ucs2decode
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
ucs2encode = function ucs2encode(array) { return String.fromCodePoint.apply(String, _toConsumableArray(array)); }
Creates a string based on an array of numeric code points. @see `punycode.ucs2.decode` @memberOf punycode.ucs2 @name encode @param {Array} codePoints The array of numeric code points. @returns {String} The new Unicode string (UCS-2).
ucs2encode
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
basicToDigit = function basicToDigit(codePoint) { if (codePoint - 0x30 < 0x0A) { return codePoint - 0x16; } if (codePoint - 0x41 < 0x1A) { return codePoint - 0x41; } if (codePoint - 0x61 < 0x1A) { return codePoint - 0x61; } return base; }
Converts a basic code point into a digit/integer. @see `digitToBasic()` @private @param {Number} codePoint The basic numeric code point value. @returns {Number} The numeric value of a basic code point (for use in representing integers) in the range `0` to `base - 1`, or `base` if the code point does not represent a value.
basicToDigit
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
digitToBasic = function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }
Converts a digit/integer into a basic code point. @see `basicToDigit()` @private @param {Number} digit The numeric value of a basic code point. @returns {Number} The basic code point whose value (when used for representing integers) is `digit`, which needs to be in the range `0` to `base - 1`. If `flag` is non-zero, the uppercase form is used; else, the lowercase form is used. The behavior is undefined if `flag` is non-zero and `digit` has no uppercase form.
digitToBasic
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
adapt = function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }
Bias adaptation function as per section 3.4 of RFC 3492. https://tools.ietf.org/html/rfc3492#section-3.4 @private
adapt
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
decode = function decode(input) { // Don't use UCS-2. var output = []; var inputLength = input.length; var i = 0; var n = initialN; var bias = initialBias; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. var basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (var j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. var oldi = i; for (var w = 1, k = base;; /* no condition */k += base) { if (index >= inputLength) { error('invalid-input'); } var digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } var baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } var out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output. output.splice(i++, 0, n); } return String.fromCodePoint.apply(String, output); }
Converts a Punycode string of ASCII-only symbols to a string of Unicode symbols. @memberOf punycode @param {String} input The Punycode string of ASCII-only symbols. @returns {String} The resulting string of Unicode symbols.
decode
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
encode = function encode(input) { var output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. var inputLength = input.length; // Initialize the state. var n = initialN; var delta = 0; var bias = initialBias; // Handle the basic code points. var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _currentValue2 = _step.value; if (_currentValue2 < 0x80) { output.push(stringFromCharCode(_currentValue2)); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var basicLength = output.length; var handledCPCount = basicLength; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: var m = maxInt; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var currentValue = _step2.value; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow. } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _currentValue = _step3.value; if (_currentValue < n && ++delta > maxInt) { error('overflow'); } if (_currentValue == n) { // Represent delta as a generalized variable-length integer. var q = delta; for (var k = base;; /* no condition */k += base) { var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } var qMinusT = q - t; var baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } ++delta; ++n; } return output.join(''); }
Converts a string of Unicode symbols (e.g. a domain name label) to a Punycode string of ASCII-only symbols. @memberOf punycode @param {String} input The string of Unicode symbols. @returns {String} The resulting Punycode string of ASCII-only symbols.
encode
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
toUnicode = function toUnicode(input) { return mapDomain(input, function (string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }
Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn't matter if you call it on a string that has already been converted to Unicode. @memberOf punycode @param {String} input The Punycoded domain name or email address to convert to Unicode. @returns {String} The Unicode representation of the given Punycode string.
toUnicode
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
toASCII = function toASCII(input) { return mapDomain(input, function (string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); }
Converts a Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if you call it with a domain that's already in ASCII. @memberOf punycode @param {String} input The domain name or email address to convert, as a Unicode string. @returns {String} The Punycode representation of the given domain name or email address.
toASCII
javascript
amol-/dukpy
dukpy/jscore/punycode.js
https://github.com/amol-/dukpy/blob/master/dukpy/jscore/punycode.js
MIT
function createFileMap(keyMapper) { var files = {}; return { get: get, set: set, contains: contains, remove: remove, forEachValue: forEachValueInMap, clear: clear }; function forEachValueInMap(f) { for (var key in files) { f(key, files[key]); } } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; } function set(path, value) { files[toKey(path)] = value; } function contains(path) { return hasProperty(files, toKey(path)); } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { files = {}; } function toKey(path) { return keyMapper ? keyMapper(path) : path; } }
Ternary values are defined such that x & y is False if either x or y is False. x & y is Maybe if either x or y is Maybe, but neither x or y is False. x & y is True if both x and y are True. x | y is False if both x and y are False. x | y is Maybe if either x or y is Maybe, but neither x or y is True. x | y is True if either x or y is True.
createFileMap
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function contains(array, value) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; if (v === value) { return true; } } } return false; }
Iterates through 'array' by index and performs the callback on each element of array until the callback returns a truthy value, then returns that value. If no such value is found, the callback is applied to each element of array and undefined is returned.
contains
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function lastOrUndefined(array) { if (array.length === 0) { return undefined; } return array[array.length - 1]; }
Returns the last element of an array if non-empty, undefined otherwise.
lastOrUndefined
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function reduceLeft(array, f, initial) { if (array) { var count = array.length; if (count > 0) { var pos = 0; var result = arguments.length <= 2 ? array[pos++] : initial; while (pos < count) { result = f(result, array[pos++]); } return result; } } return initial; }
Performs a binary search, finding the index at which 'value' occurs in 'array'. If no such index is found, returns the 2's-complement of first index at which number[index] exceeds number. @param array A sorted array whose first element must be no larger than number @param number The value to be searched for in the array.
reduceLeft
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function memoize(callback) { var value; return function () { if (callback) { value = callback(); callback = undefined; } return value; }; }
Creates a map from the elements of an array. @param array the array of input elements. @param makeKey a function that produces a key for a given element. This function makes no effort to avoid collisions; if any two elements produce the same key with the given 'makeKey' function, then the element with the higher index in the array will be the one associated with the produced key.
memoize
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isSupportedSourceFileName(fileName) { if (!fileName) { return false; } for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { var extension = supportedExtensions_1[_i]; if (fileExtensionIs(fileName, extension)) { return true; } } return false; }
List of supported extensions in order of file resolution precedence.
isSupportedSourceFileName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getLineAndCharacterOfPosition(sourceFile, position) { return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); }
We assume the first line starts at position 0 and 'position' is non-negative.
getLineAndCharacterOfPosition
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getCommentRanges(text, pos, trailing) { var result; var collecting = trailing || pos === 0; while (pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13 /* carriageReturn */: if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; } case 10 /* lineFeed */: pos++; if (trailing) { return result; } collecting = true; if (result && result.length) { ts.lastOrUndefined(result).hasTrailingNewLine = true; } continue; case 9 /* tab */: case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: pos++; continue; case 47 /* slash */: var nextChar = text.charCodeAt(pos + 1); var hasTrailingNewLine = false; if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; var startPos = pos; pos += 2; if (nextChar === 47 /* slash */) { while (pos < text.length) { if (isLineBreak(text.charCodeAt(pos))) { hasTrailingNewLine = true; break; } pos++; } } else { while (pos < text.length) { if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; break; } pos++; } } if (collecting) { if (!result) { result = []; } result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); } continue; } break; default: if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch) || isLineBreak(ch))) { if (result && result.length && isLineBreak(ch)) { ts.lastOrUndefined(result).hasTrailingNewLine = true; } pos++; continue; } break; } return result; } return result; }
Extract comments from text prefixing the token closest following `pos`. The return value is an array containing a TextRange for each comment. Single-line comment ranges include the beginning '//' characters but not the ending line break. Multi - line comment ranges include the beginning '/* and ending '<asterisk>/' characters. The return value is undefined if no comments were found. @param trailing If false, whitespace is skipped until the first line break and comments between that location and the next token are returned. If true, comments occurring between the given position and the next line break are returned.
getCommentRanges
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function scanExactNumberOfHexDigits(count) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); }
Scans the given number of hexadecimal digits in the text, returning -1 if the given number is unavailable.
scanExactNumberOfHexDigits
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function scanMinimumNumberOfHexDigits(count) { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); }
Scans as many hexadecimal digits as are available in the text, returning -1 if the given number of digits was unavailable.
scanMinimumNumberOfHexDigits
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function scanEscapeSequence() { pos++; if (pos >= end) { error(ts.Diagnostics.Unexpected_end_of_text); return ""; } var ch = text.charCodeAt(pos++); switch (ch) { case 48 /* _0 */: return "\0"; case 98 /* b */: return "\b"; case 116 /* t */: return "\t"; case 110 /* n */: return "\n"; case 118 /* v */: return "\v"; case 102 /* f */: return "\f"; case 114 /* r */: return "\r"; case 39 /* singleQuote */: return "\'"; case 34 /* doubleQuote */: return "\""; case 117 /* u */: // '\u{DDDDDDDD}' if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { hasExtendedUnicodeEscape = true; pos++; return scanExtendedUnicodeEscape(); } // '\uDDDD' return scanHexadecimalEscape(/*numDigits*/ 4); case 120 /* x */: // '\xDD' return scanHexadecimalEscape(/*numDigits*/ 2); // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), // the line terminator is interpreted to be "the empty code unit sequence". case 13 /* carriageReturn */: if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { pos++; } // fall through case 10 /* lineFeed */: case 8232 /* lineSeparator */: case 8233 /* paragraphSeparator */: return ""; default: return String.fromCharCode(ch); } }
Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or a literal component of a TemplateExpression.
scanEscapeSequence
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function reScanTemplateToken() { ts.Debug.assert(token === 16 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); }
Unconditionally back up and scan a template expression portion.
reScanTemplateToken
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isRequireCall(expression) { // of the form 'require("name")' return expression.kind === 168 /* CallExpression */ && expression.expression.kind === 69 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1 && expression.arguments[0].kind === 9 /* StringLiteral */; }
Returns true if the node is a CallExpression to the identifier 'require' with exactly one string literal argument. This function does not test if the node is in a JavaScript file or not.
isRequireCall
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isExportsPropertyAssignment(expression) { // of the form 'exports.name = expr' where 'name' and 'expr' are arbitrary return isInJavaScriptFile(expression) && (expression.kind === 181 /* BinaryExpression */) && (expression.operatorToken.kind === 56 /* EqualsToken */) && (expression.left.kind === 166 /* PropertyAccessExpression */) && (expression.left.expression.kind === 69 /* Identifier */) && ((expression.left.expression).text === "exports"); }
Returns true if the node is an assignment to a property on the identifier 'exports'. This function does not test if the node is in a JavaScript file or not.
isExportsPropertyAssignment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isModuleExportsAssignment(expression) { // of the form 'module.exports = expr' where 'expr' is arbitrary return isInJavaScriptFile(expression) && (expression.kind === 181 /* BinaryExpression */) && (expression.operatorToken.kind === 56 /* EqualsToken */) && (expression.left.kind === 166 /* PropertyAccessExpression */) && (expression.left.expression.kind === 69 /* Identifier */) && ((expression.left.expression).text === "module") && (expression.left.name.text === "exports"); }
Returns true if the node is an assignment to the property access expression 'module.exports'. This function does not test if the node is in a JavaScript file or not.
isModuleExportsAssignment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function hasDynamicName(declaration) { return declaration.name && isDynamicName(declaration.name); }
A declaration has a dynamic name if both of the following are true: 1. The declaration has a computed property name 2. The computed name is *not* expressed as Symbol.<name>, where name is a property of the Symbol constructor that denotes a built in Symbol.
hasDynamicName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isWellKnownSymbolSyntactically(node) { return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); }
Checks if the expression is of the form: Symbol.name where Symbol is literally the word "Symbol", and name is any identifierName
isWellKnownSymbolSyntactically
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isESSymbolIdentifier(node) { return node.kind === 69 /* Identifier */ && node.text === "Symbol"; }
Includes the word "Symbol" with unicode escapes
isESSymbolIdentifier
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getReplacement(c) { return escapedCharsMap[c] || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }
Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) Note that this doesn't actually wrap the input in double quotes.
getReplacement
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { // removeComments is true, only reserve pinned comment at the top of file // For example: // /*! Pinned Comment */ // // var x = 10; if (node.pos === 0) { leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; var lastComment; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so // far. break; } } detachedComments.push(comment); lastComment = comment; } if (detachedComments.length) { // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; } }
Detached comment is a comment at the top of file or function body that is separated from the next statement by space.
emitDetachedComments
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function convertToBase64(input) { var result = ""; var charCodes = getExpandedCharCodes(input); var i = 0; var length = charCodes.length; var byte1, byte2, byte3, byte4; while (i < length) { // Convert every 6-bits in the input 3 character points // into a base64 digit byte1 = charCodes[i] >> 2; byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; byte4 = charCodes[i + 2] & 63; // We are out of characters in the input, set the extra // digits to 64 (padding character). if (i + 1 >= length) { byte3 = byte4 = 64; } else if (i + 2 >= length) { byte4 = 64; } // Write to the ouput result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); i += 3; } return result; }
Converts a string to a base-64 encoded ASCII string.
convertToBase64
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function collapseTextChangeRangesAcrossMultipleVersions(changes) { if (changes.length === 0) { return ts.unchangedTextChangeRange; } if (changes.length === 1) { return changes[0]; } // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. var change0 = changes[0]; var oldStartN = change0.span.start; var oldEndN = textSpanEnd(change0.span); var newEndN = oldStartN + change0.newLength; for (var i = 1; i < changes.length; i++) { var nextChange = changes[i]; // Consider the following case: // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. // i.e. the span starting at 30 with length 30 is increased to length 40. // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------------------------------------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------------------------------------------------- // | \ // | \ // T2 | \ // | \ // | \ // ------------------------------------------------------------------------------------------------------- // // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial // it's just the min of the old and new starts. i.e.: // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------*------------------------------------------ // | / // | /---- // T1 | /---- // | /---- // | /---- // ----------------------------------------$-------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // (Note the dots represent the newly inferrred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // // 0 10 20 30 40 50 60 70 80 90 100 // --------------------------------------------------------------------------------*---------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // In other words (in this case), we're recognizing that the second edit happened after where the first edit // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started // that's the same as if we started at char 80 instead of 60. // // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter // than pusing the first edit forward to match the second, we'll push the second edit forward to match the // first. // // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange // semantics: { { start: 10, length: 70 }, newLength: 60 } // // The math then works out as follows. // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the // final result like so: // // { // oldStart3: Min(oldStart1, oldStart2), // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; var newEnd1 = newEndN; var oldStart2 = nextChange.span.start; var oldEnd2 = textSpanEnd(nextChange.span); var newEnd2 = oldStart2 + nextChange.newLength; oldStartN = Math.min(oldStart1, oldStart2); oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength:*/ newEndN - oldStartN); }
Called to merge all the changes that occurred across several versions of a script snapshot into a single change. i.e. if a user keeps making successive edits to a script we will have a text change from V1 to V2, V2 to V3, ..., Vn. This function will then merge those changes into a single change range valid between V1 and Vn.
collapseTextChangeRangesAcrossMultipleVersions
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function parseUnaryExpressionOrHigher() { if (isAwaitExpression()) { return parseAwaitExpression(); } if (isIncrementExpression()) { var incrementExpression = parseIncrementExpression(); return token === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; }
Parse ES7 unary expression and await expression ES7 UnaryExpression: 1) SimpleUnaryExpression[?yield] 2) IncrementExpression[?yield] ** UnaryExpression[?yield]
parseUnaryExpressionOrHigher
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function parseSimpleUnaryExpression() { switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: case 49 /* ExclamationToken */: return parsePrefixUnaryExpression(); case 78 /* DeleteKeyword */: return parseDeleteExpression(); case 101 /* TypeOfKeyword */: return parseTypeOfExpression(); case 103 /* VoidKeyword */: return parseVoidExpression(); case 25 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); default: return parseIncrementExpression(); } }
Parse ES7 simple-unary expression or higher: ES7 SimpleUnaryExpression: 1) IncrementExpression[?yield] 2) delete UnaryExpression[?yield] 3) void UnaryExpression[?yield] 4) typeof UnaryExpression[?yield] 5) + UnaryExpression[?yield] 6) - UnaryExpression[?yield] 7) ~ UnaryExpression[?yield] 8) ! UnaryExpression[?yield]
parseSimpleUnaryExpression
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isIncrementExpression() { // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrmentExpression directly switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: case 49 /* ExclamationToken */: case 78 /* DeleteKeyword */: case 101 /* TypeOfKeyword */: case 103 /* VoidKeyword */: return false; case 25 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; } // We are in JSX context and the token is part of JSXElement. // Fall through default: return true; } }
Check if the current token can possibly be an ES7 increment expression. ES7 IncrementExpression: LeftHandSideExpression[?Yield] LeftHandSideExpression[?Yield][no LineTerminator here]++ LeftHandSideExpression[?Yield][no LineTerminator here]-- ++LeftHandSideExpression[?Yield] --LeftHandSideExpression[?Yield]
isIncrementExpression
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function parseIncrementExpression() { if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { var node = createNode(179 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } else if (sourceFile.languageVariant === 1 /* JSX */ && token === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(180 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); return finishNode(node); } return expression; }
Parse ES7 IncrementExpression. IncrementExpression is used instead of ES6's PostFixExpression. ES7 IncrementExpression[yield]: 1) LeftHandSideExpression[?yield] 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- 4) ++LeftHandSideExpression[?yield] 5) --LeftHandSideExpression[?yield] In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
parseIncrementExpression
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function createJSDocComment() { if (!tags) { return undefined; } var result = createNode(265 /* JSDocComment */, start); result.tags = tags; return finishNode(result, end); }
".length; pos < end;) { var ch = content.charCodeAt(pos); pos++; if (ch === 64 /* at
createJSDocComment
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); var isDefaultExport = node.flags & 512 /* Default */; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict // with the 'excludes' flags we pass in. // // If we do get an existing symbol, see if it conflicts with the new symbol we're // creating. For example, a 'var' symbol and a 'class' symbol will conflict within // the same symbol table. If we have a conflict, report the issue on each // declaration we have for this symbol, and then create a new symbol for this // declaration. // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. // // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. symbol = ts.hasProperty(symbolTable, name) ? symbolTable[name] : (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; } // Report errors every position with duplicate declaration // Report errors on previous encountered declarations var message = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { if (declaration.flags & 512 /* Default */) { message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); }); file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } else { symbol = createSymbol(0 /* None */, "__missing"); } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; }
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @param symbolTable - The symbol table which node will be added to. @param parent - node's parent declaration. @param node - The declaration to be added to the symbol table @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
declareSymbol
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function bindReachableStatement(node) { if (checkUnreachable(node)) { ts.forEachChild(node, bind); return; } switch (node.kind) { case 198 /* WhileStatement */: bindWhileStatement(node); break; case 197 /* DoStatement */: bindDoStatement(node); break; case 199 /* ForStatement */: bindForStatement(node); break; case 200 /* ForInStatement */: case 201 /* ForOfStatement */: bindForInOrForOfStatement(node); break; case 196 /* IfStatement */: bindIfStatement(node); break; case 204 /* ReturnStatement */: case 208 /* ThrowStatement */: bindReturnOrThrow(node); break; case 203 /* BreakStatement */: case 202 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; case 209 /* TryStatement */: bindTryStatement(node); break; case 206 /* SwitchStatement */: bindSwitchStatement(node); break; case 220 /* CaseBlock */: bindCaseBlock(node); break; case 207 /* LabeledStatement */: bindLabeledStatement(node); break; default: ts.forEachChild(node, bind); break; } }
Returns true if node and its subnodes were successfully traversed. Returning false means that node was not examined and caller needs to dive into the node himself.
bindReachableStatement
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function appendSymbolNameOnly(symbol, writer) { writer.writeSymbol(getNameOfSymbol(symbol), symbol); }
Writes only the name of the symbol out to the writer. Uses the original source text for the name of the symbol if it is available to match how the user inputted the name.
appendSymbolNameOnly
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { var parentSymbol; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { if (symbol.flags & 16777216 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); } } writePunctuation(writer, 21 /* DotToken */); } parentSymbol = symbol; appendSymbolNameOnly(symbol, writer); } // const the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree // up front (for example, during checking) could determine if we need to emit the imports // and we could then access that data during declaration emit. writer.trackSymbol(symbol, enclosingDeclaration, meaning); function walkSymbol(symbol, meaning) { if (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); } if (accessibleSymbolChain) { for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { var accessibleSymbol = accessibleSymbolChain_1[_i]; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } else { // If we didn't find accessible symbol chain for this symbol, break if this is external module if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { return; } // if this is anonymous type break if (symbol.flags & 2048 /* TypeLiteral */ || symbol.flags & 4096 /* ObjectLiteral */) { return; } appendParentTypeArgumentsAndSymbolName(symbol); } } } // Get qualified name if the symbol is not a type parameter // and there is an enclosing declaration or we specifically // asked for it var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; var typeFormatFlag = 128 /* UseFullyQualifiedType */ & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { walkSymbol(symbol, meaning); return; } return appendParentTypeArgumentsAndSymbolName(symbol); }
Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope Meaning needs to be specified if the enclosing declaration is given
buildSymbolDisplay
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found var length_2 = resolutionTargets.length; for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; } resolutionTargets.push(target); resolutionResults.push(true); resolutionPropertyNames.push(propertyName); return true; }
Push an entry on the type resolution stack. If an entry with the given target and the given property name is already on the stack, and no entries in between already have a type, then a circularity has occurred. In this case, the result values of the existing entry and all entries pushed after it are changed to false, and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. In order to see if the same query has already been done before, the target object and the propertyName both must match the one passed in. @param target The symbol, type, or signature whose type is being queried @param propertyName The property name that should be used to query the target for its type
pushTypeResolution
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); while (constraintType && constraintType.flags & 512 /* TypeParameter */) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; }
The apparent type of a type parameter is the base constraint instantiated with the type parameter as the type argument for the 'this' type.
getApparentTypeOfTypeParameter
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); }
Returns a type that is inside a namespace at the global scope, e.g. getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type
getGlobalESSymbolConstructorSymbol
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; }
Instantiates a global type that is generic with some element type, and returns that instantiation.
createTypeFromGenericGlobalType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; var targetStack; var maybeStack; var expandingFlags; var depth = 0; var overflow = false; var elaborateErrors = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { // If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution), // then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened, // request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context // where errors were being reported. if (errorInfo.next === undefined) { errorInfo = undefined; elaborateErrors = true; isRelatedTo(source, target, errorNode !== undefined, headMessage); } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function reportRelationError(message, source, target) { var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); } reportError(message || ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceType, targetType); } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo(source, target, reportErrors, headMessage) { var result; // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return -1 /* True */; if (relation === identityRelation) { return isIdenticalTo(source, target); } if (isTypeAny(target)) return -1 /* True */; if (source === undefinedType) return -1 /* True */; if (source === nullType && target !== undefinedType) return -1 /* True */; if (source.flags & 128 /* Enum */ && target === numberType) return -1 /* True */; if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { if (isTypeAny(source)) return -1 /* True */; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; } if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0 /* False */; } // Above we check for excess properties with respect to the entire target type. When union // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. if (target.flags & 49152 /* UnionOrIntersection */) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; // Note that the "each" checks must precede the "some" checks to produce the correct results if (source.flags & 16384 /* Union */) { if (result = eachTypeRelatedToType(source, target, reportErrors)) { return result; } } else if (target.flags & 32768 /* Intersection */) { if (result = typeRelatedToEachType(source, target, reportErrors)) { return result; } } else { // It is necessary to try "some" checks on both sides because there may be nested "each" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). if (source.flags & 32768 /* Intersection */) { // If target is a union type the following check will report errors so we suppress them here if (result = someTypeRelatedToType(source, target, reportErrors && !(target.flags & 16384 /* Union */))) { return result; } } if (target.flags & 16384 /* Union */) { if (result = typeRelatedToSomeType(source, target, reportErrors)) { return result; } } } if (source.flags & 512 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1 /* Any */) { constraint = emptyObjectType; } // Report constraint errors only if the constraint is not the empty object type var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; } } else { if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. var apparentType = getApparentType(source); // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (apparentType.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } } } if (reportErrors) { reportRelationError(headMessage, source, target); } return 0 /* False */; } function isIdenticalTo(source, target) { var result; if (source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */) { if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; } } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { return typeParameterIdenticalTo(source, target); } if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } return 0 /* False */; } // Check if a property with the given name is known anywhere in the given type. In an object type, a property // is considered known if the object type is empty and the check is for assignability, if the object type has // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) || resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { return true; } } else if (type.flags & 49152 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { return true; } } } return false; } function hasExcessProperties(source, target, reportErrors) { if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && someConstituentTypeHasKind(target, 80896 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. errorNode = prop.valueDeclaration; reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } return true; } } } return false; } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { var sourceType = sourceTypes_1[_i]; var related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return 0 /* False */; } result &= related; } return result; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; for (var i = 0, len = targetTypes.length; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { return related; } } return 0 /* False */; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var targetType = targetTypes_1[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0 /* False */; } result &= related; } return result; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; for (var i = 0, len = sourceTypes.length; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } } return 0 /* False */; } function eachTypeRelatedToType(source, target, reportErrors) { var result = -1 /* True */; var sourceTypes = source.types; for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return 0 /* False */; } result &= related; } return result; } function typeArgumentsRelatedTo(source, target, reportErrors) { var sources = source.typeArguments || emptyArray; var targets = target.typeArguments || emptyArray; if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } var result = -1 /* True */; for (var i = 0; i < targets.length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0 /* False */; } result &= related; } return result; } function typeParameterIdenticalTo(source, target) { // covers case when both type parameters does not have constraint (both equal to noConstraintType) if (source.constraint === target.constraint) { return -1 /* True */; } if (source.constraint === noConstraintType || target.constraint === noConstraintType) { return 0 /* False */; } return isIdenticalTo(source.constraint, target.constraint); } // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { if (overflow) { return 0 /* False */; } var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; var related = relation[id]; if (related !== undefined) { // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate // errors, we can use the cached value. Otherwise, recompute the relation if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } if (depth > 0) { for (var i = 0; i < depth; i++) { // If source and target are already being compared, consider them related with assumptions if (maybeStack[i][id]) { return 1 /* Maybe */; } } if (depth === 100) { overflow = true; return 0 /* False */; } } else { sourceStack = []; targetStack = []; maybeStack = []; expandingFlags = 0; } sourceStack[depth] = apparentSource; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; var result; if (expandingFlags === 3) { result = 1 /* Maybe */; } else { result = propertiesRelatedTo(apparentSource, target, reportErrors); if (result) { result &= signaturesRelatedTo(apparentSource, target, 0 /* Call */, reportErrors); if (result) { result &= signaturesRelatedTo(apparentSource, target, 1 /* Construct */, reportErrors); if (result) { result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); if (result) { result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); } } } } } expandingFlags = saveExpandingFlags; depth--; if (result) { var maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; ts.copyMap(maybeCache, destinationCache); } else { // A false result goes straight into global cache (when something is false under assumptions it // will also be false without assumptions) relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */; } return result; } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } return 0 /* False */; } } else if (!(targetProp.flags & 134217728 /* Prototype */)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); if (sourcePropFlags & 16 /* Private */ || targetPropFlags & 16 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 16 /* Private */ && targetPropFlags & 16 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 /* Private */ ? source : target), typeToString(sourcePropFlags & 16 /* Private */ ? target : source)); } } return 0 /* False */; } } else if (targetPropFlags & 32 /* Protected */) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); } return 0 /* False */; } } else if (sourcePropFlags & 32 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } return 0 /* False */; } var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); } return 0 /* False */; } result &= related; if (sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. // M is a property and S' contains a property N where // if M is a required property, N is also a required property // (M - property in T) // (N - property in S) if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } return 0 /* False */; } } } } return result; } function propertiesIdenticalTo(source, target) { if (!(source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); var targetProperties = getPropertiesOfObjectType(target); if (sourceProperties.length !== targetProperties.length) { return 0 /* False */; } var result = -1 /* True */; for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0 /* False */; } var related = compareProperties(sourceProp, targetProp, isRelatedTo); if (!related) { return 0 /* False */; } result &= related; } return result; } function signaturesRelatedTo(source, target, kind, reportErrors) { if (relation === identityRelation) { return signaturesIdenticalTo(source, target, kind); } if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); var result = -1 /* True */; var saveErrorInfo = errorInfo; if (kind === 1 /* Construct */) { // Only want to compare the construct signatures for abstractness guarantees. // Because the "abstractness" of a class is the same across all construct signatures // (internally we are checking the corresponding declaration), it is enough to perform // the check and report an error once over all pairs of source and target construct signatures. // // sourceSig and targetSig are (possibly) undefined. // // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. var sourceSig = sourceSignatures[0]; var targetSig = targetSignatures[0]; result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); if (result !== -1 /* True */) { return result; } } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { var localErrors = reportErrors; var checkedAbstractAssignability = false; for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { var related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; errorInfo = saveErrorInfo; continue outer; } // Only report errors from the first failure localErrors = false; } } return 0 /* False */; } } return result; function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { if (sourceSig && targetSig) { var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); if (!sourceDecl) { // If the source object isn't itself a class declaration, it can be freely assigned, regardless // of whether the constructed object is abstract or not. return -1 /* True */; } var sourceErasedSignature = getErasedSignature(sourceSig); var targetErasedSignature = getErasedSignature(targetSig); var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. if (reportErrors) { reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); } return 0 /* False */; } } return -1 /* True */; } } function signatureRelatedTo(source, target, reportErrors) { if (source === target) { return -1 /* True */; } if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return 0 /* False */; } var sourceMax = source.parameters.length; var targetMax = target.parameters.length; var checkCount; if (source.hasRestParameter && target.hasRestParameter) { checkCount = sourceMax > targetMax ? sourceMax : targetMax; sourceMax--; targetMax--; } else if (source.hasRestParameter) { sourceMax--; checkCount = targetMax; } else if (target.hasRestParameter) { targetMax--; checkCount = sourceMax; } else { checkCount = sourceMax < targetMax ? sourceMax : targetMax; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); var result = -1 /* True */; for (var i = 0; i < checkCount; i++) { var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); var saveErrorInfo = errorInfo; var related = isRelatedTo(s, t, reportErrors); if (!related) { related = isRelatedTo(t, s, false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); } return 0 /* False */; } errorInfo = saveErrorInfo; } result &= related; } if (source.typePredicate && target.typePredicate) { var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; var hasDifferentTypes; if (hasDifferentParameterIndex || (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { if (reportErrors) { var sourceParamText = source.typePredicate.parameterName; var targetParamText = target.typePredicate.parameterName; var sourceTypeText = typeToString(source.typePredicate.type); var targetTypeText = typeToString(target.typePredicate.type); if (hasDifferentParameterIndex) { reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); } else if (hasDifferentTypes) { reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); } reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); } return 0 /* False */; } } else if (!source.typePredicate && target.typePredicate) { if (reportErrors) { reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); } return 0 /* False */; } var targetReturnType = getReturnTypeOfSignature(target); if (targetReturnType === voidType) return result; var sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); if (sourceSignatures.length !== targetSignatures.length) { return 0 /* False */; } var result = -1 /* True */; for (var i = 0, len = sourceSignatures.length; i < len; ++i) { var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return 0 /* False */; } result &= related; } return result; } function stringIndexTypesRelatedTo(source, originalSource, target, reportErrors) { if (relation === identityRelation) { return indexTypesIdenticalTo(0 /* String */, source, target); } var targetType = getIndexTypeOfType(target, 0 /* String */); if (targetType) { if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { // non-primitive assignment to any is always allowed, eg // `var x: { [index: string]: any } = { property: 12 };` return -1 /* True */; } var sourceType = getIndexTypeOfType(source, 0 /* String */); if (!sourceType) { if (reportErrors) { reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return 0 /* False */; } var related = isRelatedTo(sourceType, targetType, reportErrors); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Index_signatures_are_incompatible); } return 0 /* False */; } return related; } return -1 /* True */; } function numberIndexTypesRelatedTo(source, originalSource, target, reportErrors) { if (relation === identityRelation) { return indexTypesIdenticalTo(1 /* Number */, source, target); } var targetType = getIndexTypeOfType(target, 1 /* Number */); if (targetType) { if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { // non-primitive assignment to any is always allowed, eg // `var x: { [index: number]: any } = { property: 12 };` return -1 /* True */; } var sourceStringType = getIndexTypeOfType(source, 0 /* String */); var sourceNumberType = getIndexTypeOfType(source, 1 /* Number */); if (!(sourceStringType || sourceNumberType)) { if (reportErrors) { reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return 0 /* False */; } var related; if (sourceStringType && sourceNumberType) { // If we know for sure we're testing both string and numeric index types then only report errors from the second one related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); } else { related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); } if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Index_signatures_are_incompatible); } return 0 /* False */; } return related; } return -1 /* True */; } function indexTypesIdenticalTo(indexKind, source, target) { var targetType = getIndexTypeOfType(target, indexKind); var sourceType = getIndexTypeOfType(source, indexKind); if (!sourceType && !targetType) { return -1 /* True */; } if (sourceType && targetType) { return isRelatedTo(sourceType, targetType); } return 0 /* False */; } }
Checks if 'source' is related to 'target' (e.g.: is a assignable to). @param source The left-hand-side of the relation. @param target The right-hand-side of the relation. @param relation The relation considered. One of 'identityRelation', 'assignableRelation', or 'subTypeRelation'. Used as both to determine which checks are performed and as a cache of previously computed results. @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. @param containingMessageChain A chain of errors to prepend any new errors found.
checkTypeRelatedTo
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isTupleType(type) { return !!(type.flags & 8192 /* Tuple */); }
Check if a Type was written as a tuple type literal. Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
isTupleType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function reportWideningErrorsInType(type) { var errorReported = false; if (type.flags & 16384 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } if (isTupleType(type)) { for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } if (type.flags & 524288 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); if (t.flags & 2097152 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } errorReported = true; } } } return errorReported; }
Reports implicit any errors that occur as a result of widening 'null' and 'undefined' to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to getWidenedType. But in some cases getWidenedType is called without reporting errors (type argument inference is an example). The return value indicates whether an error was in fact reported. The particular circumstances are on a best effort basis. Currently, if the null or undefined that causes widening is inside an object literal property (arbitrarily deeply), this function reports an error. If no error is reported, reportImplicitAnyError is a suitable fallback to report a general error.
reportWideningErrorsInType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getContextualType(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (node.contextualType) { return node.contextualType; } var parent = node.parent; switch (parent.kind) { case 211 /* VariableDeclaration */: case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 163 /* BindingElement */: return getContextualTypeForInitializerExpression(node); case 174 /* ArrowFunction */: case 204 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); case 184 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); case 168 /* CallExpression */: case 169 /* NewExpression */: return getContextualTypeForArgument(parent, node); case 171 /* TypeAssertionExpression */: case 189 /* AsExpression */: return getTypeFromTypeNode(parent.type); case 181 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); case 245 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); case 164 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); case 182 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); case 190 /* TemplateSpan */: ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); case 172 /* ParenthesizedExpression */: return getContextualType(parent); case 240 /* JsxExpression */: case 239 /* JsxSpreadAttribute */: return getContextualTypeForJsxExpression(parent); } return undefined; }
Woah! Do you really want to use this function? Unless you're trying to get the *non-apparent* type for a value-literal type or you're authoring relevant portions of this algorithm, you probably meant to use 'getApparentTypeOfContextualType'. Otherwise this may not be very useful. In cases where you *are* working on this function, you should understand when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContetxualType'. - Use 'getContextualType' when you are simply going to propagate the result to the expression. - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. @param node the expression whose contextual type will be returned. @returns the contextual type of an expression.
getContextualType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isInferentialContext(mapper) { return mapper && mapper.context; }
Detect if the mapper implies an inference context. Specifically, there are 4 possible values for a mapper. Let's go through each one of them: 1. undefined - this means we are not doing inferential typing, but we may do contextual typing, which could cause us to assign a parameter a type 2. identityMapper - means we want to avoid assigning a parameter a type, whether or not we are in inferential typing (context is undefined for the identityMapper) 3. a mapper created by createInferenceMapper - we are doing inferential typing, we want to assign types to parameters and fix type parameters (context is defined) 4. an instantiation mapper created by createTypeMapper or createTypeEraser - this should never be passed as the contextual mapper when checking an expression (context is undefined for these) isInferentialContext is detecting if we are in case 3
isInferentialContext
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function isUnhyphenatedJsxName(name) { // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers return name.indexOf("-") < 0; }
Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
isUnhyphenatedJsxName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getJsxElementPropertiesName() { // JSX var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); // JSX.ElementAttributesProperty [symbol] var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properites of JSX.ElementAttributesProperty var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { // Element Attributes has zero properties, so the element attributes type will be the class instance type if (attribProperties.length === 0) { return ""; } else if (attribProperties.length === 1) { return attribProperties[0].name; } else { error(attribsPropTypeSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, JsxNames.ElementAttributesPropertyNameContainer); return undefined; } } else { // No interface exists, so the element attributes type will be an implicit any return undefined; } }
Given a JSX element that is a class element, finds the Element Instance Type. If the element is not a class element, or the class element type cannot be determined, returns 'undefined'. For example, in the element <MyClass>, the element instance type is `MyClass` (not `typeof MyClass`).
getJsxElementPropertiesName
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getJsxGlobalElementClassType() { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); } return jsxElementClassType; }
Given a JSX attribute, returns the symbol for the corresponds property of the element attributes type. Will return unknownSymbol for attributes that have no matching element attributes type property.
getJsxGlobalElementClassType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === 95 /* SuperKeyword */) { var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? node.name : node.right; // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, // a super property access is permitted and must specify a public instance member function of the base class. // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. if (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } if (flags & 128 /* Abstract */) { // A method cannot be accessed in a super property access if the method is abstract. // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); return false; } } // Public properties are otherwise accessible. if (!(flags & (16 /* Private */ | 32 /* Protected */))) { return true; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same if (flags & 16 /* Private */) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; } return true; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access if (left.kind === 95 /* SuperKeyword */) { return true; } // A protected property is accessible in the declaring class and classes derived from it if (!enclosingClass || !hasBaseType(enclosingClass, declaringClass)) { error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); return false; } // No further restrictions for static properties if (flags & 64 /* Static */) { return true; } // An instance property must be accessed through an instance of the enclosing class if (type.flags & 33554432 /* ThisType */) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) { error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; }
Check whether the requested property access is valid. Returns true if node is a valid property access, and false otherwise. @param node The node to be checked. @param left The left hand side of the property access (e.g.: the super in `super.foo`). @param type The type of left. @param prop The symbol for the right hand side of the property access.
checkClassPropertyAccess
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. if (node.kind === 214 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } if (node.kind === 138 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; if (node.kind === 144 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } if (node.kind === 141 /* PropertyDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the // parent of the member. return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; }
Returns the effective type of the first argument to a decorator. If 'node' is a class declaration or class expression, the effective argument type is the type of the static side of the class. If 'node' is a parameter declaration, the effective argument type is either the type of the static or instance side of the class for the parameter's parent method, depending on whether the method is declared static. For a constructor, the type is always the type of the static side of the class. If 'node' is a property, method, or accessor declaration, the effective argument type is the type of the static or instance side of the parent class for class element, depending on whether the element is declared static.
getEffectiveDecoratorFirstArgumentType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a paramter decorator if (node.kind === 214 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } if (node.kind === 138 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } if (node.kind === 141 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } if (node.kind === 143 /* MethodDeclaration */ || node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor<T>` // for the type of the member. var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); return unknownType; }
Returns the effective argument type for the third argument to a decorator. If 'node' is a parameter, the effective argument type is the number type. If 'node' is a method or accessor, the effective argument type is a `TypedPropertyDescriptor<T>` instantiated with the type of the member. Class and property decorators do not have a third effective argument.
getEffectiveDecoratorThirdArgumentType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function resolveCall(node, signatures, candidatesOutArray, headMessage) { var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; var isDecorator = node.kind === 139 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (node.expression.kind !== 95 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } var candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); // The following applies to any value of 'excludeArgument[i]': // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. // - false: the argument at 'i' *was* and *has been* permanently contextually typed. // // The idea is that we will perform type argument inference & assignability checking once // without using the susceptible parameters that are functions, and once more for each of those // parameters, contextually typing each as we go along. // // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var excludeArgument; if (!isDecorator) { // We do not need to call `getEffectiveArgumentCount` here as it only // applies when calculating the number of arguments for a decorator. for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { excludeArgument = new Array(args.length); } excludeArgument[i] = true; } } } // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not // assignable to a parameter. This implies that everything else about the overload // was fine. So if there is any overload that is only incorrect because of an // argument, we will report an error on that one. // // function foo(s: string) {} // function foo(n: number) {} // Report argument error on this overload // function foo() {} // foo(true); // // If none of the overloads even made it that far, there are two possibilities. // There was a problem with type arguments for some overload, in which case // report an error on that. Or none of the overloads even had correct arity, // in which case give an arity error. // // function foo<T>(x: T, y: T) {} // Report type argument inference error // function foo() {} // foo(0, true); // var candidateForArgumentError; var candidateForTypeArgumentError; var resultOfFailedInference; var result; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first // of those signatures becomes the return type of the function call. // Otherwise, the return type of the first signature in the candidate list becomes the return // type of the function call. // // Whether the call is an error is determined by assignability of the arguments. The subtype pass // is just important for choosing the best signature. So in the case where there is only one // signature, the subtype pass is useless. So skipping it is an optimization. if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation); } if (!result) { // Reinitialize these pointers for round two candidateForArgumentError = undefined; candidateForTypeArgumentError = undefined; resultOfFailedInference = undefined; result = chooseOverload(candidates, assignableRelation); } if (result) { return result; } // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. if (candidateForArgumentError) { // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] // The importance of excludeArgument is to prevent us from typing function expression parameters // in arguments too early. If possible, we'd like to only type them once we know the correct // overload. However, this matters for the case where the call is correct. When the call is // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); if (headMessage) { diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); } reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead); } } else { reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information that anySignature. // Pick the first candidate that matches the arity. This way we can get a contextual type for cases like: // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); } return candidate; } } } return resolveErrorCall(node); function reportError(message, arg0, arg1, arg2) { var errorInfo; errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); if (headMessage) { errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); } function chooseOverload(candidates, relation) { for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate)) { continue; } var candidate = void 0; var typeArgumentsAreValid = void 0; var inferenceContext = originalCandidate.typeParameters ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { typeArgumentTypes = new Array(candidate.typeParameters.length); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; typeArgumentTypes = inferenceContext.inferredTypes; } if (!typeArgumentsAreValid) { break; } candidate = getSignatureInstantiation(candidate, typeArgumentTypes); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { break; } var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; if (index < 0) { return candidate; } excludeArgument[index] = false; } // A post-mortem of this iteration of the loop. The signature was not applicable, // so we want to track it as a candidate for reporting an error. If the candidate // had no type parameters, or had no issues related to type arguments, we can // report an error based on the arguments. If there was an issue with type // arguments, then we can only report an error based on the type arguments. if (originalCandidate.typeParameters) { var instantiatedCandidate = candidate; if (typeArgumentsAreValid) { candidateForArgumentError = instantiatedCandidate; } else { candidateForTypeArgumentError = originalCandidate; if (!typeArguments) { resultOfFailedInference = inferenceContext; } } } else { ts.Debug.assert(originalCandidate === candidate); candidateForArgumentError = originalCandidate; } } return undefined; } }
Gets the error node to use when reporting errors for an effective argument.
resolveCall
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function checkCallExpression(node) { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 95 /* SuperKeyword */) { return voidType; } if (node.kind === 169 /* NewExpression */) { var declaration = signature.declaration; if (declaration && declaration.kind !== 144 /* Constructor */ && declaration.kind !== 148 /* ConstructSignature */ && declaration.kind !== 153 /* ConstructorType */) { // When resolved signature is a call signature (and not a construct signature) the result type is any if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); }
Syntactically and semantically checks a call or new expression. @param node The call/new expression to be checked. @returns On success, the expression's signature's return type. On failure, anyType.
checkCallExpression
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getTypeOfFirstParameterOfSignature(signature) { return getTypeAtPosition(signature, 0); }
Gets the "promised type" of a promise. @param type The type of the promise. @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
getTypeOfFirstParameterOfSignature
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getAwaitedType(type) { return checkAwaitedType(type, /*location*/ undefined, /*message*/ undefined); }
Gets the "awaited type" of a type. @param type The type to await. @remarks The "awaited type" of an expression is its "promised type" if the expression is a Promise-like type; otherwise, it is the type of the expression. This is used to reflect The runtime behavior of the `await` keyword.
getAwaitedType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function checkAsyncFunctionReturnType(node) { var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. return unknownType; } // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. // // An example might be (from lib.es6.d.ts): // // interface Promise<T> { ... } // interface PromiseConstructor { // new <T>(...): Promise<T>; // } // declare var Promise: PromiseConstructor; // // When an async function declares a return type annotation of `Promise<T>`, we // need to get the type of the `Promise` variable declaration above, which would // be `PromiseConstructor`. // // The same case applies to a class: // // declare class Promise<T> { // constructor(...); // then<U>(...): Promise<U>; // } // // When we get the type of the `Promise` symbol here, we get the type of the static // side of the `Promise` class, which would be `{ new <T>(...): Promise<T> }`. var promiseType = getTypeFromTypeNode(node.type); if (promiseType === unknownType && compilerOptions.isolatedModules) { // If we are compiling with isolatedModules, we may not be able to resolve the // type as a value. As such, we will just return unknownType; return unknownType; } var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { var typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } // Verify there is no local declaration that could collide with the promise constructor. var promiseName = ts.getEntityNameFromTypeNode(node.type); var root = getFirstIdentifier(promiseName); var rootSymbol = getSymbol(node.locals, root.text, 107455 /* Value */); if (rootSymbol) { error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } // Get and return the awaited type of the return type. return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); }
Checks the return type of an async function to ensure it is a compatible Promise implementation. @param node The signature to check @param returnType The return type for the function @remarks This checks that an async function has a valid Promise-compatible return type, and returns the *awaited type* of the promise. An async function has a valid Promise-compatible return type if the resolved value of the return type has a construct signature that takes in an `initializer` function that in turn supplies a `resolve` function as one of its arguments and results in an object with a callable `then` signature.
checkAsyncFunctionReturnType
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getElementTypeOfIterable(type, errorNode) { if (isTypeAny(type)) { return undefined; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable<number>), // then just grab its type argument. if ((type.flags & 4096 /* Reference */) && type.target === globalIterableType) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); if (isTypeAny(iteratorFunction)) { return undefined; } var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray; if (iteratorFunctionSignatures.length === 0) { if (errorNode) { error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); } return undefined; } typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } } return typeAsIterable.iterableElementType; }
We want to treat type as an iterable, and get the type it is an iterable of. The iterable must have the following structure (annotated with the names of the variables below): { // iterable [Symbol.iterator]: { // iteratorFunction (): Iterator<T> } } T is the type we are after. At every level that involves analyzing return types of signatures, we union the return types of all the signatures. Another thing to note is that at any step of this process, we could run into a dead end, meaning either the property is missing, or we run into the anyType. If either of these things happens, we return undefined to signal that we could not find the iterated type. If a property is missing, and the previous step did not result in 'any', then we also give an error if the caller requested it. Then the caller can decide what to do in the case where there is no iterated type. This is different from returning anyType, because that would signify that we have matched the whole pattern and that T (above) is 'any'.
getElementTypeOfIterable
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function getElementTypeOfIterator(type, errorNode) { if (isTypeAny(type)) { return undefined; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator<number>), // then just grab its type argument. if ((type.flags & 4096 /* Reference */) && type.target === globalIteratorType) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { var iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); if (isTypeAny(iteratorNextFunction)) { return undefined; } var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray; if (iteratorNextFunctionSignatures.length === 0) { if (errorNode) { error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); } return undefined; } var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); if (!iteratorNextValue) { if (errorNode) { error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); } return undefined; } typeAsIterator.iteratorElementType = iteratorNextValue; } } return typeAsIterator.iteratorElementType; }
This function has very similar logic as getElementTypeOfIterable, except that it operates on Iterators instead of Iterables. Here is the structure: { // iterator next: { // iteratorNextFunction (): { // iteratorNextResult value: T // iteratorNextValue } } }
getElementTypeOfIterator
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2 /* ES6 */); // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. var arrayType = removeTypesFromUnionType(arrayOrStringType, 258 /* StringLike */, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { if (languageVersion < 1 /* ES5 */) { error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); reportedError = true; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. if (arrayType === emptyObjectType) { return stringType; } } if (!isArrayLikeType(arrayType)) { if (!reportedError) { // Which error we report depends on whether there was a string constituent. For example, // if the input type is number | string, we want to say that number is not an array type. // But if the input was just number, we want to say that number is not an array type // or a string type. var diagnostic = hasStringConstituent ? ts.Diagnostics.Type_0_is_not_an_array_type : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(errorNode, diagnostic, typeToString(arrayType)); } return hasStringConstituent ? stringType : unknownType; } var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] if (arrayElementType.flags & 258 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType]); } return arrayElementType; }
This function does the following steps: 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents. 2. Take the element types of the array constituents. 3. Return the union of the element types, and string if there was a string constitutent. For example: string -> string number[] -> number string[] | number[] -> string | number string | number[] -> string | number string | string[] | number[] -> string | number It also errors if: 1. Some constituent is neither a string nor an array. 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable).
checkElementTypeOfArrayOrString
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT
function copySymbols(source, meaning) { if (meaning) { for (var id in source) { var symbol = source[id]; copySymbol(symbol, meaning); } } }
Copy the given symbol into symbol tables if the symbol has the given meaning and it doesn't already existed in the symbol table @param key a key for storing in symbol table; if undefined, use symbol.name @param symbol the symbol to be added into symbol table @param meaning meaning of symbol to filter by before adding to symbol table
copySymbols
javascript
amol-/dukpy
dukpy/jsmodules/typescriptServices.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
MIT