-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
MiniscriptIntrinsics.cs
1713 lines (1603 loc) · 66.6 KB
/
MiniscriptIntrinsics.cs
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
/* MiniscriptIntrinsics.cs
This file defines the Intrinsic class, which represents a built-in function
available to MiniScript code. All intrinsics are held in static storage, so
this class includes static functions such as GetByName to look up
already-defined intrinsics. See Chapter 2 of the MiniScript Integration
Guide for details on adding your own intrinsics.
This file also contains the Intrinsics static class, where all of the standard
intrinsics are defined. This is initialized automatically, so normally you
don’t need to worry about it, though it is a good place to look for examples
of how to write intrinsic functions.
Note that you should put any intrinsics you add in a separate file; leave the
MiniScript source files untouched, so you can easily replace them when updates
become available.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
namespace Miniscript {
/// <summary>
/// IntrinsicCode is a delegate to the actual C# code invoked by an intrinsic method.
/// </summary>
/// <param name="context">TAC.Context in which the intrinsic was invoked</param>
/// <param name="partialResult">partial result from a previous invocation, if any</param>
/// <returns>result of the computation: whether it's complete, a partial result if not, and a Value if so</returns>
public delegate Intrinsic.Result IntrinsicCode(TAC.Context context, Intrinsic.Result partialResult);
/// <summary>
/// Information about the app hosting MiniScript. Set this in your main program.
/// This is provided to the user via the `version` intrinsic.
/// </summary>
public static class HostInfo {
public static string name; // name of the host program
public static string info; // URL or other short info about the host
public static double version; // host program version number
}
/// <summary>
/// Intrinsic: represents an intrinsic function available to MiniScript code.
/// </summary>
public class Intrinsic {
// name of this intrinsic (should be a valid MiniScript identifier)
public string name;
// actual C# code invoked by the intrinsic
public IntrinsicCode code;
// a numeric ID (used internally -- don't worry about this)
public int id { get { return numericID; } }
// static map from Values to short names, used when displaying lists/maps;
// feel free to add to this any values (especially lists/maps) provided
// by your own intrinsics.
public static Dictionary<Value, string> shortNames = new Dictionary<Value, string>();
private Function function;
private ValFunction valFunction; // (cached wrapper for function)
int numericID; // also its index in the 'all' list
public static List<Intrinsic> all = new List<Intrinsic>() { null };
static Dictionary<string, Intrinsic> nameMap = new Dictionary<string, Intrinsic>();
/// <summary>
/// Factory method to create a new Intrinsic, filling out its name as given,
/// and other internal properties as needed. You'll still need to add any
/// parameters, and define the code it runs.
/// </summary>
/// <param name="name">intrinsic name</param>
/// <returns>freshly minted (but empty) static Intrinsic</returns>
public static Intrinsic Create(string name) {
Intrinsic result = new Intrinsic();
result.name = name;
result.numericID = all.Count;
result.function = new Function(null);
result.valFunction = new ValFunction(result.function);
all.Add(result);
nameMap[name] = result;
return result;
}
/// <summary>
/// Look up an Intrinsic by its internal numeric ID.
/// </summary>
public static Intrinsic GetByID(int id) {
return all[id];
}
/// <summary>
/// Look up an Intrinsic by its name.
/// </summary>
public static Intrinsic GetByName(string name) {
Intrinsics.InitIfNeeded();
Intrinsic result = null;
if (nameMap.TryGetValue(name, out result)) return result;
return null;
}
/// <summary>
/// Add a parameter to this Intrinsic, optionally with a default value
/// to be used if the user doesn't supply one. You must add parameters
/// in the same order in which arguments must be supplied.
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="defaultValue">default value, if any</param>
public void AddParam(string name, Value defaultValue=null) {
function.parameters.Add(new Function.Param(name, defaultValue));
}
/// <summary>
/// Add a parameter with a numeric default value. (See comments on
/// the first version of AddParam above.)
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="defaultValue">default value for this parameter</param>
public void AddParam(string name, double defaultValue) {
Value defVal;
if (defaultValue == 0) defVal = ValNumber.zero;
else if (defaultValue == 1) defVal = ValNumber.one;
else defVal = TAC.Num(defaultValue);
function.parameters.Add(new Function.Param(name, defVal));
}
/// <summary>
/// Add a parameter with a string default value. (See comments on
/// the first version of AddParam above.)
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="defaultValue">default value for this parameter</param>
public void AddParam(string name, string defaultValue) {
Value defVal;
if (string.IsNullOrEmpty(defaultValue)) defVal = ValString.empty;
else if (defaultValue == "__isa") defVal = ValString.magicIsA;
else if (defaultValue == "self") defVal = _self;
else defVal = new ValString(defaultValue);
function.parameters.Add(new Function.Param(name, defVal));
}
ValString _self = new ValString("self");
/// <summary>
/// GetFunc is used internally by the compiler to get the MiniScript function
/// that makes an intrinsic call.
/// </summary>
public ValFunction GetFunc() {
if (function.code == null) {
// Our little wrapper function is a single opcode: CallIntrinsicA.
// It really exists only to provide a local variable context for the parameters.
function.code = new List<TAC.Line>();
function.code.Add(new TAC.Line(TAC.LTemp(0), TAC.Line.Op.CallIntrinsicA, TAC.Num(numericID)));
}
return valFunction;
}
/// <summary>
/// Internally-used function to execute an intrinsic (by ID) given a
/// context and a partial result.
/// </summary>
public static Result Execute(int id, TAC.Context context, Result partialResult) {
Intrinsic item = GetByID(id);
return item.code(context, partialResult);
}
/// <summary>
/// Result represents the result of an intrinsic call. An intrinsic will either
/// be done with its work, or not yet done (e.g. because it's waiting for something).
/// If it's done, set done=true, and store the result Value in result.
/// If it's not done, set done=false, and store any partial result in result (and
/// then your intrinsic will get invoked with this Result passed in as partialResult).
/// </summary>
public class Result {
public bool done; // true if our work is complete; false if we need to Continue
public Value result; // final result if done; in-progress data if not done
/// <summary>
/// Result constructor taking a Value, and an optional done flag.
/// </summary>
/// <param name="result">result or partial result of the call</param>
/// <param name="done">whether our work is done (optional, defaults to true)</param>
public Result(Value result, bool done=true) {
this.done = done;
this.result = result;
}
/// <summary>
/// Result constructor for a simple numeric result.
/// </summary>
public Result(double resultNum) {
this.done = true;
this.result = new ValNumber(resultNum);
}
/// <summary>
/// Result constructor for a simple string result.
/// </summary>
public Result(string resultStr) {
this.done = true;
if (string.IsNullOrEmpty(resultStr)) this.result = ValString.empty;
else this.result = new ValString(resultStr);
}
/// <summary>
/// Result.Null: static Result representing null (no value).
/// </summary>
public static Result Null { get { return _null; } }
static Result _null = new Result(null, true);
/// <summary>
/// Result.EmptyString: static Result representing "" (empty string).
/// </summary>
public static Result EmptyString { get { return _emptyString; } }
static Result _emptyString = new Result(ValString.empty);
/// <summary>
/// Result.True: static Result representing true (1.0).
/// </summary>
public static Result True { get { return _true; } }
static Result _true = new Result(ValNumber.one, true);
/// <summary>
/// Result.True: static Result representing false (0.0).
/// </summary>
public static Result False { get { return _false; } }
static Result _false = new Result(ValNumber.zero, true);
/// <summary>
/// Result.Waiting: static Result representing a need to wait,
/// with no in-progress value.
/// </summary>
public static Result Waiting { get { return _waiting; } }
static Result _waiting = new Result(null, false);
}
}
/// <summary>
/// Intrinsics: a static class containing all of the standard MiniScript
/// built-in intrinsics. You shouldn't muck with these, but feel free
/// to browse them for lots of examples of how to write your own intrinics.
/// </summary>
public static class Intrinsics {
static bool initialized;
static ValMap intrinsicsMap = null; // (for "intrinsics" function)
private struct KeyedValue {
public Value sortKey;
public Value value;
//public long valueIndex;
}
// Helper method to get a stack trace, as a list of ValStrings.
// This is the heart of the stackTrace intrinsic.
// Public in case you want to call it from other places (for debugging, etc.).
public static ValList StackList(TAC.Machine vm) {
ValList result = new ValList();
if (vm == null) return result;
foreach (SourceLoc loc in vm.GetStack()) {
if (loc == null) continue;
string s = loc.context;
if (string.IsNullOrEmpty(s)) s = "(current program)";
s += " line " + loc.lineNum;
result.values.Add(new ValString(s));
}
return result;
}
/// <summary>
/// InitIfNeeded: called automatically during script setup to make sure
/// that all our standard intrinsics are defined. Note how we use a
/// private bool flag to ensure that we don't create our intrinsics more
/// than once, no matter how many times this method is called.
/// </summary>
public static void InitIfNeeded() {
if (initialized) return; // our work is already done; bail out.
initialized = true;
Intrinsic f;
// abs
// Returns the absolute value of the given number.
// x (number, default 0): number to take the absolute value of.
// Example: abs(-42) returns 42
f = Intrinsic.Create("abs");
f.AddParam("x", 0);
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.Abs(context.GetLocalDouble("x")));
};
// acos
// Returns the inverse cosine, that is, the angle
// (in radians) whose cosine is the given value.
// x (number, default 0): cosine of the angle to find.
// Returns: angle, in radians, whose cosine is x.
// Example: acos(0) returns 1.570796
f = Intrinsic.Create("acos");
f.AddParam("x", 0);
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.Acos(context.GetLocalDouble("x")));
};
// asin
// Returns the inverse sine, that is, the angle
// (in radians) whose sine is the given value.
// x (number, default 0): cosine of the angle to find.
// Returns: angle, in radians, whose cosine is x.
// Example: asin(1) return 1.570796
f = Intrinsic.Create("asin");
f.AddParam("x", 0);
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.Asin(context.GetLocalDouble("x")));
};
// atan
// Returns the arctangent of a value or ratio, that is, the
// angle (in radians) whose tangent is y/x. This will return
// an angle in the correct quadrant, taking into account the
// sign of both arguments. The second argument is optional,
// and if omitted, this function is equivalent to the traditional
// one-parameter atan function. Note that the parameters are
// in y,x order.
// y (number, default 0): height of the side opposite the angle
// x (number, default 1): length of the side adjacent the angle
// Returns: angle, in radians, whose tangent is y/x
// Example: atan(1, -1) returns 2.356194
f = Intrinsic.Create("atan");
f.AddParam("y", 0);
f.AddParam("x", 1);
f.code = (context, partialResult) => {
double y = context.GetLocalDouble("y");
double x = context.GetLocalDouble("x");
if (x == 1.0) return new Intrinsic.Result(Math.Atan(y));
return new Intrinsic.Result(Math.Atan2(y, x));
};
Func<double, Tuple<bool, ulong>> doubleToUnsignedSplit = (val) => {
return new Tuple<bool, ulong>(Math.Sign(val) == -1, (ulong)Math.Abs(val));
};
// bitAnd
// Treats its arguments as integers, and computes the bitwise
// `and`: each bit in the result is set only if the corresponding
// bit is set in both arguments.
// i (number, default 0): first integer argument
// j (number, default 0): second integer argument
// Returns: bitwise `and` of i and j
// Example: bitAnd(14, 7) returns 6
// See also: bitOr; bitXor
f = Intrinsic.Create("bitAnd");
f.AddParam("i", 0);
f.AddParam("j", 0);
f.code = (context, partialResult) => {
var i = doubleToUnsignedSplit(context.GetLocalDouble("i"));
var j = doubleToUnsignedSplit(context.GetLocalDouble("j"));
var sign = i.Item1 & j.Item1;
double val = i.Item2 & j.Item2;
return new Intrinsic.Result(sign ? -val : val);
};
// bitOr
// Treats its arguments as integers, and computes the bitwise
// `or`: each bit in the result is set if the corresponding
// bit is set in either (or both) of the arguments.
// i (number, default 0): first integer argument
// j (number, default 0): second integer argument
// Returns: bitwise `or` of i and j
// Example: bitOr(14, 7) returns 15
// See also: bitAnd; bitXor
f = Intrinsic.Create("bitOr");
f.AddParam("i", 0);
f.AddParam("j", 0);
f.code = (context, partialResult) => {
var i = doubleToUnsignedSplit(context.GetLocalDouble("i"));
var j = doubleToUnsignedSplit(context.GetLocalDouble("j"));
var sign = i.Item1 | j.Item1;
double val = i.Item2 | j.Item2;
return new Intrinsic.Result(sign ? -val : val);
};
// bitXor
// Treats its arguments as integers, and computes the bitwise
// `xor`: each bit in the result is set only if the corresponding
// bit is set in exactly one (not zero or both) of the arguments.
// i (number, default 0): first integer argument
// j (number, default 0): second integer argument
// Returns: bitwise `xor` of i and j
// Example: bitXor(14, 7) returns 9
// See also: bitAnd; bitOr
f = Intrinsic.Create("bitXor");
f.AddParam("i", 0);
f.AddParam("j", 0);
f.code = (context, partialResult) => {
var i = doubleToUnsignedSplit(context.GetLocalDouble("i"));
var j = doubleToUnsignedSplit(context.GetLocalDouble("j"));
var sign = i.Item1 ^ j.Item1;
double val = i.Item2 ^ j.Item2;
return new Intrinsic.Result(sign ? -val : val);
};
// char
// Gets a character from its Unicode code point.
// codePoint (number, default 65): Unicode code point of a character
// Returns: string containing the specified character
// Example: char(42) returns "*"
// See also: code
f = Intrinsic.Create("char");
f.AddParam("codePoint", 65);
f.code = (context, partialResult) => {
int codepoint = context.GetLocalInt("codePoint");
string s = char.ConvertFromUtf32(codepoint);
return new Intrinsic.Result(s);
};
// ceil
// Returns the "ceiling", i.e. closest whole number
// greater than or equal to the given number.
// x (number, default 0): number to get the ceiling of
// Returns: closest whole number not less than x
// Example: ceil(41.2) returns 42
// See also: floor
f = Intrinsic.Create("ceil");
f.AddParam("x", 0);
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.Ceiling(context.GetLocalDouble("x")));
};
// code
// Return the Unicode code point of the first character of
// the given string. This is the inverse of `char`.
// May be called with function syntax or dot syntax.
// self (string): string to get the code point of
// Returns: Unicode code point of the first character of self
// Example: "*".code returns 42
// Example: code("*") returns 42
f = Intrinsic.Create("code");
f.AddParam("self");
f.code = (context, partialResult) => {
Value self = context.self;
int codepoint = 0;
if (self != null) codepoint = char.ConvertToUtf32(self.ToString(), 0);
return new Intrinsic.Result(codepoint);
};
// cos
// Returns the cosine of the given angle (in radians).
// radians (number): angle, in radians, to get the cosine of
// Returns: cosine of the given angle
// Example: cos(0) returns 1
f = Intrinsic.Create("cos");
f.AddParam("radians", 0);
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.Cos(context.GetLocalDouble("radians")));
};
// floor
// Returns the "floor", i.e. closest whole number
// less than or equal to the given number.
// x (number, default 0): number to get the floor of
// Returns: closest whole number not more than x
// Example: floor(42.9) returns 42
// See also: floor
f = Intrinsic.Create("floor");
f.AddParam("x", 0);
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.Floor(context.GetLocalDouble("x")));
};
// funcRef
// Returns a map that represents a function reference in
// MiniScript's core type system. This can be used with `isa`
// to check whether a variable refers to a function (but be
// sure to use @ to avoid invoking the function and testing
// the result).
// Example: @floor isa funcRef returns 1
// See also: number, string, list, map
f = Intrinsic.Create("funcRef");
f.code = (context, partialResult) => {
if (context.vm.functionType == null) {
context.vm.functionType = FunctionType().EvalCopy(context.vm.globalContext);
}
return new Intrinsic.Result(context.vm.functionType);
};
// hash
// Returns an integer that is "relatively unique" to the given value.
// In the case of strings, the hash is case-sensitive. In the case
// of a list or map, the hash combines the hash values of all elements.
// Note that the value returned is platform-dependent, and may vary
// across different MiniScript implementations.
// obj (any type): value to hash
// Returns: integer hash of the given value
f = Intrinsic.Create("hash");
f.AddParam("obj");
f.code = (context, partialResult) => {
Value val = context.GetLocal("obj");
return new Intrinsic.Result(val.Hash());
};
// hasIndex
// Return whether the given index is valid for this object, that is,
// whether it could be used with square brackets to get some value
// from self. When self is a list or string, the result is true for
// integers from -(length of string) to (length of string-1). When
// self is a map, it is true for any key (index) in the map. If
// called on a number, this method throws a runtime exception.
// self (string, list, or map): object to check for an index on
// index (any): value to consider as a possible index
// Returns: 1 if self[index] would be valid; 0 otherwise
// Example: "foo".hasIndex(2) returns 1
// Example: "foo".hasIndex(3) returns 0
// See also: indexes
f = Intrinsic.Create("hasIndex");
f.AddParam("self");
f.AddParam("index");
f.code = (context, partialResult) => {
Value self = context.self;
Value index = context.GetLocal("index");
if (self is ValList) {
if (index is ValNumber) {
List<Value> list = ((ValList)self).values;
int i = index.IntValue();
return new Intrinsic.Result(ValNumber.Truth(i >= -list.Count && i < list.Count));
}
return Intrinsic.Result.False;
} else if (self is ValString) {
if (index is ValNumber) {
string str = ((ValString)self).value;
int i = index.IntValue();
return new Intrinsic.Result(ValNumber.Truth(i >= -str.Length && i < str.Length));
}
return new Intrinsic.Result(ValNumber.zero);
} else if (self is ValMap) {
ValMap map = (ValMap)self;
return new Intrinsic.Result(ValNumber.Truth(map.ContainsKey(index)));
}
return Intrinsic.Result.Null;
};
// indexes
// Returns the keys of a dictionary, or the non-negative indexes
// for a string or list.
// self (string, list, or map): object to get the indexes of
// Returns: a list of valid indexes for self
// Example: "foo".indexes returns [0, 1, 2]
// See also: hasIndex
f = Intrinsic.Create("indexes");
f.AddParam("self");
f.code = (context, partialResult) => {
Value self = context.self;
if (self is ValMap) {
ValMap map = (ValMap)self;
List<Value> keys = new List<Value>(map.map.Keys);
for (int i = 0; i < keys.Count; i++) if (keys[i] is ValNull) keys[i] = null;
return new Intrinsic.Result(new ValList(keys));
} else if (self is ValString) {
string str = ((ValString)self).value;
List<Value> indexes = new List<Value>(str.Length);
for (int i = 0; i < str.Length; i++) {
indexes.Add(TAC.Num(i));
}
return new Intrinsic.Result(new ValList(indexes));
} else if (self is ValList) {
List<Value> list = ((ValList)self).values;
List<Value> indexes = new List<Value>(list.Count);
for (int i = 0; i < list.Count; i++) {
indexes.Add(TAC.Num(i));
}
return new Intrinsic.Result(new ValList(indexes));
}
return Intrinsic.Result.Null;
};
// indexOf
// Returns index or key of the given value, or if not found, returns null.
// self (string, list, or map): object to search
// value (any): value to search for
// after (any, optional): if given, starts the search after this index
// Returns: first index (after `after`) such that self[index] == value, or null
// Example: "Hello World".indexOf("o") returns 4
// Example: "Hello World".indexOf("o", 4) returns 7
// Example: "Hello World".indexOf("o", 7) returns null
f = Intrinsic.Create("indexOf");
f.AddParam("self");
f.AddParam("value");
f.AddParam("after");
f.code = (context, partialResult) => {
Value self = context.self;
Value value = context.GetLocal("value");
Value after = context.GetLocal("after");
if (self is ValList) {
List<Value> list = ((ValList)self).values;
int idx;
if (after == null) idx = list.FindIndex(x =>
x == null ? value == null : x.Equality(value) == 1);
else {
int afterIdx = after.IntValue();
if (afterIdx < -1) afterIdx += list.Count;
if (afterIdx < -1 || afterIdx >= list.Count-1) return Intrinsic.Result.Null;
idx = list.FindIndex(afterIdx + 1, x =>
x == null ? value == null : x.Equality(value) == 1);
}
if (idx >= 0) return new Intrinsic.Result(idx);
} else if (self is ValString) {
string str = ((ValString)self).value;
if (value == null) return Intrinsic.Result.Null;
string s = value.ToString();
int idx;
if (after == null) idx = str.IndexOf(s, StringComparison.Ordinal);
else {
int afterIdx = after.IntValue();
if (afterIdx < -1) afterIdx += str.Length;
if (afterIdx < -1 || afterIdx >= str.Length-1) return Intrinsic.Result.Null;
idx = str.IndexOf(s, afterIdx + 1, StringComparison.Ordinal);
}
if (idx >= 0) return new Intrinsic.Result(idx);
} else if (self is ValMap) {
ValMap map = (ValMap)self;
bool sawAfter = (after == null);
foreach (var kv in map.map) {
if (!sawAfter) {
if (kv.Key.Equality(after) == 1) sawAfter = true;
} else {
if (kv.Value == null ? value == null : kv.Value.Equality(value) == 1) return new Intrinsic.Result(kv.Key);
}
}
}
return Intrinsic.Result.Null;
};
// insert
// Insert a new element into a string or list. In the case of a list,
// the list is both modified in place and returned. Strings are immutable,
// so in that case the original string is unchanged, but a new string is
// returned with the value inserted.
// self (string or list): sequence to insert into
// index (number): position at which to insert the new item
// value (any): element to insert at the specified index
// Returns: modified list, new string
// Example: "Hello".insert(2, 42) returns "He42llo"
// See also: remove
f = Intrinsic.Create("insert");
f.AddParam("self");
f.AddParam("index");
f.AddParam("value");
f.code = (context, partialResult) => {
Value self = context.self;
Value index = context.GetLocal("index");
Value value = context.GetLocal("value");
if (index == null) throw new RuntimeException("insert: index argument required");
if (!(index is ValNumber)) throw new RuntimeException("insert: number required for index argument");
int idx = index.IntValue();
if (self is ValList) {
List<Value> list = ((ValList)self).values;
if (idx < 0) idx += list.Count + 1; // +1 because we are inserting AND counting from the end.
Check.Range(idx, 0, list.Count); // and allowing all the way up to .Count here, because insert.
list.Insert(idx, value);
return new Intrinsic.Result(self);
} else if (self is ValString) {
string s = self.ToString();
if (idx < 0) idx += s.Length + 1;
Check.Range(idx, 0, s.Length);
s = s.Substring(0, idx) + value.ToString() + s.Substring(idx);
return new Intrinsic.Result(s);
} else {
throw new RuntimeException("insert called on invalid type");
}
};
// intrinsics
// Returns a read-only map of all named intrinsics.
f = Intrinsic.Create("intrinsics");
f.code = (context, partialResult) => {
if (intrinsicsMap != null) return new Intrinsic.Result(intrinsicsMap);
intrinsicsMap = new ValMap();
intrinsicsMap.assignOverride = (k,v) => {
throw new RuntimeException("Assignment to protected map");
return true;
};
foreach (var intrinsic in Intrinsic.all) {
if (intrinsic == null || string.IsNullOrEmpty(intrinsic.name)) continue;
intrinsicsMap[intrinsic.name] = intrinsic.GetFunc();
}
return new Intrinsic.Result(intrinsicsMap);
};
// self.join
// Join the elements of a list together to form a string.
// self (list): list to join
// delimiter (string, default " "): string to insert between each pair of elements
// Returns: string built by joining elements of self with delimiter
// Example: [2,4,8].join("-") returns "2-4-8"
// See also: split
f = Intrinsic.Create("join");
f.AddParam("self");
f.AddParam("delimiter", " ");
f.code = (context, partialResult) => {
Value val = context.self;
string delim = context.GetLocalString("delimiter");
if (!(val is ValList)) return new Intrinsic.Result(val);
ValList src = (val as ValList);
List<string> list = new List<string>(src.values.Count);
for (int i=0; i<src.values.Count; i++) {
if (src.values[i] == null) list.Add(null);
else list.Add(src.values[i].ToString());
}
string result = string.Join(delim, list.ToArray());
return new Intrinsic.Result(result);
};
// self.len
// Return the number of characters in a string, elements in
// a list, or key/value pairs in a map.
// May be called with function syntax or dot syntax.
// self (list, string, or map): object to get the length of
// Returns: length (number of elements) in self
// Example: "hello".len returns 5
f = Intrinsic.Create("len");
f.AddParam("self");
f.code = (context, partialResult) => {
Value val = context.self;
if (val is ValList) {
List<Value> list = ((ValList)val).values;
return new Intrinsic.Result(list.Count);
} else if (val is ValString) {
string str = ((ValString)val).value;
return new Intrinsic.Result(str.Length);
} else if (val is ValMap) {
return new Intrinsic.Result(((ValMap)val).Count);
}
return Intrinsic.Result.Null;
};
// list type
// Returns a map that represents the list datatype in
// MiniScript's core type system. This can be used with `isa`
// to check whether a variable refers to a list. You can also
// assign new methods here to make them available to all lists.
// Example: [1, 2, 3] isa list returns 1
// See also: number, string, map, funcRef
f = Intrinsic.Create("list");
f.code = (context, partialResult) => {
if (context.vm.listType == null) {
context.vm.listType = ListType().EvalCopy(context.vm.globalContext);
}
return new Intrinsic.Result(context.vm.listType);
};
// log(x, base)
// Returns the logarithm (with the given) of the given number,
// that is, the number y such that base^y = x.
// x (number): number to take the log of
// base (number, default 10): logarithm base
// Returns: a number that, when base is raised to it, produces x
// Example: log(1000) returns 3 (because 10^3 == 1000)
f = Intrinsic.Create("log");
f.AddParam("x", 0);
f.AddParam("base", 10);
f.code = (context, partialResult) => {
double x = context.GetLocalDouble("x");
double b = context.GetLocalDouble("base");
double result;
if (Math.Abs(b - 2.718282) < 0.000001) result = Math.Log(x);
else result = Math.Log(x) / Math.Log(b);
return new Intrinsic.Result(result);
};
// lower
// Return a lower-case version of a string.
// May be called with function syntax or dot syntax.
// self (string): string to lower-case
// Returns: string with all capital letters converted to lowercase
// Example: "Mo Spam".lower returns "mo spam"
// See also: upper
f = Intrinsic.Create("lower");
f.AddParam("self");
f.code = (context, partialResult) => {
Value val = context.self;
if (val is ValString) {
string str = ((ValString)val).value;
return new Intrinsic.Result(str.ToLower());
}
return new Intrinsic.Result(val);
};
// map type
// Returns a map that represents the map datatype in
// MiniScript's core type system. This can be used with `isa`
// to check whether a variable refers to a map. You can also
// assign new methods here to make them available to all maps.
// Example: {1:"one"} isa map returns 1
// See also: number, string, list, funcRef
f = Intrinsic.Create("map");
f.code = (context, partialResult) => {
if (context.vm.mapType == null) {
context.vm.mapType = MapType().EvalCopy(context.vm.globalContext);
}
return new Intrinsic.Result(context.vm.mapType);
};
// number type
// Returns a map that represents the number datatype in
// MiniScript's core type system. This can be used with `isa`
// to check whether a variable refers to a number. You can also
// assign new methods here to make them available to all maps
// (though because of a limitation in MiniScript's parser, such
// methods do not work on numeric literals).
// Example: 42 isa number returns 1
// See also: string, list, map, funcRef
f = Intrinsic.Create("number");
f.code = (context, partialResult) => {
if (context.vm.numberType == null) {
context.vm.numberType = NumberType().EvalCopy(context.vm.globalContext);
}
return new Intrinsic.Result(context.vm.numberType);
};
// pi
// Returns the universal constant π, that is, the ratio of
// a circle's circumference to its diameter.
// Example: pi returns 3.141593
f = Intrinsic.Create("pi");
f.code = (context, partialResult) => {
return new Intrinsic.Result(Math.PI);
};
// print
// Display the given value on the default output stream. The
// exact effect may vary with the environment. In most cases, the
// given string will be followed by the standard line delimiter
// (unless overridden with the second parameter).
// s (any): value to print (converted to a string as needed)
// delimiter (string or null): string to print after s; if null, use standard EOL
// Returns: null
// Example: print 6*7
f = Intrinsic.Create("print");
f.AddParam("s", ValString.empty);
f.AddParam("delimiter");
f.code = (context, partialResult) => {
Value sVal = context.GetLocal("s");
string s = (sVal == null ? "null" : sVal.ToString());
Value delimiter = context.GetLocal("delimiter");
if (delimiter == null) context.vm.standardOutput(s, true);
else context.vm.standardOutput(s + delimiter.ToString(), false);
return Intrinsic.Result.Null;
};
// pop
// Removes and returns the last item in a list, or an arbitrary
// key of a map. If the list or map is empty (or if called on
// any other data type), returns null.
// May be called with function syntax or dot syntax.
// self (list or map): object to remove an element from the end of
// Returns: value removed, or null
// Example: [1, 2, 3].pop returns (and removes) 3
// See also: pull; push; remove
f = Intrinsic.Create("pop");
f.AddParam("self");
f.code = (context, partialResult) => {
Value self = context.self;
if (self is ValList) {
List<Value> list = ((ValList)self).values;
if (list.Count < 1) return Intrinsic.Result.Null;
Value result = list[list.Count-1];
list.RemoveAt(list.Count-1);
return new Intrinsic.Result(result);
} else if (self is ValMap) {
ValMap map = (ValMap)self;
if (map.map.Count < 1) return Intrinsic.Result.Null;
Value result = map.map.Keys.First();
map.map.Remove(result);
return new Intrinsic.Result(result);
}
return Intrinsic.Result.Null;
};
// pull
// Removes and returns the first item in a list, or an arbitrary
// key of a map. If the list or map is empty (or if called on
// any other data type), returns null.
// May be called with function syntax or dot syntax.
// self (list or map): object to remove an element from the end of
// Returns: value removed, or null
// Example: [1, 2, 3].pull returns (and removes) 1
// See also: pop; push; remove
f = Intrinsic.Create("pull");
f.AddParam("self");
f.code = (context, partialResult) => {
Value self = context.self;
if (self is ValList) {
List<Value> list = ((ValList)self).values;
if (list.Count < 1) return Intrinsic.Result.Null;
Value result = list[0];
list.RemoveAt(0);
return new Intrinsic.Result(result);
} else if (self is ValMap) {
ValMap map = (ValMap)self;
if (map.map.Count < 1) return Intrinsic.Result.Null;
Value result = map.map.Keys.First();
map.map.Remove(result);
return new Intrinsic.Result(result);
}
return Intrinsic.Result.Null;
};
// push
// Appends an item to the end of a list, or inserts it into a map
// as a key with a value of 1.
// May be called with function syntax or dot syntax.
// self (list or map): object to append an element to
// Returns: self
// See also: pop, pull, insert
f = Intrinsic.Create("push");
f.AddParam("self");
f.AddParam("value");
f.code = (context, partialResult) => {
Value self = context.self;
Value value = context.GetLocal("value");
if (self is ValList) {
List<Value> list = ((ValList)self).values;
list.Add(value);
return new Intrinsic.Result(self);
} else if (self is ValMap) {
ValMap map = (ValMap)self;
map.map[value] = ValNumber.one;
return new Intrinsic.Result(self);
}
return Intrinsic.Result.Null;
};
// range
// Return a list containing a series of numbers within a range.
// from (number, default 0): first number to include in the list
// to (number, default 0): point at which to stop adding numbers to the list
// step (number, optional): amount to add to the previous number on each step;
// defaults to 1 if to > from, or -1 if to < from
// Example: range(50, 5, -10) returns [50, 40, 30, 20, 10]
f = Intrinsic.Create("range");
f.AddParam("from", 0);
f.AddParam("to", 0);
f.AddParam("step");
f.code = (context, partialResult) => {
Value p0 = context.GetLocal("from");
Value p1 = context.GetLocal("to");
Value p2 = context.GetLocal("step");
double fromVal = p0.DoubleValue();
double toVal = p1.DoubleValue();
double step = (toVal >= fromVal ? 1 : -1);
if (p2 is ValNumber) step = (p2 as ValNumber).value;
if (step == 0) throw new RuntimeException("range() error (step==0)");
List<Value> values = new List<Value>();
int count = (int)((toVal - fromVal) / step) + 1;
if (count > ValList.maxSize) throw new RuntimeException("list too large");
try {
values = new List<Value>(count);
for (double v = fromVal; step > 0 ? (v <= toVal) : (v >= toVal); v += step) {
values.Add(TAC.Num(v));
}
} catch (SystemException e) {
// uh-oh... probably out-of-memory exception; clean up and bail out
values = null;
throw(new LimitExceededException("range() error", e));
}
return new Intrinsic.Result(new ValList(values));
};
// refEquals
// Tests whether two values refer to the very same object (rather than
// merely representing the same value). For numbers, this is the same
// as ==, but for strings, lists, and maps, it is reference equality.
f = Intrinsic.Create("refEquals");
f.AddParam("a");
f.AddParam("b");
f.code = (context, partialResult) => {
Value a = context.GetLocal("a");
Value b = context.GetLocal("b");
bool result = false;
if (a == null) {
result = (b == null);
} else if (a is ValNumber) {
result = (b is ValNumber && a.DoubleValue() == b.DoubleValue());
} else if (a is ValString) {
result = (b is ValString && ReferenceEquals( ((ValString)a).value, ((ValString)b).value ));
} else if (a is ValList) {
result = (b is ValList && ReferenceEquals( ((ValList)a).values, ((ValList)b).values ));
} else if (a is ValMap) {
result = (b is ValMap && ReferenceEquals( ((ValMap)a).map, ((ValMap)b).map ));
} else if (a is ValFunction) {
result = (b is ValFunction && ReferenceEquals( ((ValFunction)a).function, ((ValFunction)b).function ));
} else {
result = (a.Equality(b) >= 1);
}
return new Intrinsic.Result(ValNumber.Truth(result));
};
// remove
// Removes part of a list, map, or string. Exact behavior depends on
// the data type of self: