summaryrefslogtreecommitdiff
path: root/deps/node/deps/npm/node_modules/genfun/lib/genfun.js
blob: c6ba01ca54bb0604226a517569400db60a016ba4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
'use strict'

const Method = require('./method')
const Role = require('./role')
const util = require('./util')

const kCache = Symbol('cache')
const kDefaultMethod = Symbol('defaultMethod')
const kMethods = Symbol('methods')
const kNoNext = Symbol('noNext')

module.exports = function genfun (opts) {
  function gf () {
    if (!gf[kMethods].length && gf[kDefaultMethod]) {
      return gf[kDefaultMethod].func.apply(this, arguments)
    } else {
      return gf.applyGenfun(this, arguments)
    }
  }
  Object.setPrototypeOf(gf, Genfun.prototype)
  gf[kMethods] = []
  gf[kCache] = {key: [], methods: [], state: STATES.UNINITIALIZED}
  if (opts && typeof opts === 'function') {
    gf.add(opts)
  } else if (opts && opts.default) {
    gf.add(opts.default)
  }
  if (opts && opts.name) {
    Object.defineProperty(gf, 'name', {
      value: opts.name
    })
  }
  if (opts && opts.noNextMethod) {
    gf[kNoNext] = true
  }
  return gf
}

class Genfun extends Function {}
Genfun.prototype.isGenfun = true

const STATES = {
  UNINITIALIZED: 0,
  MONOMORPHIC: 1,
  POLYMORPHIC: 2,
  MEGAMORPHIC: 3
}

const MAX_CACHE_SIZE = 32

/**
 * Defines a method on a generic function.
 *
 * @function
 * @param {Array-like} selector - Selector array for dispatching the method.
 * @param {Function} methodFunction - Function to execute when the method
 *                                    successfully dispatches.
 */
Genfun.prototype.add = function addMethod (selector, func) {
  if (!func && typeof selector === 'function') {
    func = selector
    selector = []
  }
  selector = [].slice.call(selector)
  for (var i = 0; i < selector.length; i++) {
    if (!selector.hasOwnProperty(i)) {
      selector[i] = Object.prototype
    }
  }
  this[kCache] = {key: [], methods: [], state: STATES.UNINITIALIZED}
  let method = new Method(this, selector, func)
  if (selector.length) {
    this[kMethods].push(method)
  } else {
    this[kDefaultMethod] = method
  }
  return this
}

/**
 * Removes a previously-defined method on `genfun` that matches
 * `selector` exactly.
 *
 * @function
 * @param {Genfun} genfun - Genfun to remove a method from.
 * @param {Array-like} selector - Objects to match on when finding a
 *                                    method to remove.
 */
Genfun.prototype.rm = function removeMethod () {
  throw new Error('not yet implemented')
}

/**
 * Returns true if there are methods that apply to the given arguments on
 * `genfun`. Additionally, makes sure the cache is warmed up for the given
 * arguments.
 *
 */
Genfun.prototype.hasMethod = function hasMethod () {
  const methods = this.getApplicableMethods(arguments)
  return !!(methods && methods.length)
}

/**
 * This generic function is called when `genfun` has been called and no
 * applicable method was found. The default method throws an `Error`.
 *
 * @function
 * @param {Genfun} genfun - Generic function instance that was called.
 * @param {*} newthis - value of `this` the genfun was called with.
 * @param {Array} callArgs - Arguments the genfun was called with.
 */
module.exports.noApplicableMethod = module.exports()
module.exports.noApplicableMethod.add([], (gf, thisArg, args) => {
  let msg =
        'No applicable method found when called with arguments of types: (' +
        [].map.call(args, (arg) => {
          return (/\[object ([a-zA-Z0-9]+)\]/)
            .exec(({}).toString.call(arg))[1]
        }).join(', ') + ')'
  let err = new Error(msg)
  err.genfun = gf
  err.thisArg = thisArg
  err.args = args
  throw err
})

/*
 * Internal
 */
Genfun.prototype.applyGenfun = function applyGenfun (newThis, args) {
  let applicableMethods = this.getApplicableMethods(args)
  if (applicableMethods.length === 1 || this[kNoNext]) {
    return applicableMethods[0].func.apply(newThis, args)
  } else if (applicableMethods.length > 1) {
    let idx = 0
    const nextMethod = function nextMethod () {
      if (arguments.length) {
        // Replace args if passed in explicitly
        args = arguments
        Array.prototype.push.call(args, nextMethod)
      }
      const next = applicableMethods[idx++]
      if (idx >= applicableMethods.length) {
        Array.prototype.pop.call(args)
      }
      return next.func.apply(newThis, args)
    }
    Array.prototype.push.call(args, nextMethod)
    return nextMethod()
  } else {
    return module.exports.noApplicableMethod(this, newThis, args)
  }
}

