doc: typo and small fixes in nitreference
[nit.git] / doc / nitreference / nitreference-main.tex
1 % This file is part of Nit ( http://www.nitlanguage.org ).
2 %
3 % Copyright 2011 Jean Privat <jean@pryen.org>
4 %
5 % Licensed under the Apache License, Version 2.0 (the "License");
6 % you may not use this file except in compliance with the License.
7 % You may obtain a copy of the License at
8 %
9 % http://www.apache.org/licenses/LICENSE-2.0
10 %
11 % Unless required by applicable law or agreed to in writing, software
12 % distributed under the License is distributed on an "AS IS" BASIS,
13 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 % See the License for the specific language governing permissions and
15 % limitations under the License.
16 \noindent\textbf{A Concise Reference of the Nit Language}
17
18 This document attempts to be as short as possible while covering all features of the language in deepth.
19 It is not a real manual to learn the language since concepts are covered when required.
20 Forward and backward references about concepts are written like this~\goto{redef} which means Section~\ref*{redef}.
21 An index\goto{index} also lists concepts and keywords for an improved navigation.
22
23 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
24 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 \section{Basic Syntax}\label{syntax}\label{end}
26 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
29 The syntax of Nit belongs to the Pascal tradition and is inspired by various script languages (especially Ruby).
30 Its objective is readability.
31
32 Indentation is not meaningful in Nit; blocks usually starts by a specific keyword and finish with @end@.
33 Newlines are only meaningful at the end of declarations, at the end of statements, and after some specific keywords.
34 The philosophy is that the newline is ignored if something (a statement, a declaration, or whatever) obviously needs more input; while the newline terminates lines that seems completed.
35 See the complete Nit grammar for more details.
36
37 \begin{lst}
38 print 1 + 1 # a first complete statement that outputs "2"
39 print 2 + # the second statement is not yet finished
40 2 # the end of the second statement, outputs "4"
41 \end{lst}
42
43 Nit tries to achieve some uniformity in its usage of the common punctuation:
44 equal (@=@) is for assignment,
45 double equal (@==@) is for equality test\goto{Bool},
46 column (@:@) is for type declaration,
47 dot (@.@) is for polymorphism\goto{call},
48 comma (@,@) separates elements,
49 and quad (@::@) is for explicit designation.
50
51 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
52 \subsection{Identifiers}\label{identifier}
53 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
54
55 Identifiers of modules, variables, methods, attributes and labels must begin with a lowercase letter and can be followed by letters, digits, or underscores.
56 However, the usage of uppercase letters (and camelcase) is discouraged and the usage of underscore to separate words in identifiers is preferred: @some_identifier@.
57
58 Identifiers of classes and types must begin with a uppercase letter and can be followed by letters, digits, or underscores.
59 However, in classes, the usage of camelcase is preferred while formal types should be written all in uppercases: @SomeClass@ and @SOME_VIRTUAL_TYPE@.
60
61 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62 \subsection{Style}
63 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
64
65 While Nit does not enforce any kind of source code formatting, the following is encouraged:
66 \begin{itemize}
67 \item indentation is done with the tabulation character and is displayed as 8 spaces;
68 \item lines are less than 80 characters long;
69 \item binary operators have spaces around them: @4 + 5@, @x = 5@;
70 \item columns (@:@) and commas (@,@) have a space after them but not before: @var x: X@, @[1, 2, 3]@;
71 \item parenthesis and brackets do not need spaces around them;
72 \item superfluous parenthesis should be avoided;
73 \item the @do@ of methods\goto{fun} and the single @do@\goto{do} is on its own line and not indented;
74 \item the other @do@ are not on a newline.
75 \end{itemize}
76
77 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
78 \subsection{Comments and Documentation}\label{comment}
79 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
80
81 As in many script languages, comments begin with a sharp (@#@) and run up to the end of the line.
82 Currently, there is no multiline-comments.
83
84 A block of comments that precede any definition of module, class, or property, is considered as its documentation and will be displayed as such by the autodoc.
85 At this point, documentation is displayed verbatim (no special formatting or meta-information).
86
87 \begin{lst}
88 # doc. of foo
89 module foo
90
91 # doc. of Bar
92 class Bar
93 # doc. of baz
94 fun baz ...
95 end
96 \end{lst}
97
98 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
99 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
100 \section{Types, Literals and Operations}
101 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
103
104 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
105 \subsection{Object}\label{Object}
106 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
107
108 Nit is a full object language.
109 Each value is the instance of a class\goto{class}.
110 Even the basic types described in this section.
111
112 @Object@ is the root of the class hierarchy.
113 All other classes, including the basic ones, are a specialization of @Object@.
114 \goto{superclass}
115
116 Classes\goto{class}, methods\goto{fun} and operators\goto{operator} presented in this section are defined in the standard Nit library that is implicitly imported in every module\goto{module}.
117 Many other classes and methods are also defined in the standard library.
118 Please look at the specific standard library documentation for all details.
119
120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
121 \subsection{Int and Float}\label{Int}\label{Float}
122 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
123
124 @1@, @-1@ are @Int@ literals, and @1.0@, @-0.1@ are @Float@ literals.
125 Standard arithmetic operators are available with a common precedence rules: @*@, @/@, and @%@ (modulo) ; then @+@ and @-@.
126 Some operators can be composed with the assignment (@=@). \goto{operator}
127 \begin{lst}
128 var i = 5
129 i += 2
130 print i # outputs 7
131 \end{lst}
132
133 Conversion from @Int@ to @Float@ and @Float@ to @Int@ must be done with the @to_f@ and @to_i@ methods.
134
135 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
136 \subsection{String}\label{String}
137 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
138
139 Literal strings are enclosed within quotes (@"@).
140 Common escaping sequences are available (@\n@, @\t@, etc.)
141 To insert a value inside a literal string, include the values inside brackets (@{}@).
142 @+@ is the concatenation operator but is less efficient than the bracket form.
143
144 \begin{lst}
145 var i = 5
146 print "i={i}; i+1={i+1}" # outputs "i=5; i+1=6"
147 \end{lst}
148
149 All objects have a @to_s@ method that converts the object to a String.
150 @print@ is a top-level method\goto{toplevel} that takes any number of arguments\goto{vararg} and prints to the standard output.
151 @print@ always add a newline, another top-level method, @printn@, does not add the newline.
152
153 \begin{lst}
154 var x: String
155 x = 5.to_s # -> the String "5"
156 print x, 6 # outputs "56"
157 \end{lst}
158
159 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
160 \subsection{Bool}\label{Bool}\label{is}
161 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
162
163 @true@ and @false@ are the only two @Bool@ values.
164 Standard Boolean operators are available with the standard precedence rule: @not@; then @and@; then @or@.
165
166 Common comparison operators are available: @==@ and @!=@ on all objects; @<@, @>@, @<=@, @>=@ and @<=>@ on @Comparable@ objects (which include @Int@, @String@ and others). \goto{operator}
167
168 \begin{itemize}
169 \item @==@, @<@, @>@, @<=@, @>=@ and @<=>@ are standard Nit operators (it means they are redefinable)\goto{operator}.
170 \item @and@, @or@ and @not@ are not standard Nit operators: they are not redefinable, also they are lazy and have adaptive typing flow effects\goto{adaptive typing}.
171 \item @==@ is not for reference equality but for value equality (like @equals@ in Java).
172 There is a special reference equality operator, @is@, but it cannot be redefined and its usage is not recommended.
173 Note also that while @==@ is redefinable, it has a special adaptive typing flow effect when used with @null@\goto{null}.
174 \item @!=@ is not a standard Nit operator. In fact @x != y@ is syntactically equivalent to @not x == y@.
175 \end{itemize}
176
177 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
178 \subsection{Array}\label{Array}
179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
180
181 @Array@ is a generic class\goto{generic}, thus @Array[Int]@ denotes an array of integers and @Array[Array[Bool]]@ denotes an array of array of Booleans.
182 Literal arrays can be declared with the bracket notation (@[]@).
183 Empty arrays can also be instantiated with the @new@\goto{new} keyword and elements added with the @add@ method.
184 Elements can be retrieved or stored with the bracket operator\goto{operator}.
185
186 \begin{lst}
187 var a = [1, 2, 3, 4] # A literal array of integers
188 print a.join(":") # outputs "1:2:3:4"
189 var b = new Array[Int] # A new empty array of integers
190 b.add(10)
191 b.add_all(a)
192 b.add(20)
193 print b[0] # outputs "10"
194 print b.length # outputs "6"
195 b[1] = 30
196 print b.join(", ") # outputs "10, 30, 2, 3, 4, 20"
197 \end{lst}
198
199 Note that the type of literal arrays is deduced using the static type combination rule\goto{combination}.
200
201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
202 \subsection{Range}\label{Range}
203 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
204
205 @Range@ is also a generic class but accepts only @Discrete@ types (@Int@ is discrete).
206 There are two kinds of literal ranges, the open one @[1..5[@ that excludes the last element, and the closed one @[1..5]@ that includes it.
207
208 \begin{lst}
209 print([1..5[.join(":")) # outputs "1:2:3:4"
210 print([1..5].join(":")) # outputs "1:2:3:4:5"
211 \end{lst}
212
213 Ranges are mainly used in @for@ loops\goto{for}.
214
215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
216 \subsection{HashMap}\label{HashMap}
217 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
218
219 @HashMap@ is a generic class that associates keys with values.
220 There is no literal hashmap, therefore the @new@\goto{new} keyword is used to create an empty @HashMap@ and the bracket operators\goto{operator} are used to store and retrieve values.
221
222 \begin{lst}
223 var h = new HashMap[String, Int]
224 # h associates strings to integers
225 h["six"] = 6
226 print h["six"] + 1 # outputs "7"
227 \end{lst}
228
229 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
230 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
231 \section{Control Structures}\label{control}
232 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
233 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
234
235 Traditional procedural control structures exist in Nit.
236 They also often exist in two versions: a one-liner and a block version.
237
238 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
239 \subsection{Control Flow}\label{control flow}
240 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
241
242 Control structures dictate the control flow of the program.
243 Nit heavily refers to the control flow in its specification:
244 \begin{itemize}
245 \item No unreachable statement;
246 \item No usage of undefined variables\goto{var};
247 \item No function without a @return@ with a value\goto{fun};
248 \item Adaptive typing\goto{adaptive typing}.
249 \end{itemize}
250
251 Some structures alter the control flow but are not described in this section: @and@, @or@, @not@\goto{Bool}, @or else@\goto{or else} and @return@\goto{return}.
252
253 Note that the control flow is determined only from the position, the order and the nesting of the control structures.
254 The real value of the expressions used has no effect on the control flow analyses.
255 \begin{multicols}{2}
256 \begin{lst}
257 if true then
258 return
259 else
260 return
261 end
262 print 1
263 # Compile error:
264 # unreachable statement
265 \end{lst}
266 \columnbreak
267 \begin{lst}
268 if true then
269 return
270 end
271 print 1
272 # OK, but never executed
273 \end{lst}
274 \end{multicols}
275
276 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
277 \subsection{if}\label{if}
278 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
279
280 \begin{multicols}{2}
281 \begin{lst}
282 if exp then stm
283 if exp then stm else stm
284 if exp then
285 stms
286 end
287 \end{lst}
288 \columnbreak
289 \begin{lst}
290 if exp then
291 stms
292 else if exp then
293 stms
294 else
295 stms
296 end
297 \end{lst}
298 \end{multicols}
299 Note that the following example is invalid since the fist line is syntactically complete thus the newline terminate the whole @if@ structure\goto{syntax}; then an error is signaled since a statement cannot begin with @else@.
300 \begin{lst}
301 if exp then stm # OK: complete 'if' structure
302 else stm # Syntax error: unexpected 'else'
303 \end{lst}
304
305 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
306 \subsection{while}\label{while}
307 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
308
309 \begin{lst}
310 while exp do stm
311 while exp do
312 stms
313 end
314 \end{lst}
315
316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
317 \subsection{for}\label{for}
318 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
319
320 @for@ declares an automatic variable\goto{var} used to iterates on @Collection@ (@Array@ and @Range@ are both @Collection@).
321
322 \begin{lst}
323 for x in [1..5] do print x # outputs 1 2 3 4 5
324 for x in [1, 4, 6] do
325 print x # outputs 1 4 6
326 end
327 \end{lst}
328
329 In fact, @for@ is syntactic sugar for a closure\goto{closure}.
330
331 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
332 \subsection{loop}\label{loop}
333 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
334
335 Infinite loops are mainly used with breaks.
336 They are useful to implement \textit{until} loops or to simulate the \textit{exit when} control of Ada.
337
338 \begin{lst}
339 loop
340 stms
341 if exp then break
342 stms
343 end
344 \end{lst}
345
346 Note that @loop@ is different from @while true@ because the control flow does not consider the values of expression\goto{control flow}.
347
348 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
349 \subsection{do}\label{do}
350 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
351
352 Single @do@ are used to create scope for variables or to be attached with labeled breaks.
353
354 \begin{lst}
355 do
356 var x = 5
357 print x
358 end
359 # x is not defined here
360 \end{lst}
361
362 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
363 \subsection{break, continue and label}\label{break}\label{continue}\label{label}
364 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
365
366 Unlabeled @break@ exits the current @for@, @while@, @loop@, or closure\goto{closure}.
367 Unlabeled @continue@ skips the current @for@, @while@, @loop@, or closure.
368
369 @label@ can be used with @break@ or @continue@ to act on a specific control structure (not necessary the current one).
370 The corresponding @label@ must be defined after the @end@ keyword of the designated control structure.
371
372 \begin{lst}
373 for i in [0..width[ do
374 for j in [0..height[ do
375 if foo(i, j) then break label outer_loop
376 # The 'break' breaks the 'for i' loop
377 end
378 end label outer_loop
379 \end{lst}
380
381 @label@ can also be used with @break@ and single @do@ structures.
382
383 \begin{lst}
384 do
385 stmts
386 if expr then break label block
387 stmts
388 end label block
389 \end{lst}
390
391 In closures, @break@ and @continue@ can return values\goto{closure return}.
392
393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
394 \subsection{abort}\label{abort}
395 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
396
397 @abort@ stops the program with a fatal error and prints a stack trace.
398 Since there is currently no exception nor run-time-errors, abort is somewhat used to simulate them.
399
400 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
401 \subsection{assert}\label{assert}
402 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
403
404 @assert@ verifies that a given Boolean expression is true, or else it aborts.
405 An optional label can be precised, it will be displayed on the error message.
406 An optional @else@ can also be added and will be executed before the abort.
407 \begin{lst}
408 assert bla: whatever else
409 # "bla" is the label
410 # "whatever" is the expression to verify
411 print "Fatal error in module blablabla."
412 print "Please contact the customer service."
413 end
414 \end{lst}
415
416 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
417 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
418 \section{Local Variables and Static Typing}\label{var}\label{static type}
419 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
420 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
421
422 @var@ declares local variables.
423 In fact there is no global variable in Nit, so in this document \textit{variable} always refers to a local variable.
424 A variable is visible up to the end of the current control structure.
425 Two variables with the same name cannot coexist: no nesting nor masking.
426
427 Variables are bound to values.
428 A variable cannot be used unless it has a value in all control flow paths (\`a la Java).
429
430 \begin{lst}
431 var x
432 var y
433 if whatever then
434 x = 5
435 y = 6
436 else
437 x = 7
438 end
439 print x # OK
440 print y # Compile error: y is possibly not initialized
441 \end{lst}
442
443 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
444 \subsection{Adaptive Typing}\label{adaptive typing}
445 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
446
447 Nit features adaptive typing, which means that the static type of a variable can change according to:
448 the assignments of variables,
449 the control flow\goto{control flow},
450 and some special operators (@and@, @or@\goto{Bool}, @or else@\goto{or else}, @==@, @!=@\goto{null}, and @isa@\goto{isa}).
451
452 \begin{multicols}{2}
453 \begin{lst}
454 var x # a variable
455 x = 5
456 # static type is Int
457 print x + 1 # outputs 6
458 x = [6, 7]
459 # static type is Array[Int]
460 print x[0] # outputs "6"
461 \end{lst}
462 \columnbreak
463 \begin{lst}
464 var x
465 if whatever then
466 x = 5
467 else
468 x = 6
469 end
470 # Static type is Int
471 \end{lst}
472 \end{multicols}
473
474 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
475 \subsection{Variable Upper Bound}\label{upper bound}
476 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
477
478 An optional type information can be added to a variable declaration.
479 This type is used as an upper bound of the type of the variable.
480 When a initial value is given in a variable declaration without a specific type information, the static type of the initial value is used as an upper bound.
481 If no type and no initial value are given, the upper bound is set to @nullable Object@\goto{null}.
482
483 \begin{lst}
484 var x: Int # Upper bound is Int
485 x = "Hello" # Compile error: expected Int
486 var y: Object # Upper bound is Object
487 y = 5 # OK since Int specializes Object
488 var z = 5 # Upper bound is Int
489 z = "Hello" # Compile error: expected Int
490 var t: Object = 5 # Upper bound is Object
491 t = "Hello" # OK
492 \end{lst}
493
494 The adaptive typing flow is straightforward, therefore loops (@for@\goto{for}, @while@\goto{for}, @loop@\goto{for}) and closures\goto{closure} have a special requirement: on entry, the upper bound is set to the current static type; on exit, the upper bound is reset to its previous value.
495
496 \begin{lst}
497 var x: Object = ...
498 # static type is Object, upper bound is Object
499 x = 5
500 # static type is Int, bound remains Object
501 while x > 0 do
502 # static type remains Int, bound sets to Int
503 x -= 1 # OK
504 x = "Hello" # Compile error: expected Int
505 end
506 # static type is Int, bound reset to Object
507 x = "Hello" # OK
508 \end{lst}
509
510 \future{A possible future version of Nit will use a fixed point analysis, thus remove the need of resetting the upper bound.}
511
512 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
513 \subsection{Type Checks}\label{isa}
514 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
515
516 @isa@ tests if an object is an instance of a given type.
517 If the expression used in an @isa@ is a variable, then its static type is automatically adapted, therefore avoiding the need of a specific cast\goto{as}.
518
519 \begin{lst}
520 var x: Object = whatever
521 if x isa Int then
522 # static type of x is Int
523 print x * 10 # OK
524 end
525 \end{lst}
526
527 Remember that adaptive typing follows the control flow\goto{control flow}, including the Boolean operators\goto{Bool}.
528
529 \begin{lst}
530 var a: Array[Object] = ...
531 for i in a do
532 # the static type of i is Object
533 if not i isa Int then continue
534 # now the static type of i is Int
535 print i * 10 # OK
536 end
537 \end{lst}
538
539 An interesting example:
540 \begin{lst}
541 var max = 0
542 for i in whatever do
543 if i isa Int and i > max then max = i
544 # the > is valid since, in the right part
545 # of the "and", the static type of i is Int
546 end
547 \end{lst}
548
549 Note that type adaptation occurs only in an @isa@ if the target type is more specific that the current type.
550 \begin{lst}
551 var a: Collection[Int] = ...
552 if a isa Comparable then
553 # the static type is still Collection[Int]
554 # even if the dynamic type of a is a subclass
555 # of both Collection[Int] and Comparable
556 ...
557 end
558 \end{lst}
559
560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
561 \subsection{Nullable Types}\label{null}\label{nullable}\label{or else}\label{not null}
562 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
563
564 @null@ is a literal value that is only accepted by some specific static types.
565 However, thanks to adaptive typing, the static type management can be mainly automatic.
566
567 @nullable@ annotates types that can accept @null@ or an expression of a compatible nullable static type.
568
569 \begin{lst}
570 var x: nullable Int
571 var y: Int
572 x = 1 # OK
573 y = 1 # OK
574 x = null # OK
575 y = null # Compile error
576 x = y # OK
577 y = x # Compile error
578 \end{lst}
579
580 Adaptive typing works well with nullable types.
581
582 \begin{lst}
583 var x
584 if whatever then
585 x = 5
586 else
587 x = null
588 end
589 # The static type of x is nullable Int
590 \end{lst}
591
592 Moreover, like the @isa@ keyword, the @==@ and @!=@ operators can adapt the static type of a variable when compared to @null@.
593
594 \begin{lst}
595 var x: nullable Int = whatever
596 if x != null then
597 # The static type of x is Int (without nullable)
598 print x + 6
599 end
600 # The static type of x is nullable Int
601 \end{lst}
602
603 And another example:
604 \begin{lst}
605 var x: nullable Int = whatever
606 loop
607 if x == null then continue
608 # The static type of x is Int
609 end
610 \end{lst}
611
612 %FIXME: Pas clair il parrait
613 @or else@ can be used to compose a nullable expression with any other expression.
614 The value of @x or else y@ is @x@ if @x@ is not @null@ and is @y@ if @x@ is null.
615 The static type of @x or else y@ is the combination\goto{combination} of the type of @y@ and the not null version of the type of @x@.
616 \begin{lst}
617 var i: nullable Int = ...
618 var j = i or else 0
619 # the static type of j is Int (without nullable)
620 \end{lst}
621
622 Note that nullable types require a special management for attributes and constructors\goto{initialization}.
623
624 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
625 \subsection{Explicit Cast}\label{as}
626 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
627
628 @as@ casts an expression to a type.
629 The expression is either casted successfully or there is an @abort@\goto{abort}.
630
631 \begin{lst}
632 var x: Object = 5 # static type of x is Object
633 print x.as(Int) * 10 # outputs 50
634 print x.as(String) # aborts: cast failed
635 \end{lst}
636
637 Note that @as@ does not change the object nor does perform conversion.
638 \begin{lst}
639 var x: Object = 5 # static type of x is Object
640 print x.as(Int) + 10 # outputs "15"
641 print x.to_s + "10" # outputs "510"
642 \end{lst}
643
644
645 Because of type adaptation, @as@ is rarely used on variables.
646 @isa@ (sometime coupled with @assert@\goto{assert}) is preferred.
647 \begin{lst}
648 var x: Object = 5 # static type of x is Object
649 assert x isa Int
650 # static type of x is now Int
651 print x * 10 # outputs 50
652 \end{lst}
653
654 @as(not null)@ can be used to cast an expression typed by a nullable type to its non nullable version.
655 This form keeps the programmer from writing explicit static types.
656
657 \begin{lst}
658 var x: nullable Int = 5 # static type of x is nullable Int
659 print x.as(not null) * 10 # cast, outputs 50
660 print x.as(Int) * 10 # same cast, outputs 50
661 assert x != null # same cast, but type of x is now Int
662 print x * 10 # outputs 50
663 \end{lst}
664
665 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
666 \subsection{Static Type Combination Rule}\label{combination}
667 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
668
669 Adaptive typing, literal arrays\goto{Array}, @or else@\goto{or else}, and valued @break@ in closure\goto{closure} need to determine a static type by combining other static types.
670 This is done by using the following rule:
671 \begin{itemize}
672 \item The final type is @nullable@ if at least one of the types is @nullable@.
673 \item The final type is the static type that is more general than all the other types.
674 \item If there is no such a type, and the thing typed is a variable, then the final type is the upper bound type of the variable; else there is a compilation error.
675 \end{itemize}
676 % FIXME: the 'thing' typed?!
677
678 \begin{lst}
679 var d: Discrete = ...
680 # Note: Int < Discrete < Object
681 var x
682 if whatever then x = 1 else x = d
683 # static type is Discrete
684 if whatever then x = 1 else x = "1"
685 # static type is nullable Object (upper bound)
686 var a1 = [1, d] # a1 is a Array[Discrete]
687 var a2 = [1, "1"] # Compile error:
688 # incompatible types Int and String
689 \end{lst}
690
691 \future{A possible future version of Nit will introduce union types, thus simplifying the rule of combination.}
692
693 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
694 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
695 \section{Modules}\label{module}
696 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
697 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
698
699 @module@ declares the name of a module.
700 While optional it is recommended to use it, at least for documentation purpose\goto{comment}.
701 The basename of the source file must match the name declared with @module@.
702 The extension of the source file must be @nit@.
703
704 A module is made of, in order:
705 \begin{itemize}
706 \item the module declaration;
707 \item module importations;
708 \item class definitions (and refinements) \goto{class};
709 \item top-level function definitions (and redefinitions) \goto{toplevel};
710 \item main instructions \goto{toplevel}.
711 \end{itemize}
712
713 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
714 \subsection{Module Importation}\label{import}
715 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
716
717 @import@ declares dependencies between modules.
718 By default, a module publicly imports the module @standard@.
719 Dependencies must not produce cycles.
720 By importing a module, the importer module can see and use classes and properties defined in the imported module.
721
722 \begin{itemize}
723 \item @import@ indicates a public importation.
724 Importers of a given module will also import its publicly imported modules.
725 %Modules that import the current module will implicitly also import the other module.
726 An analogy is using @#include@ in a header file (@.h@) in C/C++.
727 \item @private import@ indicates a private importation.
728 Importers of a given module will not automatically import its privately imported modules.
729 An analogy is using @#include@ in a body file (@.c@) in C/C++.
730 %Modules that import the current module will not see the classes and properties imported.
731 %However, while the classes and properties imported are invisible, the information that the module import an other one is still public and required to compile and run the program.
732 \item @intrude import@ indicates an intrusive importation.
733 @intrude@ @import@ bypasses the @private@ visibility and gives to the importer module a full access on the imported module.
734 Such an import may only be considered when modules are strongly bounded and developed together.
735 The closest, but insufficient, analogy is something like including a body file in a body file in C/C++.
736 \end{itemize}
737
738 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
739 \subsection{Visibility}\label{visibility}
740 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
741
742 By default, all classes\goto{class}, methods\goto{fun}, constructors\goto{init} and virtual types\goto{type} are public which means freely usable by any importer module.
743 Once something is public it belongs to the API of the module and should not be changed.
744
745 @private@ indicates classes and methods that do not belong to the API.
746 They are still freely usable inside the module but are invisible in other modules (except those that use @intrude import@).
747
748 @protected@ indicates restricted methods and constructors.
749 Such methods belong to the API of the module but they can only be used with the @self@ receiver.
750 Basically, @protected@ methods are limited to the current class and its subclasses.
751 Note that inside the module (and in intrude importers), there is still no restriction.
752
753 Visibility of attributes is more specific and is detailed in its own section\goto{attribute visibility}.
754
755 \begin{multicols}{2}
756 \begin{lst}
757 module m1
758 class Foo
759 fun pub do ...
760 protected fun pro
761 do ...
762 private fun pri
763 do ...
764 end
765 private class Bar
766 fun pri2 do ...
767 end
768 var x: Foo = ...
769 var y: Bar = ...
770 # All OK, it is
771 # inside the module
772 x.foo
773 x.pro
774 x.pro
775 y.pri2
776 \end{lst}
777 \columnbreak
778 \begin{lst}
779 module m2
780 import m1
781 class Baz
782 super Foo
783 fun derp
784 do
785 self.pro # OK
786 end
787 end
788 var x: Foo = ...
789 x.pub # OK
790 x.pro # Compile error:
791 # pro is protected
792 x.pri # Compile error:
793 # unknown method pro
794
795 var y: Bar
796 # Compile error:
797 # unknown class Bar
798 \end{lst}
799 \end{multicols}
800
801 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
802 \subsection{Visibility Coherence}
803 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
804
805 In order to guarantee the coherence in the visibility, the following rules apply:
806 \begin{itemize}
807 \item Classes and properties privately imported are considered private: they are not exported and do not belong to the API of the importer.
808 \item Properties defined in a private class are private.
809 \item A static type is private if it contains a private class or a private virtual type\goto{type}.
810 \item Signatures of public and protected properties cannot contain a private static type.
811 \item Bounds of public generic class\goto{generic} and public virtual types\goto{type} cannot contain a private static type.
812 \end{itemize}
813
814 % FIXME: What about specialization links between a public class and a privately imported public class
815
816 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
817 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
818 \section{Classes}\label{class}
819 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
820 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
821
822 @interface@, @abstract class@, @class@ and @enum@ are the four kinds of classes. All these classes can be in multiple inheritance, can define new methods and redefine inherited method (yes, even interfaces). Here are the differences:
823 \begin{itemize}
824 \item interfaces can only specialize other interfaces, cannot have attributes, cannot have constructors, cannot be instantiated.
825 \item abstract classes cannot specialize enums, can have attributes, must have constructors, cannot be instantiated.
826 \item concrete classes (i.e. @class@) cannot specialize enums, can have attributes, must have constructors, can be instantiated.
827 \item enums (e.g. @Int@ or @Bool@) can only specialize interfaces, cannot have attributes, cannot have constructors, have proper instances but they are not instantiated by the programmer---it means no @new Int@. Note that at this point there is no user-defined enums.
828 \end{itemize}
829
830 All kinds of classes must have a name, can have some superclasses and can have some definitions of properties.
831 Properties are methods\goto{fun}, attributes\goto{attribute}, constructors\goto{init} and virtual types\goto{type}.
832 All kinds of classes can also be generic\goto{generic}.
833 When we talk about ``classes'' in general, it means all these four kinds.
834 We say ``concrete classes'' to designate only the classes declared with the @class@ keyword alone.
835
836 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
837 \subsection{Class Specialization}\label{superclass}
838 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
839
840 @super@ declares superclasses.
841 Classes inherit methods, attributes and virtual-types defined in their superclasses.
842 Currently, constructors are inherited in a specific manner\goto{init inheritance}.
843
844 @Object@ is the root of the class hierarchy.
845 It is an interface and all other kinds of classes are implicitly a subclass of @Object@.
846
847 There is no repeated inheritance nor private inheritance.
848 The specialization between classes is transitive, therefore @super@ declarations are superfluous (thus ignored).
849
850 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
851 \subsection{Class Refinement}\label{refine}
852 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
853
854 @redef@ allows modules to refine imported classes (even basic ones).
855 Refining a class means:
856 \begin{itemize}
857 \item adding new properties: methods, attributes, constructors, virtual types;
858 \item redefining existing properties: methods and constructors;
859 \item adding new superclasses.
860 \end{itemize}
861
862 Note that the kind\goto{class} or the visibility\goto{visibility} of a class cannot be changed by a refinement.
863 Therefore, it is allowed to just write @redef class X@ whatever is the kind or the visibility of @X@.
864
865 In programs, the real instantiated classes are always the combination of all their refinements.
866 %This is quite powerful and permit a programing style only found in some dynamically typed languages or aspect-oriented languages.
867
868 \begin{lst}
869 redef class Int
870 fun fib
871 do
872 if self < 2 then return self
873 return (self-1).fib + (self-2).fib
874 end
875 end
876 # Now all integers have the fib method
877 print 15.fib # outputs 610
878 \end{lst}
879
880 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
881 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
882 \section{Methods}\label{fun}\label{self}\label{return}
883 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
884 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
885
886 @fun@ declares methods.
887 Methods must have a name, may have parameters, and may have a return type.
888 Parameters are typed; however, a single type can be used for multiple parameters.
889 \begin{lst}
890 fun foo(x, y: Int, s: String): Bool ...
891 \end{lst}
892
893 @do@ declares the body of methods.
894 Alike control structures\goto{control}, a one-liner version is available.
895 Moreover, a shorter version using the @=@ symbol is also available for functional methods.
896 Therefore, the three following methods are equivalent.
897 \begin{lst}
898 fun next1(i: Int): Int
899 do
900 return i + 1
901 end
902
903 fun next2(i: Int): Int do return i + 1
904
905 fun next3(i: Int): Int = i + 1
906 \end{lst}
907
908 Inside the method body, parameters are considered as variables\goto{var}.
909 They can be assigned and are subject to adaptive typing.
910
911 @self@, the current receiver, is a special parameter.
912 It is not assignable but is subject to adaptive typing.
913
914 @return@ exits the method and returns to the caller.
915 In a function, the return value must be provided with a return in all control flow paths\goto{control flow}.
916
917 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
918 \subsection{Method Call}\label{call}
919 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
920
921 Calling a method is usually done with the dotted notation @x.foo(y, z)@.
922 The dotted notation can be chained.
923
924 A method call with no argument does not need parentheses.
925 Moreover, even with arguments, the parentheses are not required in the principal method of a statement.
926 \begin{lst}
927 var a = [1]
928 a.add 5 # no () for add
929 print a.length # no () for length, no () for print
930 \end{lst}
931
932 However, this last facility requires that the first argument does not start with a parenthesis or a bracket.
933 \begin{lst}
934 foo (x).bar # will be interpreted as (foo(x)).bar
935 foo [x].bar # will be interpreted as (foo[x]).bar
936 \end{lst}
937
938 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
939 \subsection{Method Redefinition}\label{redef}
940 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
941
942 @redef@ denotes methods that are redefined in subclasses\goto{superclass} or in class refinements\goto{refine}.
943 The number and the types of the parameters must be invariant.
944 Thus, there is no need to reprecise the types of the parameters, only names are mandatory.
945
946 The return type can be redefined to be a more precise type.
947 If same type is returned, there is no need to reprecise it.
948
949 The visibility, also, cannot be changed, thus there is also no need to reprecise it.
950
951 \begin{lst}
952 class Foo
953 # implicitly an Object
954 # therefore inherit '==' and 'to_s'
955 var i: Int
956 redef to_s do return "Foo{self.i}"
957 redef ==(f) do return f isa Foo and f.i == self.i
958 end
959 \end{lst}
960
961 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
962 \subsection{Abstract Methods}\label{abstract}
963 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
964
965 @is abstract@ indicates methods defined without a body.
966 Subclasses and refinements can then redefine it (the @redef@ is still mandatory) with a proper body.
967
968 \begin{lst}
969 interface Foo
970 fun derp(x: Int): Int is abstract
971 end
972 class Bar
973 super Foo
974 redef derp(x) do return x + 1
975 end
976 \end{lst}
977
978 Concrete classes may have abstract methods.
979 It is up to a refinement\goto{refine} to provide a body.
980
981 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
982 \subsection{Call to Super}\label{super}
983 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
984
985 @super@ calls the ``previous'' definition of the method.
986 It is used in a redefinition of a method in a subclass or in a refinement,
987 It can be used with or without arguments; in the latter case, the original arguments are implicitly used.
988
989 The @super@ of Nit behave more like the @call-next-method@ of CLOS that the @super@ of Java or Smalltalk.
990 It permits the traversal of complex class hierarchies and refinement.
991 Basically, @super@ is polymorphic: the method called by @super@ is not only determined by the class of definition of the method but also by the dynamic type of @self@.
992
993 \begin{comment}
994 The principle it to produce a strict order of the redefinitions of a method (the linearization).
995 Each call to @super@ call the next method definition in the linearization.
996 From a technical point of view, the linearization algorithm used is based on C4.
997 It ensures that:
998 \begin{itemize}
999 \item A definition comes after its redefinition.
1000 \item A redefinition in a refinement comes before a redefnition in a
1001 \item The order of the declaration of the superclasses is used as the ultimate deabiguization.
1002 \end{itemize}
1003
1004 %@super@ is really powerful and can deals with very complex multiple inheritance and multiple refinement thanks to some linearization algorithm.
1005
1006 \begin{lst}
1007 class A
1008 fun derp: String do return "A"
1009 end
1010 class B
1011 super A
1012 redef fun derp do return "B" + super
1013 end
1014 class C
1015 super A
1016 redef fun derp do return "C" + super
1017 end
1018 class D
1019 super B
1020 super C
1021 redef fun derp do return "D" + super
1022 # Here the linearization order of the class D is DBCA
1023 # D before B because D specializes B
1024 # B before A because B specializes A
1025 # D before C because D specializes C
1026 # C before A because C specializes A
1027 # B before C because in D 'super B' is before 'super C'
1028 end
1029 var b = new B
1030 print b.derp # outputs "BA"
1031 var d = new D
1032 print d.derp # outputs "DBCA"
1033 \end{lst}
1034 \end{comment}
1035
1036 % TODO: linearization.
1037
1038 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1039 \subsection{Operators and Setters}\label{operator}
1040 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1041
1042 Operators and setters are methods that require a special syntax for their definition and their invocation.
1043
1044 \begin{itemize}
1045 \item binary operators: @+@, @-@, @*@, @/@, @\%@, @==@, @<@, @>@, @<=@, @>=@, @<<@, @>>@ and @<=>@.
1046 Their definitions require exactly one parameter and a return value.
1047 Their invocation is done with @x + y@ where @x@ is the receiver, @+@ is the operator, and @y@ is the argument.
1048 \item unary operator: @-@.
1049 Its definition requires a return value but no parameter.
1050 Its invocation is done with @-x@ where @x@ is the receiver.
1051 \item bracket operator: @[]@.
1052 Its definition requires one parameter or more and a return value.
1053 Its invocation is done with @x[y, z]@ where @x@ is the receiver, @y@ the first argument and @z@ the second argument.
1054 \item setters: @something=@ where @something@ can be any valid method identifier.
1055 Their definitions require one parameter or more and no return value.
1056 If there is only one parameter, the invocation is done with @x.something = y@ where @x@ is the receiver and y the argument.
1057 If there is more that one parameter, the invocation is done with @x.something(y, z) = t@ where @x@ is the receiver, @y@ the first argument, @z@ the second argument and @t@ the last argument.
1058 \item bracket setter: @[]=@.
1059 Its definition requires two parameters or more and no return value.
1060 Its invocation is done with @x[y, z] = t@ where @x@ is the receiver, @y@ the first argument, @z@ the second argument and @t@ the last argument.
1061 \end{itemize}
1062
1063 \begin{lst}
1064 class Foo
1065 fun +(a: Bar): Baz do ...
1066 fun -: Baz do ...
1067 fun [](a: Bar): Baz do ...
1068 fun derp(a: Bar): Baz do ...
1069 fun derp=(a: Bar, b: Baz) do ...
1070 fun []= (a: Bar, b: Baz) do ...
1071 end
1072 var a: Foo = ...
1073 var b: Bar = ...
1074 var c: Baz = ...
1075 c = a + b
1076 c = -b
1077 c = a[b] # The bracket operator '[]'
1078 c = a.derp(b) # A normal method 'derp'
1079 a.derp(b) = c # A setter 'derp='
1080 a[b] = c # The bracket setter '[]='
1081 \end{lst}
1082
1083 @+=@ and @-=@ are combinations of the assignment (@=@) and a binary operator.
1084 These feature are extended to setters where a single @+=@ is in fact three method calls: a function call, the operator call, then a setter call.
1085 \begin{lst}
1086 a += c # equiv. a = a + c
1087 a[b] += c # equiv. a[b] = a[b] + c
1088 a.foo += c # equiv. a.foo = a.foo + c
1089 a.bar(b) += c # equiv. a.bar(b) = a.bar(b) + c
1090 \end{lst}
1091
1092 % FIXME: priority of operators?
1093
1094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1095 \subsection{Variable Number of Arguments}\label{vararg}
1096 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1097
1098 A method can accept a variable number of arguments using ellipsis (@...@).
1099 The definition use @x: Foo...@ where @x@ is the name of the parameter and @Foo@ a type.
1100 Inside the body, the static type of @x@ is @Array[Foo]@.
1101 The caller can use 0, 1, or more arguments for the parameter @x@.
1102 Only one ellipsis is allowed in a signature.
1103
1104 \begin{lst}
1105 fun foo(x: Int, y: Int..., z: Int)
1106 do
1107 print "{x};{y.join(",")};{z}"
1108 end
1109 foo(1, 2, 3, 4, 5) # outputs "1;2,3,4;5"
1110 foo(1, 2) # outputs "1;;2"
1111 \end{lst}
1112
1113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1114 \subsection{Top-level Methods and Main Body}\label{toplevel}
1115 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1116
1117 Some functions, like @print@, are usable everywhere simply without using a specific receiver.
1118 Such methods are just defined outside any classes.
1119 In fact, these methods are implicitly defined in the @Object@ interface, therefore inherited by all classes, therefore usable everywhere.
1120 However, this principle may change in a future version.
1121
1122 In a module, the main body is a bunch of statements at the end of a file.
1123 The main body of the main module is the program entry point.
1124 In fact, the main method of a program is implicitly defined as the redefinition of the method @main@ of the @Sys@ class; and the start of the program is the implicit statement @(Sys.new).main@.
1125 Note that because it is a redefinition, the main part can use @super@\goto{super} to call the ``previous'' main part in the imported modules.
1126 If there is no main part in a module, it is inherited from imported modules.
1127
1128 Top-level methods coupled with the main body can be used to program in a pseudo-procedural way.
1129 Therefore, the following programs are valid:
1130 \begin{multicols}{2}
1131 \begin{lst}
1132 print "Hello World!"
1133 \end{lst}
1134 \columnbreak
1135 \begin{lst}
1136 fun sum(i, j: Int): Int
1137 do
1138 return i + j
1139 end
1140 print sum(4, 5)
1141 \end{lst}
1142 \end{multicols}
1143
1144 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1145 \subsection{Intern and Extern Methods}\label{intern}\label{extern}
1146 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1147
1148 @intern@ and @extern@ indicate concrete methods whose body is not written in Nit.
1149
1150 The body of @intern@ methods is provided by the compiler itself for performance or bootstrap reasons.
1151 For the same reasons, some intern methods, like @+@ in @Int@\goto{Int} are not redefinable.
1152
1153 The body of @extern@ methods is provided by libraries written in C; for instance, the system libraries required for input/output.
1154 Extern methods are always redefinable.
1155
1156 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1158 \section{Attributes}\label{attribute}\label{writable}
1159 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1160 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1161
1162 @var@, used inside concrete and abstract classes, declares attributes.
1163 Attributes require a static type and can possibly have an initial value (it may be any kind of expression, even including @self@\goto{self})
1164
1165 %In Nit, attributes cannot be directly accessed.
1166 %In fact by declaring an attribute, two methods are automatically generated.
1167 %One is the getter, the other is the setter.
1168
1169 \begin{lst}
1170 class Foo
1171 var i: Int = 5
1172 fun dec(x: Int): Int
1173 do
1174 var k = self.i
1175 if k > x then self.i = k - x else self.i = 0
1176 end
1177 end
1178 \end{lst}
1179
1180 Note that from an API point of view, there is no way to distinguish the read access of an attribute with a normal method neither to distinguish a write access of an attribute with a setter.
1181 Therefore, the read access of an attribute is called a getter while the write access is called a setter.
1182 \begin{lst}
1183 var x = foo.bar # Is bar an attribute or a method?
1184 foo.bar = y # Is bar an attribute or a setter?
1185 # In fact, we do not need to know.
1186 \end{lst}
1187
1188 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1189 \subsection{Visibility of Attributes}\label{attribute visibility}
1190 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1191
1192 By default, a getter is public and a setter is private.
1193 The visibility of getters can be precised with the @private@ or @protected@ keywords.
1194 The visibility of setters can be specified with an additional @writable@ keyword.
1195
1196 \begin{lst}
1197 class Foo
1198 var pub_pri: X
1199 protected var pro_pri: X
1200 var pub_pub: X writable
1201 private var pri_pro: X protected writable
1202 var pub_pri2: X private writable # the default
1203 end
1204 \end{lst}
1205
1206 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1207 \subsection{Redefinition of Attributes}\label{redef var}
1208 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1209
1210 Getters and setters of attributes behave like genuine methods that can be inherited and redefined.
1211 Getters and setters can also redefine inherited methods.
1212 @redef var@ declares that the getter is a redefinition while @redef writable@ declares that the setter is a redefinition.
1213
1214 \begin{lst}
1215 interface Foo
1216 fun derp: Int is abstract
1217 fun derp=(o: Int) is abstract
1218 end
1219 class Bar
1220 super Foo
1221 redef var derp: Int redef writable
1222 end
1223 class Baz
1224 super Bar
1225 redef fun derp do ...
1226 redef fun derp=(o) do ...
1227 end
1228 \end{lst}
1229
1230 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1231 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1232 \section{Constructors and Instantiation}\label{init}
1233 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1234 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1235
1236 @init@ declares constructors in concrete and in abstract classes.
1237 The role of constructors is basically to initialize the attributes of the class.
1238 Constructors can have: a visibility (by default it is public), a name (by default, constructors are anonymous) and parameters.
1239 They cannot have a return value.
1240
1241 \begin{lst}
1242 class Foo
1243 init(i:Int) do ...
1244 init herp do ...
1245 init derp(i, j: Int) do ...
1246 end
1247 \end{lst}
1248
1249 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1250 \subsection{Class Instantiation}\label{new}
1251 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1252
1253 @new@ instantiates a concrete class using a specific constructor.
1254 \begin{lst}
1255 var x = new Foo(4) # invoke init
1256 var y = new Foo.herp # invoke herp
1257 var z = new Foo.derp(1, 2) # invoke derp
1258 \end{lst}
1259 Note that syntactically, @new Bar@ means ``instantiate @Bar@ with the anonymous constructor'', and @new Bar.foo@ means ``instantiate @Bar@ with the constructor named @foo@'', but @(new Bar).foo@ means ``instantiate @Bar@ with the anonymous constructor then call the method @foo@ on the result''.
1260
1261 Constructors can also be called by other constructors in order to factorize or delegate parts of the construction process.
1262 In other constructors, @init@ denotes the anonymous constructor.
1263 \begin{lst}
1264 class Foo
1265 init(i: Int) do self.derp(i.to_s)
1266 init herp do self.init(5)
1267 init derp(s: String) do ...
1268 end
1269 \end{lst}
1270
1271 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1272 \subsection{Initialization of Attributes}\label{initialization}\label{isset}
1273 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1274
1275 The tricky part in constructors is the initialization of attributes since they cannot be initialized in an atomic way.
1276 The various steps apply in the following order:
1277 \begin{itemize}
1278 \item Attributes typed by a nullable type are initialized with @null@\goto{null}; other attributes remain uninitialized.
1279 \item Default values of all attributes (including inherited ones) are computed in the order of their definitions.
1280 \item The constructor designated in the @new@ is executed.
1281 \item During the constructor execution (including any methods or other constructors called), accessing an uninitialized attribute aborts the program.
1282 \item After the execution of the constructor designated in the @new@, if some attributes remain uninitialized, the program aborts.
1283 \end{itemize}
1284
1285 \begin{comment}
1286 @isset@ can be used to avoid aborting during the construction.
1287 It checks if an attribute is defined.
1288 \begin{lst}
1289 class Foo
1290 var x: Int
1291 fun safe_x: nullable Int
1292 do
1293 if isset self.x then
1294 return self.x
1295 else
1296 return null
1297 end
1298 end
1299 init
1300 do
1301 print safe_x or else 0 # outputs 0
1302 # "print x" would have aborted the program
1303 self.x = 5
1304 print safe_x or else 0 # outputs "5"
1305 print x # outputs "5". It is safe.
1306 end
1307 end
1308 var f = new Foo
1309 \end{lst}
1310 \end{comment}
1311
1312 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1313 \subsection{Free and Inherited Constructors}\label{init inheritance}
1314 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1315
1316 When there is no constructor defined in a concrete class or in an abstract class that specializes only interfaces (@Object@ is always a superclass), a free anonymous constructor is implicitly declared.
1317 This free constructor gathers all attributes without a initial value and assign them in order.
1318 If all attributes have an initial value (or if there is no attributes), the free constructor has no parameters.
1319
1320 \begin{lst}
1321 class Foo
1322 var x: Int
1323 var y: String
1324 var z: Int = 0
1325 # a free init(x: Int, y: String) is implicit
1326 end
1327 var f = new Foo(5, "five") # OK
1328 \end{lst}
1329
1330 When there is no constructors defined in a concrete class or in an abstract class, and this class has only one direct superclass that is a concrete class or an abstract class, and all attributes defined in this class have an initial value, then all constructors of the superclass are inherited.
1331
1332 \begin{lst}
1333 class Bar
1334 super Foo
1335 var t: String = "Hello"
1336 # init(Int, String) is inherited
1337 end
1338 \end{lst}
1339
1340 If none of these two cases apply, then there is a compilation error.
1341 The programmer usually has to define its own constructors for the class.
1342
1343 \begin{lst}
1344 class Baz
1345 super Foo
1346 var u: Int
1347 # Compile error: a constructor must be defined
1348 end
1349 \end{lst}
1350
1351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1353 \section{Generic Classes and Virtual Types}
1354 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1355 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1356
1357 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1358 \subsection{Generic Classes}\label{generic}
1359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1360
1361 Generic classes are defined with formal generic parameters declared within brackets.
1362 Formal generic parameters can then be used as a regular type inside the class.
1363 Generic classes must always be qualified when used.
1364
1365 \begin{lst}
1366 class Pair[E]
1367 var first: E
1368 var second: E
1369 fun is_same: Bool
1370 do
1371 return self.first == self.second
1372 end
1373 end
1374 var p1 = new Pair[Int](1, 2)
1375 print p1.second * 10 # outputs "20"
1376 print p1.is_same # outputs "false"
1377 var p2 = new Pair[String]("hello", "world")
1378 p2.first = "world"
1379 print p2.is_same # outputs "true"
1380 \end{lst}
1381
1382 Unlike many object-oriented languages, generic classes in Nit yield a kind of sub-typing.
1383 For example, @Pair[Int]@ is a subtype of @Pair[Object]@.
1384
1385 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1386 \subsection{Virtual Types}\label{type}
1387 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1388
1389 @type@ declares a virtual types in a class.
1390 A bound type is mandatory.
1391 Virtual types can then be used as regular types in the class and its subclasses.
1392 Subclasses can also redefine it with a more specific bound type.
1393 One can see a virtual type as an internal formal generic parameter or as a redefinable \textit{typedef}.
1394
1395 \begin{lst}
1396 class Foo
1397 type E: Object
1398 var derp: E
1399 end
1400 class Bar
1401 super Foo
1402 redef type E: Int
1403 end
1404 var b = new Bar(5)
1405 print b.derp + 1 # outputs 6
1406 \end{lst}
1407
1408 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1409 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1410 \section{Closures}\label{closure}
1411 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1412 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1413
1414 Closures are pieces of code that are passed to methods as additional arguments.
1415 Closures are defined and used with the @!@ character.
1416 The following example shows the use of the @sort@ method for arrays (defined in the Nit standard library).
1417
1418 \begin{lst}
1419 var a = [4, 2, 9, 6]
1420 a.sort !cmp(x, y) = x <=> y
1421 print a.join(", ") # outputs "2, 4, 6, 9"
1422 a.sort !cmp(x, y) = y <=> x
1423 print a.join(", ") # outputs "9, 6, 4, 2"
1424 \end{lst}
1425
1426 @!cmp@ indicates the closure parameter of the @sort@ method.
1427 The documentation of the @sort@ method says that @!cmp@ is used to compare two elements.
1428 Thus, @sort@ provides to @!cmp@ two elements and expects a Boolean result. %saying if the first element provided should be sorted before the second element provided.
1429 %Therefore, when invoking @sort@, the programmer gets two automatic variables (one associated to each element) and is expected to return a Boolean.
1430
1431 Closures can also be used to perform work.
1432 In the following example, @file_open@ is used to open a file for reading.
1433 If the opening fails, the @!error@ closure is executed with the reason as argument (``file not found'' for instance).
1434 If the opening is successful, @!work@ is executed and the automatic variable @f@ is associated with the opened file handler.
1435 @file_open@ also ensures that the file is correctly closed when the @!work@ closure returns.
1436
1437 \begin{lst}
1438 var fname = "input.txt"
1439 file_open(fname) !work(f) do
1440 print f.read_line
1441 !error(e) do
1442 print "Cannot open '{fname}': {e}"
1443 end
1444 \end{lst}
1445
1446 Note that a method can have multiple closures.
1447 Syntactically, a closure is ended by the start of another closure or by the @end@ keyword that terminates the list of the closures.
1448 In the one-liner version, there is no @end@ but only one closure can be used.
1449
1450 Closures can access visible variables.
1451 In the following example, the @iterate@ procedure asks for an @!each@ closure that is executed on each element of a @Collection@.
1452 In fact, the @for@ control structure is a call of the @iterate@ method.
1453 The following two examples are thus strictly equivalent.
1454
1455 \begin{multicols}{2}
1456 \begin{lst}
1457 var sum = 0
1458 var a = [4, 2, 9]
1459 a.iterate !each(i) do
1460 sum += i
1461 end
1462 print sum # outputs "15"
1463 \end{lst}
1464 \columnbreak
1465 \begin{lst}
1466 var sum = 0
1467 var a = [4, 2, 9]
1468 for i in a do
1469 sum += i
1470 end
1471 print sum # outputs "15"
1472 \end{lst}
1473 \end{multicols}
1474
1475 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1476 \subsection{Returning Values and Escaping}\label{closure return}
1477 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1478
1479 @break@ and @continue@ are extended to closures.
1480
1481 @continue@ exits the closure.
1482 If the closure expects a return value, @continue@ can also be used to return the correct value.
1483 As with method definition, the @do continue value@ syntax can be replaced by @= value@ as in the first @sort@ example.
1484
1485
1486 @break@ exits completely the called method.
1487 If the called method is a function, @break@ is also used to set the result returned by the function.
1488 The types returned by @break@ can be different from the return type of the function.
1489 The return type of the whole expression is the combination\goto{combination} of the return type of the function and the types of each @break@.
1490
1491 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1492 \subsection{Closures in Method Declarations}
1493 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1494
1495 Closure parameters are declared with their signature between the prototype and the @do@ of the method.
1496 Closure invocations in the body of the method simply use the closure name (without the @!@) like a standard call.
1497 More than one closure parameter can be declared.
1498 Each has to be declared on a separate line.
1499 %At the method invocations, the closure name is used to associate each closure definition with each closure parameter.
1500 The order of the closure definitions does not matter.
1501
1502 \begin{multicols}{2}
1503 \begin{lst}
1504 fun twice
1505 !work
1506 do
1507 work
1508 work
1509 end
1510 twice !work do print "One"
1511 # outputs "One One"
1512 \end{lst}
1513
1514
1515 \begin{lst}
1516 fun foo(i: String): String
1517 !f(j: String): String
1518 do
1519 var k = f(i + "B")
1520 # k will be "ABC"
1521 return k + "D"
1522 end
1523 var x = foo("A") !f(y) =
1524 y + "C"
1525 print x # outputs "ABCD"
1526 \end{lst}
1527 \columnbreak
1528 \begin{lst}
1529 fun bar(i: String)
1530 !b1(j: String): String
1531 !b2(k: String)
1532 do
1533 b2(b1(i))
1534 end
1535
1536 bar("A") !b1(y) do
1537 continue y + "B"
1538 !b2(z) do
1539 print z
1540 end
1541 # outputs "AB"
1542 \end{lst}
1543 \end{multicols}
1544
1545 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1546 \subsection{Default Closures}
1547 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1548
1549 A default closure can be given along with the closure parameter declaration in a method.
1550 If there is no default closure, then the corresponding closure argument is mandatory.
1551 Otherwise, if there is a default closure, the corresponding closure argument is optional.
1552
1553
1554 \begin{lst}
1555 fun are_all_comparable(a: Collection[Int]): Bool
1556 !cmp(x, y: Int): Bool = x == y
1557 do
1558 if a.is_empty then return true
1559 var e1 = a.first
1560 for e2 in a do if not cmp(e1, e2) then return false
1561 return true
1562 end
1563
1564 var a = [2, 2, 6, 2]
1565 print are_all_comparable(a) # outputs "false"
1566 var x = are_all_comparable(a) !cmp(i, j) = i%2 == j%2
1567 print x # outputs "true"
1568 \end{lst}
1569
1570 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1571 \subsection{Break Closures}\label{break closure}
1572 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1573
1574 Some closures, called break closures, cannot be continued.
1575 On the method definition, it means that the closure invocation does not return (like a @return@ or an @abort@).
1576 On method invocations, it means that the closure definition must not continue.
1577 Break closures are usually used to process error or exception handling.
1578
1579
1580 \begin{lst}
1581 fun open_file(fname: String)
1582 !work(f: File)
1583 break !error(e: String) do
1584 print "Cannot open {fname}: {e}."
1585 abort
1586 end
1587 do
1588 # ...
1589 end
1590
1591 open_file("config.ini") !error(e) do
1592 print "Cannot open file (config.ini): {e}."
1593 !work(f) do
1594 # ...
1595 end
1596 \end{lst}
1597
1598 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1599 \subsection{Full Closure Example}
1600 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1601
1602 To conclude the explanation about closures, the last example shows the bracket operator\goto{operator} (@[]@) of the @Map@ interface.
1603 A map, like @HashMap@, is used to implement a dictionary that associates some objects (keys) to some other objects (items).
1604 The operator returns the item associated to key.
1605 The operator has a @!def@ closure that is executed when the key is not found.
1606 @!def@ is expected to return the item associated with the new key so it can be stored in the hashmap then returned.
1607 By default, @!def@ aborts.
1608
1609
1610 \begin{lst}
1611 var map = new HashMap[Int, String]
1612 map[5] = "five" # associate '5' to "five"
1613 var x1 = map[5] # return "five"
1614 var x2 = map[6] !def = "six" # associate '6' to "six"
1615 # and return "six"
1616 var x3 = map[6] !def = "?" # return "six" since '6' is
1617 # a known key
1618 var x4 = map[7] !def do break "seven" # return "seven"
1619 # since '7' is not a known key
1620 var x5 = map[7] # aborts since '7' was not associated
1621 # with the previous statement
1622 \end{lst}
1623
1624 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1625 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1626 \section{Conclusion}
1627 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1628 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1629
1630 The specification of Nit is not yet completed.
1631 At least the major following features need to be implemented and documented:
1632 \begin{itemize}
1633 \item User-defined @enum@.
1634 \item Union and intersection types.
1635 \item A usable native interface to bind Nit with system libraries and other languages.
1636 \end{itemize}
1637 Moreover, the language also needs a complete and stable standard library.
1638
1639 Some other topics also need a deeper analysis : exceptions, threads, parallelism, contracts, etc.
1640
1641 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1642 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1643 \section{Index}\label{index}{\small\raggedleft
1644 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1645 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1646 @#@\goto{comment},
1647 @!@\goto{closure},
1648 @.@\goto{call},
1649 @..@\goto{Range},
1650 @...@\goto{vararg},
1651 @{}@\goto{String},
1652 @[]@ (array)\goto{Array},
1653 @[]@ (operator)\goto{operator},
1654 @[]@ (generic)\goto{generic},
1655 @"@\goto{String},
1656 @abstract@ (class)\goto{class},
1657 @abstract@ (method)\goto{abstract},
1658 adaptive typing\goto{adaptive typing},
1659 @and@\goto{Bool},
1660 @Array@\goto{Array},
1661 @as@\goto{as},
1662 @assert@\goto{assert},
1663 attribute\goto{attribute},
1664 @Bool@\goto{Bool},
1665 @break@\goto{break},
1666 break closure\goto{break closure},
1667 cast\goto{as},
1668 @class@\goto{class},
1669 closure\goto{closure},
1670 comment\goto{comment},
1671 constructor\goto{init},
1672 @continue@\goto{continue},
1673 control structure\goto{control},
1674 @do@\goto{do},
1675 @else@ (if)\goto{if},
1676 @else@ (abort)\goto{abort},
1677 @end@\goto{end},
1678 @enum@\goto{class},
1679 @extern@\goto{extern},
1680 @false@\goto{Bool},
1681 @Float@\goto{Float}
1682 @for@\goto{for},
1683 @fun@\goto{fun},
1684 generic class\goto{generic},
1685 getter\goto{attribute},
1686 @HashMap@\goto{HashMap},
1687 identifier\goto{identifier},
1688 @if@\goto{if},
1689 @import@\goto{import},
1690 @in@\goto{for},
1691 @init@\goto{init},
1692 inheritance\goto{superclass},
1693 @Int@\goto{Int},
1694 @interface@\goto{class},
1695 @intern@\goto{intern},
1696 @is@\goto{is},
1697 @isa@\goto{isa},
1698 @isset@\goto{isset},
1699 @label@\goto{label},
1700 @loop@\goto{loop},
1701 @module@\goto{module}
1702 @new@\goto{new},
1703 @not@\goto{Bool},
1704 @not null@\goto{null},
1705 @null@\goto{null},
1706 @nullable@\goto{null},
1707 @Object@\goto{Object},
1708 operator\goto{operator},
1709 @or@\goto{Bool},
1710 @or else@\goto{or else}
1711 @private@\goto{visibility}
1712 @protected@\goto{visibility},
1713 @Range@\goto{Range},
1714 @redef@ (class)\goto{refine},
1715 @redef@ (method)\goto{redef},
1716 @redef@ (attribute)\goto{redef var},
1717 @return@\goto{return},
1718 @self@\goto{self},
1719 setter\goto{operator},
1720 setter (attribute)\goto{attribute},
1721 specialization\goto{superclass},
1722 @String@\goto{String},
1723 @super@ (class)\goto{superclass},
1724 @super@ (method)\goto{super},
1725 syntax\goto{syntax},
1726 @then@\goto{if},
1727 @true@\goto{Bool},
1728 type (static)\goto{static type},
1729 @type@\goto{type},
1730 @upper bound@\goto{upper bound},
1731 @var@ (attribute)\goto{attribute},
1732 @var@ (variable)\goto{var},
1733 virtual type\goto{type},
1734 visibility\goto{visibility},
1735 @while@\goto{while},
1736 @writable@\goto{writable},
1737 }
1738