File: strings.py

package info (click to toggle)
python-yaql 3.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,056 kB
  • sloc: python: 7,758; sh: 25; makefile: 19
file content (1031 lines) | stat: -rw-r--r-- 28,587 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
#    Copyright (c) 2015 Mirantis, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
"""
The module describes which operations can be done with strings in YAQL.
"""

import string as string_module

from yaql.language import specs
from yaql.language import utils
from yaql.language import yaqltypes


@specs.parameter('left', yaqltypes.String())
@specs.parameter('right', yaqltypes.String())
@specs.name('#operator_>')
def gt(left, right):
    """:yaql:operator >

    Returns true if the left operand is strictly greater than the right,
    ordering lexicographically, otherwise false.

    :signature: left > right
    :arg left: left operand
    :argType left: string
    :arg right: right operand
    :argType right: string
    :returnType: boolean

    .. code::

        yaql> "abc" > "ab"
        true
        yaql> "abc" > "abb"
        true
        yaql> "abc" > "abc"
        false
    """
    return left > right


@specs.parameter('left', yaqltypes.String())
@specs.parameter('right', yaqltypes.String())
@specs.name('#operator_<')
def lt(left, right):
    """:yaql:operator <

    Returns true if the left operand is strictly less than the right, ordering
    lexicographically, otherwise false.

    :signature: left < right
    :arg left: left operand
    :argType left: string
    :arg right: right operand
    :argType right: string
    :returnType: boolean

    .. code::

        yaql> "ab" < "abc"
        true
        yaql> "abb" < "abc"
        true
        yaql> "abc" < "abc"
        false
    """
    return left < right


@specs.parameter('left', yaqltypes.String())
@specs.parameter('right', yaqltypes.String())
@specs.name('#operator_>=')
def gte(left, right):
    """:yaql:operator >=

    Returns true if the left operand is greater or equal to the right, ordering
    lexicographically, otherwise false.

    :signature: left >= right
    :arg left: left operand
    :argType left: string
    :arg right: right operand
    :argType right: string
    :returnType: boolean

    .. code::

        yaql> "abc" >= "ab"
        true
        yaql> "abc" >= "abc"
        true
    """
    return left >= right


@specs.parameter('left', yaqltypes.String())
@specs.parameter('right', yaqltypes.String())
@specs.name('#operator_<=')
def lte(left, right):
    """:yaql:operator <=

    Returns true if the left operand is less or equal to the right, ordering
    lexicographically, otherwise false.

    :signature: left <= right
    :arg left: left operand
    :argType left: string
    :arg right: right operand
    :argType right: string
    :returnType: boolean

    .. code::

        yaql> "ab" <= "abc"
        true
        yaql> "abc" <= "abc"
        true
    """
    return left <= right


@specs.parameter('args', yaqltypes.String())
def concat(*args):
    """:yaql:concat

    Returns concatenated args.

    :signature: concat([args])
    :arg [args]: values to be joined
    :argType [args]: string
    :returnType: string

    .. code::

        yaql> concat("abc", "de", "f")
        "abcdef"
    """
    return ''.join(args)


@specs.parameter('string', yaqltypes.String())
@specs.method
def to_upper(string):
    """:yaql:toUpper

    Returns a string with all case-based characters uppercase.

    :signature: string.toUpper()
    :receiverArg string: value to uppercase
    :argType string: string
    :returnType: string

    .. code::

        yaql> "aB1c".toUpper()
        "AB1C"
    """
    return string.upper()


@specs.parameter('string', yaqltypes.String())
@specs.extension_method
def len_(string):
    """:yaql:len

    Returns size of the string.

    :signature: string.len()
    :receiverArg string: input string
    :argType string: string
    :returnType: integer

    .. code::

        yaql> "abc".len()
        3
    """
    return len(string)


@specs.parameter('string', yaqltypes.String())
@specs.method
def to_lower(string):
    """:yaql:toLower

    Returns a string with all case-based characters lowercase.

    :signature: string.toLower()
    :receiverArg string: value to lowercase
    :argType string: string
    :returnType: string

    .. code::

        yaql> "AB1c".toLower()
        "ab1c"
    """
    return string.lower()


