2344659c75a88fc674f9d9e516d8a3e51aa1de15
[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 import collection
19 intrude import collection::array
20
21 `{
22 #include <stdio.h>
23 #include <string.h>
24 `}
25
26 ###############################################################################
27 # String #
28 ###############################################################################
29
30 # High-level abstraction for all text representations
31 abstract class Text
32 super Comparable
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[FlatText] is abstract
64
65 # Is the current Text empty (== "")
66 #
67 # assert "".is_empty
68 # assert not "foo".is_empty
69 fun is_empty: Bool do return self.length == 0
70
71 # Returns an empty Text of the right type
72 #
73 # This method is used internally to get the right
74 # implementation of an empty string.
75 protected fun empty: SELFTYPE is abstract
76
77 # Gets the first char of the Text
78 #
79 # DEPRECATED : Use self.chars.first instead
80 fun first: Char do return self.chars[0]
81
82 # Access a character at `index` in the string.
83 #
84 # assert "abcd"[2] == 'c'
85 #
86 # DEPRECATED : Use self.chars.[] instead
87 fun [](index: Int): Char do return self.chars[index]
88
89 # Gets the index of the first occurence of 'c'
90 #
91 # Returns -1 if not found
92 #
93 # DEPRECATED : Use self.chars.index_of instead
94 fun index_of(c: Char): Int
95 do
96 return index_of_from(c, 0)
97 end
98
99 # Gets the last char of self
100 #
101 # DEPRECATED : Use self.chars.last instead
102 fun last: Char do return self.chars[length-1]
103
104 # Gets the index of the first occurence of ´c´ starting from ´pos´
105 #
106 # Returns -1 if not found
107 #
108 # DEPRECATED : Use self.chars.index_of_from instead
109 fun index_of_from(c: Char, pos: Int): Int
110 do
111 var iter = self.chars.iterator_from(pos)
112 while iter.is_ok do
113 if iter.item == c then return iter.index
114 iter.next
115 end
116 return -1
117 end
118
119 # Gets the last index of char ´c´
120 #
121 # Returns -1 if not found
122 #
123 # DEPRECATED : Use self.chars.last_index_of instead
124 fun last_index_of(c: Char): Int
125 do
126 return last_index_of_from(c, length - 1)
127 end
128
129 # Return a null terminated char *
130 fun to_cstring: NativeString do return flatten.to_cstring
131
132 # The index of the last occurrence of an element starting from pos (in reverse order).
133 #
134 # var s = "/etc/bin/test/test.nit"
135 # assert s.last_index_of_from('/', s.length-1) == 13
136 # assert s.last_index_of_from('/', 12) == 8
137 #
138 # Returns -1 if not found
139 #
140 # DEPRECATED : Use self.chars.last_index_of_from instead
141 fun last_index_of_from(item: Char, pos: Int): Int
142 do
143 var iter = self.chars.reverse_iterator_from(pos)
144 while iter.is_ok do
145 if iter.item == item then return iter.index
146 iter.next
147 end
148 return -1
149 end
150
151 # Gets an iterator on the chars of self
152 #
153 # DEPRECATED : Use self.chars.iterator instead
154 fun iterator: Iterator[Char]
155 do
156 return self.chars.iterator
157 end
158
159
160 # Gets an Array containing the chars of self
161 #
162 # DEPRECATED : Use self.chars.to_a instead
163 fun to_a: Array[Char] do return chars.to_a
164
165 # Create a substring from `self` beginning at the `from` position
166 #
167 # assert "abcd".substring_from(1) == "bcd"
168 # assert "abcd".substring_from(-1) == "abcd"
169 # assert "abcd".substring_from(2) == "cd"
170 #
171 # As with substring, a `from` index < 0 will be replaced by 0
172 fun substring_from(from: Int): SELFTYPE
173 do
174 if from >= self.length then return empty
175 if from < 0 then from = 0
176 return substring(from, length - from)
177 end
178
179 # Does self have a substring `str` starting from position `pos`?
180 #
181 # assert "abcd".has_substring("bc",1) == true
182 # assert "abcd".has_substring("bc",2) == false
183 #
184 # Returns true iff all characters of `str` are presents
185 # at the expected index in `self.`
186 # The first character of `str` being at `pos`, the second
187 # character being at `pos+1` and so on...
188 #
189 # This means that all characters of `str` need to be inside `self`.
190 #
191 # assert "abcd".has_substring("xab", -1) == false
192 # assert "abcd".has_substring("cdx", 2) == false
193 #
194 # And that the empty string is always a valid substring.
195 #
196 # assert "abcd".has_substring("", 2) == true
197 # assert "abcd".has_substring("", 200) == true
198 fun has_substring(str: String, pos: Int): Bool
199 do
200 if str.is_empty then return true
201 if pos < 0 or pos + str.length > length then return false
202 var myiter = self.chars.iterator_from(pos)
203 var itsiter = str.chars.iterator
204 while myiter.is_ok and itsiter.is_ok do
205 if myiter.item != itsiter.item then return false
206 myiter.next
207 itsiter.next
208 end
209 if itsiter.is_ok then return false
210 return true
211 end
212
213 # Is this string prefixed by `prefix`?
214 #
215 # assert "abcd".has_prefix("ab") == true
216 # assert "abcbc".has_prefix("bc") == false
217 # assert "ab".has_prefix("abcd") == false
218 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
219
220 # Is this string suffixed by `suffix`?
221 #
222 # assert "abcd".has_suffix("abc") == false
223 # assert "abcd".has_suffix("bcd") == true
224 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
225
226 # If `self` contains only digits, return the corresponding integer
227 #
228 # assert "123".to_i == 123
229 # assert "-1".to_i == -1
230 fun to_i: Int
231 do
232 # Shortcut
233 return to_s.to_cstring.atoi
234 end
235
236 # If `self` contains a float, return the corresponding float
237 #
238 # assert "123".to_f == 123.0
239 # assert "-1".to_f == -1.0
240 # assert "-1.2e-3".to_f == -0.0012
241 fun to_f: Float
242 do
243 # Shortcut
244 return to_s.to_cstring.atof
245 end
246
247 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
248 #
249 # assert "ff".to_hex == 255
250 fun to_hex: Int do return a_to(16)
251
252 # If `self` contains only digits and letters, return the corresponding integer in a given base
253 #
254 # assert "120".a_to(3) == 15
255 fun a_to(base: Int) : Int
256 do
257 var i = 0
258 var neg = false
259
260 for j in [0..length[ do
261 var c = chars[j]
262 var v = c.to_i
263 if v > base then
264 if neg then
265 return -i
266 else
267 return i
268 end
269 else if v < 0 then
270 neg = true
271 else
272 i = i * base + v
273 end
274 end
275 if neg then
276 return -i
277 else
278 return i
279 end
280 end
281
282 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
283 #
284 # assert "123".is_numeric == true
285 # assert "1.2".is_numeric == true
286 # assert "1,2".is_numeric == true
287 # assert "1..2".is_numeric == false
288 fun is_numeric: Bool
289 do
290 var has_point_or_comma = false
291 for i in [0..length[ do
292 var c = chars[i]
293 if not c.is_numeric then
294 if (c == '.' or c == ',') and not has_point_or_comma then
295 has_point_or_comma = true
296 else
297 return false
298 end
299 end
300 end
301 return true
302 end
303
304 # Returns `true` if the string contains only Hex chars
305 #
306 # assert "048bf".is_hex == true
307 # assert "ABCDEF".is_hex == true
308 # assert "0G".is_hex == false
309 fun is_hex: Bool
310 do
311 for i in [0..length[ do
312 var c = chars[i]
313 if not (c >= 'a' and c <= 'f') and
314 not (c >= 'A' and c <= 'F') and
315 not (c >= '0' and c <= '9') then return false
316 end
317 return true
318 end
319
320 # Are all letters in `self` upper-case ?
321 #
322 # assert "HELLO WORLD".is_upper == true
323 # assert "%$&%!".is_upper == true
324 # assert "hello world".is_upper == false
325 # assert "Hello World".is_upper == false
326 fun is_upper: Bool
327 do
328 for i in [0..length[ do
329 var char = chars[i]
330 if char.is_lower then return false
331 end
332 return true
333 end
334
335 # Are all letters in `self` lower-case ?
336 #
337 # assert "hello world".is_lower == true
338 # assert "%$&%!".is_lower == true
339 # assert "Hello World".is_lower == false
340 fun is_lower: Bool
341 do
342 for i in [0..length[ do
343 var char = chars[i]
344 if char.is_upper then return false
345 end
346 return true
347 end
348
349 # Removes the whitespaces at the beginning of self
350 #
351 # assert " \n\thello \n\t".l_trim == "hello \n\t"
352 #
353 # `Char::is_whitespace` determines what is a whitespace.
354 fun l_trim: SELFTYPE
355 do
356 var iter = self.chars.iterator
357 while iter.is_ok do
358 if not iter.item.is_whitespace then break
359 iter.next
360 end
361 if iter.index == length then return self.empty
362 return self.substring_from(iter.index)
363 end
364
365 # Removes the whitespaces at the end of self
366 #
367 # assert " \n\thello \n\t".r_trim == " \n\thello"
368 #
369 # `Char::is_whitespace` determines what is a whitespace.
370 fun r_trim: SELFTYPE
371 do
372 var iter = self.chars.reverse_iterator
373 while iter.is_ok do
374 if not iter.item.is_whitespace then break
375 iter.next
376 end
377 if iter.index < 0 then return self.empty
378 return self.substring(0, iter.index + 1)
379 end
380
381 # Trims trailing and preceding white spaces
382 #
383 # assert " Hello World ! ".trim == "Hello World !"
384 # assert "\na\nb\tc\t".trim == "a\nb\tc"
385 #
386 # `Char::is_whitespace` determines what is a whitespace.
387 fun trim: SELFTYPE do return (self.l_trim).r_trim
388
389 # Is the string non-empty but only made of whitespaces?
390 #
391 # assert " \n\t ".is_whitespace == true
392 # assert " hello ".is_whitespace == false
393 # assert "".is_whitespace == false
394 #
395 # `Char::is_whitespace` determines what is a whitespace.
396 fun is_whitespace: Bool
397 do
398 if is_empty then return false
399 for c in self.chars do
400 if not c.is_whitespace then return false
401 end
402 return true
403 end
404
405 # Returns `self` removed from its last line terminator (if any).
406 #
407 # assert "Hello\n".chomp == "Hello"
408 # assert "Hello".chomp == "Hello"
409 #
410 # assert "\n".chomp == ""
411 # assert "".chomp == ""
412 #
413 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
414 # A single line terminator, the last one, is removed.
415 #
416 # assert "\r\n".chomp == ""
417 # assert "\r\n\n".chomp == "\r\n"
418 # assert "\r\n\r\n".chomp == "\r\n"
419 # assert "\r\n\r".chomp == "\r\n"
420 #
421 # Note: unlike with most IO methods like `Reader::read_line`,
422 # a single `\r` is considered here to be a line terminator and will be removed.
423 fun chomp: SELFTYPE
424 do
425 var len = length
426 if len == 0 then return self
427 var l = self.chars.last
428 if l == '\r' then
429 return substring(0, len-1)
430 else if l != '\n' then
431 return self
432 else if len > 1 and self.chars[len-2] == '\r' then
433 return substring(0, len-2)
434 else
435 return substring(0, len-1)
436 end
437 end
438
439 # Justify a self in a space of `length`
440 #
441 # `left` is the space ratio on the left side.
442 # * 0.0 for left-justified (no space at the left)
443 # * 1.0 for right-justified (all spaces at the left)
444 # * 0.5 for centered (half the spaces at the left)
445 #
446 # Examples
447 #
448 # assert "hello".justify(10, 0.0) == "hello "
449 # assert "hello".justify(10, 1.0) == " hello"
450 # assert "hello".justify(10, 0.5) == " hello "
451 #
452 # If `length` is not enough, `self` is returned as is.
453 #
454 # assert "hello".justify(2, 0.0) == "hello"
455 #
456 # REQUIRE: `left >= 0.0 and left <= 1.0`
457 # ENSURE: `self.length <= length implies result.length == length`
458 # ENSURE: `self.length >= length implies result == self`
459 fun justify(length: Int, left: Float): String
460 do
461 var diff = length - self.length
462 if diff <= 0 then return to_s
463 assert left >= 0.0 and left <= 1.0
464 var before = (diff.to_f * left).to_i
465 return " " * before + self + " " * (diff-before)
466 end
467
468 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
469 #
470 # This method is injective (two different inputs never produce the same
471 # output) and the returned string always respect the following rules:
472 #
473 # * Contains only US-ASCII letters, digits and underscores.
474 # * Never starts with a digit.
475 # * Never ends with an underscore.
476 # * Never contains two contiguous underscores.
477 #
478 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
479 # assert "__".to_cmangle == "_95d_95d"
480 # assert "__d".to_cmangle == "_95d_d"
481 # assert "_d_".to_cmangle == "_d_95d"
482 # assert "_42".to_cmangle == "_95d42"
483 # assert "foo".to_cmangle == "foo"
484 # assert "".to_cmangle == ""
485 fun to_cmangle: String
486 do
487 if is_empty then return ""
488 var res = new FlatBuffer
489 var underscore = false
490 var start = 0
491 var c = chars[0]
492
493 if c >= '0' and c <= '9' then
494 res.add('_')
495 res.append(c.ascii.to_s)
496 res.add('d')
497 start = 1
498 end
499 for i in [start..length[ do
500 c = chars[i]
501 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
502 res.add(c)
503 underscore = false
504 continue
505 end
506 if underscore then
507 res.append('_'.ascii.to_s)
508 res.add('d')
509 end
510 if c >= '0' and c <= '9' then
511 res.add(c)
512 underscore = false
513 else if c == '_' then
514 res.add(c)
515 underscore = true
516 else
517 res.add('_')
518 res.append(c.ascii.to_s)
519 res.add('d')
520 underscore = false
521 end
522 end
523 if underscore then
524 res.append('_'.ascii.to_s)
525 res.add('d')
526 end
527 return res.to_s
528 end
529
530 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
531 #
532 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
533 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
534 #
535 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
536 # Three digits are always used to avoid following digits to be interpreted as an element
537 # of the octal sequence.
538 #
539 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
540 #
541 # The exceptions are the common `\t` and `\n`.
542 fun escape_to_c: String
543 do
544 var b = new FlatBuffer
545 for i in [0..length[ do
546 var c = chars[i]
547 if c == '\n' then
548 b.append("\\n")
549 else if c == '\t' then
550 b.append("\\t")
551 else if c == '\0' then
552 b.append("\\000")
553 else if c == '"' then
554 b.append("\\\"")
555 else if c == '\'' then
556 b.append("\\\'")
557 else if c == '\\' then
558 b.append("\\\\")
559 else if c.ascii < 32 then
560 b.add('\\')
561 var oct = c.ascii.to_base(8, false)
562 # Force 3 octal digits since it is the
563 # maximum allowed in the C specification
564 if oct.length == 1 then
565 b.add('0')
566 b.add('0')
567 else if oct.length == 2 then
568 b.add('0')
569 end
570 b.append(oct)
571 else
572 b.add(c)
573 end
574 end
575 return b.to_s
576 end
577
578 # Escape additionnal characters
579 # The result might no be legal in C but be used in other languages
580 #
581 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
582 fun escape_more_to_c(chars: String): String
583 do
584 var b = new FlatBuffer
585 for c in escape_to_c.chars do
586 if chars.chars.has(c) then
587 b.add('\\')
588 end
589 b.add(c)
590 end
591 return b.to_s
592 end
593
594 # Escape to C plus braces
595 #
596 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
597 fun escape_to_nit: String do return escape_more_to_c("\{\}")
598
599 # Escape to POSIX Shell (sh).
600 #
601 # Abort if the text contains a null byte.
602 #
603 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
604 fun escape_to_sh: String do
605 var b = new FlatBuffer
606 b.chars.add '\''
607 for i in [0..length[ do
608 var c = chars[i]
609 if c == '\'' then
610 b.append("'\\''")
611 else
612 assert without_null_byte: c != '\0'
613 b.add(c)
614 end
615 end
616 b.chars.add '\''
617 return b.to_s
618 end
619
620 # Escape to include in a Makefile
621 #
622 # Unfortunately, some characters are not escapable in Makefile.
623 # These characters are `;`, `|`, `\`, and the non-printable ones.
624 # They will be rendered as `"?{hex}"`.
625 fun escape_to_mk: String do
626 var b = new FlatBuffer
627 for i in [0..length[ do
628 var c = chars[i]
629 if c == '$' then
630 b.append("$$")
631 else if c == ':' or c == ' ' or c == '#' then
632 b.add('\\')
633 b.add(c)
634 else if c.ascii < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
635 b.append("?{c.ascii.to_base(16, false)}")
636 else
637 b.add(c)
638 end
639 end
640 return b.to_s
641 end
642
643 # Return a string where Nit escape sequences are transformed.
644 #
645 # var s = "\\n"
646 # assert s.length == 2
647 # var u = s.unescape_nit
648 # assert u.length == 1
649 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
650 fun unescape_nit: String
651 do
652 var res = new FlatBuffer.with_capacity(self.length)
653 var was_slash = false
654 for i in [0..length[ do
655 var c = chars[i]
656 if not was_slash then
657 if c == '\\' then
658 was_slash = true
659 else
660 res.add(c)
661 end
662 continue
663 end
664 was_slash = false
665 if c == 'n' then
666 res.add('\n')
667 else if c == 'r' then
668 res.add('\r')
669 else if c == 't' then
670 res.add('\t')
671 else if c == '0' then
672 res.add('\0')
673 else
674 res.add(c)
675 end
676 end
677 return res.to_s
678 end
679
680 # Encode `self` to percent (or URL) encoding
681 #
682 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
683 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
684 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
685 fun to_percent_encoding: String
686 do
687 var buf = new FlatBuffer
688
689 for i in [0..length[ do
690 var c = chars[i]
691 if (c >= '0' and c <= '9') or
692 (c >= 'a' and c <= 'z') or
693 (c >= 'A' and c <= 'Z') or
694 c == '-' or c == '.' or
695 c == '_' or c == '~'
696 then
697 buf.add c
698 else buf.append "%{c.ascii.to_hex}"
699 end
700
701 return buf.to_s
702 end
703
704 # Decode `self` from percent (or URL) encoding to a clear string
705 #
706 # Replace invalid use of '%' with '?'.
707 #
708 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
709 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
710 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
711 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
712 # assert "incomplete %".from_percent_encoding == "incomplete ?"
713 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
714 fun from_percent_encoding: String
715 do
716 var buf = new FlatBuffer
717
718 var i = 0
719 while i < length do
720 var c = chars[i]
721 if c == '%' then
722 if i + 2 >= length then
723 # What follows % has been cut off
724 buf.add '?'
725 else
726 i += 1
727 var hex_s = substring(i, 2)
728 if hex_s.is_hex then
729 var hex_i = hex_s.to_hex
730 buf.add hex_i.ascii
731 i += 1
732 else
733 # What follows a % is not Hex
734 buf.add '?'
735 i -= 1
736 end
737 end
738 else buf.add c
739
740 i += 1
741 end
742
743 return buf.to_s
744 end
745
746 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
747 #
748 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
749 #
750 # 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>
751 fun html_escape: String
752 do
753 var buf = new FlatBuffer
754
755 for i in [0..length[ do
756 var c = chars[i]
757 if c == '&' then
758 buf.append "&amp;"
759 else if c == '<' then
760 buf.append "&lt;"
761 else if c == '>' then
762 buf.append "&gt;"
763 else if c == '"' then
764 buf.append "&#34;"
765 else if c == '\'' then
766 buf.append "&#39;"
767 else if c == '/' then
768 buf.append "&#47;"
769 else buf.add c
770 end
771
772 return buf.to_s
773 end
774
775 # Equality of text
776 # Two pieces of text are equals if thez have the same characters in the same order.
777 #
778 # assert "hello" == "hello"
779 # assert "hello" != "HELLO"
780 # assert "hello" == "hel"+"lo"
781 #
782 # Things that are not Text are not equal.
783 #
784 # assert "9" != '9'
785 # assert "9" != ['9']
786 # assert "9" != 9
787 #
788 # assert "9".chars.first == '9' # equality of Char
789 # assert "9".chars == ['9'] # equality of Sequence
790 # assert "9".to_i == 9 # equality of Int
791 redef fun ==(o)
792 do
793 if o == null then return false
794 if not o isa Text then return false
795 if self.is_same_instance(o) then return true
796 if self.length != o.length then return false
797 return self.chars == o.chars
798 end
799
800 # Lexicographical comparaison
801 #
802 # assert "abc" < "xy"
803 # assert "ABC" < "abc"
804 redef fun <(other)
805 do
806 var self_chars = self.chars.iterator
807 var other_chars = other.chars.iterator
808
809 while self_chars.is_ok and other_chars.is_ok do
810 if self_chars.item < other_chars.item then return true
811 if self_chars.item > other_chars.item then return false
812 self_chars.next
813 other_chars.next
814 end
815
816 if self_chars.is_ok then
817 return false
818 else
819 return true
820 end
821 end
822
823 # Escape string used in labels for graphviz
824 #
825 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
826 fun escape_to_dot: String
827 do
828 return escape_more_to_c("|\{\}<>")
829 end
830
831 # Flat representation of self
832 fun flatten: FlatText is abstract
833
834 private var hash_cache: nullable Int = null
835
836 redef fun hash
837 do
838 if hash_cache == null then
839 # djb2 hash algorithm
840 var h = 5381
841
842 for i in [0..length[ do
843 var char = chars[i]
844 h = h.lshift(5) + h + char.ascii
845 end
846
847 hash_cache = h
848 end
849 return hash_cache.as(not null)
850 end
851
852 # Gives the formatted string back as a Nit string with `args` in place
853 #
854 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
855 # assert "\\%1 This string".format("String") == "\\%1 This string"
856 fun format(args: Object...): String do
857 var s = new Array[Text]
858 var curr_st = 0
859 var i = 0
860 while i < length do
861 # Skip escaped characters
862 if self[i] == '\\' then
863 i += 1
864 # In case of format
865 else if self[i] == '%' then
866 var fmt_st = i
867 i += 1
868 var ciph_st = i
869 while i < length and self[i].is_numeric do
870 i += 1
871 end
872 i -= 1
873 var fmt_end = i
874 var ciph_len = fmt_end - ciph_st + 1
875 s.push substring(curr_st, fmt_st - curr_st)
876 s.push args[substring(ciph_st, ciph_len).to_i - 1].to_s
877 curr_st = i + 1
878 end
879 i += 1
880 end
881 s.push substring(curr_st, length - curr_st)
882 return s.to_s
883 end
884
885 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
886 #
887 # Basically a high-level synonym of NativeString::copy_to
888 #
889 # REQUIRE: `n` must be large enough to contain `len` bytes
890 #
891 # var ns = new NativeString(8)
892 # "Text is String".copy_to_native(ns, 8, 2, 0)
893 # assert ns.to_s_with_length(8) == "xt is St"
894 #
895 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
896 var mypos = src_offset
897 var itspos = dest_offset
898 while n > 0 do
899 dest[itspos] = self.chars[mypos]
900 itspos += 1
901 mypos += 1
902 n -= 1
903 end
904 end
905
906 end
907
908 # All kinds of array-based text representations.
909 abstract class FlatText
910 super Text
911
912 # Underlying C-String (`char*`)
913 #
914 # Warning : Might be void in some subclasses, be sure to check
915 # if set before using it.
916 private var items: NativeString is noinit
917
918 # Real items, used as cache for to_cstring is called
919 private var real_items: nullable NativeString = null
920
921 # Returns a char* starting at position `index_from`
922 #
923 # WARNING: If you choose to use this service, be careful of the following.
924 #
925 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
926 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
927 # deallocated at any moment, rendering the pointer returned by this function invalid.
928 # Any access to freed memory may very likely cause undefined behaviour or a crash.
929 # (Failure to do so will most certainly result in long and painful debugging hours)
930 #
931 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
932 # then immediately return).
933 #
934 # As always, do not modify the content of the String in C code, if this is what you want
935 # copy locally the char* as Nit Strings are immutable.
936 private fun fast_cstring: NativeString is abstract
937
938 redef var length: Int = 0
939
940 redef fun output
941 do
942 var i = 0
943 while i < length do
944 items[i].output
945 i += 1
946 end
947 end
948
949 redef fun flatten do return self
950
951 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
952 items.copy_to(dest, n, src_offset, dest_offset)
953 end
954 end
955
956 # Abstract class for the SequenceRead compatible
957 # views on String and Buffer objects
958 private abstract class StringCharView
959 super SequenceRead[Char]
960
961 type SELFTYPE: Text
962
963 var target: SELFTYPE
964
965 redef fun is_empty do return target.is_empty
966
967 redef fun length do return target.length
968
969 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
970
971 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
972 end
973
974 # View on Buffer objects, extends Sequence
975 # for mutation operations
976 private abstract class BufferCharView
977 super StringCharView
978 super Sequence[Char]
979
980 redef type SELFTYPE: Buffer
981
982 end
983
984 # A `String` holds and manipulates an arbitrary sequence of characters.
985 #
986 # String objects may be created using literals.
987 #
988 # assert "Hello World!" isa String
989 abstract class String
990 super Text
991
992 redef type SELFTYPE: String is fixed
993
994 redef fun to_s do return self
995
996 # Concatenates `o` to `self`
997 #
998 # assert "hello" + "world" == "helloworld"
999 # assert "" + "hello" + "" == "hello"
1000 fun +(o: Text): SELFTYPE is abstract
1001
1002 # Concatenates self `i` times
1003 #
1004 # assert "abc" * 4 == "abcabcabcabc"
1005 # assert "abc" * 1 == "abc"
1006 # assert "abc" * 0 == ""
1007 fun *(i: Int): SELFTYPE is abstract
1008
1009 # Insert `s` at `pos`.
1010 #
1011 # assert "helloworld".insert_at(" ", 5) == "hello world"
1012 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1013
1014 redef fun substrings is abstract
1015
1016 # Returns a reversed version of self
1017 #
1018 # assert "hello".reversed == "olleh"
1019 # assert "bob".reversed == "bob"
1020 # assert "".reversed == ""
1021 fun reversed: SELFTYPE is abstract
1022
1023 # A upper case version of `self`
1024 #
1025 # assert "Hello World!".to_upper == "HELLO WORLD!"
1026 fun to_upper: SELFTYPE is abstract
1027
1028 # A lower case version of `self`
1029 #
1030 # assert "Hello World!".to_lower == "hello world!"
1031 fun to_lower : SELFTYPE is abstract
1032
1033 # Takes a camel case `self` and converts it to snake case
1034 #
1035 # assert "randomMethodId".to_snake_case == "random_method_id"
1036 #
1037 # The rules are the following:
1038 #
1039 # An uppercase is always converted to a lowercase
1040 #
1041 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1042 #
1043 # An uppercase that follows a lowercase is prefixed with an underscore
1044 #
1045 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1046 #
1047 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1048 #
1049 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1050 #
1051 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1052 #
1053 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1054 fun to_snake_case: SELFTYPE
1055 do
1056 if self.is_lower then return self
1057
1058 var new_str = new FlatBuffer.with_capacity(self.length)
1059 var prev_is_lower = false
1060 var prev_is_upper = false
1061
1062 for i in [0..length[ do
1063 var char = chars[i]
1064 if char.is_lower then
1065 new_str.add(char)
1066 prev_is_lower = true
1067 prev_is_upper = false
1068 else if char.is_upper then
1069 if prev_is_lower then
1070 new_str.add('_')
1071 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1072 new_str.add('_')
1073 end
1074 new_str.add(char.to_lower)
1075 prev_is_lower = false
1076 prev_is_upper = true
1077 else
1078 new_str.add(char)
1079 prev_is_lower = false
1080 prev_is_upper = false
1081 end
1082 end
1083
1084 return new_str.to_s
1085 end
1086
1087 # Takes a snake case `self` and converts it to camel case
1088 #
1089 # assert "random_method_id".to_camel_case == "randomMethodId"
1090 #
1091 # If the identifier is prefixed by an underscore, the underscore is ignored
1092 #
1093 # assert "_private_field".to_camel_case == "_privateField"
1094 #
1095 # If `self` is upper, it is returned unchanged
1096 #
1097 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1098 #
1099 # If there are several consecutive underscores, they are considered as a single one
1100 #
1101 # assert "random__method_id".to_camel_case == "randomMethodId"
1102 fun to_camel_case: SELFTYPE
1103 do
1104 if self.is_upper then return self
1105
1106 var new_str = new FlatBuffer
1107 var is_first_char = true
1108 var follows_us = false
1109
1110 for i in [0..length[ do
1111 var char = chars[i]
1112 if is_first_char then
1113 new_str.add(char)
1114 is_first_char = false
1115 else if char == '_' then
1116 follows_us = true
1117 else if follows_us then
1118 new_str.add(char.to_upper)
1119 follows_us = false
1120 else
1121 new_str.add(char)
1122 end
1123 end
1124
1125 return new_str.to_s
1126 end
1127
1128 # Returns a capitalized `self`
1129 #
1130 # Letters that follow a letter are lowercased
1131 # Letters that follow a non-letter are upcased.
1132 #
1133 # SEE : `Char::is_letter` for the definition of letter.
1134 #
1135 # assert "jAVASCRIPT".capitalized == "Javascript"
1136 # assert "i am root".capitalized == "I Am Root"
1137 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1138 fun capitalized: SELFTYPE do
1139 if length == 0 then return self
1140
1141 var buf = new FlatBuffer.with_capacity(length)
1142
1143 var curr = chars[0].to_upper
1144 var prev = curr
1145 buf[0] = curr
1146
1147 for i in [1 .. length[ do
1148 prev = curr
1149 curr = self[i]
1150 if prev.is_letter then
1151 buf[i] = curr.to_lower
1152 else
1153 buf[i] = curr.to_upper
1154 end
1155 end
1156
1157 return buf.to_s
1158 end
1159 end
1160
1161 private class FlatSubstringsIter
1162 super Iterator[FlatText]
1163
1164 var tgt: nullable FlatText
1165
1166 redef fun item do
1167 assert is_ok
1168 return tgt.as(not null)
1169 end
1170
1171 redef fun is_ok do return tgt != null
1172
1173 redef fun next do tgt = null
1174 end
1175
1176 # Immutable strings of characters.
1177 class FlatString
1178 super FlatText
1179 super String
1180
1181 # Index in _items of the start of the string
1182 private var index_from: Int is noinit
1183
1184 # Indes in _items of the last item of the string
1185 private var index_to: Int is noinit
1186
1187 redef var chars: SequenceRead[Char] = new FlatStringCharView(self) is lazy
1188
1189 redef fun [](index)
1190 do
1191 # Check that the index (+ index_from) is not larger than indexTo
1192 # In other terms, if the index is valid
1193 assert index >= 0
1194 assert (index + index_from) <= index_to
1195 return items[index + index_from]
1196 end
1197
1198 ################################################
1199 # AbstractString specific methods #
1200 ################################################
1201
1202 redef fun reversed
1203 do
1204 var native = new NativeString(self.length + 1)
1205 var length = self.length
1206 var items = self.items
1207 var pos = 0
1208 var ipos = length-1
1209 while pos < length do
1210 native[pos] = items[ipos]
1211 pos += 1
1212 ipos -= 1
1213 end
1214 return native.to_s_with_length(self.length)
1215 end
1216
1217 redef fun fast_cstring do return items.fast_cstring(index_from)
1218
1219 redef fun substring(from, count)
1220 do
1221 assert count >= 0
1222
1223 if from < 0 then
1224 count += from
1225 if count < 0 then count = 0
1226 from = 0
1227 end
1228
1229 var new_from = index_from + from
1230
1231 if (new_from + count) > index_to then
1232 var new_len = index_to - new_from + 1
1233 if new_len <= 0 then return empty
1234 return new FlatString.with_infos(items, new_len, new_from, index_to)
1235 end
1236
1237 if count <= 0 then return empty
1238
1239 var to = new_from + count - 1
1240
1241 return new FlatString.with_infos(items, to - new_from + 1, new_from, to)
1242 end
1243
1244 redef fun empty do return "".as(FlatString)
1245
1246 redef fun to_upper
1247 do
1248 var outstr = new NativeString(self.length + 1)
1249 var out_index = 0
1250
1251 var myitems = self.items
1252 var index_from = self.index_from
1253 var max = self.index_to
1254
1255 while index_from <= max do
1256 outstr[out_index] = myitems[index_from].to_upper
1257 out_index += 1
1258 index_from += 1
1259 end
1260
1261 outstr[self.length] = '\0'
1262
1263 return outstr.to_s_with_length(self.length)
1264 end
1265
1266 redef fun to_lower
1267 do
1268 var outstr = new NativeString(self.length + 1)
1269 var out_index = 0
1270
1271 var myitems = self.items
1272 var index_from = self.index_from
1273 var max = self.index_to
1274
1275 while index_from <= max do
1276 outstr[out_index] = myitems[index_from].to_lower
1277 out_index += 1
1278 index_from += 1
1279 end
1280
1281 outstr[self.length] = '\0'
1282
1283 return outstr.to_s_with_length(self.length)
1284 end
1285
1286 redef fun output
1287 do
1288 var i = self.index_from
1289 var imax = self.index_to
1290 while i <= imax do
1291 items[i].output
1292 i += 1
1293 end
1294 end
1295
1296 ##################################################
1297 # String Specific Methods #
1298 ##################################################
1299
1300 # Low-level creation of a new string with given data.
1301 #
1302 # `items` will be used as is, without copy, to retrieve the characters of the string.
1303 # Aliasing issues is the responsibility of the caller.
1304 private init with_infos(items: NativeString, length: Int, from: Int, to: Int)
1305 do
1306 self.items = items
1307 self.length = length
1308 index_from = from
1309 index_to = to
1310 end
1311
1312 redef fun to_cstring: NativeString
1313 do
1314 if real_items != null then
1315 return real_items.as(not null)
1316 else
1317 var newItems = new NativeString(length + 1)
1318 self.items.copy_to(newItems, length, index_from, 0)
1319 newItems[length] = '\0'
1320 self.real_items = newItems
1321 return newItems
1322 end
1323 end
1324
1325 redef fun ==(other)
1326 do
1327 if not other isa FlatString then return super
1328
1329 if self.object_id == other.object_id then return true
1330
1331 var my_length = length
1332
1333 if other.length != my_length then return false
1334
1335 var my_index = index_from
1336 var its_index = other.index_from
1337
1338 var last_iteration = my_index + my_length
1339
1340 var itsitems = other.items
1341 var myitems = self.items
1342
1343 while my_index < last_iteration do
1344 if myitems[my_index] != itsitems[its_index] then return false
1345 my_index += 1
1346 its_index += 1
1347 end
1348
1349 return true
1350 end
1351
1352 redef fun <(other)
1353 do
1354 if not other isa FlatString then return super
1355
1356 if self.object_id == other.object_id then return false
1357
1358 var my_curr_char : Char
1359 var its_curr_char : Char
1360
1361 var curr_id_self = self.index_from
1362 var curr_id_other = other.index_from
1363
1364 var my_items = self.items
1365 var its_items = other.items
1366
1367 var my_length = self.length
1368 var its_length = other.length
1369
1370 var max_iterations = curr_id_self + my_length
1371
1372 while curr_id_self < max_iterations do
1373 my_curr_char = my_items[curr_id_self]
1374 its_curr_char = its_items[curr_id_other]
1375
1376 if my_curr_char != its_curr_char then
1377 if my_curr_char < its_curr_char then return true
1378 return false
1379 end
1380
1381 curr_id_self += 1
1382 curr_id_other += 1
1383 end
1384
1385 return my_length < its_length
1386 end
1387
1388 redef fun +(s)
1389 do
1390 var my_length = self.length
1391 var its_length = s.length
1392
1393 var total_length = my_length + its_length
1394
1395 var target_string = new NativeString(my_length + its_length + 1)
1396
1397 self.items.copy_to(target_string, my_length, index_from, 0)
1398 if s isa FlatString then
1399 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1400 else if s isa FlatBuffer then
1401 s.items.copy_to(target_string, its_length, 0, my_length)
1402 else
1403 var curr_pos = my_length
1404 for i in [0..s.length[ do
1405 var c = s.chars[i]
1406 target_string[curr_pos] = c
1407 curr_pos += 1
1408 end
1409 end
1410
1411 target_string[total_length] = '\0'
1412
1413 return target_string.to_s_with_length(total_length)
1414 end
1415
1416 redef fun *(i)
1417 do
1418 assert i >= 0
1419
1420 var my_length = self.length
1421
1422 var final_length = my_length * i
1423
1424 var my_items = self.items
1425
1426 var target_string = new NativeString(final_length + 1)
1427
1428 target_string[final_length] = '\0'
1429
1430 var current_last = 0
1431
1432 for iteration in [1 .. i] do
1433 my_items.copy_to(target_string, my_length, 0, current_last)
1434 current_last += my_length
1435 end
1436
1437 return target_string.to_s_with_length(final_length)
1438 end
1439
1440 redef fun hash
1441 do
1442 if hash_cache == null then
1443 # djb2 hash algorithm
1444 var h = 5381
1445 var i = index_from
1446
1447 var myitems = items
1448
1449 while i <= index_to do
1450 h = h.lshift(5) + h + myitems[i].ascii
1451 i += 1
1452 end
1453
1454 hash_cache = h
1455 end
1456
1457 return hash_cache.as(not null)
1458 end
1459
1460 redef fun substrings do return new FlatSubstringsIter(self)
1461 end
1462
1463 private class FlatStringReverseIterator
1464 super IndexedIterator[Char]
1465
1466 var target: FlatString
1467
1468 var target_items: NativeString
1469
1470 var curr_pos: Int
1471
1472 init with_pos(tgt: FlatString, pos: Int)
1473 do
1474 target = tgt
1475 target_items = tgt.items
1476 curr_pos = pos + tgt.index_from
1477 end
1478
1479 redef fun is_ok do return curr_pos >= target.index_from
1480
1481 redef fun item do return target_items[curr_pos]
1482
1483 redef fun next do curr_pos -= 1
1484
1485 redef fun index do return curr_pos - target.index_from
1486
1487 end
1488
1489 private class FlatStringIterator
1490 super IndexedIterator[Char]
1491
1492 var target: FlatString
1493
1494 var target_items: NativeString
1495
1496 var curr_pos: Int
1497
1498 init with_pos(tgt: FlatString, pos: Int)
1499 do
1500 target = tgt
1501 target_items = tgt.items
1502 curr_pos = pos + target.index_from
1503 end
1504
1505 redef fun is_ok do return curr_pos <= target.index_to
1506
1507 redef fun item do return target_items[curr_pos]
1508
1509 redef fun next do curr_pos += 1
1510
1511 redef fun index do return curr_pos - target.index_from
1512
1513 end
1514
1515 private class FlatStringCharView
1516 super StringCharView
1517
1518 redef type SELFTYPE: FlatString
1519
1520 redef fun [](index)
1521 do
1522 # Check that the index (+ index_from) is not larger than indexTo
1523 # In other terms, if the index is valid
1524 assert index >= 0
1525 var target = self.target
1526 assert (index + target.index_from) <= target.index_to
1527 return target.items[index + target.index_from]
1528 end
1529
1530 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1531
1532 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1533
1534 end
1535
1536 # A mutable sequence of characters.
1537 abstract class Buffer
1538 super Text
1539
1540 redef type SELFTYPE: Buffer is fixed
1541
1542 # Specific implementations MUST set this to `true` in order to invalidate caches
1543 protected var is_dirty = true
1544
1545 # Copy-On-Write flag
1546 #
1547 # If the `Buffer` was to_s'd, the next in-place altering
1548 # operation will cause the current `Buffer` to be re-allocated.
1549 #
1550 # The flag will then be set at `false`.
1551 protected var written = false
1552
1553 # Modifies the char contained at pos `index`
1554 #
1555 # DEPRECATED : Use self.chars.[]= instead
1556 fun []=(index: Int, item: Char) is abstract
1557
1558 # Adds a char `c` at the end of self
1559 #
1560 # DEPRECATED : Use self.chars.add instead
1561 fun add(c: Char) is abstract
1562
1563 # Clears the buffer
1564 #
1565 # var b = new FlatBuffer
1566 # b.append "hello"
1567 # assert not b.is_empty
1568 # b.clear
1569 # assert b.is_empty
1570 fun clear is abstract
1571
1572 # Enlarges the subsequent array containing the chars of self
1573 fun enlarge(cap: Int) is abstract
1574
1575 # Adds the content of text `s` at the end of self
1576 #
1577 # var b = new FlatBuffer
1578 # b.append "hello"
1579 # b.append "world"
1580 # assert b == "helloworld"
1581 fun append(s: Text) is abstract
1582
1583 # `self` is appended in such a way that `self` is repeated `r` times
1584 #
1585 # var b = new FlatBuffer
1586 # b.append "hello"
1587 # b.times 3
1588 # assert b == "hellohellohello"
1589 fun times(r: Int) is abstract
1590
1591 # Reverses itself in-place
1592 #
1593 # var b = new FlatBuffer
1594 # b.append("hello")
1595 # b.reverse
1596 # assert b == "olleh"
1597 fun reverse is abstract
1598
1599 # Changes each lower-case char in `self` by its upper-case variant
1600 #
1601 # var b = new FlatBuffer
1602 # b.append("Hello World!")
1603 # b.upper
1604 # assert b == "HELLO WORLD!"
1605 fun upper is abstract
1606
1607 # Changes each upper-case char in `self` by its lower-case variant
1608 #
1609 # var b = new FlatBuffer
1610 # b.append("Hello World!")
1611 # b.lower
1612 # assert b == "hello world!"
1613 fun lower is abstract
1614
1615 # Capitalizes each word in `self`
1616 #
1617 # Letters that follow a letter are lowercased
1618 # Letters that follow a non-letter are upcased.
1619 #
1620 # SEE: `Char::is_letter` for the definition of a letter.
1621 #
1622 # var b = new FlatBuffer.from("jAVAsCriPt")
1623 # b.capitalize
1624 # assert b == "Javascript"
1625 # b = new FlatBuffer.from("i am root")
1626 # b.capitalize
1627 # assert b == "I Am Root"
1628 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1629 # b.capitalize
1630 # assert b == "Ab_C -Ab0C Ab\nC"
1631 fun capitalize do
1632 if length == 0 then return
1633 var c = self[0].to_upper
1634 self[0] = c
1635 var prev = c
1636 for i in [1 .. length[ do
1637 prev = c
1638 c = self[i]
1639 if prev.is_letter then
1640 self[i] = c.to_lower
1641 else
1642 self[i] = c.to_upper
1643 end
1644 end
1645 end
1646
1647 redef fun hash
1648 do
1649 if is_dirty then hash_cache = null
1650 return super
1651 end
1652
1653 # In Buffers, the internal sequence of character is mutable
1654 # Thus, `chars` can be used to modify the buffer.
1655 redef fun chars: Sequence[Char] is abstract
1656 end
1657
1658 # Mutable strings of characters.
1659 class FlatBuffer
1660 super FlatText
1661 super Buffer
1662
1663 redef var chars: Sequence[Char] = new FlatBufferCharView(self) is lazy
1664
1665 private var capacity: Int = 0
1666
1667 redef fun fast_cstring do return items.fast_cstring(0)
1668
1669 redef fun substrings do return new FlatSubstringsIter(self)
1670
1671 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1672 #
1673 # This happens when an operation modifies the current `Buffer` and
1674 # the Copy-On-Write flag `written` is set at true.
1675 private fun reset do
1676 var nns = new NativeString(capacity)
1677 items.copy_to(nns, length, 0, 0)
1678 items = nns
1679 written = false
1680 end
1681
1682 redef fun [](index)
1683 do
1684 assert index >= 0
1685 assert index < length
1686 return items[index]
1687 end
1688
1689 redef fun []=(index, item)
1690 do
1691 is_dirty = true
1692 if index == length then
1693 add(item)
1694 return
1695 end
1696 if written then reset
1697 assert index >= 0 and index < length
1698 items[index] = item
1699 end
1700
1701 redef fun add(c)
1702 do
1703 is_dirty = true
1704 if capacity <= length then enlarge(length + 5)
1705 items[length] = c
1706 length += 1
1707 end
1708
1709 redef fun clear do
1710 is_dirty = true
1711 if written then reset
1712 length = 0
1713 end
1714
1715 redef fun empty do return new FlatBuffer
1716
1717 redef fun enlarge(cap)
1718 do
1719 var c = capacity
1720 if cap <= c then return
1721 while c <= cap do c = c * 2 + 2
1722 # The COW flag can be set at false here, since
1723 # it does a copy of the current `Buffer`
1724 written = false
1725 var a = new NativeString(c+1)
1726 if length > 0 then items.copy_to(a, length, 0, 0)
1727 items = a
1728 capacity = c
1729 end
1730
1731 redef fun to_s: String
1732 do
1733 written = true
1734 if length == 0 then items = new NativeString(1)
1735 return new FlatString.with_infos(items, length, 0, length - 1)
1736 end
1737
1738 redef fun to_cstring
1739 do
1740 if is_dirty then
1741 var new_native = new NativeString(length + 1)
1742 new_native[length] = '\0'
1743 if length > 0 then items.copy_to(new_native, length, 0, 0)
1744 real_items = new_native
1745 is_dirty = false
1746 end
1747 return real_items.as(not null)
1748 end
1749
1750 # Create a new empty string.
1751 init do end
1752
1753 # Low-level creation a new buffer with given data.
1754 #
1755 # `items` will be used as is, without copy, to store the characters of the buffer.
1756 # Aliasing issues is the responsibility of the caller.
1757 #
1758 # If `items` is shared, `written` should be set to true after the creation
1759 # so that a modification will do a copy-on-write.
1760 private init with_infos(items: NativeString, capacity, length: Int)
1761 do
1762 self.items = items
1763 self.length = length
1764 self.capacity = capacity
1765 end
1766
1767 # Create a new string copied from `s`.
1768 init from(s: Text)
1769 do
1770 capacity = s.length + 1
1771 length = s.length
1772 items = new NativeString(capacity)
1773 if s isa FlatString then
1774 s.items.copy_to(items, length, s.index_from, 0)
1775 else if s isa FlatBuffer then
1776 s.items.copy_to(items, length, 0, 0)
1777 else
1778 var curr_pos = 0
1779 for i in [0..s.length[ do
1780 var c = s.chars[i]
1781 items[curr_pos] = c
1782 curr_pos += 1
1783 end
1784 end
1785 end
1786
1787 # Create a new empty string with a given capacity.
1788 init with_capacity(cap: Int)
1789 do
1790 assert cap >= 0
1791 items = new NativeString(cap+1)
1792 capacity = cap
1793 length = 0
1794 end
1795
1796 redef fun append(s)
1797 do
1798 if s.is_empty then return
1799 is_dirty = true
1800 var sl = s.length
1801 if capacity < length + sl then enlarge(length + sl)
1802 if s isa FlatString then
1803 s.items.copy_to(items, sl, s.index_from, length)
1804 else if s isa FlatBuffer then
1805 s.items.copy_to(items, sl, 0, length)
1806 else
1807 var curr_pos = self.length
1808 for i in [0..s.length[ do
1809 var c = s.chars[i]
1810 items[curr_pos] = c
1811 curr_pos += 1
1812 end
1813 end
1814 length += sl
1815 end
1816
1817 # Copies the content of self in `dest`
1818 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1819 do
1820 var self_chars = self.chars
1821 var dest_chars = dest.chars
1822 for i in [0..len-1] do
1823 dest_chars[new_start+i] = self_chars[start+i]
1824 end
1825 end
1826
1827 redef fun substring(from, count)
1828 do
1829 assert count >= 0
1830 count += from
1831 if from < 0 then from = 0
1832 if count > length then count = length
1833 if from < count then
1834 var len = count - from
1835 var r_items = new NativeString(len)
1836 items.copy_to(r_items, len, from, 0)
1837 var r = new FlatBuffer.with_infos(r_items, len, len)
1838 return r
1839 else
1840 return new FlatBuffer
1841 end
1842 end
1843
1844 redef fun reverse
1845 do
1846 written = false
1847 var ns = new NativeString(capacity)
1848 var si = length - 1
1849 var ni = 0
1850 var it = items
1851 while si >= 0 do
1852 ns[ni] = it[si]
1853 ni += 1
1854 si -= 1
1855 end
1856 items = ns
1857 end
1858
1859 redef fun times(repeats)
1860 do
1861 var x = new FlatString.with_infos(items, length, 0, length - 1)
1862 for i in [1..repeats[ do
1863 append(x)
1864 end
1865 end
1866
1867 redef fun upper
1868 do
1869 if written then reset
1870 var it = items
1871 var id = length - 1
1872 while id >= 0 do
1873 it[id] = it[id].to_upper
1874 id -= 1
1875 end
1876 end
1877
1878 redef fun lower
1879 do
1880 if written then reset
1881 var it = items
1882 var id = length - 1
1883 while id >= 0 do
1884 it[id] = it[id].to_lower
1885 id -= 1
1886 end
1887 end
1888 end
1889
1890 private class FlatBufferReverseIterator
1891 super IndexedIterator[Char]
1892
1893 var target: FlatBuffer
1894
1895 var target_items: NativeString
1896
1897 var curr_pos: Int
1898
1899 init with_pos(tgt: FlatBuffer, pos: Int)
1900 do
1901 target = tgt
1902 if tgt.length > 0 then target_items = tgt.items
1903 curr_pos = pos
1904 end
1905
1906 redef fun index do return curr_pos
1907
1908 redef fun is_ok do return curr_pos >= 0
1909
1910 redef fun item do return target_items[curr_pos]
1911
1912 redef fun next do curr_pos -= 1
1913
1914 end
1915
1916 private class FlatBufferCharView
1917 super BufferCharView
1918
1919 redef type SELFTYPE: FlatBuffer
1920
1921 redef fun [](index) do return target.items[index]
1922
1923 redef fun []=(index, item)
1924 do
1925 assert index >= 0 and index <= length
1926 if index == length then
1927 add(item)
1928 return
1929 end
1930 target.items[index] = item
1931 end
1932
1933 redef fun push(c)
1934 do
1935 target.add(c)
1936 end
1937
1938 redef fun add(c)
1939 do
1940 target.add(c)
1941 end
1942
1943 fun enlarge(cap: Int)
1944 do
1945 target.enlarge(cap)
1946 end
1947
1948 redef fun append(s)
1949 do
1950 var s_length = s.length
1951 if target.capacity < s.length then enlarge(s_length + target.length)
1952 end
1953
1954 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1955
1956 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1957
1958 end
1959
1960 private class FlatBufferIterator
1961 super IndexedIterator[Char]
1962
1963 var target: FlatBuffer
1964
1965 var target_items: NativeString
1966
1967 var curr_pos: Int
1968
1969 init with_pos(tgt: FlatBuffer, pos: Int)
1970 do
1971 target = tgt
1972 if tgt.length > 0 then target_items = tgt.items
1973 curr_pos = pos
1974 end
1975
1976 redef fun index do return curr_pos
1977
1978 redef fun is_ok do return curr_pos < target.length
1979
1980 redef fun item do return target_items[curr_pos]
1981
1982 redef fun next do curr_pos += 1
1983
1984 end
1985
1986 ###############################################################################
1987 # Refinement #
1988 ###############################################################################
1989
1990 redef class Object
1991 # User readable representation of `self`.
1992 fun to_s: String do return inspect
1993
1994 # The class name of the object in NativeString format.
1995 private fun native_class_name: NativeString is intern
1996
1997 # The class name of the object.
1998 #
1999 # assert 5.class_name == "Int"
2000 fun class_name: String do return native_class_name.to_s
2001
2002 # Developer readable representation of `self`.
2003 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
2004 fun inspect: String
2005 do
2006 return "<{inspect_head}>"
2007 end
2008
2009 # Return "CLASSNAME:#OBJECTID".
2010 # This function is mainly used with the redefinition of the inspect method
2011 protected fun inspect_head: String
2012 do
2013 return "{class_name}:#{object_id.to_hex}"
2014 end
2015 end
2016
2017 redef class Bool
2018 # assert true.to_s == "true"
2019 # assert false.to_s == "false"
2020 redef fun to_s
2021 do
2022 if self then
2023 return once "true"
2024 else
2025 return once "false"
2026 end
2027 end
2028 end
2029
2030 redef class Int
2031
2032 # Wrapper of strerror C function
2033 private fun strerror_ext: NativeString is extern "strerror"
2034
2035 # Returns a string describing error number
2036 fun strerror: String do return strerror_ext.to_s
2037
2038 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
2039 # assume < to_c max const of char
2040 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
2041 do
2042 var n: Int
2043 # Sign
2044 if self < 0 then
2045 n = - self
2046 s.chars[0] = '-'
2047 else if self == 0 then
2048 s.chars[0] = '0'
2049 return
2050 else
2051 n = self
2052 end
2053 # Fill digits
2054 var pos = digit_count(base) - 1
2055 while pos >= 0 and n > 0 do
2056 s.chars[pos] = (n % base).to_c
2057 n = n / base # /
2058 pos -= 1
2059 end
2060 end
2061
2062 # C function to calculate the length of the `NativeString` to receive `self`
2063 private fun int_to_s_len: Int is extern "native_int_length_str"
2064
2065 # C function to convert an nit Int to a NativeString (char*)
2066 private fun native_int_to_s(nstr: NativeString, strlen: Int) is extern "native_int_to_s"
2067
2068 # return displayable int in base 10 and signed
2069 #
2070 # assert 1.to_s == "1"
2071 # assert (-123).to_s == "-123"
2072 redef fun to_s do
2073 # Fast case for common numbers
2074 if self == 0 then return "0"
2075 if self == 1 then return "1"
2076
2077 var nslen = int_to_s_len
2078 var ns = new NativeString(nslen + 1)
2079 ns[nslen] = '\0'
2080 native_int_to_s(ns, nslen + 1)
2081 return ns.to_s_with_length(nslen)
2082 end
2083
2084 # return displayable int in hexadecimal
2085 #
2086 # assert 1.to_hex == "1"
2087 # assert (-255).to_hex == "-ff"
2088 fun to_hex: String do return to_base(16,false)
2089
2090 # return displayable int in base base and signed
2091 fun to_base(base: Int, signed: Bool): String
2092 do
2093 var l = digit_count(base)
2094 var s = new FlatBuffer.from(" " * l)
2095 fill_buffer(s, base, signed)
2096 return s.to_s
2097 end
2098 end
2099
2100 redef class Float
2101 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
2102 #
2103 # assert 12.34.to_s == "12.34"
2104 # assert (-0120.030).to_s == "-120.03"
2105 #
2106 # see `to_precision` for a custom precision.
2107 redef fun to_s do
2108 var str = to_precision( 3 )
2109 if is_inf != 0 or is_nan then return str
2110 var len = str.length
2111 for i in [0..len-1] do
2112 var j = len-1-i
2113 var c = str.chars[j]
2114 if c == '0' then
2115 continue
2116 else if c == '.' then
2117 return str.substring( 0, j+2 )
2118 else
2119 return str.substring( 0, j+1 )
2120 end
2121 end
2122 return str
2123 end
2124
2125 # `String` representation of `self` with the given number of `decimals`
2126 #
2127 # assert 12.345.to_precision(0) == "12"
2128 # assert 12.345.to_precision(3) == "12.345"
2129 # assert (-12.345).to_precision(3) == "-12.345"
2130 # assert (-0.123).to_precision(3) == "-0.123"
2131 # assert 0.999.to_precision(2) == "1.00"
2132 # assert 0.999.to_precision(4) == "0.9990"
2133 fun to_precision(decimals: Int): String
2134 do
2135 if is_nan then return "nan"
2136
2137 var isinf = self.is_inf
2138 if isinf == 1 then
2139 return "inf"
2140 else if isinf == -1 then
2141 return "-inf"
2142 end
2143
2144 if decimals == 0 then return self.to_i.to_s
2145 var f = self
2146 for i in [0..decimals[ do f = f * 10.0
2147 if self > 0.0 then
2148 f = f + 0.5
2149 else
2150 f = f - 0.5
2151 end
2152 var i = f.to_i
2153 if i == 0 then return "0." + "0"*decimals
2154
2155 # Prepare both parts of the float, before and after the "."
2156 var s = i.abs.to_s
2157 var sl = s.length
2158 var p1
2159 var p2
2160 if sl > decimals then
2161 # Has something before the "."
2162 p1 = s.substring(0, sl-decimals)
2163 p2 = s.substring(sl-decimals, decimals)
2164 else
2165 p1 = "0"
2166 p2 = "0"*(decimals-sl) + s
2167 end
2168
2169 if i < 0 then p1 = "-" + p1
2170
2171 return p1 + "." + p2
2172 end
2173 end
2174
2175 redef class Char
2176 # assert 'x'.to_s == "x"
2177 redef fun to_s
2178 do
2179 var s = new FlatBuffer.with_capacity(1)
2180 s.chars[0] = self
2181 return s.to_s
2182 end
2183
2184 # Returns true if the char is a numerical digit
2185 #
2186 # assert '0'.is_numeric
2187 # assert '9'.is_numeric
2188 # assert not 'a'.is_numeric
2189 # assert not '?'.is_numeric
2190 fun is_numeric: Bool
2191 do
2192 return self >= '0' and self <= '9'
2193 end
2194
2195 # Returns true if the char is an alpha digit
2196 #
2197 # assert 'a'.is_alpha
2198 # assert 'Z'.is_alpha
2199 # assert not '0'.is_alpha
2200 # assert not '?'.is_alpha
2201 fun is_alpha: Bool
2202 do
2203 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2204 end
2205
2206 # Returns true if the char is an alpha or a numeric digit
2207 #
2208 # assert 'a'.is_alphanumeric
2209 # assert 'Z'.is_alphanumeric
2210 # assert '0'.is_alphanumeric
2211 # assert '9'.is_alphanumeric
2212 # assert not '?'.is_alphanumeric
2213 fun is_alphanumeric: Bool
2214 do
2215 return self.is_numeric or self.is_alpha
2216 end
2217 end
2218
2219 redef class Collection[E]
2220 # Concatenate elements.
2221 redef fun to_s
2222 do
2223 var s = new FlatBuffer
2224 for e in self do if e != null then s.append(e.to_s)
2225 return s.to_s
2226 end
2227
2228 # Concatenate and separate each elements with `sep`.
2229 #
2230 # assert [1, 2, 3].join(":") == "1:2:3"
2231 # assert [1..3].join(":") == "1:2:3"
2232 fun join(sep: Text): String
2233 do
2234 if is_empty then return ""
2235
2236 var s = new FlatBuffer # Result
2237
2238 # Concat first item
2239 var i = iterator
2240 var e = i.item
2241 if e != null then s.append(e.to_s)
2242
2243 # Concat other items
2244 i.next
2245 while i.is_ok do
2246 s.append(sep)
2247 e = i.item
2248 if e != null then s.append(e.to_s)
2249 i.next
2250 end
2251 return s.to_s
2252 end
2253 end
2254
2255 redef class Array[E]
2256
2257 # Fast implementation
2258 redef fun to_s
2259 do
2260 var l = length
2261 if l == 0 then return ""
2262 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2263 var its = _items
2264 var na = new NativeArray[String](l)
2265 var i = 0
2266 var sl = 0
2267 var mypos = 0
2268 while i < l do
2269 var itsi = its[i]
2270 if itsi == null then
2271 i += 1
2272 continue
2273 end
2274 var tmp = itsi.to_s
2275 sl += tmp.length
2276 na[mypos] = tmp
2277 i += 1
2278 mypos += 1
2279 end
2280 var ns = new NativeString(sl + 1)
2281 ns[sl] = '\0'
2282 i = 0
2283 var off = 0
2284 while i < mypos do
2285 var tmp = na[i]
2286 var tpl = tmp.length
2287 if tmp isa FlatString then
2288 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2289 off += tpl
2290 else
2291 for j in tmp.substrings do
2292 var s = j.as(FlatString)
2293 var slen = s.length
2294 s.items.copy_to(ns, slen, s.index_from, off)
2295 off += slen
2296 end
2297 end
2298 i += 1
2299 end
2300 return ns.to_s_with_length(sl)
2301 end
2302 end
2303
2304 redef class NativeArray[E]
2305 # Join all the elements using `to_s`
2306 #
2307 # REQUIRE: `self isa NativeArray[String]`
2308 # REQUIRE: all elements are initialized
2309 fun native_to_s: String
2310 do
2311 assert self isa NativeArray[String]
2312 var l = length
2313 var na = self
2314 var i = 0
2315 var sl = 0
2316 var mypos = 0
2317 while i < l do
2318 sl += na[i].length
2319 i += 1
2320 mypos += 1
2321 end
2322 var ns = new NativeString(sl + 1)
2323 ns[sl] = '\0'
2324 i = 0
2325 var off = 0
2326 while i < mypos do
2327 var tmp = na[i]
2328 var tpl = tmp.length
2329 if tmp isa FlatString then
2330 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2331 off += tpl
2332 else
2333 for j in tmp.substrings do
2334 var s = j.as(FlatString)
2335 var slen = s.length
2336 s.items.copy_to(ns, slen, s.index_from, off)
2337 off += slen
2338 end
2339 end
2340 i += 1
2341 end
2342 return ns.to_s_with_length(sl)
2343 end
2344 end
2345
2346 redef class Map[K,V]
2347 # Concatenate couple of 'key value'.
2348 # key and value are separated by `couple_sep`.
2349 # each couple is separated each couple with `sep`.
2350 #
2351 # var m = new ArrayMap[Int, String]
2352 # m[1] = "one"
2353 # m[10] = "ten"
2354 # assert m.join("; ", "=") == "1=one; 10=ten"
2355 fun join(sep: String, couple_sep: String): String
2356 do
2357 if is_empty then return ""
2358
2359 var s = new FlatBuffer # Result
2360
2361 # Concat first item
2362 var i = iterator
2363 var k = i.key
2364 var e = i.item
2365 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2366
2367 # Concat other items
2368 i.next
2369 while i.is_ok do
2370 s.append(sep)
2371 k = i.key
2372 e = i.item
2373 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2374 i.next
2375 end
2376 return s.to_s
2377 end
2378 end
2379
2380 ###############################################################################
2381 # Native classes #
2382 ###############################################################################
2383
2384 # Native strings are simple C char *
2385 extern class NativeString `{ char* `}
2386 # Creates a new NativeString with a capacity of `length`
2387 new(length: Int) is intern
2388
2389 # Returns a char* starting at `index`.
2390 #
2391 # WARNING: Unsafe for extern code, use only for temporary
2392 # pointer manipulation purposes (e.g. write to file or such)
2393 fun fast_cstring(index: Int): NativeString is intern
2394
2395 # Get char at `index`.
2396 fun [](index: Int): Char is intern
2397
2398 # Set char `item` at index.
2399 fun []=(index: Int, item: Char) is intern
2400
2401 # Copy `self` to `dest`.
2402 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2403
2404 # Position of the first nul character.
2405 fun cstring_length: Int
2406 do
2407 var l = 0
2408 while self[l] != '\0' do l += 1
2409 return l
2410 end
2411
2412 # Parse `self` as an Int.
2413 fun atoi: Int is intern
2414
2415 # Parse `self` as a Float.
2416 fun atof: Float is extern "atof"
2417
2418 redef fun to_s
2419 do
2420 return to_s_with_length(cstring_length)
2421 end
2422
2423 # Returns `self` as a String of `length`.
2424 fun to_s_with_length(length: Int): FlatString
2425 do
2426 assert length >= 0
2427 var str = new FlatString.with_infos(self, length, 0, length - 1)
2428 return str
2429 end
2430
2431 # Returns `self` as a new String.
2432 fun to_s_with_copy: FlatString
2433 do
2434 var length = cstring_length
2435 var new_self = new NativeString(length + 1)
2436 copy_to(new_self, length, 0, 0)
2437 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2438 new_self[length] = '\0'
2439 str.real_items = new_self
2440 return str
2441 end
2442 end
2443
2444 redef class Sys
2445 private var args_cache: nullable Sequence[String]
2446
2447 # The arguments of the program as given by the OS
2448 fun program_args: Sequence[String]
2449 do
2450 if _args_cache == null then init_args
2451 return _args_cache.as(not null)
2452 end
2453
2454 # The name of the program as given by the OS
2455 fun program_name: String
2456 do
2457 return native_argv(0).to_s
2458 end
2459
2460 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2461 private fun init_args
2462 do
2463 var argc = native_argc
2464 var args = new Array[String].with_capacity(0)
2465 var i = 1
2466 while i < argc do
2467 args[i-1] = native_argv(i).to_s
2468 i += 1
2469 end
2470 _args_cache = args
2471 end
2472
2473 # First argument of the main C function.
2474 private fun native_argc: Int is intern
2475
2476 # Second argument of the main C function.
2477 private fun native_argv(i: Int): NativeString is intern
2478 end
2479
2480 # Comparator that efficienlty use `to_s` to compare things
2481 #
2482 # The comparaison call `to_s` on object and use the result to order things.
2483 #
2484 # var a = [1, 2, 3, 10, 20]
2485 # (new CachedAlphaComparator).sort(a)
2486 # assert a == [1, 10, 2, 20, 3]
2487 #
2488 # Internally the result of `to_s` is cached in a HashMap to counter
2489 # uneficient implementation of `to_s`.
2490 #
2491 # Note: it caching is not usefull, see `alpha_comparator`
2492 class CachedAlphaComparator
2493 super Comparator
2494 redef type COMPARED: Object
2495
2496 private var cache = new HashMap[Object, String]
2497
2498 private fun do_to_s(a: Object): String do
2499 if cache.has_key(a) then return cache[a]
2500 var res = a.to_s
2501 cache[a] = res
2502 return res
2503 end
2504
2505 redef fun compare(a, b) do
2506 return do_to_s(a) <=> do_to_s(b)
2507 end
2508 end
2509
2510 # see `alpha_comparator`
2511 private class AlphaComparator
2512 super Comparator
2513 redef fun compare(a, b) do return a.to_s <=> b.to_s
2514 end
2515
2516 # Stateless comparator that naively use `to_s` to compare things.
2517 #
2518 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2519 # on a single instace. See `CachedAlphaComparator` as an alternative.
2520 #
2521 # var a = [1, 2, 3, 10, 20]
2522 # alpha_comparator.sort(a)
2523 # assert a == [1, 10, 2, 20, 3]
2524 fun alpha_comparator: Comparator do return once new AlphaComparator
2525
2526 # The arguments of the program as given by the OS
2527 fun args: Sequence[String]
2528 do
2529 return sys.program_args
2530 end