1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
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
14 # Most basic classes and methods.
16 # This module is the root of the module hierarchy.
17 # It provides a very minimal set of classes and services used as a
18 # foundation to define other classes and methods.
21 import end # Mark this module is a top level one. (must be only one)
28 ###############################################################################
30 ###############################################################################
32 # The root of the class hierarchy.
34 # Each other class implicitly specializes Object,
35 # therefore the services of Object are inherited by every other class and are usable
36 # on each value, including primitive types like integers (`Int`), strings (`String`) and arrays (`Array`).
38 # Note that `nullable Object`, not `Object`, is the root of the type hierarchy
39 # since the special value `null` is not considered as an instance of Object.
41 # Type of this instance, automatically specialized in every class
43 # A common use case of the virtual type `SELF` is to type an attribute and
44 # store another instance of the same type as `self`. It can also be used as as
45 # return type to a method producing a copy of `self` or returning an instance
46 # expected to be the exact same type as self.
48 # This virtual type must be used with caution as it can hinder specialization.
49 # In fact, it imposes strict restrictions on all sub-classes and their usage.
50 # For example, using `SELF` as a return type of a method `foo`
51 # forces all subclasses to ensure that `foo` returns the correct and updated
53 # A dangerous usage take the form of a method typed by `SELF` which creates
54 # and returns a new instance.
55 # If not correctly specialized, this method would break when invoked on a
58 # A general rule for safe usage of `SELF` is to ensure that inputs typed
59 # `SELF` are stored in attributes typed `SELF` and returned by methods typed
60 # `SELF`, pretty much the same things as you would do with parameter types.
63 # An internal hash code for the object based on its identity.
65 # Unless specific code, you should not use this method but
68 # As its name hints it, the internal hash code, is used internally
69 # to provide a hash value.
70 # It is also used by the `inspect` method to loosely identify objects
71 # and helps debugging.
76 # assert a.object_id == b.object_id
79 # The specific details of the internal hash code it let to the specific
80 # engine. The rules are the following:
82 # * The `object_id` MUST be invariant for the whole life of the object.
83 # * Two living instances of the same classes SHOULD NOT share the same `object_id`.
84 # * Two instances of different classes MIGHT share the same `object_id`.
85 # * The `object_id` of a garbage-collected instance MIGHT be reused by new instances.
86 # * The `object_id` of an object MIGHT be non constant across different executions.
88 # For instance, the `nitc` compiler uses the address of the object in memory
91 # TODO rename in something like `internal_hash_code`
92 fun object_id
: Int is intern
94 # Return true if `self` and `other` have the same dynamic type.
97 # assert 1.is_same_type(2)
98 # assert "Hello".is_same_type("World")
99 # assert not "Hello".is_same_type(2)
102 # The method returns false if the dynamic type of `other` is a subtype of the dynamic type of `self`
103 # (or the other way around).
105 # Unless specific code, you should not use this method because it is inconsistent
106 # with the fact that a subclass can be used in lieu of a superclass.
107 fun is_same_type
(other
: Object): Bool is intern
109 # Return true if `self` and `other` are the same instance (i.e. same identity).
115 # assert a.is_same_instance(b)
116 # assert not a.is_same_instance(c)
117 # assert a == c # because both buffers are empty
120 # Obviously, the identity of an object is preserved even if the object is mutated.
126 # assert x.is_same_instance(y)
129 # Unless specific code, you should use `==` instead of `is_same_instance` because
130 # most of the time is it the semantic (and user-defined) comparison that make sense.
132 # Moreover, relying on `is_same_instance` on objects you do not control
133 # might have unexpected effects when libraries reuse objects or intern them.
134 fun is_same_instance
(other
: nullable Object): Bool is intern
136 # Have `self` and `other` the same value?
140 # assert not 1 == "1"
141 # assert 1.to_s == "1"
144 # The exact meaning of *same value* is left to the subclasses.
145 # Implicitly, the default implementation, is `is_same_instance`.
147 # The laws of `==` are the following:
149 # * reflexivity `a.is_same_instance(b) implies a == b`
150 # * symmetry: `(a == b) == (b == a)`
151 # * transitivity: `(a == b) and (b == c) implies (a == c)`
153 # `==` might not be constant on some objects overtime because of their evolution.
159 # assert a == b and not a == c
161 # assert not a == b and a == c
164 # Lastly, `==` is highly linked with `hash` and a specific redefinition of `==` should
165 # usually be associated with a specific redefinition of `hash`.
167 # ENSURE `result implies self.hash == other.hash`
168 fun ==(other
: nullable Object): Bool do return self.is_same_instance
(other
)
170 # Have `self` and `other` different values?
172 # `!=` is equivalent with `not ==`.
173 fun !=(other
: nullable Object): Bool do return not (self == other
)
175 # Display self on stdout (debug only).
177 # This method MUST not be used by programs, it is here for debugging
178 # only and can be removed without any notice.
180 # TODO: rename to avoid blocking a good identifier like `output`.
188 # Display class name on stdout (debug only).
190 # This method MUST not be used by programs, it is here for debugging
191 # only and can be removed without any notice.
193 # TODO: rename to avoid blocking a good identifier like `output`.
194 fun output_class_name
is intern
196 # The hash code of the object.
198 # The hash code is used in many data-structures and algorithms to identify objects that might be equal.
199 # Therefore, the precise semantic of `hash` is highly linked with the semantic of `==`
200 # and the only law of `hash` is that `a == b implies a.hash == b.hash`.
203 # assert (1+1).hash == 2.hash
204 # assert 1.to_s.hash == "1".hash
207 # `hash` (like `==`) might not be constant on some objects over time because of their evolution.
213 # assert a.hash == b.hash
215 # assert a.hash == c.hash
216 # # There is a very high probability that `b.hash != c.hash`
219 # A specific redefinition of `==` should usually be associated with a specific redefinition of `hash`.
220 # Note that, unfortunately, a correct definition of `hash` that is lawful with `==` is sometime tricky
221 # and a cause of bugs.
223 # Without redefinition, `hash` is based on the `object_id` of the instance.
224 fun hash
: Int do return object_id
227 # The main class of the program.
229 # `Sys` is a singleton class, its only instance is accessible from everywhere with `sys`.
231 # Because of this, methods that should be accessible from everywhere, like `print` or `exit`,
232 # are defined in `Sys`.
233 # Moreover, unless there is an ambiguity with `self`, the receiver of a call to these methods is implicitly `sys`.
234 # Basically it means that the two following instructions are equivalent.
237 # print "Hello World"
238 # sys.print "Hello World"
241 # ## Methods Implicitly Defined in Sys
243 # `Sys` is the class where are defined top-level methods,
244 # i.e. those defined outside of any class like in a procedural language.
245 # Basically it means that
249 # fun foo do print "hello"
256 # fun foo print "hello"
259 # As a corollary, in a top-level method, `self` (the current receiver) is always `sys`.
261 # The main method of a program.
263 # In a module, the instructions defined outside any classes or methods
264 # (usually called the *main* of the module) is
265 # an implicit definition of this `main` method.
266 # Basically it means that the following program
269 # print "Hello World"
277 # print "Hello World"
283 # The entry point for the execution of the whole program.
285 # When a program starts, the following implicit sequence of instructions is executed
292 # Whereas the job of the `run` method is just to execute `main`.
294 # The only reason of the existence of `run` is to allow modules to refine it
295 # and inject specific work before or after the main part.
298 # Number of the last error
299 fun errno
: Int `{ return errno; `}
302 # Quit the program with a specific return code
303 fun exit(exit_value: Int) is intern
305 # Return the global sys object, the only instance of the `Sys` class.
306 fun sys: Sys is intern
309 ###############################################################################
311 ###############################################################################
313 # The ancestor of class where objects are in a total order.
314 # In order to work, the method '<' has to be redefined.
316 # What `self` can be compared to?
317 type OTHER: Comparable
319 # Is `self` lesser than `other
`?
320 fun <(other: OTHER): Bool is abstract
322 # not `other
` < `self`
323 # Note, the implementation must ensure that: `(x
<=y
) == (x
<y
or x
==y
)`
324 fun <=(other: OTHER): Bool do return not other < self
326 # not `self` < `other
`
327 # Note, the implementation must ensure that: `(x
>=y
) == (x
>y
or x
==y
)`
328 fun >=(other: OTHER): Bool do return not self < other
331 fun >(other: OTHER): Bool do return other < self
333 # -1 if <, +1 if > and 0 otherwise
334 # Note, the implementation must ensure that: (x<=>y == 0) == (x==y)
335 fun <=>(other: OTHER): Int
339 else if other < self then
347 fun is_between(c: OTHER, d: OTHER): Bool
349 return c <= self and self <= d
352 # The maximum between `self` and `other
` (prefers `self` if equals).
353 fun max(other: OTHER): OTHER
362 # The minimum between `self` and `c
` (prefer `self` if equals)
363 fun min(c: OTHER): OTHER
373 # Discrete total orders.
377 redef type OTHER: Discrete
380 fun successor(i: Int): OTHER is abstract
382 # The previous element.
383 fun predecessor(i: Int): OTHER is abstract
385 # The distance between self and d.
387 # assert 10.distance(15) == 5
388 # assert 'Z'.distance('A') == 25
389 fun distance(d: OTHER): Int
396 else if self > d then
404 while cursor < stop do
405 cursor = cursor.successor(1)
412 # Something that can be cloned
414 # This interface introduces the `clone
` method used to duplicate an instance
415 # Its specific semantic is left to the subclasses.
419 # The specific semantic of this method is left to the subclasses;
420 # Especially, if (and how) attributes are cloned (depth vs. shallow).
422 # As a rule of thumb, the principle of least astonishment should
423 # be used to guide the semantic.
425 # Note that as the returned clone depends on the semantic,
426 # the `==` method, if redefined, should ensure the equality
427 # between an object and its clone.
428 fun clone: SELF is abstract
431 # A numeric value supporting mathematical operations
435 redef type OTHER: Numeric
437 # Addition of `self` with `i
`
438 fun +(i: OTHER): OTHER is abstract
440 # Substraction of `i
` from `self`
441 fun -(i: OTHER): OTHER is abstract
444 fun -: OTHER is abstract
446 # Multiplication of `self` with `i
`
447 fun *(i: OTHER): OTHER is abstract
449 # Division of `self` with `i
`
450 fun /(i: OTHER): OTHER is abstract
452 # The integer part of `self`.
454 # assert (0.0).to_i == 0
455 # assert (0.9).to_i == 0
456 # assert (-0.9).to_i == 0
457 # assert (9.9).to_i == 9
458 # assert (-9.9).to_i == -9
459 fun to_i: Int is abstract
461 # The float equivalent of `self`
463 # assert 5.to_f == 5.0
464 # assert 5.to_f != 5 # Float and Int are not equals
465 fun to_f: Float is abstract
467 # The byte equivalent of `self`
469 # assert (-1).to_b == 0xFF.to_b
470 # assert (1.9).to_b == 1.to_b
471 fun to_b: Byte is abstract
473 # Is this the value of zero in its domain?
474 fun is_zero: Bool do return self == zero
476 # The value of zero in the domain of `self`
477 fun zero: OTHER is abstract
479 # The value of `val
` in the domain of `self`
481 # assert 1.0.value_of(2) == 2.0
482 # assert 1.0.value_of(2.0) == 2.0
483 # assert 1.value_of(2) == 2
484 # assert 1.value_of(2.0) == 2
485 fun value_of(val: Numeric): OTHER is abstract
488 ###############################################################################
490 ###############################################################################
493 # `true` and `false` are the only instances.
495 # Boolean are manipulated trough three special operators:
496 # `and`, `or`, `not`.
498 # Booleans are mainly used by conditional statement and loops.
500 redef fun object_id is intern
501 redef fun ==(b) is intern
502 redef fun !=(b) is intern
503 redef fun output is intern
504 redef fun hash do return to_i
506 # 1 if true and 0 if false
517 # Native floating point numbers.
518 # Corresponds to C float.
522 redef type OTHER: Float
524 redef fun object_id is intern
525 redef fun ==(i) is intern
526 redef fun !=(i) is intern
527 redef fun output is intern
529 redef fun <=(i) is intern
530 redef fun <(i) is intern
531 redef fun >=(i) is intern
532 redef fun >(i) is intern
534 redef fun +(i) is intern
535 redef fun - is intern
536 redef fun -(i) is intern
537 redef fun *(i) is intern
538 redef fun /(i) is intern
540 redef fun to_i is intern
541 redef fun to_f do return self
542 redef fun to_b is intern
544 redef fun zero do return 0.0
545 redef fun value_of(val) do return val.to_f
551 else if other < self then
558 redef fun is_between(c, d)
560 if self < c or d < self then
567 # Compare float numbers with a given precision.
569 # Because of the loss of precision in floating numbers,
570 # the `==` method is often not the best way to compare them.
573 # assert 0.01.is_approx(0.02, 0.1) == true
574 # assert 0.01.is_approx(0.02, 0.001) == false
576 fun is_approx(other, precision: Float): Bool
578 assert precision >= 0.0
579 return self <= other + precision and self >= other - precision
602 # Same as a C `unsigned char
`
607 redef type OTHER: Byte
609 redef fun successor(i) do return self + i.to_b
610 redef fun predecessor(i) do return self - i.to_b
612 redef fun object_id is intern
613 redef fun hash do return self.to_i
614 redef fun ==(i) is intern
615 redef fun !=(i) is intern
616 redef fun output is intern
618 redef fun <=(i) is intern
619 redef fun <(i) is intern
620 redef fun >=(i) is intern
621 redef fun >(i) is intern
622 redef fun +(i) is intern
624 # On an Byte, unary minus will return `(256 - self) % 256`
626 # assert -1u8 == 0xFFu8
627 # assert -0u8 == 0x00u8
628 redef fun - is intern
629 redef fun -(i) is intern
630 redef fun *(i) is intern
631 redef fun /(i) is intern
633 # Modulo of `self` with `i
`.
635 # Finds the remainder of division of `self` by `i
`.
637 # assert 5u8 % 2u8 == 1u8
638 # assert 10u8 % 2u8 == 0u8
639 fun %(i: Byte): Byte is intern
641 redef fun zero do return 0.to_b
642 redef fun value_of(val) do return val.to_b
644 # `i
` bits shift fo the left
646 # assert 5u8 << 1 == 10u8
647 fun <<(i: Int): Byte is intern `{ return self << i; `}
649 # `i` bits shift fo the right
651 # assert 5u8 >> 1 == 2u8
652 fun >>(i
: Int): Byte is intern `{ return self >> i; `}
654 # Returns the character equivalent of `self`
656 # REQUIRE: `self <= 127u8
`
657 fun ascii: Char is intern `{ return (uint32_t)self; `}
659 redef fun to_i
is intern
660 redef fun to_f
is intern
661 redef fun to_b
do return self
663 redef fun distance
(i
) do return (self - i
).to_i
669 else if other
< self then
676 redef fun is_between
(c
, d
)
678 if self < c
or d
< self then
703 # Is `self` an ASCII whitespace ?
704 fun is_whitespace
: Bool do return self == 0x7Fu
8 or self <= 0x20u
8
707 # Native integer numbers.
708 # Correspond to C int.
713 redef type OTHER: Int
715 redef fun successor
(i
) do return self + i
716 redef fun predecessor
(i
) do return self - i
718 redef fun object_id
is intern
719 redef fun hash
do return self
720 redef fun ==(i
) is intern
721 redef fun !=(i
) is intern
722 redef fun output
is intern
724 redef fun <=(i
) is intern
725 redef fun <(i
) is intern
726 redef fun >=(i
) is intern
727 redef fun >(i
) is intern
728 redef fun +(i
) is intern
730 redef fun - is intern
731 redef fun -(i
) is intern
732 redef fun *(i
) is intern
733 redef fun /(i
) is intern
735 # Modulo of `self` with `i`.
737 # Finds the remainder of division of `self` by `i`.
741 fun %(i
: Int): Int is intern
743 redef fun zero
do return 0
744 redef fun value_of
(val
) do return val
.to_i
746 # `i` bits shift fo the left
748 # assert 5 << 1 == 10
749 fun <<(i
: Int): Int is intern `{ return self << i; `}
751 # `i
` bits shift fo the right
754 fun >>(i: Int): Int is intern `{ return self >> i; `}
756 redef fun to_i
do return self
757 redef fun to_f
is intern
758 redef fun to_b
is intern
760 redef fun distance
(i
)
774 else if other
< self then
781 redef fun is_between
(c
, d
)
783 if self < c
or d
< self then
808 # The character which code point (unicode-wise) is `self`
810 # assert 65.code_point == 'A'
811 # assert 10.code_point == '\n'
812 # assert 0x220B.code_point == '∋'
813 fun code_point
: Char is intern `{ return (uint32_t)self; `}
815 # Number of digits of an integer in base `b
` (plus one if negative)
817 # assert 123.digit_count(10) == 3
818 # assert 123.digit_count(2) == 7 # 1111011 in binary
819 fun digit_count(b: Int): Int
821 if b == 10 then return digit_count_base_10
822 var d: Int # number of digits
823 var n: Int # current number
828 else if self == 0 then
837 n = n / b # euclidian division /
842 # Optimized version for base 10
843 fun digit_count_base_10: Int
855 if val < 10 then return result
856 if val < 100 then return result+1
857 if val < 1000 then return result+2
858 if val < 10000 then return result+3
864 # Return the corresponding digit character
865 # If 0 <= `self` <= 9, return the corresponding character.
866 # assert 5.to_c == '5'
867 # If 10 <= `self` <= 36, return the corresponding letter [a..z].
868 # assert 15.to_c == 'f'
871 assert self >= 0 and self <= 36 # TODO plan for this
873 return (self + '0'.code_point).code_point
875 return (self - 10 + 'a'.code_point).code_point
879 # The absolute value of self
881 # assert (-10).abs == 10
882 # assert 10.abs == 10
884 fun abs: Int do return if self >= 0 then self else -self
888 # Characters are denoted with simple quote.
889 # eg. `'a'` or `'\n'`.
892 redef type OTHER: Char
894 redef fun object_id is intern
898 }else if(self < 2048){
899 printf
("%c%c", 0xC0 | ((0x7C0 & self) >> 6), 0x80 | (0x3F & self));
900 }else if(self < 65536){
901 printf
("%c%c%c", 0xE0 | ((0xF000 & self) >> 12), 0x80 | ((0xFC0 & self) >> 6) ,0x80 | (0x3F & self));
902 }else if(self < 2097152){
903 printf
("%c%c%c%c", 0xF0 | ((0x1C0000 & self) >> 18), 0x80 | ((0x3F000 & self) >> 12), 0x80 | ((0xFC0 & self) >> 6), 0x80 | (0x3F & self));
909 redef fun hash do return code_point
910 redef fun ==(o) is intern
911 redef fun !=(o) is intern
913 redef fun <=(i) is intern
914 redef fun <(i) is intern
915 redef fun >=(i) is intern
916 redef fun >(i) is intern
918 redef fun successor(i) is intern
919 redef fun predecessor(i) is intern
921 redef fun distance(c)
923 var d = self.code_point - c.code_point
931 # If `self` is a digit then return this digit else return -1.
933 # assert '5'.to_i == 5
939 else if is_digit then
940 return self.code_point - '0'.code_point
942 return self.to_lower.code_point - 'a'.code_point + 10
946 # The ascii value of `self`
948 # assert 'a'.ascii == 97u8
949 # assert '\n'.ascii == 10u8
951 # REQUIRE: `is_ascii
`
952 fun ascii: Byte do return code_point.to_b
954 # The unicode code point value of `self`
956 # assert 'A'.code_point == 65
957 # assert '\n'.code_point == 10
958 # assert '∋'.code_point == 0x220B
959 fun code_point: Int is intern `{ return (long)self; `}
961 # Is `self` an ASCII character ?
963 # assert 'x'.is_ascii
964 # assert not 'ま'.is_ascii
965 fun is_ascii
: Bool do return code_point
<= 127
967 # Return the lower case version of self.
968 # If self is not a letter, then return self
970 # assert 'A'.to_lower == 'a'
971 # assert 'a'.to_lower == 'a'
972 # assert '$'.to_lower == '$'
976 return (code_point
+ ('a'.distance
('A'))).code_point
982 # Return the upper case version of self.
983 # If self is not a letter, then return self
985 # assert 'a'.to_upper == 'A'
986 # assert 'A'.to_upper == 'A'
987 # assert '$'.to_upper == '$'
991 return (code_point
- ('a'.distance
('A'))).code_point
997 # Is self a digit? (from '0' to '9')
999 # assert '0'.is_digit == true
1000 # assert '9'.is_digit == true
1001 # assert 'a'.is_digit == false
1004 return self >= '0' and self <= '9'
1007 # Is self a lower case letter? (from 'a' to 'z')
1009 # assert 'a'.is_lower == true
1010 # assert 'z'.is_lower == true
1011 # assert 'A'.is_lower == false
1012 # assert '$'.is_lower == false
1015 return self >= 'a' and self <= 'z'
1018 # Is self a upper case letter? (from 'A' to 'Z')
1020 # assert 'A'.is_upper == true
1021 # assert 'A'.is_upper == true
1022 # assert 'z'.is_upper == false
1023 # assert '$'.is_upper == false
1026 return self >= 'A' and self <= 'Z'
1029 # Is self a letter? (from 'A' to 'Z' and 'a' to 'z')
1031 # assert 'A'.is_letter == true
1032 # assert 'A'.is_letter == true
1033 # assert 'z'.is_letter == true
1034 # assert '$'.is_letter == false
1035 fun is_letter
: Bool
1037 return is_lower
or is_upper
1040 # Is self a whitespace character?
1042 # These correspond to the "Other" and "Separator" groups of the Unicode.
1044 # In the ASCII encoding, this is those <= to space (0x20) plus delete (0x7F).
1046 # assert 'A'.is_whitespace == false
1047 # assert ','.is_whitespace == false
1048 # assert ' '.is_whitespace == true
1049 # assert '\t'.is_whitespace == true
1050 fun is_whitespace
: Bool
1053 return i
<= 0x20 or i
== 0x7F
1057 # Pointer classes are used to manipulate extern C structures.
1058 extern class Pointer
1059 # Is the address behind this Object at NULL?
1060 fun address_is_null
: Bool `{ return self == NULL; `}
1062 # Free the memory pointed by this pointer
1063 fun free `{ free(self); `}
1066 # Task with a `main` method to be implemented by subclasses
1068 # This class is provided for compatibility between different parallelization systems.
1069 # It can be used to run a fragment of code on a different thread and
1070 # to register a reaction to UI events.
1073 # Main method of this task