@specs.parameter('string', yaqltypes.String())
@specs.parameter('separator', yaqltypes.String(nullable=True))
@specs.parameter('max_splits', int)
@specs.method
def split(string, separator=None, max_splits=-1):
    """:yaql:split

    Returns a list of tokens in the string, using separator as the
    delimiter.

    :signature: string.split(separator => null, maxSplits => -1)
    :receiverArg string: value to be splitted
    :argType string: string
    :arg separator: delimiter for splitting. null by default, which means
        splitting with whitespace characters
    :argType separator: string
    :arg maxSplits: maximum number of splittings. -1 by default, which means
        all possible splits are done
    :argType maxSplits: integer
    :returnType: list

    .. code::

        yaql> "abc     de  f".split()
        ["abc", "de", "f"]
        yaql> "abc     de  f".split(maxSplits => 1)
        ["abc", "de  f"]
        yaql> "abcde".split("c")
        ["ab", "de"]
    """
    return string.split(separator, max_splits)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('separator', yaqltypes.String(nullable=True))
@specs.parameter('max_splits', int)
@specs.method
def right_split(string, separator=None, max_splits=-1):
    """:yaql:rightSplit

    Returns a list of tokens in the string, using separator as the
    delimiter. If maxSplits is given then at most maxSplits splits are done -
    the rightmost ones.

    :signature: string.rightSplit(separator => null, maxSplits => -1)
    :receiverArg string: value to be splitted
    :argType string: string
    :arg separator: delimiter for splitting. null by default, which means
        splitting with whitespace characters
    :argType separator: string
    :arg maxSplits: number of splits to be done - the rightmost ones.
        -1 by default, which means all possible splits are done
    :argType maxSplits: integer
    :returnType: list

    .. code::

        yaql> "abc     de  f".rightSplit()
        ["abc", "de", "f"]
        yaql> "abc     de  f".rightSplit(maxSplits => 1)
        ["abc     de", "f"]
    """
    return string.rsplit(separator, max_splits)


@specs.parameter('sequence', yaqltypes.Iterable())
@specs.parameter('separator', yaqltypes.String())
@specs.inject('str_delegate', yaqltypes.Delegate('str'))
@specs.method
def join(sequence, separator, str_delegate):
    """:yaql:join

    Returns a string with sequence elements joined by the separator.

    :signature: sequence.join(separator)
    :receiverArg sequence: chain of values to be joined
    :argType sequence: sequence of strings
    :arg separator: value to be placed between joined pairs
    :argType separator: string
    :returnType: string

    .. code::

        yaql> ["abc", "de", "f"].join("")
        "abcdef"
        yaql> ["abc", "de", "f"].join("|")
        "abc|de|f"
    """
    return separator.join(map(str_delegate, sequence))


@specs.parameter('sequence', yaqltypes.Iterable())
@specs.parameter('separator', yaqltypes.String())
@specs.inject('str_delegate', yaqltypes.Delegate('str'))
@specs.method
def join_(separator, sequence, str_delegate):
    """:yaql:join

    Returns a string with sequence elements joined by the separator.

    :signature: separator.join(sequence)
    :receiverArg separator: value to be placed between joined pairs
    :argType separator: string
    :arg sequence: chain of values to be joined
    :argType sequence: sequence of strings
    :returnType: string

    .. code::

        yaql> "|".join(["abc", "de", "f"])
        "abc|de|f"
    """
    return join(sequence, separator, str_delegate)


@specs.parameter('value', nullable=True)
def str_(value):
    """:yaql:str

    Returns a string representation of the value.

    :signature: str(value)
    :arg value: value to be evaluated to string
    :argType value: any
    :returnType: string

    .. code::

        yaql> str(["abc", "de"])
        "(u'abc', u'd')"
        yaql> str(123)
        "123"
    """
    if value is None:
        return 'null'
    elif value is True:
        return 'true'
    elif value is False:
        return 'false'
    else:
        return str(value)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('chars', yaqltypes.String(nullable=True))
@specs.method
def trim(string, chars=None):
    """:yaql:trim

    Returns a string with the leading and trailing chars removed.

    :signature: string.trim(chars => null)
    :receiverArg string: value to be trimmed
    :argType string: string
    :arg chars: symbols to be removed from input string. null by default,
        which means trim is done with whitespace characters
    :argType chars: string
    :returnType: string

    .. code::

        yaql> "  abcd ".trim()
        "abcd"
        yaql> "aababa".trim("a")
        "bab"
    """
    return string.strip(chars)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('chars', yaqltypes.String(nullable=True))
