forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.jl
1400 lines (1207 loc) · 38.2 KB
/
string.jl
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
## core text I/O ##
print(io::IO, x) = show(io, x)
print(io::IO, xs...) = for x in xs print(io, x) end
println(io::IO, xs...) = print(io, xs..., '\n')
print(xs...) = print(STDOUT, xs...)
println(xs...) = println(STDOUT, xs...)
## core string functions ##
endof(s::String) = error("you must implement endof(", typeof(s), ")")
next(s::String, i::Int) = error("you must implement next(", typeof(s), ",Int)")
next(s::DirectIndexString, i::Int) = (s[i],i+1)
next(s::String, i::Integer) = next(s,int(i))
## conversion of general objects to strings ##
function print_to_string(xs...)
s = IOBuffer(Array(Uint8,isa(xs[1],String) ? endof(xs[1]) : 0), true, true)
truncate(s,0)
for x in xs
print(s, x)
end
takebuf_string(s)
end
string() = ""
string(s::String) = s
string(xs...) = print_to_string(xs...)
bytestring() = ""
bytestring(s::Array{Uint8,1}) = bytestring(pointer(s),length(s))
bytestring(s::String...) = print_to_string(s...)
function bytestring(p::Union(Ptr{Uint8},Ptr{Int8}))
p == C_NULL ? error("cannot convert NULL to string") :
ccall(:jl_cstr_to_string, ByteString, (Ptr{Uint8},), p)
end
function bytestring(p::Union(Ptr{Uint8},Ptr{Int8}),len::Integer)
p == C_NULL ? error("cannot convert NULL to string") :
ccall(:jl_pchar_to_string, ByteString, (Ptr{Uint8},Int), p, len)
end
convert(::Type{Array{Uint8,1}}, s::String) = bytestring(s).data
convert(::Type{Array{Uint8}}, s::String) = bytestring(s).data
convert(::Type{ByteString}, s::String) = bytestring(s)
convert(::Type{Array{Char,1}}, s::String) = collect(s)
## generic supplied functions ##
start(s::String) = 1
done(s::String,i) = (i > endof(s))
isempty(s::String) = done(s,start(s))
getindex(s::String, i::Int) = next(s,i)[1]
getindex(s::String, i::Integer) = s[int(i)]
getindex(s::String, x::Real) = s[to_index(x)]
getindex{T<:Integer}(s::String, r::Range1{T}) = s[int(first(r)):int(last(r))]
# TODO: handle other ranges with stride ±1 specially?
getindex(s::String, v::AbstractVector) =
sprint(length(v), io->(for i in v write(io,s[i]) end))
symbol(s::String) = symbol(bytestring(s))
print(io::IO, s::String) = write(io, s)
write(io::IO, s::String) = for c in s write(io, c) end
show(io::IO, s::String) = print_quoted(io, s)
sizeof(s::String) = error("type $(typeof(s)) has no canonical binary representation")
(*)(s::String...) = string(s...)
(^)(s::String, r::Integer) = repeat(s,r)
length(s::DirectIndexString) = endof(s)
function length(s::String)
i = start(s)
if done(s,i)
return 0
end
n = 1
while true
c, j = next(s,i)
if done(s,j)
return n
end
n += 1
i = j
end
end
isvalid(s::DirectIndexString, i::Integer) = (start(s) <= i <= endof(s))
function isvalid(s::String, i::Integer)
try
next(s,i)
true
catch
false
end
end
prevind(s::DirectIndexString, i::Integer) = i-1
prevind(s , i::Integer) = i-1
thisind(s::DirectIndexString, i::Integer) = i
thisind(s , i::Integer) = i
nextind(s::DirectIndexString, i::Integer) = i+1
nextind(s , i::Integer) = i+1
prevind(s::String, i::Integer) = thisind(s,thisind(s,i)-1)
function thisind(s::String, i::Integer)
for j = i:-1:1
if isvalid(s,j)
return j
end
end
return 0 # out of range
end
function nextind(s::String, i::Integer)
for j = i+1:endof(s)
if isvalid(s,j)
return j
end
end
endof(s)+1 # out of range
end
ind2chr(s::DirectIndexString, i::Integer) = i
chr2ind(s::DirectIndexString, i::Integer) = i
function ind2chr(s::String, i::Integer)
s[i] # throws error if invalid
j = 1
k = start(s)
while true
c, l = next(s,k)
if i <= k
return j
end
j += 1
k = l
end
end
function chr2ind(s::String, i::Integer)
if i < 1
return i
end
j = 1
k = start(s)
while true
c, l = next(s,k)
if i == j
return k
end
j += 1
k = l
end
end
typealias Chars Union(Char,AbstractVector{Char},Set{Char})
function search(s::String, c::Chars, i::Integer)
if isempty(c)
return 1 <= i <= endof(s)+1 ? i :
i == endof(s)+2 ? 0 :
error(BoundsError)
end
if i < 1 error(BoundsError) end
i = nextind(s,i-1)
while !done(s,i)
d, j = next(s,i)
if contains(c,d)
return i
end
i = j
end
return 0
end
search(s::String, c::Chars) = search(s,c,start(s))
contains(s::String, c::Char) = (search(s,c)!=0)
function _search(s, t, i)
if isempty(t)
return 1 <= i <= endof(s)+1 ? (i:i-1) :
i == endof(s)+2 ? (0:-1) :
error(BoundsError)
end
t1, j2 = next(t,start(t))
while true
i = search(s,t1,i)
if i == 0 return (0:-1) end
c, ii = next(s,i)
j = j2; k = ii
matched = true
while !done(t,j)
if done(s,k)
matched = false
break
end
c, k = next(s,k)
d, j = next(t,j)
if c != d
matched = false
break
end
end
if matched
return i:k-1
end
i = ii
end
end
search(s::Union(Array{Uint8,1},Array{Int8,1}),t::Union(Array{Uint8,1},Array{Int8,1}),i) = _search(s,t,i)
search(s::String, t::String, i::Integer) = _search(s,t,i)
search(s::String, t::String) = search(s,t,start(s))
rsearch(s::String, c::Chars) = rsearch(s,c,endof(s))
function _rsearch(s, t, i)
if isempty(t)
return 1 <= i <= endof(s)+1 ? (i:i-1) :
i == endof(s)+2 ? (0:-1) :
error(BoundsError)
end
t = reverse(t)
rs = reverse(s)
l = endof(s)
t1, j2 = next(t,start(t))
while true
i = rsearch(s,t1,i)
if i == 0 return (0:-1) end
c, ii = next(rs,l-i+1)
j = j2; k = ii
matched = true
while !done(t,j)
if done(rs,k)
matched = false
break
end
c, k = next(rs,k)
d, j = next(t,j)
if c != d
matched = false
break
end
end
if matched
fst = nextind(s,l-k+1)
# NOTE: there's a subtle difference between
# nexind(s,i) and next(s,i)[2] if s::UTF8String
# since at the end nextind returns endof(s)+1
# while next returns length(s.data)+1
lst = next(s,i)[2]-1
return fst:lst
end
i = l-ii+1
end
end
rsearch(s::Union(Array{Uint8,1},Array{Int8,1}),t::Union(Array{Uint8,1},Array{Int8,1}),i) = _rsearch(s,t,i)
rsearch(s::String, t::String, i::Integer) = _rsearch(s,t,i)
rsearch(s::String, t::String) = (isempty(s) && isempty(t)) ? (1:0) : rsearch(s,t,endof(s))
contains(::String, ::String) = error("use search() to look for substrings")
function cmp(a::String, b::String)
if a === b
return 0
end
i = start(a)
j = start(b)
while !done(a,i) && !done(b,i)
c, i = next(a,i)
d, j = next(b,j)
if c != d
return c < d ? -1 : +1
end
end
done(a,i) && !done(b,j) ? -1 :
!done(a,i) && done(b,j) ? +1 : 0
end
isequal(a::String, b::String) = cmp(a,b) == 0
isless(a::String, b::String) = cmp(a,b) < 0
hash(s::String) = hash(bytestring(s))
# begins with and ends with predicates
function beginswith(a::String, b::String)
i = start(a)
j = start(b)
while !done(a,i) && !done(b,i)
c, i = next(a,i)
d, j = next(b,j)
if c != d return false end
end
done(b,i)
end
beginswith(a::String, c::Char) = !isempty(a) && a[start(a)] == c
function endswith(a::String, b::String)
i = endof(a)
j = endof(b)
a1 = start(a)
b1 = start(b)
while a1 <= i && b1 <= j
c = a[i]
d = b[j]
if c != d return false end
i = prevind(a,i)
j = prevind(b,j)
end
j < b1
end
endswith(a::String, c::Char) = !isempty(a) && a[end] == c
# faster comparisons for byte strings
cmp(a::ByteString, b::ByteString) = cmp(a.data, b.data)
isequal(a::ByteString, b::ByteString) = endof(a)==endof(b) && cmp(a,b)==0
beginswith(a::ByteString, b::ByteString) = beginswith(a.data, b.data)
beginswith(a::Array{Uint8,1}, b::Array{Uint8,1}) =
(length(a) >= length(b) && ccall(:strncmp, Int32, (Ptr{Uint8}, Ptr{Uint8}, Uint), a, b, length(b)) == 0)
cmp(a::Symbol, b::Symbol) =
int(sign(ccall(:strcmp, Int32, (Ptr{Uint8}, Ptr{Uint8}), a, b)))
isless(a::Symbol, b::Symbol) = cmp(a,b)<0
# TODO: fast endswith
## character column width function ##
charwidth(c::Char) = max(0,int(ccall(:wcwidth, Int32, (Uint32,), c)))
strwidth(s::String) = (w=0; for c in s; w += charwidth(c); end; w)
strwidth(s::ByteString) = int(ccall(:u8_strwidth, Csize_t, (Ptr{Uint8},), s.data))
# TODO: implement and use u8_strnwidth that takes a length argument
## libc character class predicates ##
isascii(c::Char) = c < 0x80
for name = ("alnum", "alpha", "cntrl", "digit", "graph",
"lower", "print", "punct", "space", "upper")
f = symbol(string("is",name))
@eval ($f)(c::Char) = bool(ccall($(string("isw",name)), Int32, (Cwchar_t,), c))
end
isblank(c::Char) = c==' ' || c=='\t'
## generic string uses only endof and next ##
immutable GenericString <: String
string::String
end
endof(s::GenericString) = endof(s.string)
next(s::GenericString, i::Int) = next(s.string, i)
## plain old character arrays ##
immutable CharString <: DirectIndexString
chars::Array{Char,1}
CharString(a::Array{Char,1}) = new(a)
CharString(c::Char...) = new([ c[i] for i=1:length(c) ])
end
CharString(x...) = CharString(map(char,x)...)
next(s::CharString, i::Int) = (s.chars[i], i+1)
endof(s::CharString) = length(s.chars)
length(s::CharString) = length(s.chars)
convert(::Type{CharString}, s::String) = CharString(Char[c for c in s])
## substrings reference original strings ##
immutable SubString{T<:String} <: String
string::T
offset::Int
endof::Int
function SubString(s::T, i::Int, j::Int)
if i > endof(s)
return new(s, i, 0)
else
o = thisind(s,i)-1
new(s, o, max(0, thisind(s,j)-o))
end
end
end
SubString{T<:String}(s::T, i::Int, j::Int) = SubString{T}(s, i, j)
SubString(s::SubString, i::Int, j::Int) = SubString(s.string, s.offset+i, s.offset+j)
SubString(s::String, i::Integer, j::Integer) = SubString(s, int(i), int(j))
SubString(s::String, i::Integer) = SubString(s, i, endof(s))
write{T<:ByteString}(to::IOBuffer, s::SubString{T}) =
s.endof==0 ? 0 : write_sub(to, s.string.data, s.offset+1, next(s,s.endof)[2]-1)
print(io::IOBuffer, s::SubString) = write(io, s)
sizeof{T<:ByteString}(s::SubString{T}) = s.endof==0 ? 0 : next(s,s.endof)[2]-1
function next(s::SubString, i::Int)
if i < 1 || i > s.endof
error(BoundsError)
end
c, i = next(s.string, i+s.offset)
c, i-s.offset
end
getindex(s::SubString, i::Int) = getindex(s.string, i+s.offset)
endof(s::SubString) = s.endof
# TODO: length(s::SubString) = ??
# default implementation will work but it's slow
# can this be delegated efficiently somehow?
# that may require additional string interfaces
thisind(s::SubString, i::Integer) = thisind(s.string, i+s.offset)-s.offset
nextind(s::SubString, i::Integer) = nextind(s.string, i+s.offset)-s.offset
convert{T<:String}(::Type{SubString{T}}, s::T) = SubString(s, 1, endof(s))
function serialize{T}(s, ss::SubString{T})
# avoid saving a copy of the parent string, keeping the type of ss
invoke(serialize, (Any,Any), s, convert(SubString{T}, convert(T,ss)))
end
function getindex(s::String, r::Range1{Int})
if first(r) < 1 || endof(s) < last(r)
error(BoundsError)
end
SubString(s, first(r), last(r))
end
## efficient representation of repeated strings ##
immutable RepString <: String
string::String
repeat::Integer
end
endof(s::RepString) = endof(s.string)*s.repeat
length(s::RepString) = length(s.string)*s.repeat
sizeof(s::RepString) = sizeof(s.string)*s.repeat
function next(s::RepString, i::Int)
if i < 1 || i > endof(s)
error(BoundsError)
end
j = mod1(i,length(s.string))
c, k = next(s.string, j)
c, k-j+i
end
function repeat(s::String, r::Integer)
r < 0 ? error("can't repeat a string ",r," times") :
r == 0 ? "" :
r == 1 ? s :
RepString(s,r)
end
convert(::Type{RepString}, s::String) = RepString(s,1)
function repeat(s::ByteString, r::Integer)
if r < 0
error("can't repeat a string ",r," times")
end
d = s.data; n = length(d)
out = Array(Uint8, n*r)
for i=1:r
copy!(out, 1+(i-1)*n, d, 1, n)
end
convert(typeof(s), out)
end
## reversed strings without data movement ##
immutable RevString <: String
string::String
end
endof(s::RevString) = endof(s.string)
length(s::RevString) = length(s.string)
sizeof(s::RevString) = sizeof(s.string)
function next(s::RevString, i::Int)
n = endof(s); j = n-i+1
(s.string[j], n-thisind(s.string,j-1)+1)
end
reverse(s::String) = RevString(s)
reverse(s::RevString) = s.string
## ropes for efficient concatenation, etc. ##
immutable RopeString <: String
head::String
tail::String
depth::Int32
endof::Int
RopeString(h::RopeString, t::RopeString) =
strdepth(h.tail) + strdepth(t) < strdepth(h.head) ?
RopeString(h.head, RopeString(h.tail, t)) :
new(h, t, max(h.depth,t.depth)+1, endof(h)+endof(t))
RopeString(h::RopeString, t::String) =
strdepth(h.tail) < strdepth(h.head) ?
RopeString(h.head, RopeString(h.tail, t)) :
new(h, t, h.depth+1, endof(h)+endof(t))
RopeString(h::String, t::RopeString) =
strdepth(t.head) < strdepth(t.tail) ?
RopeString(RopeString(h, t.head), t.tail) :
new(h, t, t.depth+1, endof(h)+endof(t))
RopeString(h::String, t::String) =
new(h, t, 1, endof(h)+endof(t))
end
RopeString(s::String) = RopeString(s,"")
strdepth(s::String) = 0
strdepth(s::RopeString) = s.depth
function next(s::RopeString, i::Int)
eh = endof(s.head)
if i <= eh
return next(s.head, i)
else
c, j = next(s.tail, i-eh)
return c, j+eh
end
end
endof(s::RopeString) = s.endof
length(s::RopeString) = length(s.head) + length(s.tail)
print(io::IO, s::RopeString) = print(io, s.head, s.tail)
write(io::IO, s::RopeString) = (write(io, s.head); write(io, s.tail))
sizeof(s::RopeString) = sizeof(s.head) + sizeof(s.tail)
## uppercase and lowercase transformations ##
uppercase(c::Char) = convert(Char, ccall(:towupper, Cwchar_t, (Cwchar_t,), c))
lowercase(c::Char) = convert(Char, ccall(:towlower, Cwchar_t, (Cwchar_t,), c))
uppercase(s::String) = map(uppercase, s)
lowercase(s::String) = map(lowercase, s)
ucfirst(s::String) = isupper(s[1]) ? s : string(uppercase(s[1]),s[nextind(s,1):end])
lcfirst(s::String) = islower(s[1]) ? s : string(lowercase(s[1]),s[nextind(s,1):end])
## string map, filter, has ##
function map(f::Function, s::String)
out = IOBuffer(Array(Uint8,endof(s)),true,true)
truncate(out,0)
for c in s
c2 = f(c)
if !isa(c2,Char)
error("map(f,s::String) requires f to return Char. Try map(f,collect(s)) or a comprehension instead.")
end
write(out, c2::Char)
end
takebuf_string(out)
end
function filter(f::Function, s::String)
out = IOBuffer(Array(Uint8,endof(s)),true,true)
truncate(out,0)
for c in s
if f(c)
write(out, c)
end
end
takebuf_string(out)
end
## string promotion rules ##
promote_rule(::Type{UTF8String} , ::Type{ASCIIString}) = UTF8String
promote_rule(::Type{UTF8String} , ::Type{CharString} ) = UTF8String
promote_rule(::Type{ASCIIString}, ::Type{CharString} ) = UTF8String
promote_rule{T<:String}(::Type{RepString}, ::Type{T}) = RepString
## printing literal quoted string data ##
# TODO: this is really the inverse of print_unbackslashed
function print_quoted_literal(io, s::String)
print(io, '"')
for c = s; c == '"' ? print(io, "\\\"") : print(io, c); end
print(io, '"')
end
## string escaping & unescaping ##
escape_nul(s::String, i::Int) =
!done(s,i) && '0' <= next(s,i)[1] <= '7' ? "\\x00" : "\\0"
isxdigit(c::Char) = '0'<=c<='9' || 'a'<=c<='f' || 'A'<=c<='F'
need_full_hex(s::String, i::Int) = !done(s,i) && isxdigit(next(s,i)[1])
function print_escaped(io, s::String, esc::String)
i = start(s)
while !done(s,i)
c, j = next(s,i)
c == '\0' ? print(io, escape_nul(s,j)) :
c == '\e' ? print(io, "\\e") :
c == '\\' ? print(io, "\\\\") :
contains(esc,c) ? print(io, '\\', c) :
7 <= c <= 13 ? print(io, '\\', "abtnvfr"[int(c-6)]) :
isprint(c) ? print(io, c) :
c <= '\x7f' ? print(io, "\\x", hex(c, 2)) :
c <= '\uffff' ? print(io, "\\u", hex(c, need_full_hex(s,j) ? 4 : 2)) :
print(io, "\\U", hex(c, need_full_hex(s,j) ? 8 : 4))
i = j
end
end
escape_string(s::String) = sprint(endof(s), print_escaped, s, "\"")
function print_quoted(io, s::String)
print(io, '"')
print_escaped(io, s, "\"\$") #"# work around syntax highlighting problem
print(io, '"')
end
# bare minimum unescaping function unescapes only given characters
function print_unescaped_chars(io, s::String, esc::String)
if !contains(esc,'\\')
esc = string("\\", esc)
end
i = start(s)
while !done(s,i)
c, i = next(s,i)
if c == '\\' && !done(s,i) && contains(esc,s[i])
c, i = next(s,i)
end
print(io, c)
end
end
unescape_chars(s::String, esc::String) =
sprint(endof(s), print_unescaped_chars, s, esc)
# general unescaping of traditional C and Unicode escape sequences
function print_unescaped(io, s::String)
i = start(s)
while !done(s,i)
c, i = next(s,i)
if !done(s,i) && c == '\\'
c, i = next(s,i)
if c == 'x' || c == 'u' || c == 'U'
n = k = 0
m = c == 'x' ? 2 :
c == 'u' ? 4 : 8
while (k+=1) <= m && !done(s,i)
c, j = next(s,i)
n = '0' <= c <= '9' ? n<<4 + c-'0' :
'a' <= c <= 'f' ? n<<4 + c-'a'+10 :
'A' <= c <= 'F' ? n<<4 + c-'A'+10 : break
i = j
end
if k == 1
error("\\x used with no following hex digits")
end
if m == 2 # \x escape sequence
write(io, uint8(n))
else
print(io, char(n))
end
elseif '0' <= c <= '7'
k = 1
n = c-'0'
while (k+=1) <= 3 && !done(s,i)
c, j = next(s,i)
n = ('0' <= c <= '7') ? n<<3 + c-'0' : break
i = j
end
if n > 255
error("octal escape sequence out of range")
end
write(io, uint8(n))
else
print(io, c == 'a' ? '\a' :
c == 'b' ? '\b' :
c == 't' ? '\t' :
c == 'n' ? '\n' :
c == 'v' ? '\v' :
c == 'f' ? '\f' :
c == 'r' ? '\r' :
c == 'e' ? '\e' : c)
end
else
print(io, c)
end
end
end
unescape_string(s::String) = sprint(endof(s), print_unescaped, s)
## checking UTF-8 & ACSII validity ##
byte_string_classify(data::Array{Uint8,1}) =
ccall(:u8_isvalid, Int32, (Ptr{Uint8}, Int), data, length(data))
byte_string_classify(s::ByteString) = byte_string_classify(s.data)
# 0: neither valid ASCII nor UTF-8
# 1: valid ASCII
# 2: valid UTF-8
is_valid_ascii(s::Union(Array{Uint8,1},ByteString)) = byte_string_classify(s) == 1
is_valid_utf8 (s::Union(Array{Uint8,1},ByteString)) = byte_string_classify(s) != 0
## multiline strings ##
function blank_width(c::Char)
c == ' ' ? 1 :
c == '\t' ? 8 :
error("not a blank character")
end
# width of leading blank space, also check if string is blank
function indentation(s::String)
count = 0
for c in s
if isblank(c)
count += blank_width(c)
else
return count, false
end
end
count, true
end
function unindent(s::String, indent::Int)
buf = IOBuffer(Array(Uint8,endof(s)), true, true)
truncate(buf,0)
a = i = start(s)
cutting = false
cut = 0
while !done(s,i)
c,i_ = next(s,i)
if cutting && isblank(c)
a = i_
cut += blank_width(c)
if cut > indent
cutting = false
for _ = (indent+1):cut write(buf, ' ') end
end
elseif c == '\n'
print(buf, s[a:i])
a = i_
cutting = true
cut = 0
else
cutting = false
end
i = i_
end
print(buf, s[a:end])
takebuf_string(buf)
end
function triplequoted(args...)
sx = { isa(arg,ByteString) ? arg : esc(arg) for arg in args }
indent = 0
rlines = split(reverse(sx[end]), '\n', 2)
last_line = rlines[1]
if length(rlines) > 1 && lstrip(last_line) == ""
indent,_ = indentation(last_line)
else
indent = typemax(Int)
for s in sx
if isa(s,ByteString)
lines = split(s,'\n')
for line in lines[2:end]
n,blank = indentation(line)
if !blank
indent = min(indent, n)
end
end
end
end
end
for i in 1:length(sx)
if isa(sx[i],ByteString)
sx[i] = unindent(sx[i], indent)
end
end
# strip leading blank line
s = sx[1]
j = search(s,'\n')
if j != 0 && lstrip(s[1:j]) == ""
sx[1] = s[j+1:end]
end
length(sx) == 1 ? sx[1] : Expr(:call, :string, sx...)
end
## core string macros ##
macro b_str(s); :($(unescape_string(s)).data); end
macro mstr(s...); triplequoted(s...); end
## shell-like command parsing ##
function shell_parse(raw::String, interp::Bool)
s = strip(raw)
isempty(s) && return interp ? Expr(:tuple,:()) : {}
in_single_quotes = false
in_double_quotes = false
args = {}
arg = {}
i = start(s)
j = i
function update_arg(x)
if !isa(x,String) || !isempty(x)
push!(arg, x)
end
end
function append_arg()
if isempty(arg); arg = {"",}; end
push!(args, arg)
arg = {}
end
while !done(s,j)
c, k = next(s,j)
if !in_single_quotes && !in_double_quotes && isspace(c)
update_arg(s[i:j-1])
append_arg()
j = k
while !done(s,j)
c, k = next(s,j)
if !isspace(c)
i = j
break
end
j = k
end
elseif interp && !in_single_quotes && c == '$'
update_arg(s[i:j-1]); i = k; j = k
if done(s,k)
error("\$ right before end of command")
end
if isspace(s[k])
error("space not allowed right after \$")
end
ex, j = parse(s,j,false)
update_arg(esc(ex)); i = j
else
if !in_double_quotes && c == '\''
in_single_quotes = !in_single_quotes
update_arg(s[i:j-1]); i = k
elseif !in_single_quotes && c == '"'
in_double_quotes = !in_double_quotes
update_arg(s[i:j-1]); i = k
elseif c == '\\'
if in_double_quotes
if done(s,k)
error("unterminated double quote")
end
if s[k] == '"' || s[k] == '$'
update_arg(s[i:j-1]); i = k
c, k = next(s,k)
end
elseif !in_single_quotes
if done(s,k)
error("dangling backslash")
end
update_arg(s[i:j-1]); i = k
c, k = next(s,k)
end
end
j = k
end
end
if in_single_quotes; error("unterminated single quote"); end
if in_double_quotes; error("unterminated double quote"); end
update_arg(s[i:])
append_arg()
if !interp
return args
end
# construct an expression
ex = Expr(:tuple)
for arg in args
push!(ex.args, Expr(:tuple, arg...))
end
ex
end
shell_parse(s::String) = shell_parse(s,true)
function shell_split(s::String)
parsed = shell_parse(s,false)
args = String[]
for arg in parsed
push!(args, string(arg...))
end
args
end
function print_shell_word(io::IO, word::String)
if isempty(word)
print(io, "''")
end
has_single = false
has_special = false
for c in word
if isspace(c) || c=='\\' || c=='\'' || c=='"' || c=='$'
has_special = true
if c == '\''
has_single = true
end
end
end
if !has_special
print(io, word)
elseif !has_single
print(io, '\'', word, '\'')
else
print(io, '"')
for c in word
if c == '"' || c == '$'
print(io, '\\')
end
print(io, c)
end
print(io, '"')
end
end
function print_shell_escaped(io::IO, cmd::String, args::String...)
print_shell_word(io, cmd)
for arg in args
print(io, ' ')
print_shell_word(io, arg)
end
end
print_shell_escaped(io::IO) = nothing
shell_escape(args::String...) = sprint(print_shell_escaped, args...)
## interface to parser ##
function parse(str::String, pos::Int, greedy::Bool=true, err::Bool=true)
# returns (expr, end_pos). expr is () in case of parse error.
ex, pos = ccall(:jl_parse_string, Any,
(Ptr{Uint8}, Int32, Int32),
str, pos-1, greedy ? 1:0)
if err && isa(ex,Expr) && is(ex.head,:error)
throw(ParseError(ex.args[1]))
end
if ex == ()
if err
throw(ParseError("end of input"))
else
ex = Expr(:error, "end of input")
end
end
ex, pos+1 # C is zero-based, Julia is 1-based
end
function parse(str::String)
ex, pos = parse(str, start(str))
done(str, pos) || error("syntax: extra token after end of expression")
return ex
end
## miscellaneous string functions ##
function lpad(s::String, n::Integer, p::String)
m = n - length(s)
if m <= 0; return s; end
l = length(p)
if l==1
return bytestring(p^m * s)
end
q = div(m,l)
r = m - q*l