b34e04317b80c1f6ffca0c7b21b409ba86b88c08
[nit.git] / lib / standard / string.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
5 #
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
12 # another product.
13
14 # Basic manipulations of strings of characters
15 module string
16
17 import math
18 intrude import collection # FIXME should be collection::array
19
20 `{
21 #include <stdio.h>
22 `}
23
24 ###############################################################################
25 # String #
26 ###############################################################################
27
28 # High-level abstraction for all text representations
29 abstract class Text
30 super Comparable
31 super StringCapable
32
33 redef type OTHER: Text
34
35 # Type of the view on self (.chars)
36 type SELFVIEW: StringCharView
37
38 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
39 type SELFTYPE: Text
40
41 var hash_cache: nullable Int = null
42
43 # Gets a view on the chars of the Text object
44 fun chars: SELFVIEW is abstract
45
46 # Number of characters contained in self.
47 fun length: Int is abstract
48
49 # Create a substring.
50 #
51 # assert "abcd".substring(1, 2) == "bc"
52 # assert "abcd".substring(-1, 2) == "a"
53 # assert "abcd".substring(1, 0) == ""
54 # assert "abcd".substring(2, 5) == "cd"
55 #
56 # A `from` index < 0 will be replaced by 0.
57 # Unless a `count` value is > 0 at the same time.
58 # In this case, `from += count` and `count -= from`.
59 fun substring(from: Int, count: Int): SELFTYPE is abstract
60
61 # Concatenates `o` to `self`
62 fun +(o: Text): SELFTYPE is abstract
63
64 # Auto-concatenates self `i` times
65 fun *(i: Int): SELFTYPE is abstract
66
67 # Is the current Text empty (== "")
68 # assert "".is_empty
69 # assert not "foo".is_empty
70 fun is_empty: Bool do return self.length == 0
71
72 # Returns an empty Text of the right type
73 fun empty: SELFTYPE is abstract
74
75 # Gets the first char of the Text
76 #
77 # DEPRECATED : Use self.chars.first instead
78 fun first: Char do return self.chars[0]
79
80 # Access a character at `index` in the string.
81 #
82 # assert "abcd"[2] == 'c'
83 #
84 # DEPRECATED : Use self.chars.[] instead
85 fun [](index: Int): Char do return self.chars[index]
86
87 # Gets the index of the first occurence of 'c'
88 #
89 # Returns -1 if not found
90 #
91 # DEPRECATED : Use self.chars.index_of instead
92 fun index_of(c: Char): Int
93 do
94 return index_of_from(c, 0)
95 end
96
97 # Gets the last char of self
98 #
99 # DEPRECATED : Use self.chars.last instead
100 fun last: Char do return self.chars[length-1]
101
102 # Gets the index of the first occurence of ´c´ starting from ´pos´
103 #
104 # Returns -1 if not found
105 #
106 # DEPRECATED : Use self.chars.index_of_from instead
107 fun index_of_from(c: Char, pos: Int): Int
108 do
109 var iter = self.chars.iterator_from(pos)
110 while iter.is_ok do
111 if iter.item == c then return iter.index
112 end
113 return -1
114 end
115
116 # Gets the last index of char ´c´
117 #
118 # Returns -1 if not found
119 #
120 # DEPRECATED : Use self.chars.last_index_of instead
121 fun last_index_of(c: Char): Int
122 do
123 return last_index_of_from(c, length - 1)
124 end
125
126 # Return a null terminated char *
127 fun to_cstring: NativeString do return flatten.to_cstring
128
129 # The index of the last occurrence of an element starting from pos (in reverse order).
130 # Example :
131 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
132 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
133 #
134 # Returns -1 if not found
135 #
136 # DEPRECATED : Use self.chars.last_index_of_from instead
137 fun last_index_of_from(item: Char, pos: Int): Int
138 do
139 var iter = self.chars.reverse_iterator_from(pos)
140 while iter.is_ok do
141 if iter.item == item then return iter.index
142 iter.next
143 end
144 return -1
145 end
146
147 # Gets an iterator on the chars of self
148 #
149 # DEPRECATED : Use self.chars.iterator instead
150 fun iterator: Iterator[Char]
151 do
152 return self.chars.iterator
153 end
154
155 # Is 'c' contained in self ?
156 #
157 # DEPRECATED : Use self.chars.has instead
158 fun has(c: Char): Bool
159 do
160 return self.chars.has(c)
161 end
162
163 # Gets an Array containing the chars of self
164 #
165 # DEPRECATED : Use self.chars.to_a instead
166 fun to_a: Array[Char] do return chars.to_a
167
168 # Create a substring from `self` beginning at the `from` position
169 #
170 # assert "abcd".substring_from(1) == "bcd"
171 # assert "abcd".substring_from(-1) == "abcd"
172 # assert "abcd".substring_from(2) == "cd"
173 #
174 # As with substring, a `from` index < 0 will be replaced by 0
175 fun substring_from(from: Int): SELFTYPE
176 do
177 if from > self.length then return empty
178 if from < 0 then from = 0
179 return substring(from, length - from)
180 end
181
182 # Returns a reversed version of self
183 fun reversed: SELFTYPE is abstract
184
185 # Does self have a substring `str` starting from position `pos`?
186 #
187 # assert "abcd".has_substring("bc",1) == true
188 # assert "abcd".has_substring("bc",2) == false
189 fun has_substring(str: String, pos: Int): Bool
190 do
191 var myiter = self.chars.iterator_from(pos)
192 var itsiter = str.iterator
193 while myiter.is_ok and itsiter.is_ok do
194 if myiter.item != itsiter.item then return false
195 myiter.next
196 itsiter.next
197 end
198 if itsiter.is_ok then return false
199 return true
200 end
201
202 # Is this string prefixed by `prefix`?
203 #
204 # assert "abcd".has_prefix("ab") == true
205 # assert "abcbc".has_prefix("bc") == false
206 # assert "ab".has_prefix("abcd") == false
207 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
208
209 # Is this string suffixed by `suffix`?
210 #
211 # assert "abcd".has_suffix("abc") == false
212 # assert "abcd".has_suffix("bcd") == true
213 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
214
215 # If `self` contains only digits, return the corresponding integer
216 #
217 # assert "123".to_i == 123
218 # assert "-1".to_i == -1
219 fun to_i: Int
220 do
221 # Shortcut
222 return to_s.to_cstring.atoi
223 end
224
225 # If `self` contains a float, return the corresponding float
226 #
227 # assert "123".to_f == 123.0
228 # assert "-1".to_f == -1.0
229 # assert "-1.2e-3".to_f == -0.0012
230 fun to_f: Float
231 do
232 # Shortcut
233 return to_s.to_cstring.atof
234 end
235
236 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
237 fun to_hex: Int do return a_to(16)
238
239 # If `self` contains only digits and letters, return the corresponding integer in a given base
240 #
241 # assert "120".a_to(3) == 15
242 fun a_to(base: Int) : Int
243 do
244 var i = 0
245 var neg = false
246
247 for c in self.chars
248 do
249 var v = c.to_i
250 if v > base then
251 if neg then
252 return -i
253 else
254 return i
255 end
256 else if v < 0 then
257 neg = true
258 else
259 i = i * base + v
260 end
261 end
262 if neg then
263 return -i
264 else
265 return i
266 end
267 end
268
269 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
270 #
271 # assert "123".is_numeric == true
272 # assert "1.2".is_numeric == true
273 # assert "1,2".is_numeric == true
274 # assert "1..2".is_numeric == false
275 fun is_numeric: Bool
276 do
277 var has_point_or_comma = false
278 for i in self.chars
279 do
280 if not i.is_numeric
281 then
282 if (i == '.' or i == ',') and not has_point_or_comma
283 then
284 has_point_or_comma = true
285 else
286 return false
287 end
288 end
289 end
290 return true
291 end
292
293 # A upper case version of `self`
294 #
295 # assert "Hello World!".to_upper == "HELLO WORLD!"
296 fun to_upper: SELFTYPE is abstract
297
298 # A lower case version of `self`
299 #
300 # assert "Hello World!".to_lower == "hello world!"
301 fun to_lower : SELFTYPE is abstract
302
303 # Removes the whitespaces at the beginning of self
304 fun l_trim: SELFTYPE
305 do
306 var iter = self.chars.iterator
307 while iter.is_ok do
308 if iter.item.ascii > 32 then break
309 iter.next
310 end
311 if iter.index == length then return self.empty
312 return self.substring_from(iter.index)
313 end
314
315 # Removes the whitespaces at the end of self
316 fun r_trim: SELFTYPE
317 do
318 var iter = self.chars.reverse_iterator
319 while iter.is_ok do
320 if iter.item.ascii > 32 then break
321 iter.next
322 end
323 if iter.index == length then return self.empty
324 return self.substring(0, iter.index + 1)
325 end
326
327 # Trims trailing and preceding white spaces
328 # A whitespace is defined as any character which ascii value is less than or equal to 32
329 #
330 # assert " Hello World ! ".trim == "Hello World !"
331 # assert "\na\nb\tc\t".trim == "a\nb\tc"
332 fun trim: SELFTYPE do return (self.l_trim).r_trim
333
334 # Mangle a string to be a unique string only made of alphanumeric characters
335 fun to_cmangle: String
336 do
337 var res = new FlatBuffer
338 var underscore = false
339 for c in self.chars do
340 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
341 res.add(c)
342 underscore = false
343 continue
344 end
345 if underscore then
346 res.append('_'.ascii.to_s)
347 res.add('d')
348 end
349 if c >= '0' and c <= '9' then
350 res.add(c)
351 underscore = false
352 else if c == '_' then
353 res.add(c)
354 underscore = true
355 else
356 res.add('_')
357 res.append(c.ascii.to_s)
358 res.add('d')
359 underscore = false
360 end
361 end
362 return res.to_s
363 end
364
365 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
366 #
367 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
368 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
369 fun escape_to_c: String
370 do
371 var b = new FlatBuffer
372 for c in self.chars do
373 if c == '\n' then
374 b.append("\\n")
375 else if c == '\0' then
376 b.append("\\0")
377 else if c == '"' then
378 b.append("\\\"")
379 else if c == '\'' then
380 b.append("\\\'")
381 else if c == '\\' then
382 b.append("\\\\")
383 else if c.ascii < 32 then
384 b.append("\\{c.ascii.to_base(8, false)}")
385 else
386 b.add(c)
387 end
388 end
389 return b.to_s
390 end
391
392 # Escape additionnal characters
393 # The result might no be legal in C but be used in other languages
394 #
395 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
396 fun escape_more_to_c(chars: String): String
397 do
398 var b = new FlatBuffer
399 for c in escape_to_c do
400 if chars.chars.has(c) then
401 b.add('\\')
402 end
403 b.add(c)
404 end
405 return b.to_s
406 end
407
408 # Escape to c plus braces
409 #
410 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
411 fun escape_to_nit: String do return escape_more_to_c("\{\}")
412
413 # Return a string where Nit escape sequences are transformed.
414 #
415 # Example:
416 # var s = "\\n"
417 # assert s.length == 2
418 # var u = s.unescape_nit
419 # assert u.length == 1
420 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
421 fun unescape_nit: String
422 do
423 var res = new FlatBuffer.with_capacity(self.length)
424 var was_slash = false
425 for c in self do
426 if not was_slash then
427 if c == '\\' then
428 was_slash = true
429 else
430 res.add(c)
431 end
432 continue
433 end
434 was_slash = false
435 if c == 'n' then
436 res.add('\n')
437 else if c == 'r' then
438 res.add('\r')
439 else if c == 't' then
440 res.add('\t')
441 else if c == '0' then
442 res.add('\0')
443 else
444 res.add(c)
445 end
446 end
447 return res.to_s
448 end
449
450 redef fun ==(o)
451 do
452 if o == null then return false
453 if not o isa Text then return false
454 if self.is_same_instance(o) then return true
455 if self.length != o.length then return false
456 return self.chars == o.chars
457 end
458
459 redef fun <(o)
460 do
461 return self.chars < o.chars
462 end
463
464 # Flat representation of self
465 fun flatten: FlatText is abstract
466
467 redef fun hash
468 do
469 if hash_cache == null then
470 # djb2 hash algorithm
471 var h = 5381
472 var i = length - 1
473
474 for char in self.chars do
475 h = (h * 32) + h + char.ascii
476 i -= 1
477 end
478
479 hash_cache = h
480 end
481 return hash_cache.as(not null)
482 end
483
484 end
485
486 # All kinds of array-based text representations.
487 abstract class FlatText
488 super Text
489
490 private var items: NativeString
491
492 # Real items, used as cache for to_cstring is called
493 private var real_items: nullable NativeString = null
494
495 redef var length: Int
496
497 init do end
498
499 redef fun output
500 do
501 var i = 0
502 while i < length do
503 items[i].output
504 i += 1
505 end
506 end
507
508 redef fun flatten do return self
509 end
510
511 # Abstract class for the SequenceRead compatible
512 # views on String and Buffer objects
513 abstract class StringCharView
514 super SequenceRead[Char]
515 super Comparable
516
517 type SELFTYPE: Text
518
519 redef type OTHER: StringCharView
520
521 private var target: SELFTYPE
522
523 private init(tgt: SELFTYPE)
524 do
525 target = tgt
526 end
527
528 redef fun is_empty do return target.is_empty
529
530 redef fun length do return target.length
531
532 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
533
534 # Gets a new Iterator starting at position `pos`
535 #
536 # Ex :
537 # var iter = "abcd".iterator_from(2)
538 # while iter.is_ok do
539 # printn iter.item
540 # iter.next
541 # end
542 #
543 # Outputs : cd
544 fun iterator_from(pos: Int): IndexedIterator[Char] is abstract
545
546 # Gets an iterator starting at the end and going backwards
547 #
548 # Ex :
549 # var reviter = "now step live...".reverse_iterator
550 # while reviter.is_ok do
551 # printn reviter.item
552 # reviter.next
553 # end
554 #
555 # Outputs : ...evil pets won
556 fun reverse_iterator: IndexedIterator[Char] do return self.reverse_iterator_from(self.length - 1)
557
558 # Gets an iterator on the chars of self starting from `pos`
559 #
560 # Ex :
561 # var iter = "abcd".reverse_iterator_from(1)
562 # while iter.is_ok do
563 # printn iter.item
564 # iter.next
565 # end
566 #
567 # Outputs : ba
568 fun reverse_iterator_from(pos: Int): IndexedIterator[Char] is abstract
569
570 redef fun has(c: Char): Bool
571 do
572 for i in self do
573 if i == c then return true
574 end
575 return false
576 end
577
578 redef fun ==(other)
579 do
580 if other == null then return false
581 if not other isa StringCharView then return false
582 var other_chars = other.iterator
583 for i in self do
584 if i != other_chars.item then return false
585 other_chars.next
586 end
587 return true
588 end
589
590 redef fun <(other)
591 do
592 var self_chars = self.iterator
593 var other_chars = other.iterator
594
595 while self_chars.is_ok and other_chars.is_ok do
596 if self_chars.item < other_chars.item then return true
597 if self_chars.item > other_chars.item then return false
598 self_chars.next
599 other_chars.next
600 end
601
602 if self_chars.is_ok then
603 return false
604 else
605 return true
606 end
607 end
608 end
609
610 # View on Buffer objects, extends Sequence
611 # for mutation operations
612 abstract class BufferCharView
613 super StringCharView
614 super Sequence[Char]
615
616 redef type SELFTYPE: Buffer
617
618 end
619
620 abstract class String
621 super Text
622
623 redef type SELFTYPE: String
624
625 redef fun to_s do return self
626
627 end
628
629 # Immutable strings of characters.
630 class FlatString
631 super FlatText
632 super String
633
634 redef type SELFTYPE: FlatString
635 redef type SELFVIEW: FlatStringCharView
636
637 # Index in _items of the start of the string
638 private var index_from: Int
639
640 # Indes in _items of the last item of the string
641 private var index_to: Int
642
643 redef var chars: SELFVIEW = new FlatStringCharView(self)
644
645 ################################################
646 # AbstractString specific methods #
647 ################################################
648
649 redef fun [](index) do
650 assert index >= 0
651 # Check that the index (+ index_from) is not larger than indexTo
652 # In other terms, if the index is valid
653 assert (index + index_from) <= index_to
654 return items[index + index_from]
655 end
656
657 redef fun reversed
658 do
659 var native = calloc_string(self.length + 1)
660 var reviter = chars.reverse_iterator
661 var pos = 0
662 while reviter.is_ok do
663 native[pos] = reviter.item
664 pos += 1
665 reviter.next
666 end
667 return native.to_s_with_length(self.length)
668 end
669
670 redef fun substring(from, count)
671 do
672 assert count >= 0
673
674 if from < 0 then
675 count += from
676 if count < 0 then count = 0
677 from = 0
678 end
679
680 var realFrom = index_from + from
681
682 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
683
684 if count == 0 then return empty
685
686 var to = realFrom + count - 1
687
688 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
689 end
690
691 redef fun empty do return "".as(FlatString)
692
693 redef fun to_upper
694 do
695 var outstr = calloc_string(self.length + 1)
696 var out_index = 0
697
698 var myitems = self.items
699 var index_from = self.index_from
700 var max = self.index_to
701
702 while index_from <= max do
703 outstr[out_index] = myitems[index_from].to_upper
704 out_index += 1
705 index_from += 1
706 end
707
708 outstr[self.length] = '\0'
709
710 return outstr.to_s_with_length(self.length)
711 end
712
713 redef fun to_lower
714 do
715 var outstr = calloc_string(self.length + 1)
716 var out_index = 0
717
718 var myitems = self.items
719 var index_from = self.index_from
720 var max = self.index_to
721
722 while index_from <= max do
723 outstr[out_index] = myitems[index_from].to_lower
724 out_index += 1
725 index_from += 1
726 end
727
728 outstr[self.length] = '\0'
729
730 return outstr.to_s_with_length(self.length)
731 end
732
733 redef fun output
734 do
735 var i = self.index_from
736 var imax = self.index_to
737 while i <= imax do
738 items[i].output
739 i += 1
740 end
741 end
742
743 ##################################################
744 # String Specific Methods #
745 ##################################################
746
747 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
748 do
749 self.items = items
750 length = len
751 index_from = from
752 index_to = to
753 end
754
755 # Return a null terminated char *
756 redef fun to_cstring: NativeString
757 do
758 if real_items != null then return real_items.as(not null)
759 if index_from > 0 or index_to != items.cstring_length - 1 then
760 var newItems = calloc_string(length + 1)
761 self.items.copy_to(newItems, length, index_from, 0)
762 newItems[length] = '\0'
763 self.real_items = newItems
764 return newItems
765 end
766 return items
767 end
768
769 redef fun ==(other)
770 do
771 if not other isa FlatString then return super
772
773 if self.object_id == other.object_id then return true
774
775 var my_length = length
776
777 if other.length != my_length then return false
778
779 var my_index = index_from
780 var its_index = other.index_from
781
782 var last_iteration = my_index + my_length
783
784 var itsitems = other.items
785 var myitems = self.items
786
787 while my_index < last_iteration do
788 if myitems[my_index] != itsitems[its_index] then return false
789 my_index += 1
790 its_index += 1
791 end
792
793 return true
794 end
795
796 # The comparison between two strings is done on a lexicographical basis
797 #
798 # assert ("aa" < "b") == true
799 redef fun <(other)
800 do
801 if not other isa FlatString then return super
802
803 if self.object_id == other.object_id then return false
804
805 var my_curr_char : Char
806 var its_curr_char : Char
807
808 var curr_id_self = self.index_from
809 var curr_id_other = other.index_from
810
811 var my_items = self.items
812 var its_items = other.items
813
814 var my_length = self.length
815 var its_length = other.length
816
817 var max_iterations = curr_id_self + my_length
818
819 while curr_id_self < max_iterations do
820 my_curr_char = my_items[curr_id_self]
821 its_curr_char = its_items[curr_id_other]
822
823 if my_curr_char != its_curr_char then
824 if my_curr_char < its_curr_char then return true
825 return false
826 end
827
828 curr_id_self += 1
829 curr_id_other += 1
830 end
831
832 return my_length < its_length
833 end
834
835 # The concatenation of `self` with `s`
836 #
837 # assert "hello " + "world!" == "hello world!"
838 redef fun +(s)
839 do
840 var my_length = self.length
841 var its_length = s.length
842
843 var total_length = my_length + its_length
844
845 var target_string = calloc_string(my_length + its_length + 1)
846
847 self.items.copy_to(target_string, my_length, index_from, 0)
848 if s isa FlatString then
849 s.items.copy_to(target_string, its_length, s.index_from, my_length)
850 else if s isa FlatBuffer then
851 s.items.copy_to(target_string, its_length, 0, my_length)
852 else
853 var curr_pos = my_length
854 for i in s.chars do
855 target_string[curr_pos] = i
856 curr_pos += 1
857 end
858 end
859
860 target_string[total_length] = '\0'
861
862 return target_string.to_s_with_length(total_length)
863 end
864
865 # assert "abc"*3 == "abcabcabc"
866 # assert "abc"*1 == "abc"
867 # assert "abc"*0 == ""
868 redef fun *(i)
869 do
870 assert i >= 0
871
872 var my_length = self.length
873
874 var final_length = my_length * i
875
876 var my_items = self.items
877
878 var target_string = calloc_string((final_length) + 1)
879
880 target_string[final_length] = '\0'
881
882 var current_last = 0
883
884 for iteration in [1 .. i] do
885 my_items.copy_to(target_string, my_length, 0, current_last)
886 current_last += my_length
887 end
888
889 return target_string.to_s_with_length(final_length)
890 end
891
892 redef fun hash
893 do
894 if hash_cache == null then
895 # djb2 hash algorythm
896 var h = 5381
897 var i = length - 1
898
899 var myitems = items
900 var strStart = index_from
901
902 i += strStart
903
904 while i >= strStart do
905 h = (h * 32) + h + self.items[i].ascii
906 i -= 1
907 end
908
909 hash_cache = h
910 end
911
912 return hash_cache.as(not null)
913 end
914 end
915
916 private class FlatStringReverseIterator
917 super IndexedIterator[Char]
918
919 var target: FlatString
920
921 var target_items: NativeString
922
923 var curr_pos: Int
924
925 init with_pos(tgt: FlatString, pos: Int)
926 do
927 target = tgt
928 target_items = tgt.items
929 curr_pos = pos + tgt.index_from
930 end
931
932 redef fun is_ok do return curr_pos >= 0
933
934 redef fun item do return target_items[curr_pos]
935
936 redef fun next do curr_pos -= 1
937
938 redef fun index do return curr_pos - target.index_from
939
940 end
941
942 private class FlatStringIterator
943 super IndexedIterator[Char]
944
945 var target: FlatString
946
947 var target_items: NativeString
948
949 var curr_pos: Int
950
951 init with_pos(tgt: FlatString, pos: Int)
952 do
953 target = tgt
954 target_items = tgt.items
955 curr_pos = pos + target.index_from
956 end
957
958 redef fun is_ok do return curr_pos <= target.index_to
959
960 redef fun item do return target_items[curr_pos]
961
962 redef fun next do curr_pos += 1
963
964 redef fun index do return curr_pos - target.index_from
965
966 end
967
968 private class FlatStringCharView
969 super StringCharView
970
971 redef type SELFTYPE: FlatString
972
973 redef fun [](index)
974 do
975 # Check that the index (+ index_from) is not larger than indexTo
976 # In other terms, if the index is valid
977 assert index >= 0
978 assert (index + target.index_from) <= target.index_to
979 return target.items[index + target.index_from]
980 end
981
982 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
983
984 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
985
986 end
987
988 abstract class Buffer
989 super Text
990
991 redef type SELFVIEW: BufferCharView
992 redef type SELFTYPE: Buffer
993
994 var is_dirty = true
995
996 # Modifies the char contained at pos `index`
997 #
998 # DEPRECATED : Use self.chars.[]= instead
999 fun []=(index: Int, item: Char) is abstract
1000
1001 # Adds a char `c` at the end of self
1002 #
1003 # DEPRECATED : Use self.chars.add instead
1004 fun add(c: Char) is abstract
1005
1006 # Clears the buffer
1007 fun clear is abstract
1008
1009 # Enlarges the subsequent array containing the chars of self
1010 fun enlarge(cap: Int) is abstract
1011
1012 # Adds the content of text `s` at the end of self
1013 fun append(s: Text) is abstract
1014
1015 end
1016
1017 # Mutable strings of characters.
1018 class FlatBuffer
1019 super FlatText
1020 super Buffer
1021
1022 redef type SELFVIEW: FlatBufferCharView
1023 redef type SELFTYPE: FlatBuffer
1024
1025 redef var chars: SELFVIEW = new FlatBufferCharView(self)
1026
1027 var capacity: Int
1028
1029 redef fun []=(index, item)
1030 do
1031 is_dirty = true
1032 if index == length then
1033 add(item)
1034 return
1035 end
1036 assert index >= 0 and index < length
1037 items[index] = item
1038 end
1039
1040 redef fun add(c)
1041 do
1042 is_dirty = true
1043 if capacity <= length then enlarge(length + 5)
1044 items[length] = c
1045 length += 1
1046 end
1047
1048 redef fun clear do
1049 is_dirty = true
1050 length = 0
1051 end
1052
1053 redef fun empty do return new FlatBuffer
1054
1055 redef fun enlarge(cap)
1056 do
1057 is_dirty = true
1058 var c = capacity
1059 if cap <= c then return
1060 while c <= cap do c = c * 2 + 2
1061 var a = calloc_string(c+1)
1062 items.copy_to(a, length, 0, 0)
1063 items = a
1064 capacity = c
1065 items.copy_to(a, length, 0, 0)
1066 end
1067
1068 redef fun to_s: String
1069 do
1070 return to_cstring.to_s_with_length(length)
1071 end
1072
1073 redef fun to_cstring
1074 do
1075 if is_dirty then
1076 var new_native = calloc_string(length + 1)
1077 new_native[length] = '\0'
1078 items.copy_to(new_native, length, 0, 0)
1079 real_items = new_native
1080 is_dirty = false
1081 end
1082 return real_items.as(not null)
1083 end
1084
1085 # Create a new empty string.
1086 init
1087 do
1088 with_capacity(5)
1089 end
1090
1091 init from(s: Text)
1092 do
1093 capacity = s.length + 1
1094 length = s.length
1095 items = calloc_string(capacity)
1096 if s isa FlatString then
1097 s.items.copy_to(items, length, s.index_from, 0)
1098 else if s isa FlatBuffer then
1099 s.items.copy_to(items, length, 0, 0)
1100 else
1101 var curr_pos = 0
1102 for i in s.chars do
1103 items[curr_pos] = i
1104 curr_pos += 1
1105 end
1106 end
1107 end
1108
1109 # Create a new empty string with a given capacity.
1110 init with_capacity(cap: Int)
1111 do
1112 assert cap >= 0
1113 # _items = new NativeString.calloc(cap)
1114 items = calloc_string(cap+1)
1115 capacity = cap
1116 length = 0
1117 end
1118
1119 redef fun append(s)
1120 do
1121 is_dirty = true
1122 var sl = s.length
1123 if capacity < length + sl then enlarge(length + sl)
1124 if s isa FlatString then
1125 s.items.copy_to(items, sl, s.index_from, length)
1126 else if s isa FlatBuffer then
1127 s.items.copy_to(items, sl, 0, length)
1128 else
1129 var curr_pos = self.length
1130 for i in s.chars do
1131 items[curr_pos] = i
1132 curr_pos += 1
1133 end
1134 end
1135 length += sl
1136 end
1137
1138 # Copies the content of self in `dest`
1139 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1140 do
1141 var self_chars = self.chars
1142 var dest_chars = dest.chars
1143 for i in [0..len-1] do
1144 dest_chars[new_start+i] = self_chars[start+i]
1145 end
1146 end
1147
1148 redef fun substring(from, count)
1149 do
1150 assert count >= 0
1151 count += from
1152 if from < 0 then from = 0
1153 if count > length then count = length
1154 if from < count then
1155 var r = new FlatBuffer.with_capacity(count - from)
1156 while from < count do
1157 r.chars.push(items[from])
1158 from += 1
1159 end
1160 return r
1161 else
1162 return new FlatBuffer
1163 end
1164 end
1165
1166 redef fun reversed
1167 do
1168 var new_buf = new FlatBuffer.with_capacity(self.length)
1169 var reviter = self.chars.reverse_iterator
1170 while reviter.is_ok do
1171 new_buf.add(reviter.item)
1172 reviter.next
1173 end
1174 return new_buf
1175 end
1176
1177 redef fun +(other)
1178 do
1179 var new_buf = new FlatBuffer.with_capacity(self.length + other.length)
1180 new_buf.append(self)
1181 new_buf.append(other)
1182 return new_buf
1183 end
1184
1185 redef fun *(repeats)
1186 do
1187 var new_buf = new FlatBuffer.with_capacity(self.length * repeats)
1188 for i in [0..repeats[ do
1189 new_buf.append(self)
1190 end
1191 return new_buf
1192 end
1193 end
1194
1195 private class FlatBufferReverseIterator
1196 super IndexedIterator[Char]
1197
1198 var target: FlatBuffer
1199
1200 var target_items: NativeString
1201
1202 var curr_pos: Int
1203
1204 init with_pos(tgt: FlatBuffer, pos: Int)
1205 do
1206 target = tgt
1207 target_items = tgt.items
1208 curr_pos = pos
1209 end
1210
1211 redef fun index do return curr_pos
1212
1213 redef fun is_ok do return curr_pos >= 0
1214
1215 redef fun item do return target_items[curr_pos]
1216
1217 redef fun next do curr_pos -= 1
1218
1219 end
1220
1221 private class FlatBufferCharView
1222 super BufferCharView
1223 super StringCapable
1224
1225 redef type SELFTYPE: FlatBuffer
1226
1227 redef fun [](index) do return target.items[index]
1228
1229 redef fun []=(index, item)
1230 do
1231 assert index >= 0 and index <= length
1232 if index == length then
1233 add(item)
1234 return
1235 end
1236 target.items[index] = item
1237 end
1238
1239 redef fun push(c)
1240 do
1241 target.add(c)
1242 end
1243
1244 redef fun add(c)
1245 do
1246 target.add(c)
1247 end
1248
1249 fun enlarge(cap: Int)
1250 do
1251 target.enlarge(cap)
1252 end
1253
1254 redef fun append(s)
1255 do
1256 var my_items = target.items
1257 var s_length = s.length
1258 if target.capacity < s.length then enlarge(s_length + target.length)
1259 end
1260
1261 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1262
1263 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1264
1265 end
1266
1267 private class FlatBufferIterator
1268 super IndexedIterator[Char]
1269
1270 var target: FlatBuffer
1271
1272 var target_items: NativeString
1273
1274 var curr_pos: Int
1275
1276 init with_pos(tgt: FlatBuffer, pos: Int)
1277 do
1278 target = tgt
1279 target_items = tgt.items
1280 curr_pos = pos
1281 end
1282
1283 redef fun index do return curr_pos
1284
1285 redef fun is_ok do return curr_pos < target.length
1286
1287 redef fun item do return target_items[curr_pos]
1288
1289 redef fun next do curr_pos += 1
1290
1291 end
1292
1293 ###############################################################################
1294 # Refinement #
1295 ###############################################################################
1296
1297 redef class Object
1298 # User readable representation of `self`.
1299 fun to_s: String do return inspect
1300
1301 # The class name of the object in NativeString format.
1302 private fun native_class_name: NativeString is intern
1303
1304 # The class name of the object.
1305 #
1306 # assert 5.class_name == "Int"
1307 fun class_name: String do return native_class_name.to_s
1308
1309 # Developer readable representation of `self`.
1310 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1311 fun inspect: String
1312 do
1313 return "<{inspect_head}>"
1314 end
1315
1316 # Return "CLASSNAME:#OBJECTID".
1317 # This function is mainly used with the redefinition of the inspect method
1318 protected fun inspect_head: String
1319 do
1320 return "{class_name}:#{object_id.to_hex}"
1321 end
1322
1323 protected fun args: Sequence[String]
1324 do
1325 return sys.args
1326 end
1327 end
1328
1329 redef class Bool
1330 # assert true.to_s == "true"
1331 # assert false.to_s == "false"
1332 redef fun to_s
1333 do
1334 if self then
1335 return once "true"
1336 else
1337 return once "false"
1338 end
1339 end
1340 end
1341
1342 redef class Int
1343 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1344 # assume < to_c max const of char
1345 fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1346 do
1347 var n: Int
1348 # Sign
1349 if self < 0 then
1350 n = - self
1351 s.chars[0] = '-'
1352 else if self == 0 then
1353 s.chars[0] = '0'
1354 return
1355 else
1356 n = self
1357 end
1358 # Fill digits
1359 var pos = digit_count(base) - 1
1360 while pos >= 0 and n > 0 do
1361 s.chars[pos] = (n % base).to_c
1362 n = n / base # /
1363 pos -= 1
1364 end
1365 end
1366
1367 # C function to convert an nit Int to a NativeString (char*)
1368 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1369
1370 # return displayable int in base 10 and signed
1371 #
1372 # assert 1.to_s == "1"
1373 # assert (-123).to_s == "-123"
1374 redef fun to_s do
1375 var len = digit_count(10)
1376 return native_int_to_s(len).to_s_with_length(len)
1377 end
1378
1379 # return displayable int in hexadecimal (unsigned (not now))
1380 fun to_hex: String do return to_base(16,false)
1381
1382 # return displayable int in base base and signed
1383 fun to_base(base: Int, signed: Bool): String
1384 do
1385 var l = digit_count(base)
1386 var s = new FlatBuffer.from(" " * l)
1387 fill_buffer(s, base, signed)
1388 return s.to_s
1389 end
1390 end
1391
1392 redef class Float
1393 # Pretty print self, print needoed decimals up to a max of 3.
1394 redef fun to_s do
1395 var str = to_precision( 3 )
1396 if is_inf != 0 or is_nan then return str
1397 var len = str.length
1398 for i in [0..len-1] do
1399 var j = len-1-i
1400 var c = str.chars[j]
1401 if c == '0' then
1402 continue
1403 else if c == '.' then
1404 return str.substring( 0, j+2 )
1405 else
1406 return str.substring( 0, j+1 )
1407 end
1408 end
1409 return str
1410 end
1411
1412 # `self` representation with `nb` digits after the '.'.
1413 fun to_precision(nb: Int): String
1414 do
1415 if is_nan then return "nan"
1416
1417 var isinf = self.is_inf
1418 if isinf == 1 then
1419 return "inf"
1420 else if isinf == -1 then
1421 return "-inf"
1422 end
1423
1424 if nb == 0 then return self.to_i.to_s
1425 var f = self
1426 for i in [0..nb[ do f = f * 10.0
1427 if self > 0.0 then
1428 f = f + 0.5
1429 else
1430 f = f - 0.5
1431 end
1432 var i = f.to_i
1433 if i == 0 then return "0.0"
1434 var s = i.to_s
1435 var sl = s.length
1436 if sl > nb then
1437 var p1 = s.substring(0, s.length-nb)
1438 var p2 = s.substring(s.length-nb, nb)
1439 return p1 + "." + p2
1440 else
1441 return "0." + ("0"*(nb-sl)) + s
1442 end
1443 end
1444
1445 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1446 int size;
1447 char *str;
1448
1449 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1450 str = malloc(size + 1);
1451 sprintf(str, "%.*f", (int)nb, recv );
1452
1453 return NativeString_to_s( str );
1454 `}
1455 end
1456
1457 redef class Char
1458 # assert 'x'.to_s == "x"
1459 redef fun to_s
1460 do
1461 var s = new FlatBuffer.with_capacity(1)
1462 s.chars[0] = self
1463 return s.to_s
1464 end
1465
1466 # Returns true if the char is a numerical digit
1467 fun is_numeric: Bool
1468 do
1469 if self >= '0' and self <= '9'
1470 then
1471 return true
1472 end
1473 return false
1474 end
1475
1476 # Returns true if the char is an alpha digit
1477 fun is_alpha: Bool
1478 do
1479 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1480 return false
1481 end
1482
1483 # Returns true if the char is an alpha or a numeric digit
1484 fun is_alphanumeric: Bool
1485 do
1486 if self.is_numeric or self.is_alpha then return true
1487 return false
1488 end
1489 end
1490
1491 redef class Collection[E]
1492 # Concatenate elements.
1493 redef fun to_s
1494 do
1495 var s = new FlatBuffer
1496 for e in self do if e != null then s.append(e.to_s)
1497 return s.to_s
1498 end
1499
1500 # Concatenate and separate each elements with `sep`.
1501 #
1502 # assert [1, 2, 3].join(":") == "1:2:3"
1503 # assert [1..3].join(":") == "1:2:3"
1504 fun join(sep: String): String
1505 do
1506 if is_empty then return ""
1507
1508 var s = new FlatBuffer # Result
1509
1510 # Concat first item
1511 var i = iterator
1512 var e = i.item
1513 if e != null then s.append(e.to_s)
1514
1515 # Concat other items
1516 i.next
1517 while i.is_ok do
1518 s.append(sep)
1519 e = i.item
1520 if e != null then s.append(e.to_s)
1521 i.next
1522 end
1523 return s.to_s
1524 end
1525 end
1526
1527 redef class Array[E]
1528 # Fast implementation
1529 redef fun to_s
1530 do
1531 var s = new FlatBuffer
1532 var i = 0
1533 var l = length
1534 while i < l do
1535 var e = self[i]
1536 if e != null then s.append(e.to_s)
1537 i += 1
1538 end
1539 return s.to_s
1540 end
1541 end
1542
1543 redef class Map[K,V]
1544 # Concatenate couple of 'key value'.
1545 # key and value are separated by `couple_sep`.
1546 # each couple is separated each couple with `sep`.
1547 #
1548 # var m = new ArrayMap[Int, String]
1549 # m[1] = "one"
1550 # m[10] = "ten"
1551 # assert m.join("; ", "=") == "1=one; 10=ten"
1552 fun join(sep: String, couple_sep: String): String
1553 do
1554 if is_empty then return ""
1555
1556 var s = new FlatBuffer # Result
1557
1558 # Concat first item
1559 var i = iterator
1560 var k = i.key
1561 var e = i.item
1562 s.append("{k}{couple_sep}{e or else "<null>"}")
1563
1564 # Concat other items
1565 i.next
1566 while i.is_ok do
1567 s.append(sep)
1568 k = i.key
1569 e = i.item
1570 s.append("{k}{couple_sep}{e or else "<null>"}")
1571 i.next
1572 end
1573 return s.to_s
1574 end
1575 end
1576
1577 ###############################################################################
1578 # Native classes #
1579 ###############################################################################
1580
1581 # Native strings are simple C char *
1582 class NativeString
1583 super StringCapable
1584
1585 fun [](index: Int): Char is intern
1586 fun []=(index: Int, item: Char) is intern
1587 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1588
1589 # Position of the first nul character.
1590 fun cstring_length: Int
1591 do
1592 var l = 0
1593 while self[l] != '\0' do l += 1
1594 return l
1595 end
1596 fun atoi: Int is intern
1597 fun atof: Float is extern "atof"
1598
1599 redef fun to_s
1600 do
1601 return to_s_with_length(cstring_length)
1602 end
1603
1604 fun to_s_with_length(length: Int): FlatString
1605 do
1606 assert length >= 0
1607 return new FlatString.with_infos(self, length, 0, length - 1)
1608 end
1609
1610 fun to_s_with_copy: FlatString
1611 do
1612 var length = cstring_length
1613 var new_self = calloc_string(length + 1)
1614 copy_to(new_self, length, 0, 0)
1615 return new FlatString.with_infos(new_self, length, 0, length - 1)
1616 end
1617
1618 end
1619
1620 # StringCapable objects can create native strings
1621 interface StringCapable
1622 protected fun calloc_string(size: Int): NativeString is intern
1623 end
1624
1625 redef class Sys
1626 var _args_cache: nullable Sequence[String]
1627
1628 redef fun args: Sequence[String]
1629 do
1630 if _args_cache == null then init_args
1631 return _args_cache.as(not null)
1632 end
1633
1634 # The name of the program as given by the OS
1635 fun program_name: String
1636 do
1637 return native_argv(0).to_s
1638 end
1639
1640 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1641 private fun init_args
1642 do
1643 var argc = native_argc
1644 var args = new Array[String].with_capacity(0)
1645 var i = 1
1646 while i < argc do
1647 args[i-1] = native_argv(i).to_s
1648 i += 1
1649 end
1650 _args_cache = args
1651 end
1652
1653 # First argument of the main C function.
1654 private fun native_argc: Int is intern
1655
1656 # Second argument of the main C function.
1657 private fun native_argv(i: Int): NativeString is intern
1658 end
1659