@specs.method
def trim_left(string, chars=None):
    """:yaql:trimLeft

    Returns a string with the leading chars removed.

    :signature: string.trimLeft(chars => null)
    :receiverArg string: value to be trimmed
    :argType string: string
    :arg chars: symbols to be removed from start of input string. null by
        default, which means trim is done with whitespace characters
    :argType chars: string
    :returnType: string

    .. code::

        yaql> "  abcd ".trimLeft()
        "abcd "
        yaql> "aababa".trimLeft("a")
        "baba"
    """
    return string.lstrip(chars)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('chars', yaqltypes.String(nullable=True))
@specs.method
def trim_right(string, chars=None):
    """:yaql:trimRight

    Returns a string with the trailing chars removed.

    :signature: string.trimRight(chars => null)
    :receiverArg string: value to be trimmed
    :argType string: string
    :arg chars: symbols to be removed from end of input string. null by
        default, which means trim is done with whitespace characters
    :argType chars: string
    :returnType: string

    .. code::

        yaql> "  abcd ".trimRight()
        "  abcd"
        yaql> "aababa".trimRight("a")
        "aabab"
    """
    return string.rstrip(chars)


@specs.parameter('string', yaqltypes.String(nullable=True))
@specs.parameter('chars', yaqltypes.String(nullable=True))
@specs.extension_method
def norm(string, chars=None):
    """:yaql:norm

    Returns a string with the leading and trailing chars removed.
    If the resulting string is empty, returns null.

    :signature: string.norm(chars => null)
    :receiverArg string: value to be cut with specified chars
    :argType string: string
    :arg chars: symbols to be removed from the start and the end of input
        string. null by default, which means norm is done with whitespace
        characters
    :argType chars: string
    :returnType: string

    .. code::

        yaql> "  abcd ".norm()
        "abcd"
        yaql> "aaaa".norm("a")
        null
    """
    if string is None:
        return None
    value = string.strip(chars)
    return None if not value else value


@specs.parameter('string', yaqltypes.String(nullable=True))
@specs.parameter('trim_spaces', bool, alias='trim')
@specs.parameter('chars', yaqltypes.String(nullable=True))
@specs.extension_method
def is_empty(string, trim_spaces=True, chars=None):
    """:yaql:isEmpty

    Returns true if the string with removed leading and trailing chars is
    empty.

    :signature: string.isEmpty(trimSpaces => true, chars => null)
    :receiverArg string: value to be checked for emptiness after trim
    :argType string: string
    :arg trimSpaces: true by default, which means string to be trimmed with
        chars. false means checking whether input string is empty
    :argType trimSpaces: boolean
    :arg chars: symbols for trimming. null by default, which means trim is
        done with whitespace characters
    :argType chars: string
    :returnType: boolean

    .. code::

        yaql> "abaab".isEmpty(chars=>"ab")
        true
        yaql> "aba".isEmpty(chars=>"a")
        false
    """
    if string is None:
        return True
    if trim_spaces:
        string = string.strip(chars)
    return not string


@specs.parameter('string', yaqltypes.String())
@specs.parameter('old', yaqltypes.String())
@specs.parameter('new', yaqltypes.String())
@specs.parameter('count', int)
@specs.method
def replace(string, old, new, count=-1):
    """:yaql:replace

    Returns a string with first count occurrences of old replaced with new.

    :signature: string.replace(old, new, count => -1)
    :receiverArg string: input string
    :argType string: string
    :arg old: value to be replaced
    :argType old: string
    :arg new: replacement for old value
    :argType new: string
    :arg count: how many first replacements to do. -1 by default, which means
        to do all replacements
    :argType count: integer
    :returnType: string

    .. code::

        yaql> "abaab".replace("ab", "cd")
        "cdacd"
    """
    return string.replace(old, new, count)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('replacements', utils.MappingType)
