29646cb09a5927c7ddc2393876930f97ad954d3e.svn-base
8.82 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
;(function() {
'use strict'
/* global define */
var esprima
var exportFn
var toString = Object.prototype.toString
if (typeof module === 'object' && typeof module.exports === 'object' && typeof require === 'function') {
// server side
esprima = require('esprima')
exportFn = function(redeyed) { module.exports = redeyed }
bootstrap(esprima, exportFn)
} else if (typeof define === 'function' && define.amd) {
// client side
// amd
define(['esprima'], function(esprima) {
return bootstrap(esprima)
})
} else if (typeof window === 'object') {
// no amd -> attach to window if it exists
// Note that this requires 'esprima' to be defined on the window, so that script has to be loaded first
window.redeyed = bootstrap(window.esprima)
}
function bootstrap(esprima, exportFn) {
function isFunction(obj) {
return toString.call(obj) === '[object Function]'
}
function isString(obj) {
return toString.call(obj) === '[object String]'
}
function isObject(obj) {
return toString.call(obj) === '[object Object]'
}
function surroundWith(before, after) {
return function(s) { return before + s + after }
}
function isNonCircular(key) {
return key !== '_parent'
}
function objectizeString(value) {
var vals = value.split(':')
if (vals.length === 0 || vals.length > 2) {
throw new Error(
'illegal string config: ' + value +
'\nShould be of format "before:after"'
)
}
if (vals.length === 1 || vals[1].length === 0) {
return vals.indexOf(':') < 0 ? { _before: vals[0] } : { _after: vals[0] }
} else {
return { _before: vals[0], _after: vals[1] }
}
}
function objectize(node) {
// Converts 'bef:aft' to { _before: bef, _after: aft }
// and resolves undefined before/after from parent or root
function resolve(value, key) {
// resolve before/after from root or parent if it isn't present on the current node
if (!value._parent) return undefined
// Immediate parent
if (value._parent._default && value._parent._default[key]) return value._parent._default[key]
// Root
var root = value._parent._parent
if (!root) return undefined
return root._default ? root._default[key] : undefined
}
function process(key) {
var value = node[key]
if (!value) return
if (isFunction(value)) return
// normalize all strings to objects
if (isString(value)) {
node[key] = value = objectizeString(value)
}
value._parent = node
if (isObject(value)) {
if (!value._before && !value._after) return objectize(value)
// resolve missing _before or _after from parent(s)
// in case we only have either one on this node
value._before = value._before || resolve(value, '_before')
value._after = value._after || resolve(value, '_after')
return
}
throw new Error('nodes need to be either {String}, {Object} or {Function}.' + value + ' is neither.')
}
// Process _default ones first so children can resolve missing before/after from them
if (node._default) process('_default')
Object.keys(node)
.filter(function(key) {
return isNonCircular(key)
&& node.hasOwnProperty(key)
&& key !== '_before'
&& key !== '_after'
&& key !== '_default'
})
.forEach(process)
}
function functionize(node) {
Object.keys(node)
.filter(function(key) {
return isNonCircular(key) && node.hasOwnProperty(key)
})
.forEach(function(key) {
var value = node[key]
if (isFunction(value)) return
if (isObject(value)) {
if (!value._before && !value._after) return functionize(value)
// at this point before/after were "inherited" from the parent or root
// (see objectize)
var before = value._before || ''
var after = value._after || ''
node[key] = surroundWith(before, after)
return node[key]
}
})
}
function normalize(root) {
objectize(root)
functionize(root)
}
function mergeTokensAndComments(tokens, comments) {
var all = {}
function addToAllByRangeStart(t) { all[ t.range[0] ] = t }
tokens.forEach(addToAllByRangeStart)
comments.forEach(addToAllByRangeStart)
// keys are sorted automatically
return Object.keys(all)
.map(function(k) { return all[k] })
}
function redeyed(code, config, opts) {
opts = opts || {}
var parser = opts.parser || esprima
var jsx = !!opts.jsx
// tokenizer doesn't support JSX at this point (esprima@4.0.0)
// therefore we need to generate the AST via the parser not only to
// avoid the tokenizer from erroring but also to get JSXIdentifier tokens
var buildAst = jsx || !!opts.buildAst
var hashbang = ''
var ast
var tokens
var comments
var lastSplitEnd = 0
var splits = []
var transformedCode
var all
var info
// Replace hashbang line with empty whitespaces to preserve token locations
if (code[0] === '#' && code[1] === '!') {
hashbang = code.substr(0, code.indexOf('\n') + 1)
code = Array.apply(0, Array(hashbang.length)).join(' ') + '\n' + code.substr(hashbang.length)
}
if (buildAst) {
ast = parser.parse(code, { tokens: true, comment: true, range: true, loc: true, tolerant: true, jsx: true })
tokens = ast.tokens
comments = ast.comments
} else {
tokens = []
comments = []
parser.tokenize(code, { range: true, loc: true, comment: true }, function(token) {
if (token.type === 'LineComment') {
token.type = 'Line'
comments.push(token)
} else if (token.type === 'BlockComment') {
token.type = 'Block'
comments.push(token)
} else {
// Optimistically upgrade 'static' to a keyword
if (token.type === 'Identifier' && token.value === 'static') token.type = 'Keyword'
tokens.push(token)
}
})
}
normalize(config)
function tokenIndex(tokens, tkn, start) {
var current
var rangeStart = tkn.range[0]
for (current = start; current < tokens.length; current++) {
if (tokens[current].range[0] === rangeStart) return current
}
throw new Error('Token %s not found at or after index: %d', tkn, start)
}
function process(surround) {
var result
var currentIndex
var nextIndex
var skip = 0
var splitEnd
result = surround(code.slice(start, end), info)
if (isObject(result)) {
splits.push(result.replacement)
currentIndex = info.tokenIndex
nextIndex = tokenIndex(info.tokens, result.skipPastToken, currentIndex)
skip = nextIndex - currentIndex
splitEnd = skip > 0 ? tokens[nextIndex - 1].range[1] : end
} else {
splits.push(result)
splitEnd = end
}
return { skip: skip, splitEnd: splitEnd }
}
function addSplit(start, end, surround, info) {
var result
var skip = 0
if (start >= end) return
if (surround) {
result = process(surround)
skip = result.skip
lastSplitEnd = result.splitEnd
} else {
splits.push(code.slice(start, end))
lastSplitEnd = end
}
return skip
}
all = mergeTokensAndComments(tokens, comments)
for (var tokenIdx = 0; tokenIdx < all.length; tokenIdx++) {
var token = all[tokenIdx]
var surroundForType = config[token.type]
var surround
var start
var end
// At least the type (e.g., 'Keyword') needs to be specified for the token to be surrounded
if (surroundForType) {
// root defaults are only taken into account while resolving before/after otherwise
// a root default would apply to everything, even if no type default was specified
surround = surroundForType
&& surroundForType.hasOwnProperty(token.value)
&& surroundForType[token.value]
&& isFunction(surroundForType[token.value])
? surroundForType[token.value]
: surroundForType._default
start = token.range[0]
end = token.range[1]
addSplit(lastSplitEnd, start)
info = { tokenIndex: tokenIdx, tokens: all, ast: ast, code: code }
tokenIdx += addSplit(start, end, surround, info)
}
}
if (lastSplitEnd < code.length) {
addSplit(lastSplitEnd, code.length)
}
if (!opts.nojoin) {
transformedCode = splits.join('')
if (hashbang.length > 0) {
transformedCode = hashbang + transformedCode.substr(hashbang.length)
}
}
return {
ast : ast
, tokens : tokens
, comments : comments
, splits : splits
, code : transformedCode
}
}
return exportFn ? exportFn(redeyed) : redeyed
}
})()