01e72e3c1e9dcc7ff5555acf2160852f1b056edc
[nit.git] / lib / standard / kernel.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 # Most minimal classes and methods.
15 # This module is the root of the standard module hierarchy.
16 module kernel
17
18 import end # Mark this module is a top level one. (must be only one)
19
20 `{
21 #include <errno.h>
22 `}
23
24 ###############################################################################
25 # System Classes #
26 ###############################################################################
27
28 # The root of the class hierarchy.
29 # Each class implicitly specialize Object.
30 #
31 # Currently, Object is also used to collect all top-level methods.
32 interface Object
33 # Type of this instance, automatically specialized in every class
34 #
35 # A common use case of the virtual type `SELF` is to type an attribute and
36 # store another instance of the same type as `self`. It can also be used as as
37 # return type to a method producing a copy of `self` or returning an instance
38 # expected to be the exact same type as self.
39 #
40 # This virtual type must be used with caution as it can hinder specialization.
41 # In fact, it imposes strict restrictions on all sub-classes and their usage.
42 # For example, using `SELF` as a return type of a method `foo`
43 # forces all subclasses to ensure that `foo` returns the correct and updated
44 # type.
45 # A dangerous usage take the form of a method typed by `SELF` which creates
46 # and returns a new instance.
47 # If not correctly specialized, this method would break when invoked on a
48 # sub-class.
49 #
50 # A general rule for safe usage of `SELF` is to ensure that inputs typed
51 # `SELF` are stored in attributes typed `SELF` and returned by methods typed
52 # `SELF`, pretty much the same things as you would do with parameter types.
53 type SELF: Object
54
55 # The unique object identifier in the class.
56 # Unless specific code, you should not use this method.
57 # The identifier is used internally to provide a hash value.
58 fun object_id: Int is intern
59
60 # Return true if `self` and `other` have the same dynamic type.
61 # Unless specific code, you should not use this method.
62 fun is_same_type(other: Object): Bool is intern
63
64 # Return true if `self` and `other` are the same instance.
65 # Unless specific code, you should use `==` instead.
66 fun is_same_instance(other: nullable Object): Bool is intern
67
68 # Have `self` and `other` the same value?
69 #
70 # The exact meaning of "same value" is let to the subclasses.
71 # Implicitly, the default implementation, is `is_same_instance`
72 fun ==(other: nullable Object): Bool do return self.is_same_instance(other)
73
74 # Have `self` and `other` different values?
75 #
76 # != is equivalent with "not ==".
77 fun !=(other: nullable Object): Bool do return not (self == other)
78
79 # Display self on stdout (debug only).
80 # This method MUST not be used by programs, it is here for debugging
81 # only and can be removed without any notice
82 fun output
83 do
84 '<'.output
85 object_id.output
86 '>'.output
87 end
88
89 # Display class name on stdout (debug only).
90 # This method MUST not be used by programs, it is here for debugging
91 # only and can be removed without any notice
92 fun output_class_name is intern
93
94 # The hash code of the object.
95 # Assuming that a == b -> a.hash == b.hash
96 #
97 # Without redefinition, it is based on the `object_id` of the instance.
98 fun hash: Int do return object_id / 8
99 end
100
101 # The main class of the program.
102 # `Sys` is a singleton class, its only instance is `sys` defined in `Object`.
103 # `sys` is used to invoke methods on the program on the system.
104 class Sys
105 # Instructions outside classes implicitly redefine this method.
106 fun main do end
107
108 # The entry point for the execution of the whole program.
109 # Its job is to call `main` but some modules may want to refine it
110 # and inject specific work before or after the main part.
111 fun run do main
112
113 # Number of the last error
114 fun errno: Int is extern `{
115 return errno;
116 `}
117 end
118
119 # Quit the program with a specific return code
120 fun exit(exit_value: Int) is intern
121
122 # Return the global sys object, the only instance of the `Sys` class.
123 fun sys: Sys is intern
124
125
126 ###############################################################################
127 # Abstract Classes #
128 ###############################################################################
129
130 # The ancestor of class where objects are in a total order.
131 # In order to work, the method '<' has to be redefined.
132 interface Comparable
133 # What `self` can be compared to?
134 type OTHER: Comparable
135
136 # Is `self` lesser than `other`?
137 fun <(other: OTHER): Bool is abstract
138
139 # not `other` < `self`
140 # Note, the implementation must ensure that: `(x<=y) == (x<y or x==y)`
141 fun <=(other: OTHER): Bool do return not other < self
142
143 # not `self` < `other`
144 # Note, the implementation must ensure that: `(x>=y) == (x>y or x==y)`
145 fun >=(other: OTHER): Bool do return not self < other
146
147 # `other` < `self`
148 fun >(other: OTHER): Bool do return other < self
149
150 # -1 if <, +1 if > and 0 otherwise
151 # Note, the implementation must ensure that: (x<=>y == 0) == (x==y)
152 fun <=>(other: OTHER): Int
153 do
154 if self < other then
155 return -1
156 else if other < self then
157 return 1
158 else
159 return 0
160 end
161 end
162
163 # c <= self <= d
164 fun is_between(c: OTHER, d: OTHER): Bool
165 do
166 return c <= self and self <= d
167 end
168
169 # The maximum between `self` and `other` (prefers `self` if equals).
170 fun max(other: OTHER): OTHER
171 do
172 if self < other then
173 return other
174 else
175 return self
176 end
177 end
178
179 # The minimum between `self` and `c` (prefer `self` if equals)
180 fun min(c: OTHER): OTHER
181 do
182 if c < self then
183 return c
184 else
185 return self
186 end
187 end
188 end
189
190 # Discrete total orders.
191 interface Discrete
192 super Comparable
193
194 redef type OTHER: Discrete
195
196 # The next element.
197 fun successor(i: Int): OTHER is abstract
198
199 # The previous element.
200 fun predecessor(i: Int): OTHER is abstract
201
202 # The distance between self and d.
203 #
204 # assert 10.distance(15) == 5
205 # assert 'Z'.distance('A') == 25
206 fun distance(d: OTHER): Int
207 do
208 var cursor: OTHER
209 var stop: OTHER
210 if self < d then
211 cursor = self
212 stop = d
213 else if self > d then
214 cursor = d
215 stop = self
216 else
217 return 0
218 end
219
220 var nb = 0
221 while cursor < stop do
222 cursor = cursor.successor(1)
223 nb += 1
224 end
225 return nb
226 end
227 end
228
229 # Something that can be cloned
230 #
231 # This interface introduces the `clone` method used to duplicate an instance
232 # Its specific semantic is let to the subclasses.
233 interface Cloneable
234 # Duplicate `self`
235 #
236 # The specific semantic of this method is let to the subclasses;
237 # Especially, if (and how) attributes are cloned (depth vs. shallow).
238 #
239 # As a rule of thumb, the principle of least astonishment should
240 # be used to guide the semantic.
241 #
242 # Note that as the returned clone depends on the semantic,
243 # the `==` method, if redefined, should ensure the equality
244 # between an object and its clone.
245 fun clone: SELF is abstract
246 end
247
248 # A numeric value supporting mathematical operations
249 interface Numeric
250 super Comparable
251
252 redef type OTHER: Numeric
253
254 # Addition of `self` with `i`
255 fun +(i: OTHER): OTHER is abstract
256
257 # Substraction of `i` from `self`
258 fun -(i: OTHER): OTHER is abstract
259
260 # Inverse of `self`
261 fun -: OTHER is abstract
262
263 # Multiplication of `self` with `i`
264 fun *(i: OTHER): OTHER is abstract
265
266 # Division of `self` with `i`
267 fun /(i: OTHER): OTHER is abstract
268
269 # The integer part of `self`.
270 #
271 # assert (0.0).to_i == 0
272 # assert (0.9).to_i == 0
273 # assert (-0.9).to_i == 0
274 # assert (9.9).to_i == 9
275 # assert (-9.9).to_i == -9
276 fun to_i: Int is abstract
277
278 # The float equivalent of `self`
279 #
280 # assert 5.to_f == 5.0
281 # assert 5.to_f != 5 # Float and Int are not equals
282 fun to_f: Float is abstract
283
284 # Is this the value of zero in its domain?
285 fun is_zero: Bool do return self == zero
286
287 # The value of zero in the domain of `self`
288 fun zero: OTHER is abstract
289
290 # The value of `val` in the domain of `self`
291 #
292 # assert 1.0.value_of(2) == 2.0
293 # assert 1.0.value_of(2.0) == 2.0
294 # assert 1.value_of(2) == 2
295 # assert 1.value_of(2.0) == 2
296 fun value_of(val: Numeric): OTHER is abstract
297 end
298
299 ###############################################################################
300 # Native classes #
301 ###############################################################################
302
303 # Native Booleans.
304 # `true` and `false` are the only instances.
305 #
306 # Boolean are manipulated trough three special operators:
307 # `and`, `or`, `not`.
308 #
309 # Booleans are mainly used by conditional statement and loops.
310 universal Bool
311 redef fun object_id is intern
312 redef fun ==(b) is intern
313 redef fun !=(b) is intern
314 redef fun output is intern
315 redef fun hash do return to_i
316
317 # 1 if true and 0 if false
318 fun to_i: Int
319 do
320 if self then
321 return 1
322 else
323 return 0
324 end
325 end
326 end
327
328 # Native floating point numbers.
329 # Corresponds to C float.
330 universal Float
331 super Numeric
332
333 redef type OTHER: Float
334
335 redef fun object_id is intern
336 redef fun ==(i) is intern
337 redef fun !=(i) is intern
338 redef fun output is intern
339
340 redef fun <=(i): Bool is intern
341 redef fun <(i): Bool is intern
342 redef fun >=(i): Bool is intern
343 redef fun >(i): Bool is intern
344
345 redef fun +(i) is intern
346 redef fun - is intern
347 redef fun -(i) is intern
348 redef fun *(i) is intern
349 redef fun /(i) is intern
350
351 redef fun to_i is intern
352 redef fun to_f do return self
353
354 redef fun zero do return 0.0
355 redef fun value_of(val) do return val.to_f
356
357 redef fun <=>(other)
358 do
359 if self < other then
360 return -1
361 else if other < self then
362 return 1
363 else
364 return 0
365 end
366 end
367
368 redef fun is_between(c, d)
369 do
370 if self < c or d < self then
371 return false
372 else
373 return true
374 end
375 end
376
377 # Compare float numbers with a given precision.
378 #
379 # Because of the loss of precision in floating numbers,
380 # the `==` method is often not the best way to compare them.
381 #
382 # ~~~
383 # assert 0.01.is_approx(0.02, 0.1) == true
384 # assert 0.01.is_approx(0.02, 0.001) == false
385 # ~~~
386 fun is_approx(other, precision: Float): Bool
387 do
388 assert precision >= 0.0
389 return self <= other + precision and self >= other - precision
390 end
391
392 redef fun max(other)
393 do
394 if self < other then
395 return other
396 else
397 return self
398 end
399 end
400
401 redef fun min(c)
402 do
403 if c < self then
404 return c
405 else
406 return self
407 end
408 end
409 end
410
411 # Native integer numbers.
412 # Correspond to C int.
413 universal Int
414 super Discrete
415 super Numeric
416
417 redef type OTHER: Int
418
419 redef fun successor(i) do return self + i
420 redef fun predecessor(i) do return self - i
421
422 redef fun object_id is intern
423 redef fun hash do return self
424 redef fun ==(i) is intern
425 redef fun !=(i) is intern
426 redef fun output is intern
427
428 redef fun <=(i) is intern
429 redef fun <(i) is intern
430 redef fun >=(i) is intern
431 redef fun >(i) is intern
432 redef fun +(i) is intern
433
434 redef fun - is intern
435 redef fun -(i) is intern
436 redef fun *(i) is intern
437 redef fun /(i) is intern
438
439 # Modulo of `self` with `i`.
440 #
441 # Finds the remainder of division of `self` by `i`.
442 #
443 # assert 5 % 2 == 1
444 # assert 10 % 2 == 0
445 fun %(i: Int): Int is intern
446
447 redef fun zero do return 0
448 redef fun value_of(val) do return val.to_i
449
450 # `i` bits shift fo the left (aka <<)
451 #
452 # assert 5.lshift(1) == 10
453 fun lshift(i: Int): Int is intern
454
455 # `i` bits shift fo the right (aka >>)
456 #
457 # assert 5.rshift(1) == 2
458 fun rshift(i: Int): Int is intern
459
460 redef fun to_i do return self
461 redef fun to_f is intern
462
463 redef fun distance(i)
464 do
465 var d = self - i
466 if d >= 0 then
467 return d
468 else
469 return -d
470 end
471 end
472
473 redef fun <=>(other)
474 do
475 if self < other then
476 return -1
477 else if other < self then
478 return 1
479 else
480 return 0
481 end
482 end
483
484 redef fun is_between(c, d)
485 do
486 if self < c or d < self then
487 return false
488 else
489 return true
490 end
491 end
492
493 redef fun max(other)
494 do
495 if self < other then
496 return other
497 else
498 return self
499 end
500 end
501
502 redef fun min(c)
503 do
504 if c < self then
505 return c
506 else
507 return self
508 end
509 end
510
511 # The character whose ASCII value is `self`.
512 #
513 # assert 65.ascii == 'A'
514 # assert 10.ascii == '\n'
515 fun ascii: Char is intern
516
517 # Number of digits of an integer in base `b` (plus one if negative)
518 #
519 # assert 123.digit_count(10) == 3
520 # assert 123.digit_count(2) == 7 # 1111011 in binary
521 fun digit_count(b: Int): Int
522 do
523 if b == 10 then return digit_count_base_10
524 var d: Int # number of digits
525 var n: Int # current number
526 # Sign
527 if self < 0 then
528 d = 1
529 n = - self
530 else if self == 0 then
531 return 1
532 else
533 d = 0
534 n = self
535 end
536 # count digits
537 while n > 0 do
538 d += 1
539 n = n / b # euclidian division /
540 end
541 return d
542 end
543
544 # Optimized version for base 10
545 fun digit_count_base_10: Int
546 do
547 var val: Int
548 var result: Int
549 if self < 0 then
550 result = 2
551 val = -self
552 else
553 result = 1
554 val = self
555 end
556 loop
557 if val < 10 then return result
558 if val < 100 then return result+1
559 if val < 1000 then return result+2
560 if val < 10000 then return result+3
561 val = val / 10000
562 result += 4
563 end
564 end
565
566 # Return the corresponding digit character
567 # If 0 <= `self` <= 9, return the corresponding character.
568 # assert 5.to_c == '5'
569 # If 10 <= `self` <= 36, return the corresponding letter [a..z].
570 # assert 15.to_c == 'f'
571 fun to_c: Char
572 do
573 assert self >= 0 and self <= 36 # TODO plan for this
574 if self < 10 then
575 return (self + '0'.ascii).ascii
576 else
577 return (self + ('a'.ascii - 10)).ascii
578 end
579 end
580
581 # The absolute value of self
582 #
583 # assert (-10).abs == 10
584 # assert 10.abs == 10
585 # assert 0.abs == 0
586 fun abs: Int
587 do
588 if self >= 0
589 then
590 return self
591 else
592 return -1 * self
593 end
594 end
595 end
596
597 # Native characters.
598 # Characters are denoted with simple quote.
599 # eg. `'a'` or `'\n'`.
600 universal Char
601 super Discrete
602 redef type OTHER: Char
603
604 redef fun object_id is intern
605 redef fun hash do return ascii
606 redef fun ==(o) is intern
607 redef fun !=(o) is intern
608 redef fun output is intern
609
610 redef fun <=(i) is intern
611 redef fun <(i) is intern
612 redef fun >=(i) is intern
613 redef fun >(i) is intern
614
615 redef fun successor(i) is intern
616 redef fun predecessor(i) is intern
617
618 redef fun distance(c)
619 do
620 var d = self.ascii - c.ascii
621 if d >= 0 then
622 return d
623 else
624 return -d
625 end
626 end
627
628 # If `self` is a digit then return this digit else return -1.
629 #
630 # assert '5'.to_i == 5
631 fun to_i: Int
632 do
633
634 if self == '-' then
635 return -1
636 else if is_digit then
637 return self.ascii - '0'.ascii
638 else
639 return self.to_lower.ascii - 'a'.ascii + 10
640 end
641 end
642
643 # the ascii value of self
644 #
645 # assert 'a'.ascii == 97
646 # assert '\n'.ascii == 10
647 fun ascii: Int is intern
648
649 # Return the lower case version of self.
650 # If self is not a letter, then return self
651 #
652 # assert 'A'.to_lower == 'a'
653 # assert 'a'.to_lower == 'a'
654 # assert '$'.to_lower == '$'
655 fun to_lower: Char
656 do
657 if is_upper then
658 return (ascii + ('a'.distance('A'))).ascii
659 else
660 return self
661 end
662 end
663
664 # Return the upper case version of self.
665 # If self is not a letter, then return self
666 #
667 # assert 'a'.to_upper == 'A'
668 # assert 'A'.to_upper == 'A'
669 # assert '$'.to_upper == '$'
670 fun to_upper: Char
671 do
672 if is_lower then
673 return (ascii - ('a'.distance('A'))).ascii
674 else
675 return self
676 end
677 end
678
679 # Is self a digit? (from '0' to '9')
680 #
681 # assert '0'.is_digit == true
682 # assert '9'.is_digit == true
683 # assert 'a'.is_digit == false
684 fun is_digit : Bool
685 do
686 return self >= '0' and self <= '9'
687 end
688
689 # Is self a lower case letter? (from 'a' to 'z')
690 #
691 # assert 'a'.is_lower == true
692 # assert 'z'.is_lower == true
693 # assert 'A'.is_lower == false
694 # assert '$'.is_lower == false
695 fun is_lower : Bool
696 do
697 return self >= 'a' and self <= 'z'
698 end
699
700 # Is self a upper case letter? (from 'A' to 'Z')
701 #
702 # assert 'A'.is_upper == true
703 # assert 'A'.is_upper == true
704 # assert 'z'.is_upper == false
705 # assert '$'.is_upper == false
706 fun is_upper : Bool
707 do
708 return self >= 'A' and self <= 'Z'
709 end
710
711 # Is self a letter? (from 'A' to 'Z' and 'a' to 'z')
712 #
713 # assert 'A'.is_letter == true
714 # assert 'A'.is_letter == true
715 # assert 'z'.is_letter == true
716 # assert '$'.is_letter == false
717 fun is_letter : Bool
718 do
719 return is_lower or is_upper
720 end
721
722 # Is self a whitespace character?
723 #
724 # These correspond to the "Other" and "Separator" groups of the Unicode.
725 #
726 # In the ASCII encoding, this is those <= to space (0x20) plus delete (0x7F).
727 #
728 # assert 'A'.is_whitespace == false
729 # assert ','.is_whitespace == false
730 # assert ' '.is_whitespace == true
731 # assert '\t'.is_whitespace == true
732 fun is_whitespace: Bool
733 do
734 var i = ascii
735 return i <= 0x20 or i == 0x7F
736 end
737 end
738
739 # Pointer classes are used to manipulate extern C structures.
740 extern class Pointer
741 # Is the address behind this Object at NULL?
742 fun address_is_null: Bool is extern "address_is_null"
743
744 # Free the memory pointed by this pointer
745 fun free is extern "free"
746 end