@specs.parameter('count', int)
@specs.inject('str_func', yaqltypes.Delegate('str'))
@specs.method
@specs.name('replace')
def replace_with_dict(string, str_func, replacements, count=-1):
    """:yaql:replace

    Returns a string with all occurrences of replacements' keys replaced
    with corresponding replacements' values.
    If count is specified, only the first count occurrences of every key
    are replaced.

    :signature: string.replace(replacements, count => -1)
    :receiverArg string: input string
    :argType string: string
    :arg replacements: dict of replacements in format {old => new ...}
    :argType replacements: mapping
    :arg count: how many first occurrences of every key are replaced. -1 by
        default, which means to do all replacements
    :argType count: integer
    :returnType: string

    .. code::

        yaql> "abc ab abc".replace({abc => xx, ab => yy})
        "xx yy xx"
        yaql> "abc ab abc".replace({ab => yy, abc => xx})
        "yyc yy yyc"
        yaql> "abc ab abc".replace({ab => yy, abc => xx}, 1)
        "yyc ab xx"
    """
    for key, value in replacements.items():
        string = string.replace(str_func(key), str_func(value), count)
    return string


@specs.parameter('left', yaqltypes.String())
@specs.parameter('right', int)
@specs.name('#operator_*')
def string_by_int(left, right, engine):
    """:yaql:operator *

    Returns string repeated count times.

    :signature: left * right
    :arg left: left operand
    :argType left: string
    :arg right: right operator, how many times repeat input string
    :argType right: integer
    :returnType: string

    .. code::

        yaql> "ab" * 2
        "abab"
    """
    utils.limit_memory_usage(engine, (-right + 1, ''), (right, left))
    return left * right


@specs.parameter('left', yaqltypes.String())
@specs.parameter('right', yaqltypes.String())
@specs.name('#operator_in')
def in_(left, right):
    """:yaql:operator in

    Returns true if there is at least one occurrence of left string in right.

    :signature: left in right
    :arg left: left operand, which occurrence is checked
    :argType left: string
    :arg right: right operand
    :argType right: string
    :returnType: boolean

    .. code::

        yaql> "ab" in "abc"
        true
        yaql> "ab" in "acb"
        false
    """
    return left in right


@specs.parameter('left', int)
@specs.parameter('right', yaqltypes.String())
@specs.name('#operator_*')
def int_by_string(left, right, engine):
    """:yaql:operator *

    Returns string repeated count times.

    :signature: left * right
    :arg left: left operand, how many times repeat input string
    :argType left: integer
    :arg right: right operator
    :argType right: string
    :returnType: string

    .. code::

        yaql> 2 * "ab"
        "abab"
    """
    return string_by_int(right, left, engine)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('start', int)
@specs.parameter('length', int)
@specs.method
def substring(string, start, length=-1):
    """:yaql:substring

    Returns a substring beginning from start index ending with start+end index.

    :signature: string.substring(start, length => -1)
    :receiverArg string: input string
    :argType string: string
    :arg start: index for substring to start with
    :argType start: integer
    :arg length: length of substring. -1 by default, which means end of
        substring to be equal to the end of input string
    :argType length: integer
    :returnType: string

    .. code::

        yaql> "abcd".substring(1)
        "bcd"
        yaql> "abcd".substring(1, 2)
        "bc"
    """
    if length < 0:
        length = len(string)
    if start < 0:
        start += len(string)
    return string[start:start + length]


@specs.parameter('string', yaqltypes.String())
@specs.parameter('sub', yaqltypes.String())
@specs.parameter('start', int)
@specs.method
def index_of(string, sub, start=0):
    """:yaql:indexOf

    Returns an index of first occurrence sub in string beginning from start.
    -1 is a return value if there is no any occurrence.

    :signature: string.indexOf(sub, start => 0)
    :receiverArg string: input string
    :argType string: string
    :arg sub: substring to find in string
    :argType sub: string
    :arg start: index to start search with, 0 by default
    :argType start: integer
    :returnType: integer

    .. code::

        yaql> "cabcdab".indexOf("ab")
        1
        yaql> "cabcdab".indexOf("ab", 2)
        5
        yaql> "cabcdab".indexOf("ab", 6)
        -1
    """
    return string.find(sub, start)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('sub', yaqltypes.String())
