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