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 `{ return self << i; `}
649 # `i` bits shift fo the right
651 # assert 5u8 >> 1 == 2u8
652 fun >>(i
: Int): Byte `{ return self >> i; `}
654 redef fun to_i is intern
655 redef fun to_f is intern
656 redef fun to_b do return self
658 redef fun distance(i) do return (self - i).to_i
664 else if other < self then
671 redef fun is_between(c, d)
673 if self < c or d < self then
699 # Native integer numbers.
700 # Correspond to C int.
705 redef type OTHER: Int
707 redef fun successor(i) do return self + i
708 redef fun predecessor(i) do return self - i
710 redef fun object_id is intern
711 redef fun hash do return self
712 redef fun ==(i) is intern
713 redef fun !=(i) is intern
714 redef fun output is intern
716 redef fun <=(i) is intern
717 redef fun <(i) is intern
718 redef fun >=(i) is intern
719 redef fun >(i) is intern
720 redef fun +(i) is intern
722 redef fun - is intern
723 redef fun -(i) is intern
724 redef fun *(i) is intern
725 redef fun /(i) is intern
727 # Modulo of `self` with `i
`.
729 # Finds the remainder of division of `self` by `i
`.
733 fun %(i: Int): Int is intern
735 redef fun zero do return 0
736 redef fun value_of(val) do return val.to_i
738 # `i
` bits shift fo the left
740 # assert 5 << 1 == 10
741 fun <<(i: Int): Int `{ return self << i; `}
743 # `i` bits shift fo the right
746 fun >>(i
: Int): Int `{ return self >> i; `}
748 redef fun to_i do return self
749 redef fun to_f is intern
750 redef fun to_b is intern
752 redef fun distance(i)
766 else if other < self then
773 redef fun is_between(c, d)
775 if self < c or d < self then
800 # The character whose ASCII value is `self`.
802 # assert 65.ascii == 'A'
803 # assert 10.ascii == '\n'
804 fun ascii: Char is intern
806 # Number of digits of an integer in base `b
` (plus one if negative)
808 # assert 123.digit_count(10) == 3
809 # assert 123.digit_count(2) == 7 # 1111011 in binary
810 fun digit_count(b: Int): Int
812 if b == 10 then return digit_count_base_10
813 var d: Int # number of digits
814 var n: Int # current number
819 else if self == 0 then
828 n = n / b # euclidian division /
833 # Optimized version for base 10
834 fun digit_count_base_10: Int
846 if val < 10 then return result
847 if val < 100 then return result+1
848 if val < 1000 then return result+2
849 if val < 10000 then return result+3
855 # Return the corresponding digit character
856 # If 0 <= `self` <= 9, return the corresponding character.
857 # assert 5.to_c == '5'
858 # If 10 <= `self` <= 36, return the corresponding letter [a..z].
859 # assert 15.to_c == 'f'
862 assert self >= 0 and self <= 36 # TODO plan for this
864 return (self + '0'.ascii).ascii
866 return (self + ('a'.ascii - 10)).ascii
870 # The absolute value of self
872 # assert (-10).abs == 10
873 # assert 10.abs == 10
887 # Characters are denoted with simple quote.
888 # eg. `'a'` or `'\n'`.
891 redef type OTHER: Char
893 redef fun object_id is intern
897 }else if(self < 2048){
898 printf
("%c%c", 0xC0 | ((0x7C0 & self) >> 6), 0x80 | (0x3F & self));
899 }else if(self < 65536){
900 printf
("%c%c%c", 0xE0 | ((0xF000 & self) >> 12), 0x80 | ((0xFC0 & self) >> 6) ,0x80 | (0x3F & self));
901 }else if(self < 2097152){
902 printf
("%c%c%c%c", 0xF0 | ((0x1C0000 & self) >> 18), 0x80 | ((0x3F000 & self) >> 12), 0x80 | ((0xFC0 & self) >> 6), 0x80 | (0x3F & self));
908 redef fun hash do return ascii
909 redef fun ==(o) is intern
910 redef fun !=(o) is intern
912 redef fun <=(i) is intern
913 redef fun <(i) is intern
914 redef fun >=(i) is intern
915 redef fun >(i) is intern
917 redef fun successor(i) is intern
918 redef fun predecessor(i) is intern
920 redef fun distance(c)
922 var d = self.ascii - c.ascii
930 # If `self` is a digit then return this digit else return -1.
932 # assert '5'.to_i == 5
938 else if is_digit then
939 return self.ascii - '0'.ascii
941 return self.to_lower.ascii - 'a'.ascii + 10
945 # the ascii value of self
947 # assert 'a'.ascii == 97
948 # assert '\n'.ascii == 10
949 fun ascii: Int is intern
951 # Return the lower case version of self.
952 # If self is not a letter, then return self
954 # assert 'A'.to_lower == 'a'
955 # assert 'a'.to_lower == 'a'
956 # assert '$'.to_lower == '$'
960 return (ascii + ('a'.distance('A'))).ascii
966 # Return the upper case version of self.
967 # If self is not a letter, then return self
969 # assert 'a'.to_upper == 'A'
970 # assert 'A'.to_upper == 'A'
971 # assert '$'.to_upper == '$'
975 return (ascii - ('a'.distance('A'))).ascii
981 # Is self a digit? (from '0' to '9')
983 # assert '0'.is_digit == true
984 # assert '9'.is_digit == true
985 # assert 'a'.is_digit == false
988 return self >= '0' and self <= '9'
991 # Is self a lower case letter? (from 'a' to 'z')
993 # assert 'a'.is_lower == true
994 # assert 'z'.is_lower == true
995 # assert 'A'.is_lower == false
996 # assert '$'.is_lower == false
999 return self >= 'a' and self <= 'z'
1002 # Is self a upper case letter? (from 'A' to 'Z')
1004 # assert 'A'.is_upper == true
1005 # assert 'A'.is_upper == true
1006 # assert 'z'.is_upper == false
1007 # assert '$'.is_upper == false
1010 return self >= 'A' and self <= 'Z'
1013 # Is self a letter? (from 'A' to 'Z' and 'a' to 'z')
1015 # assert 'A'.is_letter == true
1016 # assert 'A'.is_letter == true
1017 # assert 'z'.is_letter == true
1018 # assert '$'.is_letter == false
1019 fun is_letter : Bool
1021 return is_lower or is_upper
1024 # Is self a whitespace character?
1026 # These correspond to the "Other" and "Separator" groups of the Unicode.
1028 # In the ASCII encoding, this is those <= to space (0x20) plus delete (0x7F).
1030 # assert 'A'.is_whitespace == false
1031 # assert ','.is_whitespace == false
1032 # assert ' '.is_whitespace == true
1033 # assert '\t'.is_whitespace == true
1034 fun is_whitespace: Bool
1037 return i <= 0x20 or i == 0x7F
1041 # Pointer classes are used to manipulate extern C structures.
1042 extern class Pointer
1043 # Is the address behind this Object at NULL?
1044 fun address_is_null: Bool `{ return self == NULL; `}
1046 # Free the memory pointed by this pointer
1047 fun free
`{ free(self); `}