@specs.parameter('start', int)
@specs.parameter('length', int)
@specs.method
def index_of_(string, sub, start, length):
    """:yaql:indexOf

    Returns an index of first occurrence sub in string beginning from start
    ending with start+length.
    -1 is a return value if there is no any occurrence.

    :signature: string.indexOf(sub, start, length)
    :receiverArg string: input string
    :argType string: string
    :arg sub: substring to find in string
    :argType sub: string
    :arg start: index to start search with, 0 by default
    :argType start: integer
    :arg length: length of string to find substring in
    :argType length: integer
    :returnType: integer

    .. code::

        yaql> "cabcdab".indexOf("bc", 2, 2)
        2
    """
    if start < 0:
        start += len(string)
    if length < 0:
        length = len(string) - start
    return string.find(sub, start, start + length)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('sub', yaqltypes.String())
@specs.parameter('start', int)
@specs.method
def last_index_of(string, sub, start=0):
    """:yaql:lastIndexOf

    Returns an index of last occurrence sub in string beginning from start.
    -1 is a return value if there is no any occurrence.

    :signature: string.lastIndexOf(sub, start => 0)
    :receiverArg string: input string
    :argType string: string
    :arg sub: substring to find in string
    :argType sub: string
    :arg start: index to start search with, 0 by default
    :argType start: integer
    :returnType: integer

    .. code::

        yaql> "cabcdab".lastIndexOf("ab")
        5
    """
    return string.rfind(sub, start)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('sub', yaqltypes.String())
@specs.parameter('start', int)
@specs.parameter('length', int)
@specs.method
def last_index_of_(string, sub, start, length):
    """:yaql:lastIndexOf

    Returns an index of last occurrence sub in string beginning from start
    ending with start+length.
    -1 is a return value if there is no any occurrence.

    :signature: string.lastIndexOf(sub, start, length)
    :receiverArg string: input string
    :argType string: string
    :arg sub: substring to find in string
    :argType sub: string
    :arg start: index to start search with, 0 by default
    :argType start: integer
    :arg length: length of string to find substring in
    :argType length: integer
    :returnType: integer

    .. code::

        yaql> "cabcdbc".lastIndexOf("bc", 2, 5)
        5
    """
    if start < 0:
        start += len(string)
    if length < 0:
        length = len(string) - start
    return string.rfind(sub, start, start + length)


@specs.parameter('string', yaqltypes.String())
@specs.method
def to_char_array(string):
    """:yaql:toCharArray

    Converts a string to array of one character strings.

    :signature: string.toCharArray()
    :receiverArg string: input string
    :argType string: string
    :returnType: list

    .. code::

        yaql> "abc de".toCharArray()
        ["a", "b", "c", " ", "d", "e"]
    """
    return tuple(string)


def characters(
        digits=False, hexdigits=False,
        ascii_lowercase=False, ascii_uppercase=False,
        ascii_letters=False, letters=False,
        octdigits=False, punctuation=False, printable=False,
        lowercase=False, uppercase=False, whitespace=False):
    """:yaql:characters

    Returns a list of all distinct items of specified types.

    :signature: characters(digits => false, hexdigits => false,
                           asciiLowercase => false, asciiUppercase => false,
                           asciiLetters => false, letters => false,
                           octdigits => false, punctuation => false,
                           printable => false, lowercase => false,
                           uppercase => false, whitespace => false)
    :arg digits: include digits in output list if true, false by default
    :argType digits: boolean
    :arg hexdigits: include hexademical digits in output list if true, false
        by default
    :argType hexdigits: boolean
    :arg asciiLowercase: include ASCII lowercase letters in output list if
        true, false by default
    :argType asciiLowercase: boolean
    :arg asciiUppercase: include ASCII uppercase letters in output list if
        true, false by default
    :argType asciiUppercase: boolean
    :arg asciiLetters: include both ASCII lowercase and uppercase letters
        in output list if true, false by default
    :argType asciiLetters: boolean
    :arg letters: include both lowercase and uppercase letters in output list
        if true, false by default
    :argType letters: boolean
    :arg octdigits: include digits from 0 to 7 in output list if true, false
        by default
    :argType octdigits: boolean
    :arg punctuation: include ASCII characters, which are considered
        punctuation, in output list if true, false by default
    :argType punctuation: boolean
    :arg printable: include digits, letters, punctuation, and whitespace in
        output list if true, false by default
    :argType printable: boolean
    :arg lowercase: include lowercase letters in output list if true, false
        by default
    :argType lowercase: boolean
    :arg uppercase: include uppercase letters in output list if true, false
        by default
    :argType uppercase: boolean
    :arg whitespace: include all characters that are considered whitespace
        in output list if true, false by default
    :argType whitespace: boolean
    :returnType: list

    .. code::

        yaql> characters(digits => true)
        ["1", "0", "3", "2", "5", "4", "7", "6", "9", "8"]

    """
    string = ''
    if digits:
        string += string_module.digits
    if hexdigits:
        string += string_module.hexdigits
    if ascii_lowercase:
        string += string_module.ascii_lowercase
    if ascii_uppercase:
        string += string_module.ascii_uppercase
    if ascii_letters:
        string += string_module.ascii_letters
    if letters:
        string += string_module.letters
    if octdigits:
        string += string_module.octdigits
    if punctuation:
        string += string_module.punctuation
    if printable:
        string += string_module.printable
    if lowercase:
        string += string_module.lowercase
    if uppercase:
        string += string_module.uppercase
    if whitespace:
        string += string_module.whitespace
    return tuple(set(string))


