Merge: Opportunity i18n & traduction française
[nit.git] / lib / standard / text / abstract_text.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Abstract class for manipulation of sequences of characters
12 module abstract_text
13
14 import native
15 import math
16 import collection
17 intrude import collection::array
18
19 in "C" `{
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 `}
24
25 # High-level abstraction for all text representations
26 abstract class Text
27 super Comparable
28
29 redef type OTHER: Text
30
31 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
32 type SELFTYPE: Text
33
34 # Gets a view on the chars of the Text object
35 #
36 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
37 fun chars: SequenceRead[Char] is abstract
38
39 # Number of characters contained in self.
40 #
41 # assert "12345".length == 5
42 # assert "".length == 0
43 fun length: Int is abstract
44
45 # Create a substring.
46 #
47 # assert "abcd".substring(1, 2) == "bc"
48 # assert "abcd".substring(-1, 2) == "a"
49 # assert "abcd".substring(1, 0) == ""
50 # assert "abcd".substring(2, 5) == "cd"
51 #
52 # A `from` index < 0 will be replaced by 0.
53 # Unless a `count` value is > 0 at the same time.
54 # In this case, `from += count` and `count -= from`.
55 fun substring(from: Int, count: Int): SELFTYPE is abstract
56
57 # Iterates on the substrings of self if any
58 fun substrings: Iterator[FlatText] is abstract
59
60 # Is the current Text empty (== "")
61 #
62 # assert "".is_empty
63 # assert not "foo".is_empty
64 fun is_empty: Bool do return self.length == 0
65
66 # Returns an empty Text of the right type
67 #
68 # This method is used internally to get the right
69 # implementation of an empty string.
70 protected fun empty: SELFTYPE is abstract
71
72 # Gets the first char of the Text
73 #
74 # DEPRECATED : Use self.chars.first instead
75 fun first: Char do return self.chars[0]
76
77 # Access a character at `index` in the string.
78 #
79 # assert "abcd"[2] == 'c'
80 #
81 # DEPRECATED : Use self.chars.[] instead
82 fun [](index: Int): Char do return self.chars[index]
83
84 # Gets the index of the first occurence of 'c'
85 #
86 # Returns -1 if not found
87 #
88 # DEPRECATED : Use self.chars.index_of instead
89 fun index_of(c: Char): Int
90 do
91 return index_of_from(c, 0)
92 end
93
94 # Gets the last char of self
95 #
96 # DEPRECATED : Use self.chars.last instead
97 fun last: Char do return self.chars[length-1]
98
99 # Gets the index of the first occurence of ´c´ starting from ´pos´
100 #
101 # Returns -1 if not found
102 #
103 # DEPRECATED : Use self.chars.index_of_from instead
104 fun index_of_from(c: Char, pos: Int): Int
105 do
106 var iter = self.chars.iterator_from(pos)
107 while iter.is_ok do
108 if iter.item == c then return iter.index
109 iter.next
110 end
111 return -1
112 end
113
114 # Gets the last index of char ´c´
115 #
116 # Returns -1 if not found
117 #
118 # DEPRECATED : Use self.chars.last_index_of instead
119 fun last_index_of(c: Char): Int
120 do
121 return last_index_of_from(c, length - 1)
122 end
123
124 # Return a null terminated char *
125 fun to_cstring: NativeString is abstract
126
127 # The index of the last occurrence of an element starting from pos (in reverse order).
128 #
129 # var s = "/etc/bin/test/test.nit"
130 # assert s.last_index_of_from('/', s.length-1) == 13
131 # assert s.last_index_of_from('/', 12) == 8
132 #
133 # Returns -1 if not found
134 #
135 # DEPRECATED : Use self.chars.last_index_of_from instead
136 fun last_index_of_from(item: Char, pos: Int): Int
137 do
138 var iter = self.chars.reverse_iterator_from(pos)
139 while iter.is_ok do
140 if iter.item == item then return iter.index
141 iter.next
142 end
143 return -1
144 end
145
146 # Gets an iterator on the chars of self
147 #
148 # DEPRECATED : Use self.chars.iterator instead
149 fun iterator: Iterator[Char]
150 do
151 return self.chars.iterator
152 end
153
154
155 # Gets an Array containing the chars of self
156 #
157 # DEPRECATED : Use self.chars.to_a instead
158 fun to_a: Array[Char] do return chars.to_a
159
160 # Create a substring from `self` beginning at the `from` position
161 #
162 # assert "abcd".substring_from(1) == "bcd"
163 # assert "abcd".substring_from(-1) == "abcd"
164 # assert "abcd".substring_from(2) == "cd"
165 #
166 # As with substring, a `from` index < 0 will be replaced by 0
167 fun substring_from(from: Int): SELFTYPE
168 do
169 if from >= self.length then return empty
170 if from < 0 then from = 0
171 return substring(from, length - from)
172 end
173
174 # Does self have a substring `str` starting from position `pos`?
175 #
176 # assert "abcd".has_substring("bc",1) == true
177 # assert "abcd".has_substring("bc",2) == false
178 #
179 # Returns true iff all characters of `str` are presents
180 # at the expected index in `self.`
181 # The first character of `str` being at `pos`, the second
182 # character being at `pos+1` and so on...
183 #
184 # This means that all characters of `str` need to be inside `self`.
185 #
186 # assert "abcd".has_substring("xab", -1) == false
187 # assert "abcd".has_substring("cdx", 2) == false
188 #
189 # And that the empty string is always a valid substring.
190 #
191 # assert "abcd".has_substring("", 2) == true
192 # assert "abcd".has_substring("", 200) == true
193 fun has_substring(str: String, pos: Int): Bool
194 do
195 if str.is_empty then return true
196 if pos < 0 or pos + str.length > length then return false
197 var myiter = self.chars.iterator_from(pos)
198 var itsiter = str.chars.iterator
199 while myiter.is_ok and itsiter.is_ok do
200 if myiter.item != itsiter.item then return false
201 myiter.next
202 itsiter.next
203 end
204 if itsiter.is_ok then return false
205 return true
206 end
207
208 # Is this string prefixed by `prefix`?
209 #
210 # assert "abcd".has_prefix("ab") == true
211 # assert "abcbc".has_prefix("bc") == false
212 # assert "ab".has_prefix("abcd") == false
213 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
214
215 # Is this string suffixed by `suffix`?
216 #
217 # assert "abcd".has_suffix("abc") == false
218 # assert "abcd".has_suffix("bcd") == true
219 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
220
221 # If `self` contains only digits, return the corresponding integer
222 #
223 # assert "123".to_i == 123
224 # assert "-1".to_i == -1
225 fun to_i: Int
226 do
227 # Shortcut
228 return to_s.to_cstring.atoi
229 end
230
231 # If `self` contains a float, return the corresponding float
232 #
233 # assert "123".to_f == 123.0
234 # assert "-1".to_f == -1.0
235 # assert "-1.2e-3".to_f == -0.0012
236 fun to_f: Float
237 do
238 # Shortcut
239 return to_s.to_cstring.atof
240 end
241
242 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
243 #
244 # assert "ff".to_hex == 255
245 fun to_hex: Int do return a_to(16)
246
247 # If `self` contains only digits <= '7', return the corresponding integer.
248 #
249 # assert "714".to_oct == 460
250 fun to_oct: Int do return a_to(8)
251
252 # If `self` contains only '0' et '1', return the corresponding integer.
253 #
254 # assert "101101".to_bin == 45
255 fun to_bin: Int do return a_to(2)
256
257 # If `self` contains only digits and letters, return the corresponding integer in a given base
258 #
259 # assert "120".a_to(3) == 15
260 fun a_to(base: Int) : Int
261 do
262 var i = 0
263 var neg = false
264
265 for j in [0..length[ do
266 var c = chars[j]
267 var v = c.to_i
268 if v > base then
269 if neg then
270 return -i
271 else
272 return i
273 end
274 else if v < 0 then
275 neg = true
276 else
277 i = i * base + v
278 end
279 end
280 if neg then
281 return -i
282 else
283 return i
284 end
285 end
286
287 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
288 #
289 # assert "123".is_numeric == true
290 # assert "1.2".is_numeric == true
291 # assert "1,2".is_numeric == true
292 # assert "1..2".is_numeric == false
293 fun is_numeric: Bool
294 do
295 var has_point_or_comma = false
296 for i in [0..length[ do
297 var c = chars[i]
298 if not c.is_numeric then
299 if (c == '.' or c == ',') and not has_point_or_comma then
300 has_point_or_comma = true
301 else
302 return false
303 end
304 end
305 end
306 return true
307 end
308
309 # Returns `true` if the string contains only Hex chars
310 #
311 # assert "048bf".is_hex == true
312 # assert "ABCDEF".is_hex == true
313 # assert "0G".is_hex == false
314 fun is_hex: Bool
315 do
316 for i in [0..length[ do
317 var c = chars[i]
318 if not (c >= 'a' and c <= 'f') and
319 not (c >= 'A' and c <= 'F') and
320 not (c >= '0' and c <= '9') then return false
321 end
322 return true
323 end
324
325 # Are all letters in `self` upper-case ?
326 #
327 # assert "HELLO WORLD".is_upper == true
328 # assert "%$&%!".is_upper == true
329 # assert "hello world".is_upper == false
330 # assert "Hello World".is_upper == false
331 fun is_upper: Bool
332 do
333 for i in [0..length[ do
334 var char = chars[i]
335 if char.is_lower then return false
336 end
337 return true
338 end
339
340 # Are all letters in `self` lower-case ?
341 #
342 # assert "hello world".is_lower == true
343 # assert "%$&%!".is_lower == true
344 # assert "Hello World".is_lower == false
345 fun is_lower: Bool
346 do
347 for i in [0..length[ do
348 var char = chars[i]
349 if char.is_upper then return false
350 end
351 return true
352 end
353
354 # Removes the whitespaces at the beginning of self
355 #
356 # assert " \n\thello \n\t".l_trim == "hello \n\t"
357 #
358 # `Char::is_whitespace` determines what is a whitespace.
359 fun l_trim: SELFTYPE
360 do
361 var iter = self.chars.iterator
362 while iter.is_ok do
363 if not iter.item.is_whitespace then break
364 iter.next
365 end
366 if iter.index == length then return self.empty
367 return self.substring_from(iter.index)
368 end
369
370 # Removes the whitespaces at the end of self
371 #
372 # assert " \n\thello \n\t".r_trim == " \n\thello"
373 #
374 # `Char::is_whitespace` determines what is a whitespace.
375 fun r_trim: SELFTYPE
376 do
377 var iter = self.chars.reverse_iterator
378 while iter.is_ok do
379 if not iter.item.is_whitespace then break
380 iter.next
381 end
382 if iter.index < 0 then return self.empty
383 return self.substring(0, iter.index + 1)
384 end
385
386 # Trims trailing and preceding white spaces
387 #
388 # assert " Hello World ! ".trim == "Hello World !"
389 # assert "\na\nb\tc\t".trim == "a\nb\tc"
390 #
391 # `Char::is_whitespace` determines what is a whitespace.
392 fun trim: SELFTYPE do return (self.l_trim).r_trim
393
394 # Is the string non-empty but only made of whitespaces?
395 #
396 # assert " \n\t ".is_whitespace == true
397 # assert " hello ".is_whitespace == false
398 # assert "".is_whitespace == false
399 #
400 # `Char::is_whitespace` determines what is a whitespace.
401 fun is_whitespace: Bool
402 do
403 if is_empty then return false
404 for c in self.chars do
405 if not c.is_whitespace then return false
406 end
407 return true
408 end
409
410 # Returns `self` removed from its last line terminator (if any).
411 #
412 # assert "Hello\n".chomp == "Hello"
413 # assert "Hello".chomp == "Hello"
414 #
415 # assert "\n".chomp == ""
416 # assert "".chomp == ""
417 #
418 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
419 # A single line terminator, the last one, is removed.
420 #
421 # assert "\r\n".chomp == ""
422 # assert "\r\n\n".chomp == "\r\n"
423 # assert "\r\n\r\n".chomp == "\r\n"
424 # assert "\r\n\r".chomp == "\r\n"
425 #
426 # Note: unlike with most IO methods like `Reader::read_line`,
427 # a single `\r` is considered here to be a line terminator and will be removed.
428 fun chomp: SELFTYPE
429 do
430 var len = length
431 if len == 0 then return self
432 var l = self.chars.last
433 if l == '\r' then
434 return substring(0, len-1)
435 else if l != '\n' then
436 return self
437 else if len > 1 and self.chars[len-2] == '\r' then
438 return substring(0, len-2)
439 else
440 return substring(0, len-1)
441 end
442 end
443
444 # Justify a self in a space of `length`
445 #
446 # `left` is the space ratio on the left side.
447 # * 0.0 for left-justified (no space at the left)
448 # * 1.0 for right-justified (all spaces at the left)
449 # * 0.5 for centered (half the spaces at the left)
450 #
451 # Examples
452 #
453 # assert "hello".justify(10, 0.0) == "hello "
454 # assert "hello".justify(10, 1.0) == " hello"
455 # assert "hello".justify(10, 0.5) == " hello "
456 #
457 # If `length` is not enough, `self` is returned as is.
458 #
459 # assert "hello".justify(2, 0.0) == "hello"
460 #
461 # REQUIRE: `left >= 0.0 and left <= 1.0`
462 # ENSURE: `self.length <= length implies result.length == length`
463 # ENSURE: `self.length >= length implies result == self`
464 fun justify(length: Int, left: Float): String
465 do
466 var diff = length - self.length
467 if diff <= 0 then return to_s
468 assert left >= 0.0 and left <= 1.0
469 var before = (diff.to_f * left).to_i
470 return " " * before + self + " " * (diff-before)
471 end
472
473 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
474 #
475 # This method is injective (two different inputs never produce the same
476 # output) and the returned string always respect the following rules:
477 #
478 # * Contains only US-ASCII letters, digits and underscores.
479 # * Never starts with a digit.
480 # * Never ends with an underscore.
481 # * Never contains two contiguous underscores.
482 #
483 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
484 # assert "__".to_cmangle == "_95d_95d"
485 # assert "__d".to_cmangle == "_95d_d"
486 # assert "_d_".to_cmangle == "_d_95d"
487 # assert "_42".to_cmangle == "_95d42"
488 # assert "foo".to_cmangle == "foo"
489 # assert "".to_cmangle == ""
490 fun to_cmangle: String
491 do
492 if is_empty then return ""
493 var res = new Buffer
494 var underscore = false
495 var start = 0
496 var c = chars[0]
497
498 if c >= '0' and c <= '9' then
499 res.add('_')
500 res.append(c.ascii.to_s)
501 res.add('d')
502 start = 1
503 end
504 for i in [start..length[ do
505 c = chars[i]
506 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
507 res.add(c)
508 underscore = false
509 continue
510 end
511 if underscore then
512 res.append('_'.ascii.to_s)
513 res.add('d')
514 end
515 if c >= '0' and c <= '9' then
516 res.add(c)
517 underscore = false
518 else if c == '_' then
519 res.add(c)
520 underscore = true
521 else
522 res.add('_')
523 res.append(c.ascii.to_s)
524 res.add('d')
525 underscore = false
526 end
527 end
528 if underscore then
529 res.append('_'.ascii.to_s)
530 res.add('d')
531 end
532 return res.to_s
533 end
534
535 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
536 #
537 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
538 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
539 #
540 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
541 # Three digits are always used to avoid following digits to be interpreted as an element
542 # of the octal sequence.
543 #
544 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
545 #
546 # The exceptions are the common `\t` and `\n`.
547 fun escape_to_c: String
548 do
549 var b = new Buffer
550 for i in [0..length[ do
551 var c = chars[i]
552 if c == '\n' then
553 b.append("\\n")
554 else if c == '\t' then
555 b.append("\\t")
556 else if c == '\0' then
557 b.append("\\000")
558 else if c == '"' then
559 b.append("\\\"")
560 else if c == '\'' then
561 b.append("\\\'")
562 else if c == '\\' then
563 b.append("\\\\")
564 else if c.ascii < 32 then
565 b.add('\\')
566 var oct = c.ascii.to_base(8, false)
567 # Force 3 octal digits since it is the
568 # maximum allowed in the C specification
569 if oct.length == 1 then
570 b.add('0')
571 b.add('0')
572 else if oct.length == 2 then
573 b.add('0')
574 end
575 b.append(oct)
576 else
577 b.add(c)
578 end
579 end
580 return b.to_s
581 end
582
583 # Escape additionnal characters
584 # The result might no be legal in C but be used in other languages
585 #
586 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
587 fun escape_more_to_c(chars: String): String
588 do
589 var b = new Buffer
590 for c in escape_to_c.chars do
591 if chars.chars.has(c) then
592 b.add('\\')
593 end
594 b.add(c)
595 end
596 return b.to_s
597 end
598
599 # Escape to C plus braces
600 #
601 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
602 fun escape_to_nit: String do return escape_more_to_c("\{\}")
603
604 # Escape to POSIX Shell (sh).
605 #
606 # Abort if the text contains a null byte.
607 #
608 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
609 fun escape_to_sh: String do
610 var b = new Buffer
611 b.chars.add '\''
612 for i in [0..length[ do
613 var c = chars[i]
614 if c == '\'' then
615 b.append("'\\''")
616 else
617 assert without_null_byte: c != '\0'
618 b.add(c)
619 end
620 end
621 b.chars.add '\''
622 return b.to_s
623 end
624
625 # Escape to include in a Makefile
626 #
627 # Unfortunately, some characters are not escapable in Makefile.
628 # These characters are `;`, `|`, `\`, and the non-printable ones.
629 # They will be rendered as `"?{hex}"`.
630 fun escape_to_mk: String do
631 var b = new Buffer
632 for i in [0..length[ do
633 var c = chars[i]
634 if c == '$' then
635 b.append("$$")
636 else if c == ':' or c == ' ' or c == '#' then
637 b.add('\\')
638 b.add(c)
639 else if c.ascii < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
640 b.append("?{c.ascii.to_base(16, false)}")
641 else
642 b.add(c)
643 end
644 end
645 return b.to_s
646 end
647
648 # Return a string where Nit escape sequences are transformed.
649 #
650 # var s = "\\n"
651 # assert s.length == 2
652 # var u = s.unescape_nit
653 # assert u.length == 1
654 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
655 fun unescape_nit: String
656 do
657 var res = new Buffer.with_cap(self.length)
658 var was_slash = false
659 for i in [0..length[ do
660 var c = chars[i]
661 if not was_slash then
662 if c == '\\' then
663 was_slash = true
664 else
665 res.add(c)
666 end
667 continue
668 end
669 was_slash = false
670 if c == 'n' then
671 res.add('\n')
672 else if c == 'r' then
673 res.add('\r')
674 else if c == 't' then
675 res.add('\t')
676 else if c == '0' then
677 res.add('\0')
678 else
679 res.add(c)
680 end
681 end
682 return res.to_s
683 end
684
685 # Encode `self` to percent (or URL) encoding
686 #
687 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
688 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
689 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
690 fun to_percent_encoding: String
691 do
692 var buf = new Buffer
693
694 for i in [0..length[ do
695 var c = chars[i]
696 if (c >= '0' and c <= '9') or
697 (c >= 'a' and c <= 'z') or
698 (c >= 'A' and c <= 'Z') or
699 c == '-' or c == '.' or
700 c == '_' or c == '~'
701 then
702 buf.add c
703 else buf.append "%{c.ascii.to_hex}"
704 end
705
706 return buf.to_s
707 end
708
709 # Decode `self` from percent (or URL) encoding to a clear string
710 #
711 # Replace invalid use of '%' with '?'.
712 #
713 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
714 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
715 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
716 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
717 # assert "incomplete %".from_percent_encoding == "incomplete ?"
718 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
719 fun from_percent_encoding: String
720 do
721 var buf = new Buffer
722
723 var i = 0
724 while i < length do
725 var c = chars[i]
726 if c == '%' then
727 if i + 2 >= length then
728 # What follows % has been cut off
729 buf.add '?'
730 else
731 i += 1
732 var hex_s = substring(i, 2)
733 if hex_s.is_hex then
734 var hex_i = hex_s.to_hex
735 buf.add hex_i.ascii
736 i += 1
737 else
738 # What follows a % is not Hex
739 buf.add '?'
740 i -= 1
741 end
742 end
743 else buf.add c
744
745 i += 1
746 end
747
748 return buf.to_s
749 end
750
751 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
752 #
753 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
754 #
755 # SEE: <https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content>
756 fun html_escape: String
757 do
758 var buf = new Buffer
759
760 for i in [0..length[ do
761 var c = chars[i]
762 if c == '&' then
763 buf.append "&amp;"
764 else if c == '<' then
765 buf.append "&lt;"
766 else if c == '>' then
767 buf.append "&gt;"
768 else if c == '"' then
769 buf.append "&#34;"
770 else if c == '\'' then
771 buf.append "&#39;"
772 else if c == '/' then
773 buf.append "&#47;"
774 else buf.add c
775 end
776
777 return buf.to_s
778 end
779
780 # Equality of text
781 # Two pieces of text are equals if thez have the same characters in the same order.
782 #
783 # assert "hello" == "hello"
784 # assert "hello" != "HELLO"
785 # assert "hello" == "hel"+"lo"
786 #
787 # Things that are not Text are not equal.
788 #
789 # assert "9" != '9'
790 # assert "9" != ['9']
791 # assert "9" != 9
792 #
793 # assert "9".chars.first == '9' # equality of Char
794 # assert "9".chars == ['9'] # equality of Sequence
795 # assert "9".to_i == 9 # equality of Int
796 redef fun ==(o)
797 do
798 if o == null then return false
799 if not o isa Text then return false
800 if self.is_same_instance(o) then return true
801 if self.length != o.length then return false
802 return self.chars == o.chars
803 end
804
805 # Lexicographical comparaison
806 #
807 # assert "abc" < "xy"
808 # assert "ABC" < "abc"
809 redef fun <(other)
810 do
811 var self_chars = self.chars.iterator
812 var other_chars = other.chars.iterator
813
814 while self_chars.is_ok and other_chars.is_ok do
815 if self_chars.item < other_chars.item then return true
816 if self_chars.item > other_chars.item then return false
817 self_chars.next
818 other_chars.next
819 end
820
821 if self_chars.is_ok then
822 return false
823 else
824 return true
825 end
826 end
827
828 # Escape string used in labels for graphviz
829 #
830 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
831 fun escape_to_dot: String
832 do
833 return escape_more_to_c("|\{\}<>")
834 end
835
836 private var hash_cache: nullable Int = null
837
838 redef fun hash
839 do
840 if hash_cache == null then
841 # djb2 hash algorithm
842 var h = 5381
843
844 for i in [0..length[ do
845 var char = chars[i]
846 h = h.lshift(5) + h + char.ascii
847 end
848
849 hash_cache = h
850 end
851 return hash_cache.as(not null)
852 end
853
854 # Gives the formatted string back as a Nit string with `args` in place
855 #
856 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
857 # assert "\\%1 This string".format("String") == "\\%1 This string"
858 fun format(args: Object...): String do
859 var s = new Array[Text]
860 var curr_st = 0
861 var i = 0
862 while i < length do
863 # Skip escaped characters
864 if self[i] == '\\' then
865 i += 1
866 # In case of format
867 else if self[i] == '%' then
868 var fmt_st = i
869 i += 1
870 var ciph_st = i
871 while i < length and self[i].is_numeric do
872 i += 1
873 end
874 i -= 1
875 var fmt_end = i
876 var ciph_len = fmt_end - ciph_st + 1
877
878 var arg_index = substring(ciph_st, ciph_len).to_i - 1
879 if arg_index >= args.length then continue
880
881 s.push substring(curr_st, fmt_st - curr_st)
882 s.push args[arg_index].to_s
883 curr_st = i + 1
884 end
885 i += 1
886 end
887 s.push substring(curr_st, length - curr_st)
888 return s.plain_to_s
889 end
890
891 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
892 #
893 # Basically a high-level synonym of NativeString::copy_to
894 #
895 # REQUIRE: `n` must be large enough to contain `len` bytes
896 #
897 # var ns = new NativeString(8)
898 # "Text is String".copy_to_native(ns, 8, 2, 0)
899 # assert ns.to_s_with_length(8) == "xt is St"
900 #
901 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
902 var mypos = src_offset
903 var itspos = dest_offset
904 while n > 0 do
905 dest[itspos] = self.chars[mypos]
906 itspos += 1
907 mypos += 1
908 n -= 1
909 end
910 end
911
912 end
913
914 # All kinds of array-based text representations.
915 abstract class FlatText
916 super Text
917
918 # Underlying C-String (`char*`)
919 #
920 # Warning : Might be void in some subclasses, be sure to check
921 # if set before using it.
922 private var items: NativeString is noinit
923
924 # Real items, used as cache for to_cstring is called
925 private var real_items: nullable NativeString = null
926
927 # Returns a char* starting at position `index_from`
928 #
929 # WARNING: If you choose to use this service, be careful of the following.
930 #
931 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
932 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
933 # deallocated at any moment, rendering the pointer returned by this function invalid.
934 # Any access to freed memory may very likely cause undefined behaviour or a crash.
935 # (Failure to do so will most certainly result in long and painful debugging hours)
936 #
937 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
938 # then immediately return).
939 #
940 # As always, do not modify the content of the String in C code, if this is what you want
941 # copy locally the char* as Nit Strings are immutable.
942 private fun fast_cstring: NativeString is abstract
943
944 redef var length = 0
945
946 redef fun output
947 do
948 var i = 0
949 while i < length do
950 items[i].output
951 i += 1
952 end
953 end
954
955 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
956 items.copy_to(dest, n, src_offset, dest_offset)
957 end
958 end
959
960 # Abstract class for the SequenceRead compatible
961 # views on String and Buffer objects
962 private abstract class StringCharView
963 super SequenceRead[Char]
964
965 type SELFTYPE: Text
966
967 var target: SELFTYPE
968
969 redef fun is_empty do return target.is_empty
970
971 redef fun length do return target.length
972
973 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
974
975 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
976 end
977
978 # Immutable sequence of characters.
979 #
980 # String objects may be created using literals.
981 #
982 # assert "Hello World!" isa String
983 abstract class String
984 super Text
985
986 redef type SELFTYPE: String is fixed
987
988 redef fun to_s do return self
989
990 # Concatenates `o` to `self`
991 #
992 # assert "hello" + "world" == "helloworld"
993 # assert "" + "hello" + "" == "hello"
994 fun +(o: Text): SELFTYPE is abstract
995
996 # Concatenates self `i` times
997 #
998 # assert "abc" * 4 == "abcabcabcabc"
999 # assert "abc" * 1 == "abc"
1000 # assert "abc" * 0 == ""
1001 fun *(i: Int): SELFTYPE is abstract
1002
1003 # Insert `s` at `pos`.
1004 #
1005 # assert "helloworld".insert_at(" ", 5) == "hello world"
1006 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1007
1008 redef fun substrings is abstract
1009
1010 # Returns a reversed version of self
1011 #
1012 # assert "hello".reversed == "olleh"
1013 # assert "bob".reversed == "bob"
1014 # assert "".reversed == ""
1015 fun reversed: SELFTYPE is abstract
1016
1017 # A upper case version of `self`
1018 #
1019 # assert "Hello World!".to_upper == "HELLO WORLD!"
1020 fun to_upper: SELFTYPE is abstract
1021
1022 # A lower case version of `self`
1023 #
1024 # assert "Hello World!".to_lower == "hello world!"
1025 fun to_lower : SELFTYPE is abstract
1026
1027 # Takes a camel case `self` and converts it to snake case
1028 #
1029 # assert "randomMethodId".to_snake_case == "random_method_id"
1030 #
1031 # The rules are the following:
1032 #
1033 # An uppercase is always converted to a lowercase
1034 #
1035 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1036 #
1037 # An uppercase that follows a lowercase is prefixed with an underscore
1038 #
1039 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1040 #
1041 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1042 #
1043 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1044 #
1045 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1046 #
1047 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1048 fun to_snake_case: SELFTYPE
1049 do
1050 if self.is_lower then return self
1051
1052 var new_str = new Buffer.with_cap(self.length)
1053 var prev_is_lower = false
1054 var prev_is_upper = false
1055
1056 for i in [0..length[ do
1057 var char = chars[i]
1058 if char.is_lower then
1059 new_str.add(char)
1060 prev_is_lower = true
1061 prev_is_upper = false
1062 else if char.is_upper then
1063 if prev_is_lower then
1064 new_str.add('_')
1065 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1066 new_str.add('_')
1067 end
1068 new_str.add(char.to_lower)
1069 prev_is_lower = false
1070 prev_is_upper = true
1071 else
1072 new_str.add(char)
1073 prev_is_lower = false
1074 prev_is_upper = false
1075 end
1076 end
1077
1078 return new_str.to_s
1079 end
1080
1081 # Takes a snake case `self` and converts it to camel case
1082 #
1083 # assert "random_method_id".to_camel_case == "randomMethodId"
1084 #
1085 # If the identifier is prefixed by an underscore, the underscore is ignored
1086 #
1087 # assert "_private_field".to_camel_case == "_privateField"
1088 #
1089 # If `self` is upper, it is returned unchanged
1090 #
1091 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1092 #
1093 # If there are several consecutive underscores, they are considered as a single one
1094 #
1095 # assert "random__method_id".to_camel_case == "randomMethodId"
1096 fun to_camel_case: SELFTYPE
1097 do
1098 if self.is_upper then return self
1099
1100 var new_str = new Buffer
1101 var is_first_char = true
1102 var follows_us = false
1103
1104 for i in [0..length[ do
1105 var char = chars[i]
1106 if is_first_char then
1107 new_str.add(char)
1108 is_first_char = false
1109 else if char == '_' then
1110 follows_us = true
1111 else if follows_us then
1112 new_str.add(char.to_upper)
1113 follows_us = false
1114 else
1115 new_str.add(char)
1116 end
1117 end
1118
1119 return new_str.to_s
1120 end
1121
1122 # Returns a capitalized `self`
1123 #
1124 # Letters that follow a letter are lowercased
1125 # Letters that follow a non-letter are upcased.
1126 #
1127 # SEE : `Char::is_letter` for the definition of letter.
1128 #
1129 # assert "jAVASCRIPT".capitalized == "Javascript"
1130 # assert "i am root".capitalized == "I Am Root"
1131 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1132 fun capitalized: SELFTYPE do
1133 if length == 0 then return self
1134
1135 var buf = new Buffer.with_cap(length)
1136
1137 var curr = chars[0].to_upper
1138 var prev = curr
1139 buf[0] = curr
1140
1141 for i in [1 .. length[ do
1142 prev = curr
1143 curr = self[i]
1144 if prev.is_letter then
1145 buf[i] = curr.to_lower
1146 else
1147 buf[i] = curr.to_upper
1148 end
1149 end
1150
1151 return buf.to_s
1152 end
1153 end
1154
1155 # A mutable sequence of characters.
1156 abstract class Buffer
1157 super Text
1158
1159 # Returns an arbitrary subclass of `Buffer` with default parameters
1160 new is abstract
1161
1162 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1163 new with_cap(i: Int) is abstract
1164
1165 redef type SELFTYPE: Buffer is fixed
1166
1167 # Specific implementations MUST set this to `true` in order to invalidate caches
1168 protected var is_dirty = true
1169
1170 # Copy-On-Write flag
1171 #
1172 # If the `Buffer` was to_s'd, the next in-place altering
1173 # operation will cause the current `Buffer` to be re-allocated.
1174 #
1175 # The flag will then be set at `false`.
1176 protected var written = false
1177
1178 # Modifies the char contained at pos `index`
1179 #
1180 # DEPRECATED : Use self.chars.[]= instead
1181 fun []=(index: Int, item: Char) is abstract
1182
1183 # Adds a char `c` at the end of self
1184 #
1185 # DEPRECATED : Use self.chars.add instead
1186 fun add(c: Char) is abstract
1187
1188 # Clears the buffer
1189 #
1190 # var b = new Buffer
1191 # b.append "hello"
1192 # assert not b.is_empty
1193 # b.clear
1194 # assert b.is_empty
1195 fun clear is abstract
1196
1197 # Enlarges the subsequent array containing the chars of self
1198 fun enlarge(cap: Int) is abstract
1199
1200 # Adds the content of text `s` at the end of self
1201 #
1202 # var b = new Buffer
1203 # b.append "hello"
1204 # b.append "world"
1205 # assert b == "helloworld"
1206 fun append(s: Text) is abstract
1207
1208 # `self` is appended in such a way that `self` is repeated `r` times
1209 #
1210 # var b = new Buffer
1211 # b.append "hello"
1212 # b.times 3
1213 # assert b == "hellohellohello"
1214 fun times(r: Int) is abstract
1215
1216 # Reverses itself in-place
1217 #
1218 # var b = new Buffer
1219 # b.append("hello")
1220 # b.reverse
1221 # assert b == "olleh"
1222 fun reverse is abstract
1223
1224 # Changes each lower-case char in `self` by its upper-case variant
1225 #
1226 # var b = new Buffer
1227 # b.append("Hello World!")
1228 # b.upper
1229 # assert b == "HELLO WORLD!"
1230 fun upper is abstract
1231
1232 # Changes each upper-case char in `self` by its lower-case variant
1233 #
1234 # var b = new Buffer
1235 # b.append("Hello World!")
1236 # b.lower
1237 # assert b == "hello world!"
1238 fun lower is abstract
1239
1240 # Capitalizes each word in `self`
1241 #
1242 # Letters that follow a letter are lowercased
1243 # Letters that follow a non-letter are upcased.
1244 #
1245 # SEE: `Char::is_letter` for the definition of a letter.
1246 #
1247 # var b = new FlatBuffer.from("jAVAsCriPt")
1248 # b.capitalize
1249 # assert b == "Javascript"
1250 # b = new FlatBuffer.from("i am root")
1251 # b.capitalize
1252 # assert b == "I Am Root"
1253 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1254 # b.capitalize
1255 # assert b == "Ab_C -Ab0C Ab\nC"
1256 fun capitalize do
1257 if length == 0 then return
1258 var c = self[0].to_upper
1259 self[0] = c
1260 var prev = c
1261 for i in [1 .. length[ do
1262 prev = c
1263 c = self[i]
1264 if prev.is_letter then
1265 self[i] = c.to_lower
1266 else
1267 self[i] = c.to_upper
1268 end
1269 end
1270 end
1271
1272 redef fun hash
1273 do
1274 if is_dirty then hash_cache = null
1275 return super
1276 end
1277
1278 # In Buffers, the internal sequence of character is mutable
1279 # Thus, `chars` can be used to modify the buffer.
1280 redef fun chars: Sequence[Char] is abstract
1281 end
1282
1283 # View on Buffer objects, extends Sequence
1284 # for mutation operations
1285 private abstract class BufferCharView
1286 super StringCharView
1287 super Sequence[Char]
1288
1289 redef type SELFTYPE: Buffer
1290
1291 end
1292
1293 redef class Object
1294 # User readable representation of `self`.
1295 fun to_s: String do return inspect
1296
1297 # The class name of the object in NativeString format.
1298 private fun native_class_name: NativeString is intern
1299
1300 # The class name of the object.
1301 #
1302 # assert 5.class_name == "Int"
1303 fun class_name: String do return native_class_name.to_s
1304
1305 # Developer readable representation of `self`.
1306 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1307 fun inspect: String
1308 do
1309 return "<{inspect_head}>"
1310 end
1311
1312 # Return "CLASSNAME:#OBJECTID".
1313 # This function is mainly used with the redefinition of the inspect method
1314 protected fun inspect_head: String
1315 do
1316 return "{class_name}:#{object_id.to_hex}"
1317 end
1318 end
1319
1320 redef class Bool
1321 # assert true.to_s == "true"
1322 # assert false.to_s == "false"
1323 redef fun to_s
1324 do
1325 if self then
1326 return once "true"
1327 else
1328 return once "false"
1329 end
1330 end
1331 end
1332
1333 redef class Byte
1334 # C function to calculate the length of the `NativeString` to receive `self`
1335 private fun byte_to_s_len: Int `{
1336 return snprintf(NULL, 0, "0x%02x", self);
1337 `}
1338
1339 # C function to convert an nit Int to a NativeString (char*)
1340 private fun native_byte_to_s(nstr: NativeString, strlen: Int) `{
1341 snprintf(nstr, strlen, "0x%02x", self);
1342 `}
1343
1344 # Displayable byte in its hexadecimal form (0x..)
1345 #
1346 # assert 1.to_b.to_s == "0x01"
1347 # assert (-123).to_b.to_s == "0x85"
1348 redef fun to_s do
1349 var nslen = byte_to_s_len
1350 var ns = new NativeString(nslen + 1)
1351 ns[nslen] = '\0'
1352 native_byte_to_s(ns, nslen + 1)
1353 return ns.to_s_with_length(nslen)
1354 end
1355 end
1356
1357 redef class Int
1358
1359 # Wrapper of strerror C function
1360 private fun strerror_ext: NativeString `{ return strerror(self); `}
1361
1362 # Returns a string describing error number
1363 fun strerror: String do return strerror_ext.to_s
1364
1365 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1366 # assume < to_c max const of char
1367 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1368 do
1369 var n: Int
1370 # Sign
1371 if self < 0 then
1372 n = - self
1373 s.chars[0] = '-'
1374 else if self == 0 then
1375 s.chars[0] = '0'
1376 return
1377 else
1378 n = self
1379 end
1380 # Fill digits
1381 var pos = digit_count(base) - 1
1382 while pos >= 0 and n > 0 do
1383 s.chars[pos] = (n % base).to_c
1384 n = n / base # /
1385 pos -= 1
1386 end
1387 end
1388
1389 # C function to calculate the length of the `NativeString` to receive `self`
1390 private fun int_to_s_len: Int `{
1391 return snprintf(NULL, 0, "%ld", self);
1392 `}
1393
1394 # C function to convert an nit Int to a NativeString (char*)
1395 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1396 snprintf(nstr, strlen, "%ld", self);
1397 `}
1398
1399 # return displayable int in base base and signed
1400 fun to_base(base: Int, signed: Bool): String is abstract
1401
1402 # return displayable int in hexadecimal
1403 #
1404 # assert 1.to_hex == "1"
1405 # assert (-255).to_hex == "-ff"
1406 fun to_hex: String do return to_base(16,false)
1407 end
1408
1409 redef class Float
1410 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1411 #
1412 # assert 12.34.to_s == "12.34"
1413 # assert (-0120.030).to_s == "-120.03"
1414 #
1415 # see `to_precision` for a custom precision.
1416 redef fun to_s do
1417 var str = to_precision( 3 )
1418 if is_inf != 0 or is_nan then return str
1419 var len = str.length
1420 for i in [0..len-1] do
1421 var j = len-1-i
1422 var c = str.chars[j]
1423 if c == '0' then
1424 continue
1425 else if c == '.' then
1426 return str.substring( 0, j+2 )
1427 else
1428 return str.substring( 0, j+1 )
1429 end
1430 end
1431 return str
1432 end
1433
1434 # `String` representation of `self` with the given number of `decimals`
1435 #
1436 # assert 12.345.to_precision(0) == "12"
1437 # assert 12.345.to_precision(3) == "12.345"
1438 # assert (-12.345).to_precision(3) == "-12.345"
1439 # assert (-0.123).to_precision(3) == "-0.123"
1440 # assert 0.999.to_precision(2) == "1.00"
1441 # assert 0.999.to_precision(4) == "0.9990"
1442 fun to_precision(decimals: Int): String
1443 do
1444 if is_nan then return "nan"
1445
1446 var isinf = self.is_inf
1447 if isinf == 1 then
1448 return "inf"
1449 else if isinf == -1 then
1450 return "-inf"
1451 end
1452
1453 if decimals == 0 then return self.to_i.to_s
1454 var f = self
1455 for i in [0..decimals[ do f = f * 10.0
1456 if self > 0.0 then
1457 f = f + 0.5
1458 else
1459 f = f - 0.5
1460 end
1461 var i = f.to_i
1462 if i == 0 then return "0." + "0"*decimals
1463
1464 # Prepare both parts of the float, before and after the "."
1465 var s = i.abs.to_s
1466 var sl = s.length
1467 var p1
1468 var p2
1469 if sl > decimals then
1470 # Has something before the "."
1471 p1 = s.substring(0, sl-decimals)
1472 p2 = s.substring(sl-decimals, decimals)
1473 else
1474 p1 = "0"
1475 p2 = "0"*(decimals-sl) + s
1476 end
1477
1478 if i < 0 then p1 = "-" + p1
1479
1480 return p1 + "." + p2
1481 end
1482 end
1483
1484 redef class Char
1485 # assert 'x'.to_s == "x"
1486 redef fun to_s
1487 do
1488 var s = new Buffer.with_cap(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 # String representation of the content of the collection.
1530 #
1531 # The standard representation is the list of elements separated with commas.
1532 #
1533 # ~~~
1534 # assert [1,2,3].to_s == "[1,2,3]"
1535 # assert [1..3].to_s == "[1,2,3]"
1536 # assert (new Array[Int]).to_s == "[]" # empty collection
1537 # ~~~
1538 #
1539 # Subclasses may return a more specific string representation.
1540 redef fun to_s
1541 do
1542 return "[" + join(",") + "]"
1543 end
1544
1545 # Concatenate elements without separators
1546 #
1547 # ~~~
1548 # assert [1,2,3].plain_to_s == "123"
1549 # assert [11..13].plain_to_s == "111213"
1550 # assert (new Array[Int]).plain_to_s == "" # empty collection
1551 # ~~~
1552 fun plain_to_s: String
1553 do
1554 var s = new Buffer
1555 for e in self do if e != null then s.append(e.to_s)
1556 return s.to_s
1557 end
1558
1559 # Concatenate and separate each elements with `sep`.
1560 #
1561 # assert [1, 2, 3].join(":") == "1:2:3"
1562 # assert [1..3].join(":") == "1:2:3"
1563 fun join(sep: Text): String
1564 do
1565 if is_empty then return ""
1566
1567 var s = new Buffer # Result
1568
1569 # Concat first item
1570 var i = iterator
1571 var e = i.item
1572 if e != null then s.append(e.to_s)
1573
1574 # Concat other items
1575 i.next
1576 while i.is_ok do
1577 s.append(sep)
1578 e = i.item
1579 if e != null then s.append(e.to_s)
1580 i.next
1581 end
1582 return s.to_s
1583 end
1584 end
1585
1586 redef class Map[K,V]
1587 # Concatenate couple of 'key value'.
1588 # key and value are separated by `couple_sep`.
1589 # each couple is separated each couple with `sep`.
1590 #
1591 # var m = new ArrayMap[Int, String]
1592 # m[1] = "one"
1593 # m[10] = "ten"
1594 # assert m.join("; ", "=") == "1=one; 10=ten"
1595 fun join(sep: String, couple_sep: String): String is abstract
1596 end
1597
1598 redef class Sys
1599 private var args_cache: nullable Sequence[String] = null
1600
1601 # The arguments of the program as given by the OS
1602 fun program_args: Sequence[String]
1603 do
1604 if _args_cache == null then init_args
1605 return _args_cache.as(not null)
1606 end
1607
1608 # The name of the program as given by the OS
1609 fun program_name: String
1610 do
1611 return native_argv(0).to_s
1612 end
1613
1614 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
1615 private fun init_args
1616 do
1617 var argc = native_argc
1618 var args = new Array[String].with_capacity(0)
1619 var i = 1
1620 while i < argc do
1621 args[i-1] = native_argv(i).to_s
1622 i += 1
1623 end
1624 _args_cache = args
1625 end
1626
1627 # First argument of the main C function.
1628 private fun native_argc: Int is intern
1629
1630 # Second argument of the main C function.
1631 private fun native_argv(i: Int): NativeString is intern
1632 end
1633
1634 # Comparator that efficienlty use `to_s` to compare things
1635 #
1636 # The comparaison call `to_s` on object and use the result to order things.
1637 #
1638 # var a = [1, 2, 3, 10, 20]
1639 # (new CachedAlphaComparator).sort(a)
1640 # assert a == [1, 10, 2, 20, 3]
1641 #
1642 # Internally the result of `to_s` is cached in a HashMap to counter
1643 # uneficient implementation of `to_s`.
1644 #
1645 # Note: it caching is not usefull, see `alpha_comparator`
1646 class CachedAlphaComparator
1647 super Comparator
1648 redef type COMPARED: Object
1649
1650 private var cache = new HashMap[Object, String]
1651
1652 private fun do_to_s(a: Object): String do
1653 if cache.has_key(a) then return cache[a]
1654 var res = a.to_s
1655 cache[a] = res
1656 return res
1657 end
1658
1659 redef fun compare(a, b) do
1660 return do_to_s(a) <=> do_to_s(b)
1661 end
1662 end
1663
1664 # see `alpha_comparator`
1665 private class AlphaComparator
1666 super Comparator
1667 redef fun compare(a, b) do return a.to_s <=> b.to_s
1668 end
1669
1670 # Stateless comparator that naively use `to_s` to compare things.
1671 #
1672 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1673 # on a single instace. See `CachedAlphaComparator` as an alternative.
1674 #
1675 # var a = [1, 2, 3, 10, 20]
1676 # alpha_comparator.sort(a)
1677 # assert a == [1, 10, 2, 20, 3]
1678 fun alpha_comparator: Comparator do return once new AlphaComparator
1679
1680 # The arguments of the program as given by the OS
1681 fun args: Sequence[String]
1682 do
1683 return sys.program_args
1684 end
1685
1686 redef class NativeString
1687 # Returns `self` as a new String.
1688 fun to_s_with_copy: String is abstract
1689
1690 # Returns `self` as a String of `length`.
1691 fun to_s_with_length(length: Int): String is abstract
1692 end
1693
1694 redef class NativeArray[E]
1695 # Join all the elements using `to_s`
1696 #
1697 # REQUIRE: `self isa NativeArray[String]`
1698 # REQUIRE: all elements are initialized
1699 fun native_to_s: String is abstract
1700 end