forked from arturo-lang/arturo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconversion.nim
640 lines (573 loc) · 26.1 KB
/
conversion.nim
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#=======================================================
# Arturo
# Programming Language + Bytecode VM compiler
# (c) 2019-2025 Yanis Zafirópulos
#
# @file: helpers/conversion.nim
#=======================================================
#=======================================
# Libraries
#=======================================
import algorithm, parseutils, sequtils, strformat, strutils, sugar, tables, times, unicode
when defined(GMP):
import helpers/bignums
import helpers/objects
import helpers/ranges
when not defined(WEB):
import helpers/stores
import vm/[checks, errors, eval, exec, parse, stack]
import vm/values/[value, printable]
import vm/values/custom/[vbinary, vcolor, verror, vlogical, vquantity, vrange, vrational]
#=======================================
# Constants
#=======================================
let currentBuiltinName = "to"
#=======================================
# Helpers
#=======================================
proc parseFL(s: string): float =
result = 0.0
let L = parseutils.parseFloat(s, result, 0)
if L != s.len or L == 0:
raise newException(ValueError, "invalid float: " & s)
template throwCannotConvert(): untyped =
Error_CannotConvert(dumped(y), $(y.kind), (if x.tpKind==UserType: x.tid else: $(x.t)))
template throwConversionFailed(hnt: string = ""): untyped =
Error_ConversionFailed(dumped(y), $(y.kind), (if x.tpKind==UserType: x.tid else: $(x.t)), hnt)
#=======================================
# Methods
#=======================================
# TODO(Converters) Make sure `convertedValueToType` works fine + add tests
# labels: library, cleanup, unit-test
proc convertedValueToType*(x, y: Value, tp: ValueKind, aFormat:Value = nil): Value =
if unlikely(y.kind == tp):
return y
else:
case y.kind:
of Null:
case tp:
# TODO(Converters) should support :null -> :floating
of Logical: return VFALSE
of Integer: return I0
of String: return newString("null")
else: throwCannotConvert()
of Logical:
case tp:
of Integer:
if isTrue(y): return I1
elif isFalse(y): return I0
else: return VNULL
of Floating:
if isTrue(y): return F1
elif isFalse(y): return F0
else: return VNULL
of String:
if y.b==True: return newString("true")
elif y.b==False: return newString("false")
else: return newString("maybe")
else: throwCannotConvert()
of Integer:
case tp:
of Logical: return newLogical(y.i!=0)
of Floating: return newFloating(float(y.i))
of Rational:
if y.iKind == NormalInteger:
return newRational(y.i)
else:
when defined(GMP):
return newRational(y.bi)
of Char: return newChar(toUTF8(Rune(y.i)))
of String:
if y.iKind==NormalInteger:
if (not aFormat.isNil):
try:
var ret: string
formatValue(ret, y.i, aFormat.s)
return newString(ret)
except CatchableError:
throwConversionFailed("Make sure the number format specified via `.format:` is valid.")
else:
return newString($(y.i))
else:
when defined(GMP):
return newString($(y.bi))
of Quantity:
return newQuantity(y, @[])
of Date:
return newDate(local(fromUnix(y.i)))
of Binary:
if y.iKind==NormalInteger:
return newBinary(numberToBinary(y.i))
else:
throwConversionFailed("Cannot convert big integer values to binary.")
else: throwCannotConvert()
of Floating:
case tp:
of Logical: return newLogical(y.f!=0.0)
of Integer: return newInteger(int(y.f))
of Rational: return newRational(y.f)
of Char: return newChar(chr(int(y.f)))
of String:
if (not aFormat.isNil):
try:
var ret: string
formatValue(ret, y.f, aFormat.s)
return newString(ret)
except CatchableError:
throwConversionFailed("Make sure the number format specified via `.format:` is valid.")
else:
return newString($(y.f))
of Quantity:
return newQuantity(y, @[])
of Binary:
return newBinary(numberToBinary(y.f))
else: throwCannotConvert()
of Complex:
case tp:
of String:
if (not aFormat.isNil):
try:
var ret: string
formatValue(ret, y.z.re, aFormat.s)
var ret2: string
formatValue(ret2, y.z.im, aFormat.s)
return newString($(ret) & (if y.z.im >= 0: "+" else: "") & $(ret2) & "i")
except CatchableError:
throwConversionFailed("Make sure the floating-number format specified via `.format:` is valid.")
else:
return newString($(y))
of Block:
return newBlock(@[
newFloating(y.z.re),
newFloating(y.z.im)
])
else: throwCannotConvert()
of Rational:
case tp:
of Integer:
return newInteger(toInt(y.rat))
of Floating:
return newFloating(toFloat(y.rat))
of String:
return newString($(y))
of Block:
if y.rat.rKind == NormalRational:
return newBlock(@[
newInteger(getNumerator(y.rat)),
newInteger(getDenominator(y.rat))
])
else:
return newBlock(@[
newInteger(getNumerator(y.rat, big=true)),
newInteger(getDenominator(y.rat, big=true))
])
of Quantity:
return newQuantity(y, @[])
else: throwCannotConvert()
of Version:
if tp==String: return newString($(y))
else: throwCannotConvert()
of Type:
if tp==String: return newString(($(y.t)).toLowerAscii())
else: throwCannotConvert()
of Char:
case tp:
of Integer: return newInteger(ord(y.c))
of Floating: return newFloating(float(ord(y.c)))
of String: return newString($(y.c))
of Binary: return newBinary(@[byte(ord(y.c))])
else: throwCannotConvert()
of String:
case tp:
of Logical:
if y.s=="true": return VTRUE
elif y.s=="false": return VFALSE
elif y.s=="maybe": return VMAYBE
else: throwConversionFailed("Make sure the passed string contains one of the supported values: `true`, `false`, or `maybe`.")
of Integer:
try:
return newInteger(y.s)
except ValueError:
throwConversionFailed("Make sure the string contains a valid/parseable integer value.")
of Floating:
try:
return newFloating(parseFL(y.s))
except ValueError:
throwConversionFailed("Make sure the string contains a valid/parseable floating-point value.")
of Version:
try:
return newVersion(y.s)
except ValueError:
throwConversionFailed("Make sure the string contains a valid/parseable SemVer-compatible value; see also: <https://semver.org/>.")
of Type:
return newType(y.s)
of Char:
if y.s.runeLen() == 1:
return newChar(y.s)
else:
throwConversionFailed("Make sure the string contains exactly one character.")
of Word:
return newWord(y.s)
of Literal:
return newLiteral(y.s)
of Label:
return newLabel(y.s)
of Attribute:
return newAttribute(y.s)
of AttributeLabel:
return newAttributeLabel(y.s)
of Symbol:
try:
return newSymbol(y.s)
except ValueError:
throwConversionFailed("Make sure the string contains one of the supported symbols; see also: <https://github.com/arturo-lang/arturo/blob/564d547378d3897c1853e5466dd1b202f583245a/src/vm/values/custom/vsymbol.nim#L21-L124>.")
of ErrorKind:
return newErrorKind(y.s)
of Regex:
return newRegex(y.s)
of Binary:
var ret: VBinary = newSeq[byte](y.s.len)
for i,ch in y.s:
ret[i] = byte(ord(ch))
return newBinary(ret)
of Block:
return doParse(y.s, isFile=false)
of Color:
try:
return newColor(y.s)
except CatchableError:
throwConversionFailed("Make sure the string contains a parseable color value, either an RGB/A hex value or a valid color name; see also: <https://github.com/arturo-lang/arturo/blob/564d547378d3897c1853e5466dd1b202f583245a/src/vm/values/custom/vcolor.nim#L615-L1191>.")
of Date:
var dateFormat = "yyyy-MM-dd'T'HH:mm:sszzz"
if (not aFormat.isNil):
dateFormat = aFormat.s
let timeFormat = initTimeFormat(dateFormat)
try:
return newDate(parse(y.s, timeFormat))
except CatchableError:
throwConversionFailed("Make sure the string contains a parseable date value, that follows the format: `" & dateFormat & "`. You may also set an alternative format, by using the option: `.format:`.")
else:
throwCannotConvert()
of Literal,
Word,
Label:
case tp:
of String:
return newString(y.s)
of Literal:
return newLiteral(y.s)
of Word:
return newWord(y.s)
else:
throwCannotConvert()
of Attribute,
AttributeLabel:
case tp:
of String:
return newString(y.s)
of Literal:
return newLiteral(y.s)
of Word:
return newWord(y.s)
else:
throwCannotConvert()
of Inline:
case tp:
of Block:
return newBlock(y.a)
else:
throwCannotConvert()
# TODO(Converters) Block -> String conversion not supported!
# as incredible as it may sound `to :string [1 2 3]` is not supported
# this must be fixed ASAP
# labels: library, bug, enhancement, critical
of Block:
case tp:
of Complex:
requireBlockSize(y, 2)
let firstElem {.cursor} = y.a[0]
let secondElem {.cursor} = y.a[1]
requireValue(firstElem, {Floating, Integer})
requireValue(secondElem, {Floating, Integer})
return newComplex(firstElem, secondElem)
of Rational:
requireBlockSize(y, 2)
let firstElem {.cursor} = y.a[0]
let secondElem {.cursor} = y.a[1]
requireValue(firstElem, {Floating, Integer})
requireValue(secondElem, {Floating, Integer})
return newRational(firstElem, secondElem)
of String:
return newString($(y))
of Inline:
return newInline(y.a)
of Dictionary:
let stop = SP
execUnscoped(y)
let arr: ValueArray = sTopsFrom(stop)
var dict: ValueDict = initOrderedTable[string,Value]()
SP = stop
var i = 0
while i<arr.len:
if i+1<arr.len:
dict[$(arr[i])] = arr[i+1]
i += 2
return(newDictionary(dict))
of Object:
# TODO(convertedValueToType) should throw in case the user type is not initialized
# right now, if we do `to :person []` without first having done `define :person ...`
# seems to be working. But what is that supposed to do?
# labels: error handling, bug, oop, vm, values
if x.tpKind==UserType:
let stop = SP
execUnscoped(y)
let arr: ValueArray = sTopsFrom(stop)
SP = stop
if (let xProto = getType(x.tid); not xProto.isNil):
return generateNewObject(xProto, arr)
else:
Error_UsingUndefinedType(x.tid)
else:
throwCannotConvert()
of Quantity:
requireBlockSize(y, 2)
let firstElem {.cursor} = y.a[0]
let secondElem {.cursor} = y.a[1]
requireValue(firstElem, {Integer, Floating, Rational})
requireValue(secondElem, {Unit, Word, Literal, String})
if secondElem.kind == Unit:
return newQuantity(firstElem, secondElem.u)
else:
return newQuantity(firstElem, secondElem.s)
of Color:
requireBlockSize(y, 3, 4)
if (hadAttr("hsl")):
requireValue(y.a[0], {Integer})
requireValue(y.a[1], {Floating})
requireValue(y.a[2], {Floating})
if y.a.len==3:
return newColor(HSLtoRGB((y.a[0].i, y.a[1].f, y.a[2].f, 1.0)))
elif y.a.len==4:
requireValue(y.a[3], {Floating})
return newColor(HSLtoRGB((y.a[0].i, y.a[1].f, y.a[2].f, y.a[3].f)))
elif (hadAttr("hsv")):
requireValue(y.a[0], {Integer})
requireValue(y.a[1], {Floating})
requireValue(y.a[2], {Floating})
if y.a.len==3:
return newColor(HSVtoRGB((y.a[0].i, y.a[1].f, y.a[2].f, 1.0)))
elif y.a.len==4:
requireValue(y.a[3], {Floating})
return newColor(HSVtoRGB((y.a[0].i, y.a[1].f, y.a[2].f, y.a[3].f)))
else:
requireValueBlock(y, {Integer})
if y.a.len==3:
return newColor((y.a[0].i, y.a[1].i, y.a[2].i, 255))
elif y.a.len==4:
return newColor((y.a[0].i, y.a[1].i, y.a[2].i, y.a[3].i))
of Binary:
var res: VBinary
for item in y.a:
requireValue(item, {Integer, Floating})
if item.kind==Integer:
res &= numberToBinary(item.i)
else:
res &= numberToBinary(item.f)
return newBinary(res)
of Bytecode:
var evaled = doEval(y, omitNewlines=hadAttr("intrepid"))
return newBytecode(evaled)
else:
throwCannotConvert()
of Range:
if tp == Block:
return newBlock(toSeq(y.rng.items))
else:
throwCannotConvert()
of Dictionary:
case tp:
of String:
return newString($(y))
of Object:
if x.tpKind==UserType:
if (let xProto = getType(x.tid); not xProto.isNil):
return generateNewObject(xProto, y.d)
else:
Error_UsingUndefinedType(x.tid)
else:
throwCannotConvert()
of Bytecode:
var evaled = Translation(constants: y.d["data"].a, instructions: y.d["code"].a.map(proc (x:Value):byte = byte(x.i)))
return newBytecode(evaled)
else:
throwCannotConvert()
of Object:
case tp:
of String:
if y.magic.fetch(ToStringM):
mgk(@[y])
return stack.pop()
else:
return newString($(y))
of Integer:
if y.magic.fetch(ToIntegerM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Floating:
if y.magic.fetch(ToFloatingM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Rational:
if y.magic.fetch(ToRationalM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Complex:
if y.magic.fetch(ToComplexM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Quantity:
if y.magic.fetch(ToQuantityM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Logical:
if y.magic.fetch(ToLogicalM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Block:
if y.magic.fetch(ToBlockM):
mgk(@[y])
return stack.pop()
else:
throwCannotConvert()
of Dictionary:
if y.magic.fetch(ToDictionaryM):
mgk(@[y])
return stack.pop()
else:
let dd = newOrderedTable[string,Value]()
for k,v in y.o.objectPairs:
dd[k] = copyValue(v)
return newDictionary(dd)
else:
throwCannotConvert()
of Store:
case tp:
of String:
return newString($(y))
of Dictionary:
ensureStoreIsLoaded(y.sto)
return newDictionary(y.sto.data)
else:
throwCannotConvert()
of Bytecode:
case tp:
of Dictionary:
return newDictionary({
"data": newBlock(y.trans.constants),
"code": newBlock(y.trans.instructions.map((w) => newInteger(int(w))))
}.toOrderedTable)
else:
throwCannotConvert()
of Symbol:
case tp:
of String:
return newString($(y))
of Literal:
return newLiteral($(y))
else:
throwCannotConvert()
of SymbolLiteral:
case tp:
of String:
return newString($(y))
of Literal:
return newLiteral($(y))
else:
throwCannotConvert()
of Quantity:
case tp:
of Floating:
return newFloating(toFloat(y.q.original))
of Rational:
return newRational(y.q.original)
of String:
return newString($(y.q))
of Unit:
return newUnit(y.q.atoms)
else:
throwCannotConvert()
of Unit:
if tp == String:
return newString($(y.u))
else:
throwCannotConvert()
of Error:
case tp:
of String:
return newString($(y.err.kind.label))
of Literal:
return newLiteral($(y.err.kind.label))
else:
throwCannotConvert()
of ErrorKind:
case tp:
of String:
return newString($(y.errKind.label))
of Literal:
return newLiteral($(y.errKind.label))
else:
throwCannotConvert()
of Regex:
case tp:
of String:
return newString($(y))
else:
throwCannotConvert()
of Date:
case tp:
of Integer:
return newInteger(toUnix(toTime(y.eobj)))
of String:
var dateFormat = "yyyy-MM-dd'T'HH:mm:sszzz"
if (not aFormat.isNil):
dateFormat = aFormat.s
try:
return newString(format(y.eobj, dateFormat))
except CatchableError:
throwConversionFailed("Make sure the date format specified via `.format:` is valid. The current format is: `" & dateFormat & "`.")
else:
throwCannotConvert()
of Color:
case tp:
of String:
return newString($(y))
else:
throwCannotConvert()
of Binary:
case tp:
of String:
return newString($(split(y.n.map((c) => chr(c)), [])).join)
else:
throwCannotConvert()
of Function,
Method,
Module,
Database,
Socket,
Nothing,
Any,
Path,
PathLabel,
PathLiteral: throwCannotConvert()