def is_string(arg):
    """:yaql:isString

    Returns true if arg is a string.

    :signature: isString(arg)
    :arg arg: input value
    :argType arg: any
    :returnType: boolean

    .. code::

        yaql> isString("ab")
        true
        yaql> isString(1)
        false
    """
    return isinstance(arg, str)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('prefixes', yaqltypes.String())
@specs.method
def starts_with(string, *prefixes):
    """:yaql:startsWith

    Returns true if a string starts with any of given args.

    :signature: string.startsWith([args])
    :receiverArg string: input string
    :argType string: string
    :arg [args]: chain of strings to check input string with
    :argType [args]: strings
    :returnType: boolean

    .. code::

        yaql> "abcd".startsWith("ab", "xx")
        true
        yaql> "abcd".startsWith("yy", "xx", "zz")
        false
    """
    return string.startswith(prefixes)


@specs.parameter('string', yaqltypes.String())
@specs.parameter('suffixes', yaqltypes.String())
@specs.method
def ends_with(string, *suffixes):
    """:yaql:endsWith

    Returns true if a string ends with any of given args.

    :signature: string.endsWith([args])
    :receiverArg string: input string
    :argType string: string
    :arg [args]: chain of strings to check input string with
    :argType [args]: strings
    :returnType: boolean

    .. code::

        yaql> "abcd".endsWith("cd", "xx")
        true
        yaql> "abcd".endsWith("yy", "xx", "zz")
        false
    """
    return string.endswith(suffixes)


@specs.parameter('num', yaqltypes.Number(nullable=True))
def hex_(num):
    """:yaql:hex

    Returns a string with hexadecimal representation of num.

    :signature: hex(num)
    :arg num: input number to be converted to hexademical
    :argType num: number
    :returnType: string

    .. code::

        yaql> hex(256)
        "0x100"
    """
    return hex(num)


def register(context):
    context.register_function(gt)
    context.register_function(lt)
    context.register_function(gte)
    context.register_function(lte)
    context.register_function(len_)
    context.register_function(to_lower)
    context.register_function(to_upper)
    context.register_function(split)
    context.register_function(right_split)
    context.register_function(join)
    context.register_function(join_)
    context.register_function(str_)
    context.register_function(concat)
    context.register_function(concat, name='#operator_+')
    context.register_function(trim)
    context.register_function(trim_left)
    context.register_function(trim_right)
    context.register_function(replace)
    context.register_function(replace_with_dict)
    context.register_function(is_empty)
    context.register_function(string_by_int)
    context.register_function(int_by_string)
    context.register_function(substring)
    context.register_function(index_of)
    context.register_function(index_of_)
    context.register_function(last_index_of)
    context.register_function(last_index_of_)
    context.register_function(to_char_array)
    context.register_function(characters)
    context.register_function(is_string)
    context.register_function(norm)
    context.register_function(in_)
    context.register_function(starts_with)
    context.register_function(ends_with)
    context.register_function(hex_)