forked from google/skylark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.go
2099 lines (1932 loc) · 57.4 KB
/
library.go
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
// Copyright 2017 The Bazel Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package skylark
// This file defines the library of built-ins.
//
// Built-ins must explicitly check the "frozen" flag before updating
// mutable types such as lists and dicts.
import (
"bytes"
"fmt"
"log"
"math/big"
"os"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/google/skylark/syntax"
)
// Universe defines the set of universal built-ins, such as None, True, and len.
//
// The Go application may add or remove items from the
// universe dictionary before Skylark evaluation begins.
// All values in the dictionary must be immutable.
// Skylark programs cannot modify the dictionary.
var Universe StringDict
func init() {
// https://github.com/google/skylark/blob/master/doc/spec.md#built-in-constants-and-functions
Universe = StringDict{
"None": None,
"True": True,
"False": False,
"any": NewBuiltin("any", any),
"all": NewBuiltin("all", all),
"bool": NewBuiltin("bool", bool_),
"chr": NewBuiltin("chr", chr),
"dict": NewBuiltin("dict", dict),
"dir": NewBuiltin("dir", dir),
"enumerate": NewBuiltin("enumerate", enumerate),
"float": NewBuiltin("float", float), // requires resolve.AllowFloat
"getattr": NewBuiltin("getattr", getattr),
"hasattr": NewBuiltin("hasattr", hasattr),
"hash": NewBuiltin("hash", hash),
"int": NewBuiltin("int", int_),
"len": NewBuiltin("len", len_),
"list": NewBuiltin("list", list),
"max": NewBuiltin("max", minmax),
"min": NewBuiltin("min", minmax),
"ord": NewBuiltin("ord", ord),
"print": NewBuiltin("print", print),
"range": NewBuiltin("range", range_),
"repr": NewBuiltin("repr", repr),
"reversed": NewBuiltin("reversed", reversed),
"set": NewBuiltin("set", set), // requires resolve.AllowSet
"sorted": NewBuiltin("sorted", sorted),
"str": NewBuiltin("str", str),
"tuple": NewBuiltin("tuple", tuple),
"type": NewBuiltin("type", type_),
"zip": NewBuiltin("zip", zip),
}
}
type builtinMethod func(fnname string, recv Value, args Tuple, kwargs []Tuple) (Value, error)
// methods of built-in types
// https://github.com/google/skylark/blob/master/doc/spec.md#built-in-methods
var (
dictMethods = map[string]builtinMethod{
"clear": dict_clear,
"get": dict_get,
"items": dict_items,
"keys": dict_keys,
"pop": dict_pop,
"popitem": dict_popitem,
"setdefault": dict_setdefault,
"update": dict_update,
"values": dict_values,
}
listMethods = map[string]builtinMethod{
"append": list_append,
"clear": list_clear,
"extend": list_extend,
"index": list_index,
"insert": list_insert,
"pop": list_pop,
"remove": list_remove,
}
stringMethods = map[string]builtinMethod{
"bytes": string_iterable,
"capitalize": string_capitalize,
"codepoints": string_iterable,
"count": string_count,
"endswith": string_endswith,
"find": string_find,
"format": string_format,
"index": string_index,
"isalnum": string_isalnum,
"isalpha": string_isalpha,
"isdigit": string_isdigit,
"islower": string_islower,
"isspace": string_isspace,
"istitle": string_istitle,
"isupper": string_isupper,
"join": string_join,
"lower": string_lower,
"lstrip": string_strip, // sic
"partition": string_partition,
"replace": string_replace,
"rfind": string_rfind,
"rindex": string_rindex,
"rpartition": string_partition, // sic
"rsplit": string_split, // sic
"rstrip": string_strip, // sic
"split": string_split,
"splitlines": string_splitlines,
"split_bytes": string_iterable, // sic
"split_codepoints": string_iterable, // sic
"startswith": string_startswith,
"strip": string_strip,
"title": string_title,
"upper": string_upper,
}
setMethods = map[string]builtinMethod{
"union": set_union,
}
)
func builtinMethodOf(recv Value, name string) builtinMethod {
switch recv.(type) {
case String:
return stringMethods[name]
case *List:
return listMethods[name]
case *Dict:
return dictMethods[name]
case *Set:
return setMethods[name]
}
return nil
}
func builtinAttr(recv Value, name string, methods map[string]builtinMethod) (Value, error) {
method := methods[name]
if method == nil {
return nil, nil // no such method
}
// Allocate a closure over 'method'.
impl := func(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
return method(b.Name(), b.Receiver(), args, kwargs)
}
return NewBuiltin(name, impl).BindReceiver(recv), nil
}
func builtinAttrNames(methods map[string]builtinMethod) []string {
names := make([]string, 0, len(methods))
for name := range methods {
names = append(names, name)
}
sort.Strings(names)
return names
}
// UnpackArgs unpacks the positional and keyword arguments into the
// supplied parameter variables. pairs is an alternating list of names
// and pointers to variables.
//
// If the variable is a bool, int, string, *List, *Dict, Callable,
// Iterable, or user-defined implementation of Value,
// UnpackArgs performs the appropriate type check.
// (An int uses the AsInt32 check.)
// If the parameter name ends with "?",
// it and all following parameters are optional.
//
// If the variable implements Value, UnpackArgs may call
// its Type() method while constructing the error message.
//
// Beware: an optional *List, *Dict, Callable, Iterable, or Value variable that is
// not assigned is not a valid Skylark Value, so the caller must
// explicitly handle such cases by interpreting nil as None or some
// computed default.
func UnpackArgs(fnname string, args Tuple, kwargs []Tuple, pairs ...interface{}) error {
nparams := len(pairs) / 2
var defined intset
defined.init(nparams)
// positional arguments
if len(args) > nparams {
return fmt.Errorf("%s: got %d arguments, want at most %d",
fnname, len(args), nparams)
}
for i, arg := range args {
defined.set(i)
if err := unpackOneArg(arg, pairs[2*i+1]); err != nil {
return fmt.Errorf("%s: for parameter %d: %s", fnname, i+1, err)
}
}
// keyword arguments
kwloop:
for _, item := range kwargs {
name, arg := item[0].(String), item[1]
for i := 0; i < nparams; i++ {
paramName := pairs[2*i].(string)
if paramName[len(paramName)-1] == '?' {
paramName = paramName[:len(paramName)-1]
}
if paramName == string(name) {
// found it
if defined.set(i) {
return fmt.Errorf("%s: got multiple values for keyword argument %s",
fnname, name)
}
ptr := pairs[2*i+1]
if err := unpackOneArg(arg, ptr); err != nil {
return fmt.Errorf("%s: for parameter %s: %s", fnname, name, err)
}
continue kwloop
}
}
return fmt.Errorf("%s: unexpected keyword argument %s", fnname, name)
}
// Check that all non-optional parameters are defined.
// (We needn't check the first len(args).)
for i := len(args); i < nparams; i++ {
name := pairs[2*i].(string)
if strings.HasSuffix(name, "?") {
break // optional
}
if !defined.get(i) {
return fmt.Errorf("%s: missing argument for %s", fnname, name)
}
}
return nil
}
// UnpackPositionalArgs unpacks the positional arguments into
// corresponding variables. Each element of vars is a pointer; see
// UnpackArgs for allowed types and conversions.
//
// UnpackPositionalArgs reports an error if the number of arguments is
// less than min or greater than len(vars), if kwargs is nonempty, or if
// any conversion fails.
func UnpackPositionalArgs(fnname string, args Tuple, kwargs []Tuple, min int, vars ...interface{}) error {
if len(kwargs) > 0 {
return fmt.Errorf("%s: unexpected keyword arguments", fnname)
}
max := len(vars)
if len(args) < min {
var atleast string
if min < max {
atleast = "at least "
}
return fmt.Errorf("%s: got %d arguments, want %s%d", fnname, len(args), atleast, min)
}
if len(args) > max {
var atmost string
if max > min {
atmost = "at most "
}
return fmt.Errorf("%s: got %d arguments, want %s%d", fnname, len(args), atmost, max)
}
for i, arg := range args {
if err := unpackOneArg(arg, vars[i]); err != nil {
return fmt.Errorf("%s: for parameter %d: %s", fnname, i+1, err)
}
}
return nil
}
func unpackOneArg(v Value, ptr interface{}) error {
ok := true
switch ptr := ptr.(type) {
case *Value:
*ptr = v
case *string:
*ptr, ok = AsString(v)
if !ok {
return fmt.Errorf("got %s, want string", v.Type())
}
case *bool:
*ptr = bool(v.Truth())
case *int:
var err error
*ptr, err = AsInt32(v)
if err != nil {
return err
}
case **List:
*ptr, ok = v.(*List)
if !ok {
return fmt.Errorf("got %s, want list", v.Type())
}
case **Dict:
*ptr, ok = v.(*Dict)
if !ok {
return fmt.Errorf("got %s, want dict", v.Type())
}
case *Callable:
*ptr, ok = v.(Callable)
if !ok {
return fmt.Errorf("got %s, want callable", v.Type())
}
case *Iterable:
*ptr, ok = v.(Iterable)
if !ok {
return fmt.Errorf("got %s, want iterable", v.Type())
}
default:
param := reflect.ValueOf(ptr).Elem()
if !reflect.TypeOf(v).AssignableTo(param.Type()) {
// Detect mistakes by caller.
if !param.Type().AssignableTo(reflect.TypeOf(new(Value)).Elem()) {
log.Fatalf("internal error: invalid ptr type: %T", ptr)
}
// Assume it's safe to call Type() on a zero instance.
paramType := param.Interface().(Value).Type()
return fmt.Errorf("got %s, want %s", v.Type(), paramType)
}
param.Set(reflect.ValueOf(v))
}
return nil
}
// ---- built-in functions ----
// https://github.com/google/skylark/blob/master/doc/spec.md#all
func all(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
if err := UnpackPositionalArgs("all", args, kwargs, 1, &iterable); err != nil {
return nil, err
}
iter := iterable.Iterate()
defer iter.Done()
var x Value
for iter.Next(&x) {
if !x.Truth() {
return False, nil
}
}
return True, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#any
func any(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
if err := UnpackPositionalArgs("all", args, kwargs, 1, &iterable); err != nil {
return nil, err
}
iter := iterable.Iterate()
defer iter.Done()
var x Value
for iter.Next(&x) {
if x.Truth() {
return True, nil
}
}
return False, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#bool
func bool_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var x Value = False
if err := UnpackPositionalArgs("bool", args, kwargs, 0, &x); err != nil {
return nil, err
}
return x.Truth(), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#chr
func chr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
if len(kwargs) > 0 {
return nil, fmt.Errorf("chr does not accept keyword arguments")
}
if len(args) != 1 {
return nil, fmt.Errorf("chr: got %d arguments, want 1", len(args))
}
i, err := AsInt32(args[0])
if err != nil {
return nil, fmt.Errorf("chr: got %s, want int", args[0].Type())
}
if i < 0 {
return nil, fmt.Errorf("chr: Unicode code point %d out of range (<0)", i)
}
if i > unicode.MaxRune {
return nil, fmt.Errorf("chr: Unicode code point U+%X out of range (>0x10FFFF)", i)
}
return String(string(i)), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#dict
func dict(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
if len(args) > 1 {
return nil, fmt.Errorf("dict: got %d arguments, want at most 1", len(args))
}
dict := new(Dict)
if err := updateDict(dict, args, kwargs); err != nil {
return nil, fmt.Errorf("dict: %v", err)
}
return dict, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#dir
func dir(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
if len(kwargs) > 0 {
return nil, fmt.Errorf("dir does not accept keyword arguments")
}
if len(args) != 1 {
return nil, fmt.Errorf("dir: got %d arguments, want 1", len(args))
}
var names []string
if x, ok := args[0].(HasAttrs); ok {
names = x.AttrNames()
}
elems := make([]Value, len(names))
for i, name := range names {
elems[i] = String(name)
}
return NewList(elems), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#enumerate
func enumerate(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
var start int
if err := UnpackPositionalArgs("enumerate", args, kwargs, 1, &iterable, &start); err != nil {
return nil, err
}
iter := iterable.Iterate()
if iter == nil {
return nil, fmt.Errorf("enumerate: got %s, want iterable", iterable.Type())
}
defer iter.Done()
var pairs []Value
var x Value
if n := Len(iterable); n >= 0 {
// common case: known length
pairs = make([]Value, 0, n)
array := make(Tuple, 2*n) // allocate a single backing array
for i := 0; iter.Next(&x); i++ {
pair := array[:2:2]
array = array[2:]
pair[0] = MakeInt(start + i)
pair[1] = x
pairs = append(pairs, pair)
}
} else {
// non-sequence (unknown length)
for i := 0; iter.Next(&x); i++ {
pair := Tuple{MakeInt(start + i), x}
pairs = append(pairs, pair)
}
}
return NewList(pairs), nil
}
func float(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
if len(kwargs) > 0 {
return nil, fmt.Errorf("float does not accept keyword arguments")
}
if len(args) == 0 {
return Float(0.0), nil
}
if len(args) != 1 {
return nil, fmt.Errorf("float got %d arguments, wants 1", len(args))
}
switch x := args[0].(type) {
case Bool:
if x {
return Float(1.0), nil
} else {
return Float(0.0), nil
}
case Int:
return x.Float(), nil
case Float:
return x, nil
case String:
f, err := strconv.ParseFloat(string(x), 64)
if err != nil {
return nil, err
}
return Float(f), nil
default:
return nil, fmt.Errorf("float got %s, want number or string", x.Type())
}
}
// https://github.com/google/skylark/blob/master/doc/spec.md#getattr
func getattr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var object, dflt Value
var name string
if err := UnpackPositionalArgs("getattr", args, kwargs, 2, &object, &name, &dflt); err != nil {
return nil, err
}
if o, ok := object.(HasAttrs); ok {
if v, err := o.Attr(name); v != nil || err != nil {
return v, err
}
}
if dflt != nil {
return dflt, nil
}
return nil, fmt.Errorf("%s has no .%s field or method", object.Type(), name)
}
// https://github.com/google/skylark/blob/master/doc/spec.md#hasattr
func hasattr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var object Value
var name string
if err := UnpackPositionalArgs("hasattr", args, kwargs, 2, &object, &name); err != nil {
return nil, err
}
if object, ok := object.(HasAttrs); ok {
if v, err := object.Attr(name); v != nil || err != nil {
return True, nil
}
}
return False, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#hash
func hash(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var x Value
if err := UnpackPositionalArgs("hash", args, kwargs, 1, &x); err != nil {
return nil, err
}
h, err := x.Hash()
return MakeUint(uint(h)), err
}
// https://github.com/google/skylark/blob/master/doc/spec.md#int
func int_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var x Value = zero
var base Value
if err := UnpackArgs("int", args, kwargs, "x?", &x, "base?", &base); err != nil {
return nil, err
}
// "If x is not a number or base is given, x must be a string."
if s, ok := AsString(x); ok {
b := 10
if base != nil {
var err error
b, err = AsInt32(base)
if err != nil || b != 0 && (b < 2 || b > 36) {
return nil, fmt.Errorf("int: base must be an integer >= 2 && <= 36")
}
}
orig := s // save original for error message
if len(s) > 1 {
var sign string
i := 0
if s[0] == '+' || s[0] == '-' {
sign = s[:1]
i++
}
if i < len(s) && s[i] == '0' {
hasbase := 0
if i+2 < len(s) {
switch s[i+1] {
case 'o', 'O':
// SetString doesn't understand "0o755"
// so modify s to "0755".
// Octals are rare, so allocation is fine.
s = sign + "0" + s[i+2:]
hasbase = 8
case 'x', 'X':
hasbase = 16
case 'b', 'B':
hasbase = 2
}
if hasbase != 0 && b != 0 {
// Explicit base doesn't match prefix,
// e.g. int("0o755", 16).
if hasbase != b {
goto invalid
}
// SetString requires base=0
// if there's a base prefix.
b = 0
}
}
// For automatic base detection,
// a string starting with zero
// must be all zeros.
// Thus we reject "0755".
if hasbase == 0 && b == 0 {
for ; i < len(s); i++ {
if s[i] != '0' {
goto invalid
}
}
}
}
}
// NOTE: int(x) permits arbitrary precision, unlike the scanner.
if i, ok := new(big.Int).SetString(s, b); ok {
return Int{i}, nil
}
invalid:
return nil, fmt.Errorf("int: invalid literal with base %d: %s", b, orig)
}
if base != nil {
return nil, fmt.Errorf("int: can't convert non-string with explicit base")
}
if b, ok := x.(Bool); ok {
if b {
return one, nil
} else {
return zero, nil
}
}
i, err := NumberToInt(x)
if err != nil {
return nil, fmt.Errorf("int: %s", err)
}
return i, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#len
func len_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var x Value
if err := UnpackPositionalArgs("len", args, kwargs, 1, &x); err != nil {
return nil, err
}
len := Len(x)
if len < 0 {
return nil, fmt.Errorf("value of type %s has no len", x.Type())
}
return MakeInt(len), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#list
func list(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
if err := UnpackPositionalArgs("list", args, kwargs, 0, &iterable); err != nil {
return nil, err
}
var elems []Value
if iterable != nil {
iter := iterable.Iterate()
defer iter.Done()
if n := Len(iterable); n > 0 {
elems = make([]Value, 0, n) // preallocate if length known
}
var x Value
for iter.Next(&x) {
elems = append(elems, x)
}
}
return NewList(elems), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#min
func minmax(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
if len(args) == 0 {
return nil, fmt.Errorf("%s requires at least one positional argument", fn.Name())
}
var keyFunc Callable
if err := UnpackArgs(fn.Name(), nil, kwargs, "key?", &keyFunc); err != nil {
return nil, err
}
var op syntax.Token
if fn.Name() == "max" {
op = syntax.GT
} else {
op = syntax.LT
}
var iterable Value
if len(args) == 1 {
iterable = args[0]
} else {
iterable = args
}
iter := Iterate(iterable)
if iter == nil {
return nil, fmt.Errorf("%s: %s value is not iterable", fn.Name(), iterable.Type())
}
defer iter.Done()
var extremum Value
if !iter.Next(&extremum) {
return nil, fmt.Errorf("%s: argument is an empty sequence", fn.Name())
}
var extremeKey Value
var keyargs Tuple
if keyFunc == nil {
extremeKey = extremum
} else {
keyargs = Tuple{extremum}
res, err := Call(thread, keyFunc, keyargs, nil)
if err != nil {
return nil, err
}
extremeKey = res
}
var x Value
for iter.Next(&x) {
var key Value
if keyFunc == nil {
key = x
} else {
keyargs[0] = x
res, err := Call(thread, keyFunc, keyargs, nil)
if err != nil {
return nil, err
}
key = res
}
if ok, err := Compare(op, key, extremeKey); err != nil {
return nil, err
} else if ok {
extremum = x
extremeKey = key
}
}
return extremum, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#ord
func ord(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
if len(kwargs) > 0 {
return nil, fmt.Errorf("ord does not accept keyword arguments")
}
if len(args) != 1 {
return nil, fmt.Errorf("ord: got %d arguments, want 1", len(args))
}
s, ok := AsString(args[0])
if !ok {
return nil, fmt.Errorf("ord: got %s, want string", args[0].Type())
}
r, sz := utf8.DecodeRuneInString(s)
if sz == 0 || sz != len(s) {
n := utf8.RuneCountInString(s)
return nil, fmt.Errorf("ord: string encodes %d Unicode code points, want 1", n)
}
return MakeInt(int(r)), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#print
func print(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var buf bytes.Buffer
path := make([]Value, 0, 4)
sep := ""
for _, v := range args {
buf.WriteString(sep)
if s, ok := AsString(v); ok {
buf.WriteString(s)
} else {
writeValue(&buf, v, path)
}
sep = " "
}
for _, pair := range kwargs {
buf.WriteString(sep)
buf.WriteString(string(pair[0].(String)))
buf.WriteString("=")
if s, ok := AsString(pair[1]); ok {
buf.WriteString(s)
} else {
writeValue(&buf, pair[1], path)
}
sep = " "
}
if thread.Print != nil {
thread.Print(thread, buf.String())
} else {
fmt.Fprintln(os.Stderr, &buf)
}
return None, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#range
func range_(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var start, stop, step int
step = 1
if err := UnpackPositionalArgs("range", args, kwargs, 1, &start, &stop, &step); err != nil {
return nil, err
}
// TODO(adonovan): analyze overflow/underflows cases for 32-bit implementations.
var n int
switch len(args) {
case 1:
// range(stop)
start, stop = 0, start
fallthrough
case 2:
// range(start, stop)
if stop > start {
n = stop - start
}
case 3:
// range(start, stop, step)
switch {
case step > 0:
if stop > start {
n = (stop-1-start)/step + 1
}
case step < 0:
if start > stop {
n = (start-1-stop)/-step + 1
}
default:
return nil, fmt.Errorf("range: step argument must not be zero")
}
}
return rangeValue{start: start, stop: stop, step: step, len: n}, nil
}
// A rangeValue is a comparable, immutable, indexable sequence of integers
// defined by the three parameters to a range(...) call.
// Invariant: step != 0.
type rangeValue struct{ start, stop, step, len int }
var (
_ Indexable = rangeValue{}
_ Sequence = rangeValue{}
_ Comparable = rangeValue{}
)
func (r rangeValue) Len() int { return r.len }
func (r rangeValue) Index(i int) Value { return MakeInt(r.start + i*r.step) }
func (r rangeValue) Iterate() Iterator { return &rangeIterator{r, 0} }
func (r rangeValue) Freeze() {} // immutable
func (r rangeValue) String() string {
if r.step != 1 {
return fmt.Sprintf("range(%d, %d, %d)", r.start, r.stop, r.step)
} else if r.start != 0 {
return fmt.Sprintf("range(%d, %d)", r.start, r.stop)
} else {
return fmt.Sprintf("range(%d)", r.stop)
}
}
func (r rangeValue) Type() string { return "range" }
func (r rangeValue) Truth() Bool { return r.len > 0 }
func (r rangeValue) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: range") }
func (x rangeValue) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) {
y := y_.(rangeValue)
switch op {
case syntax.EQL:
return rangeEqual(x, y), nil
case syntax.NEQ:
return !rangeEqual(x, y), nil
default:
return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
}
}
func rangeEqual(x, y rangeValue) bool {
// Two ranges compare equal if they denote the same sequence.
return x.len == y.len &&
(x.len == 0 || x.start == y.start && x.step == y.step)
}
func (r rangeValue) contains(x Int) bool {
x32, err := AsInt32(x)
if err != nil {
return false // out of range
}
delta := x32 - r.start
quo, rem := delta/r.step, delta%r.step
return rem == 0 && 0 <= quo && quo < r.len
}
type rangeIterator struct {
r rangeValue
i int
}
func (it *rangeIterator) Next(p *Value) bool {
if it.i < it.r.len {
*p = it.r.Index(it.i)
it.i++
return true
}
return false
}
func (*rangeIterator) Done() {}
// https://github.com/google/skylark/blob/master/doc/spec.md#repr
func repr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var x Value
if err := UnpackPositionalArgs("repr", args, kwargs, 1, &x); err != nil {
return nil, err
}
return String(x.String()), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#reversed
func reversed(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
if err := UnpackPositionalArgs("reversed", args, kwargs, 1, &iterable); err != nil {
return nil, err
}
iter := iterable.Iterate()
defer iter.Done()
var elems []Value
if n := Len(args[0]); n >= 0 {
elems = make([]Value, 0, n) // preallocate if length known
}
var x Value
for iter.Next(&x) {
elems = append(elems, x)
}
n := len(elems)
for i := 0; i < n>>1; i++ {
elems[i], elems[n-1-i] = elems[n-1-i], elems[i]
}
return NewList(elems), nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#set
func set(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
if err := UnpackPositionalArgs("set", args, kwargs, 0, &iterable); err != nil {
return nil, err
}
set := new(Set)
if iterable != nil {
iter := iterable.Iterate()
defer iter.Done()
var x Value
for iter.Next(&x) {
if err := set.Insert(x); err != nil {
return nil, err
}
}
}
return set, nil
}
// https://github.com/google/skylark/blob/master/doc/spec.md#sorted
func sorted(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
var iterable Iterable
var key Callable
var reverse bool
if err := UnpackArgs("sorted", args, kwargs,
"iterable", &iterable,
"key?", &key,
"reverse?", &reverse,
); err != nil {
return nil, err
}
iter := iterable.Iterate()
defer iter.Done()
var values []Value
if n := Len(iterable); n > 0 {
values = make(Tuple, 0, n) // preallocate if length is known
}
var x Value
for iter.Next(&x) {
values = append(values, x)
}
// Derive keys from values by applying key function.
var keys []Value
if key != nil {
keys = make([]Value, len(values))
for i, v := range values {
k, err := Call(thread, key, Tuple{v}, nil)
if err != nil {