-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathCore.nim
1938 lines (1700 loc) · 63.5 KB
/
Core.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#=======================================================
# Arturo
# Programming Language + Bytecode VM compiler
# (c) 2019-2025 Yanis Zafirópulos
#
# @file: library/Core.nim
#=======================================================
## The main Core module
## (part of the standard library)
# TODO(Core) General cleanup needed
# labels: library, enhancement, cleanup
#=======================================
# Pragmas
#=======================================
{.used.}
#=======================================
# Libraries
#=======================================
import algorithm, hashes, options
import sequtils, sugar
when not defined(WEB):
import oids
import helpers/ffi
when not defined(MINI):
import os
import vm/[packager]
else:
import random
import helpers/datasource
import helpers/objects
import vm/values/printable
import vm/lib
import vm/[errors, eval, exec, parse, runtime]
when defined(BUNDLE):
import std/private/ospaths2
import vm/bundle/resources
#=======================================
# Helpers
#=======================================
proc replacingAmpersands(va: Value, what: Value): Value =
var theBlock = newBlock()
for v in va.a:
if v.kind == Symbol and v.m == ampersand:
theBlock.a.add(what)
elif v.kind == Block:
theBlock.a.add(v.replacingAmpersands(what))
else:
theBlock.a.add(v)
return theBlock
#=======================================
# Definitions
#=======================================
proc defineLibrary*() =
#----------------------------
# Functions
#----------------------------
builtin "alias",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "assign symbol to given function",
args = {
"symbol" : {Symbol, SymbolLiteral, String, Block},
"function" : {Word, Literal, String}
},
attrs = {
"infix" : ({Logical},"use infix precedence")
},
returns = {Nothing},
example = """
addThem: function [x, y][
x + y
]
alias '--> 'addThem!
print --> 2 3
; 5
..........
multiplyThem: function [x, y][ x * y ]
alias.infix {<=>} 'multiplyThem!
print 2 <=> 3
; 6
""":
#=======================================================
var prec = PrefixPrecedence
if (hadAttr("infix")):
prec = InfixPrecedence
var sym: VSymbol
if xKind==String:
sym = doParse(x.s, isFile=false).a[0].m
elif xKind==Block:
let elem {.cursor.} = x.a[0]
requireValue(elem, {Symbol, SymbolLiteral})
sym = elem.m
else:
sym = x.m
Aliases[sym] = AliasBinding(
precedence: prec,
name: newWord(y.s)
)
builtin "break",
alias = unaliased,
op = opBreak,
rule = PrefixPrecedence,
description = "break out of current block or loop",
args = NoArgs,
attrs = NoAttrs,
returns = {Nothing},
example = """
loop 1..5 'x [
print ["x:" x]
if x=3 -> break
print "after check"
]
print "after loop"
; x: 1
; after check
; x: 2
; after check
; x: 3
; after loop
""":
#=======================================================
raise BreakTriggered()
builtin "call",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "call function with given list of parameters",
args = {
"function" : {String,Word,Literal,PathLiteral,Function,Method},
"params" : {Block}
},
attrs = {
"external" : ({String},"path to external library"),
"expect" : ({Type},"expect given return type")
},
returns = {Any},
example = """
multiply: function [x y][
x * y
]
call 'multiply [3 5] ; => 15
..........
call $[x][x+2] [5] ; 7
..........
; Calling external (C code) functions
; compile with:
; clang -c -w mylib.c
; clang -shared -o libmylib.dylib mylib.o
;
; NOTE:
; * If you're using GCC, just replace `clang` by `gcc`
; * If you're not on MacOS, replace your `dylib` by the right extension
; normally they can be `.so` or `.dll` in other Operational Systems.
; #include <stdio.h>
;
; void sayHello(char* name){
; printf("Hello %s!\n", name);
; }
;
; int doubleNum(int num){
; return num * 2;
;}
; call an external function directly
call.external: "mylib" 'sayHello ["John"]
; map an external function to a native one
doubleNum: function [num][
ensure -> integer? num
call .external: "mylib"
.expect: :integer
'doubleNum @[num]
]
loop 1..3 'x [
print ["The double of" x "is" doubleNum x]
]
""":
#=======================================================
if checkAttr("external"):
when not defined(WEB):
let externalLibrary = aExternal.s
var expected = Nothing
if checkAttr("expect"):
expected = aExpect.t
push(execForeignMethod(externalLibrary, x.s, y.a, expected))
else:
var fun: Value
if xKind in {Literal, String, Word}:
fun = FetchSym(x.s)
elif xKind == PathLiteral:
fun = FetchPathSym(x.p)
else:
fun = x
for v in y.a.reversed:
push(v)
if fun.kind == Function:
if fun.fnKind==UserFunction:
var fid: Hash
if xKind in {Literal,String}:
fid = hash(x.s)
else:
fid = hash(fun)
execFunction(fun, fid)
else:
fun.action()()
else:
var fid: Hash
if xKind in {Literal,String}:
fid = hash(x.s)
else:
fid = hash(fun)
execMethod(fun, fid)
# TODO(Core\case) could add `.match` option
# that would actually allow us to match and
# extract pattern matches
# Previous implementation:
# ```
# if unlikely(doMatch):
# while i < arr.len-1:
# var comparable {.cursor.}: Value
# if arr[i].kind == Block:
# let stop = SP
# execUnscoped(arr[i])
# let pattern: ValueArray = sTopsFrom(stop)
# comparable = newBlock(pattern)
# SP = stop
# else:
# comparable = arr[i]
#
# if x == comparable:
# handleBranching:
# execUnscoped(arr[i+1])
# do:
# break
# i += 2
# ```
# labels: library, new feature,
builtin "case",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "match given argument against different values and execute corresponding block",
args = {
"argument" : {Any},
"matches" : {Block, Dictionary}
},
attrs = NoAttrs,
returns = {Logical},
example = """
x: 2
; the main block is always evaluated!
case x [
1 -> print "x is one!"
2 -> print "x is two!"
any -> print "x is none of the above"
]
; x is two!
..........
key: "one"
case key [
"one" 1, ; we can also return
"two" 2 ; simple constant values directly
]
; => 2
..........
case "hello" #[
hello: "hola"
adios: "goodbye"
]
; => "hola"
""":
#=======================================================
if likely(yKind == Block):
let stop = SP
execUnscoped(y)
let arr: ValueArray = sTopsFrom(stop)
SP = stop
var i = 0
while i < arr.len-1:
if x == arr[i]:
let blk {.cursor.} = arr[i+1]
if likely(blk.kind == Block):
handleBranching:
execUnscoped(arr[i+1])
do:
break
else:
push(blk)
i += 2
else:
var gotValue: Value = nil
case xKind:
of String, Word, Literal:
gotValue = GetDictionaryKey(y, x.s, withError=false)
else:
gotValue = GetDictionaryKey(y, $(x), withError=false)
if gotValue.isNil:
gotValue = GetDictionaryKey(y, "any", withError=false)
if not gotValue.isNil:
if gotValue.kind == Block:
handleBranching:
execUnscoped(gotValue)
do:
discard
else:
push(gotValue)
builtin "coalesce",
alias = doublequestion,
op = opNop,
rule = InfixPrecedence,
description = "if first value is null or false, return second value; otherwise return the first one",
args = {
"value" : {Any},
"alternative" : {Any}
},
attrs = NoAttrs,
returns = {Any},
example = """
; Note that 'attr returns null if it has no attribute
print coalesce attr "myAttr" "attr not found"
print (attr "myAttr") ?? "attr not found"
print (myData) ?? defaultData
""":
#=======================================================
let condition = not (xKind==Null or isFalse(x))
if condition:
push(x)
else:
push(y)
builtin "continue",
alias = unaliased,
op = opContinue,
rule = PrefixPrecedence,
description = "immediately continue with next iteration",
args = NoArgs,
attrs = NoAttrs,
returns = {Nothing},
example = """
loop 1..5 'x [
print ["x:" x]
if x=3 -> continue
print "after check"
]
print "after loop"
; x: 1
; after check
; x: 2
; after check
; x: 3
; x: 4
; after check
; x: 5
; after check
; after loop
""":
#=======================================================
raise ContinueTriggered()
# TODO(Core\discard) could be assigned an individual *op*?
# this could potentially allow us to further optimize it, at a bytecode level.
# for example, `push - opdiscard` could be reduced to... nothing at all ;-)
# labels: library, bytecode, enhancement
builtin "discard",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "discard given value, without pushing it onto the stack",
args = {
"value" : {Any}
},
attrs = NoAttrs,
returns = {Nothing},
example = """
validInteger?: function [str][
not? throws? [
discard to :integer str
; we don't really need the value here -
; we just want to see if the operation throws an error
]
]
print validInteger? "123"
; true
""":
#=======================================================
discard
# TODO(Core\do) not working well with Bytecode?
# labels: bug, critical, library, values
builtin "do",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "evaluate and execute given code",
args = {
"code" : {String,Block,Bytecode}
},
attrs = {
"times" : ({Integer},"repeat block execution given number of times")
},
returns = {Any},
example = """
do "print 123" ; 123
..........
do [
x: 3
print ["x =>" x] ; x => 3
]
..........
print do "https://raw.githubusercontent.com/arturo-lang/arturo/master/examples/projecteuler/euler1.art"
; 233168
..........
do.times: 3 [
print "Hello!"
]
; Hello!
; Hello!
; Hello!
..........
; Importing modules
; let's say you have a 'module.art' with this code:
;
; pi: 3.14
;
; hello: $[name :string] [
; print ["Hello" name]
;]
do relative "module.art"
print pi
; 3.14
do [
hello "John Doe"
; Hello John Doe
]
; Note: always use imported functions inside a 'do block
; since they need to be evaluated beforehand.
; On the other hand, simple variables can be used without
; issues, as 'pi in this example
""":
#=======================================================
var times = 1
var currentTime = 0
if checkAttr("times"):
times = aTimes.i
var evaled: Translation
if xKind != String:
evaled = evalOrGet(x)
while currentTime < times:
if xKind in {Block,Bytecode}:
execUnscoped(evaled)
else: # string
let (src, tp) = getSource(x.s)
if tp==FileData:
pushFrame(x.s, fromFile=true)
let parsed = doParse(src, isFile=false)
if not parsed.isNil:
execUnscoped(parsed)
if tp==FileData:
discardFrame()
currentTime += 1
builtin "dup",
alias = thickarrowleft,
op = opNop,
rule = PrefixPrecedence,
description = "duplicate the top of the stack and convert non-returning call to a do-return call",
args = {
"value" : {Any}
},
attrs = NoAttrs,
returns = {Any},
example = """
; a label normally consumes its inputs
; and returns nothing
; using dup before a call, the non-returning function
; becomes a returning one
a: b: <= 3
print a ; 3
print b ; 3
""":
#=======================================================
push(x)
push(x)
# TODO(Core\else) should be marked as deprecated
# https://github.com/arturo-lang/arturo/pull/1735
# labels: library,→ Core, deprecated
builtin "else",
alias = unaliased,
op = opElse,
rule = PrefixPrecedence,
description = "perform action, if last condition was not true",
args = {
"otherwise" : {Block,Bytecode}
},
attrs = NoAttrs,
returns = {Nothing},
example = """
x: 2
z: 3
if? x>z [
print "x was greater than z"
]
else [
print "nope, x was not greater than z"
]
""":
#=======================================================
let y = stack.pop() # pop the value of the previous operation (hopefully an 'if?' or 'when?')
if isFalse(y):
execUnscoped(x)
builtin "ensure",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "assert given condition is true, or exit",
args = {
"condition" : {Block}
},
attrs = {
"that" : ({String},"prints a custom message when ensure fails")
},
returns = {Nothing},
example = """
num: input "give me a positive number"
ensure [num > 0]
print "good, the number is positive indeed. let's continue..."
..........
ensure.that: "Wrong calc" -> 0 = 1 + 1
; >> Assertion | "Wrong calc": [0 = 1 + 1]
; error |
""":
#=======================================================
if checkAttr("that"):
execUnscoped(x)
if isFalse(stack.pop()):
Error_AssertionFailed(x.codify(), aThat.s)
else:
execUnscoped(x)
if isFalse(stack.pop()):
Error_AssertionFailed(x.codify())
builtin "export",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "export given container children to current scope",
args = {
"module" : {Module, Dictionary, Object}
},
attrs = {
"all" : ({Logical},"export everything, regardless of whether it's been marked as public (makes sense only for modules)")
},
returns = {Nothing},
example = """
greeting: module [
greet: method.public [user :string][
print ~"Hello, |user|!"
]
]
export greeting!
greet "Anonymous" ; Hello, Anonymous!
..........
; You can't use private methods
greeting: module [
greet: method [user :string][
print ~"Bye, bye, |user|!"
]
]
export greeting!
greet "Anonymous"
; Cannot resolve requested value
;
; Identifier not found:
; greet
;
; ┃ File: example.art
; ┃ Line: 9
; ┃
; ┃ 7 ║ ]
; ┃ 8 ║
; ┃ 9 ║► export greeting!
; ┃ 10 ║
; ┃ 11 ║ greet "Anonymous"
;
; Hint: Perhaps you meant... greeting ?
; or... repeat ?
; or... greater? ?
..........
; You can export private functions using the `.all` attribute
greeting: module [
greet: method [user :string][
print ~"Bye, bye, |user|!"
]
]
export.all greeting!
greet "Anonymous" ; Bye, bye, Anonymous!
""":
#=======================================================
let exportAll = hadAttr("all")
if xKind in {Module, Object}:
var internalObjName =
if xKind == Module:
"__" & x.singleton.proto.name
else:
when not defined(WEB):
"__omodule" & "_" & $(genOid())
else:
"__omodule" & "_" & $(rand(1_000_000_000..2_000_000_000))
SetSym(internalObjName, x.singleton)
var valuePairs =
if xKind == Module:
x.singleton.o
else:
x.o
for k,v in valuePairs.pairs:
if v.kind == Method and (exportAll or v.mpublic):
let newParams = v.mparams.filter((prm) => prm != "this").map((prm) => newString(prm))
var newBody = copyValue(v.mmain)
newBody = newBlock(@[
newLabel("this"),
newWord(internalObjName),
newWord("do"),
newBody
])
var inPath: ref string = nil
if (let methodPath = v.info.path; not methodPath.isNil):
new(inPath)
inPath[] = methodPath[]
let fnc = newFunctionFromDefinition(newParams,newBody, inPath=inPath)
SetSym(k, fnc)
else:
for k,v in x.d.pairs:
SetSym(k, v)
builtin "function",
alias = dollar,
op = opFunc,
rule = PrefixPrecedence,
description = "create function with given arguments and body",
args = {
"arguments" : {Literal, Block},
"body" : {Block}
},
attrs = {
"import" : ({Block},"import/embed given list of symbols from current environment"),
"export" : ({Block},"export given symbols to parent"),
"memoize" : ({Logical},"store results of function calls"),
"inline" : ({Logical},"execute function without scope")
},
returns = {Function},
example = """
f: function [x][ x + 2 ]
print f 10 ; 12
f: $[x][x+2]
print f 10 ; 12
..........
multiply: function [x,y][
x * y
]
print multiply 3 5 ; 15
..........
; forcing typed parameters
addThem: function [
x :integer
y :integer :floating
][
x + y
]
..........
; adding complete documentation for user function
; using data comments within the body
addThem: function [
x :integer :floating
y :integer :floating
][
;; description: « takes two numbers and adds them up
;; options: [
;; mul: :integer « also multiply by given number
;; ]
;; returns: :integer :floating
;; example: {
;; addThem 10 20
;; addThem.mult:3 10 20
;; }
mult?: attr 'mult
switch not? null? mult?
-> return mult? * x + y
-> return x + y
]
info'addThem
; |--------------------------------------------------------------------------------
; | addThem :function 0x10EF0E528
; |--------------------------------------------------------------------------------
; | takes two numbers and adds them up
; |--------------------------------------------------------------------------------
; | usage addThem x :integer :floating
; | y :integer :floating
; |
; | options .mult :integer -> also multiply by given number
; |
; | returns :integer :floating
; |--------------------------------------------------------------------------------
..........
publicF: function .export:['x] [z][
print ["z =>" z]
x: 5
]
publicF 10
; z => 10
print x
; 5
..........
; memoization
fib: $[x].memoize[
switch x<2 -> 1
-> (fib x-1) + (fib x-2)
]
loop 1..25 [x][
print ["Fibonacci of" x "=" fib x]
]
""":
#=======================================================
var imports: Value = nil
if checkAttr("import"):
var ret = initOrderedTable[string,Value]()
for item in aImport.a:
requireAttrValue("import", item, {Word, Literal})
ret[item.s] = FetchSym(item.s)
imports = newDictionary(ret)
var exports: Value = nil
if checkAttr("export"):
requireAttrValueBlock("export", aExport, {Word, Literal})
exports = aExport
var memoize = (hadAttr("memoize"))
var inline = (hadAttr("inline"))
let argBlock {.cursor.} =
if xKind == Block:
requireValueBlock(x, {Word, Literal, Type})
x.a
else: @[x]
var inPath: ref string = nil
if (let currentF = currentFrame(); currentF != entryFrame()):
new(inPath)
inPath[] = currentF.path
push(newFunctionFromDefinition(argBlock, y, imports, exports, memoize, inline, inPath))
builtin "if",
alias = unaliased,
op = opIf,
rule = PrefixPrecedence,
description = "perform action, if given condition is not false or null",
args = {
"condition" : {Any},
"action" : {Block,Bytecode}
},
attrs = NoAttrs,
returns = {Nothing},
example = """
x: 2
if x=2 -> print "yes, that's right!"
; yes, that's right!
""":
#=======================================================
let condition = not (xKind==Null or isFalse(x))
if condition:
execUnscoped(y)
when (not defined(MINI)) or defined(BUNDLE):
# TODO(Core/__VerbosePackager) Find an elegant way to inject hidden functions
# labels: library, enhancement, cleanup
builtin "__VerbosePackager",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "",
args = NoArgs,
attrs = NoAttrs,
returns = {Nothing,Dictionary,Block},
example = """
""":
#=======================================================
VerbosePackager = true
# TODO(Core/import) `.lean` not always working properly
# basically, if you make 2 imports of the same package, one `.lean` and another normal one
# the 2nd one breaks. Does it have to do with our `execDictionary`?
# labels: library, bug, unit-test
builtin "import",
alias = unaliased,
op = opNop,
rule = PrefixPrecedence,
description = "import given package",
args = {
"package" : {String,Literal,Block}
},
attrs = {
"version" : ({Version},"specify package version"),
"min" : ({Logical},"get any version >= the specified one"),
"branch" : ({String,Literal},"use specific branch for repository url (default: main)"),
"latest" : ({Logical},"always check for the latest version available"),
"lean" : ({Logical},"return as a dictionary, instead of importing in main namespace"),
"only" : ({Block},"import only selected symbols, if available"),
"verbose" : ({Logical},"output extra information")
},
returns = {Nothing,Dictionary,Block},
example = """
import "dummy" ; import the package 'dummy'
do ::
print dummyFunc 10 ; and use it :)
..........
import.version:0.0.3 "dummy" ; import a specific version
import.min.version:0.0.3 "dummy" ; import at least the give version;
; if there is a newer one, it will pull this one
..........
import.latest "dummy" ; whether we already have the package or not
; always try to pull the latest version
..........
import "https://github.com/arturo-lang/dummy-package"
; we may also import user repositories directly
import.branch:"main" "https://github.com/arturo-lang/dummy-package"
; even specifying the branch to pull
..........
import "somefile.art" ; importing a local file is possible
import "somepackage" ; the same works if we have a folder that
; is actually structured like a package
..........
d: import.lean "dummy" ; importing a package as a dictionary
; for better namespace isolation
do [
print d\dummyFunc 10 ; works fine :)
]
""":
#=======================================================
var branch = "main"
let latest = hadAttr("latest")
let verbose = hadAttr("verbose")
let lean = hadAttr("lean")
var importOnly: seq[string] = @[]
when defined(BUNDLE):
let (src, path) = getBundledResource(x.s)
pushFrame(path, fromFile=true)
let parsed = doParse(src, isFile=false)
if not parsed.isNil:
if importOnly.len > 0:
let got = execScopedModule(parsed, importOnly)
for k,v in got.pairs:
if importOnly.contains(k) or k.startsWith("__module"):
SetSym(k, v)
else:
execUnscoped(parsed)
discardFrame()
else:
var verspec = (true, NoPackageVersion)
var pkgs: seq[string]
if xKind in {String, Literal}:
pkgs.add(x.s)
else:
pkgs = x.a.map((p)=>p.s)
let multiple = pkgs.len > 1
if checkAttr("version"):
verspec = (hadAttr("min"), aVersion.version)
if checkAttr("branch"):
branch = aBranch.s
if checkAttr("only"):
importOnly = aOnly.a.map((w) => w.s)
let verboseBefore = VerbosePackager
if verbose:
VerbosePackager = true
var ret: ValueArray
for pkg in pkgs:
if (let res = getEntryForPackage(pkg, verspec, branch, latest); res.isSome):
let src = res.get()
if not src.fileExists():
Error_PackageNotValid(pkg)
pushFrame(src, fromFile=true)
if not lean:
let parsed = doParse(src, isFile=true)
if not parsed.isNil:
if importOnly.len > 0:
let got = execScopedModule(parsed, importOnly)
for k,v in got.pairs:
if importOnly.contains(k) or k.startsWith("__module"):
SetSym(k, v)
else:
execUnscoped(parsed)
else:
let parsed = doParse(src, isFile=true)