forked from shaunxcode/jsedn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
edn.coffee
363 lines (293 loc) · 8.75 KB
/
edn.coffee
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
us = require "underscore"
class Prim
constructor: (val) ->
if us.isArray val
@val = us.filter val, (x) -> not (x instanceof Discard)
else
@val = val
value: -> @val
toString: -> JSON.stringify @val
class StringObj extends Prim
toString: -> @val
is: (test) -> @val is test
class Tag
constructor: (@namespace, @name...) ->
if arguments.length is 1
[@namespace, @name...] = arguments[0].split('/')
ns: -> @namespace
dn: -> [@namespace].concat(@name).join('/')
class Tagged extends Prim
constructor: (@_tag, @_obj) ->
ednEncode: ->
"\##{@tag().dn()} #{encode @obj()}"
jsonEncode: ->
Tagged: [@tag().dn(), if @obj().jsonEncode? then @obj().jsonEncode() else @obj()]
tag: -> @_tag
obj: -> @_obj
class Discard
class Iterable extends Prim
ednEncode: ->
(@map (i) -> encode i).join " "
jsonEncode: ->
(@map (i) -> if i.jsonEncode? then i.jsonEncode() else i)
jsEncode: ->
(@map (i) -> if i.jsEncode? then i.jsEncode() else i)
exists: (index) ->
@val[index]?
at: (index) ->
if @exists index then @val[index]
set: (index, val) ->
@val[index] = val
this
methods = [
'forEach', 'each', 'map', 'reduce', 'reduceRight', 'find'
'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any'
'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex'
'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf'
'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'
]
for method in methods
do (method) ->
Iterable.prototype[method] = ->
us[method].apply us, [@val].concat(us.toArray arguments)
for method in ['concat', 'join', 'slice']
do (method) ->
Iterable.prototype[method] = ->
Array.prototype[method].apply @val, arguments
class List extends Iterable
ednEncode: ->
"(#{super()})"
jsonEncode: ->
List: super()
class Vector extends Iterable
ednEncode: ->
"[#{super()}]"
jsonEncode: ->
Vector: super()
class Set extends Iterable
ednEncode: ->
"\#{#{super()}}"
jsonEncode: ->
Set: super()
constructor: (val) ->
super()
@val = us.uniq val
if not us.isEqual val, @val
throw "set not distinct"
class Map
ednEncode: ->
"{#{(encode i for i in @value()).join " "}}"
jsonEncode: ->
{Map: ((if i.jsonEncode? then i.jsonEncode() else i) for i in @value())}
jsEncode: ->
result = {}
for k, i in @keys
hashId = if k.hashId? then k.hashId() else k
result[hashId] = if @vals[i].jsEncode? then @vals[i].jsEncode() else @vals[i]
result
constructor: (@val) ->
@keys = []
@vals = []
for v, i in @val
if i % 2 is 0
@keys.push v
else
@vals.push v
@val = false
value: ->
result = []
for v, i in @keys
result.push v
if @vals[i]? then result.push @vals[i]
result
exists: (key) ->
for k, i in @keys
if us.isEqual k, key
return i
return undefined
at: (key) ->
if (id = @exists key)?
@vals[id]
else
throw "key does not exist"
set: (key, val) ->
if (id = @exists key)?
@vals[id] = val
else
@keys.push key
@vals.push val
this
#based on the work of martin keefe: http://martinkeefe.com/dcpl/sexp_lib.html
parens = '()[]{}'
specialChars = parens + ' \t\n\r,'
parenTypes =
'(' : closing: ')', class: List
'[' : closing: ']', class: Vector
'{' : closing: '}', class: Map
lex = (string) ->
list = []
token = ''
for c in string
if not in_string? and c is ";"
in_comment = true
if in_comment
if c is "\n"
in_comment = undefined
if token
list.push token
token = ''
continue
if c is '"'
if in_string?
list.push (new StringObj in_string)
in_string = undefined
else
in_string = ''
continue
if in_string?
in_string += c
else if c in specialChars
if token
list.push token
token = ''
if c in parens
list.push c
else
if token is "#_"
list.push token
token = ''
token += c
if token
list.push(token)
list
#based roughly on the work of norvig from his lisp in python
read = (tokens) ->
read_ahead = (token) ->
if token is undefined then return
if paren = parenTypes[token]
closeParen = paren.closing
L = []
while true
token = tokens.shift()
if token is undefined then throw 'unexpected end of list'
if token is paren.closing then return (new paren.class L) else L.push read_ahead token
else if token in ")]}" then throw "unexpected #{token}"
else
handledToken = handle token
if handledToken instanceof Tag
token = tokens.shift()
if token is undefined then throw 'was expecting something to follow a tag'
tagged = new Tagged handledToken, read_ahead token
if tagged.tag().dn() is ""
if tagged.obj() instanceof Map
return new Set tagged.obj().value()
if tagged.tag().dn() is "_"
return new Discard
if tagActions[tagged.tag().dn()]?
return tagActions[tagged.tag().dn()].action tagged.obj()
return tagged
else
return handledToken
token1 = tokens.shift()
if token1 is undefined
return undefined
else
result = read_ahead token1
if result instanceof Discard
return ""
return result
handle = (token) ->
if token instanceof StringObj
return token.toString()
for name, handler of tokenHandlers
if handler.pattern.test token
return handler.action token
token
tokenHandlers =
nil: pattern: /^nil$/, action: (token) -> null
boolean: pattern: /^true$|^false$/, action: (token) -> token is "true"
character: pattern: /^\\[A-z0-9]$/, action: (token) -> token[-1..-1]
tab: pattern: /^\\tab$/, action: (token) -> "\t"
newLine: pattern: /^\\newline$/, action: (token) -> "\n"
space: pattern: /^\\space$/, action: (token) -> " "
literal: pattern: /^[<>\?\$].*$/, action: (token) -> token
keyword: pattern: /^[\:].*$/, action: (token) -> token[1..-1]
integer: pattern: /^\-?[0-9]*$/, action: (token) -> parseInt token
float: pattern: /^\-?[0-9]*\.[0-9]*$/, action: (token) -> parseFloat token
tagged: pattern: /^#.*$/, action: (token) -> new Tag token[1..-1]
tagActions =
uuid: tag: (new Tag "uuid"), action: (obj) -> obj
inst: tag: (new Tag "inst"), action: (obj) -> obj
encodeHandlers =
array:
test: (obj) -> us.isArray obj
action: (obj) -> "[#{(encode v for v in obj).join " "}]"
integer:
test: (obj) -> tokenHandlers.integer.pattern.test "#{obj}"
action: (obj) -> parseInt obj
float:
test: (obj) -> tokenHandlers.float.pattern.test "#{obj}"
action: (obj) -> parseFloat obj
literal:
test: (obj) -> (us.isString obj) and (tokenHandlers.literal.pattern.test obj)
action: (obj) -> obj
keyword:
test: (obj) -> (us.isString obj) and (" " not in obj) and (tokenHandlers.keyword.pattern.test obj)
action: (obj) -> obj
string:
test: (obj) -> us.isString obj
action: (obj) -> "\"#{obj.toString()}\""
boolean:
test: (obj) -> us.isBoolean obj
action: (obj) -> if obj then "true" else "false"
null:
test: (obj) -> us.isNull obj
action: (obj) -> "nil"
object:
test: (obj) -> us.isObject obj
action: (obj) ->
result = []
for k, v of obj
result.push encode (if tokenHandlers.integer.pattern.test k then k else ":#{k}")
result.push encode v
"{#{result.join " "}}"
#ENCODING
encode = (obj) ->
return obj.ednEncode() if obj.ednEncode?
for name, handler of encodeHandlers
if handler.test obj
return handler.action obj
throw "unhandled encoding for #{JSON.stringify obj}"
encodeJson = (obj, prettyPrint) ->
return (encodeJson obj.jsonEncode(), prettyPrint) if obj.jsonEncode?
return if prettyPrint then (JSON.stringify obj, null, 4) else JSON.stringify obj
atPath = (obj, path) ->
path = path.trim().replace(/[ ]{2,}/g, ' ').split(' ')
value = obj
for part in path
if value.exists
if value.exists(part)?
value = value.at part
else
throw "Could not find " + part
else
throw "Not a composite object"
value
exports.List = List
exports.Vector = Vector
exports.Map = Map
exports.Set = Set
exports.Tag = Tag
exports.Tagged = Tagged
exports.setTagAction = (tag, action) -> tagActions[tag.dn()] = tag: tag, action: action
exports.setTokenHandler = (handler, pattern, action) -> tokenHandlers[handler] = {pattern, action}
exports.setTokenPattern = (handler, pattern) -> tokenHandlers[handler].pattern = pattern
exports.setTokenAction = (handler, action) -> tokenHandlers[handler].action = action
exports.setEncodeHandler = (handler, test, action) -> encodeHandlers[handler] = {test, action}
exports.setEncodeTest = (type, test) -> encodeHandlers[type].test = test
exports.setEncodeAction = (type, action) -> encodeHandlers[type].action = action
exports.parse = (string) -> read lex string
exports.encode = encode
exports.encodeJson = encodeJson
exports.atPath = atPath
exports.toJS = (obj) -> if obj.jsEncode? then obj.jsEncode() else obj