Genfun.prototype.getApplicableMethods = function getApplicableMethods (args) {
  if (!args.length || !this[kMethods].length) {
    return this[kDefaultMethod] ? [this[kDefaultMethod]] : []
  }
  let applicableMethods
  let maybeMethods = cachedMethods(this, args)
  if (maybeMethods) {
    applicableMethods = maybeMethods
  } else {
    applicableMethods = computeApplicableMethods(this, args)
    cacheArgs(this, args, applicableMethods)
  }
  return applicableMethods
}

function cacheArgs (genfun, args, methods) {
  if (genfun[kCache].state === STATES.MEGAMORPHIC) { return }
  var key = []
  var proto
  for (var i = 0; i < args.length; i++) {
    proto = cacheableProto(genfun, args[i])
    if (proto) {
      key[i] = proto
    } else {
      return null
    }
  }
  genfun[kCache].key.unshift(key)
  genfun[kCache].methods.unshift(methods)
  if (genfun[kCache].key.length === 1) {
    genfun[kCache].state = STATES.MONOMORPHIC
  } else if (genfun[kCache].key.length < MAX_CACHE_SIZE) {
    genfun[kCache].state = STATES.POLYMORPHIC
  } else {
    genfun[kCache].state = STATES.MEGAMORPHIC
  }
}

function cacheableProto (genfun, arg) {
  var dispatchable = util.dispatchableObject(arg)
  if (Object.hasOwnProperty.call(dispatchable, Role.roleKeyName)) {
    for (var j = 0; j < dispatchable[Role.roleKeyName].length; j++) {
      var role = dispatchable[Role.roleKeyName][j]
      if (role.method.genfun === genfun) {
        return null
      }
    }
  }
  return Object.getPrototypeOf(dispatchable)
}

function cachedMethods (genfun, args) {
  if (genfun[kCache].state === STATES.UNINITIALIZED ||
      genfun[kCache].state === STATES.MEGAMORPHIC) {
    return null
  }
  var protos = []
  var proto
  for (var i = 0; i < args.length; i++) {
    proto = cacheableProto(genfun, args[i])
    if (proto) {
      protos[i] = proto
    } else {
      return
    }
  }
  for (i = 0; i < genfun[kCache].key.length; i++) {
    if (matchCachedMethods(genfun[kCache].key[i], protos)) {
      return genfun[kCache].methods[i]
    }
  }
}

function matchCachedMethods (key, protos) {
  if (key.length !== protos.length) { return false }
  for (var i = 0; i < key.length; i++) {
    if (key[i] !== protos[i]) {
      return false
    }
  }
  return true
}

function computeApplicableMethods (genfun, args) {
  args = [].slice.call(args)
  let discoveredMethods = []
  function findAndRankRoles (object, hierarchyPosition, index) {
    var roles = Object.hasOwnProperty.call(object, Role.roleKeyName)
    ? object[Role.roleKeyName]
    : []
    roles.forEach(role => {
      if (role.method.genfun === genfun && index === role.position) {
        if (discoveredMethods.indexOf(role.method) < 0) {
          Method.clearRank(role.method)
          discoveredMethods.push(role.method)
        }
        Method.setRankHierarchyPosition(role.method, index, hierarchyPosition)
      }
    })
    // When a discovered method would receive more arguments than
    // were specialized, we pretend all extra arguments have a role
    // on Object.prototype.
    if (util.isObjectProto(object)) {
      discoveredMethods.forEach(method => {
        if (method.minimalSelector <= index) {
          Method.setRankHierarchyPosition(method, index, hierarchyPosition)
        }
      })
    }
  }
  args.forEach((arg, index) => {
    getPrecedenceList(util.dispatchableObject(arg))
      .forEach((obj, hierarchyPosition) => {
        findAndRankRoles(obj, hierarchyPosition, index)
      })
  })
  let applicableMethods = discoveredMethods.filter(method => {
    return (args.length === method._rank.length &&
            Method.isFullySpecified(method))
  })
  applicableMethods.sort((a, b) => Method.score(a) - Method.score(b))
  if (genfun[kDefaultMethod]) {
    applicableMethods.push(genfun[kDefaultMethod])
  }
  return applicableMethods
}

/*
 * Helper function for getting an array representing the entire
 * inheritance/precedence chain for an object by navigating its
 * prototype pointers.
 */
function getPrecedenceList (obj) {
  var precedenceList = []
  var nextObj = obj
  while (nextObj) {
    precedenceList.push(nextObj)
    nextObj = Object.getPrototypeOf(nextObj)
  }
  return precedenceList
}