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