Merge: doc: fixed some typos and other misc. corrections
[nit.git] / tests / test_ffi_c_casts.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
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
17 redef class Object
18 fun foo do print "obj"
19 end
20
21 class A
22 redef fun foo do print "a"
23 end
24
25 class B
26 super A
27
28 redef fun foo do print "b"
29 end
30
31 redef class Int
32 redef fun foo do print self
33 end
34
35 fun callbacks_with_as_casts(a: A, b: B) import B.foo, A.foo, B.as(A), A.as(B) `{
36 A_foo(a);
37 B_foo(b);
38
39 A aa = B_as_A(b);
40 A_foo(aa);
41
42 if (!A_is_a_B(a)) {
43 printf("Instance of A is not a B.\n");
44 return;
45 }
46 B bb = A_as_B(a);
47 B_foo(bb);
48 `}
49
50 fun callbacks_with_nullable_casts(a: A, b: nullable B) import B.as not nullable, A.as nullable, A.as(nullable B), B.foo `{
51 if (!nullable_B_is_a_B(b)) {
52 printf("Instance b is not a B (it is null)\n");
53 } else {
54 B bb = nullable_B_as_B(b);
55 B_foo(bb);
56 }
57
58 if (!A_is_a_nullable_A(a)) {
59 printf("Instance a is not a nullable A\n");
60 }
61 if (!A_is_a_nullable_B(a)) {
62 printf("Instance a is not a nullable B\n");
63 }
64 `}
65
66 fun callbacks_with_failed_checks(a: A, b: nullable B) import B.as not nullable, B.as nullable, A.as(B), B.as(A) `{
67 if (!A_is_a_B(a)) {
68 printf("Instance of A is not a B.\n");
69 }
70 if (!nullable_B_is_a_B(b)) {
71 printf("Instance of B is null\n");
72 }
73 `}
74
75 fun callbacks_with_primitives(o: Object, i: Int, ni: nullable Int) import Object.as(Int), Int.as(Object), nullable Int.as(Int), Int.foo, Object.foo `{
76 Object_foo(o);
77 Int_foo(i);
78
79 if (!Object_is_a_Int(o))
80 printf("Instance o is not a Int\n");
81 else {
82 int oo = Object_as_Int(o);
83 Int_foo(oo);
84 }
85
86 Object ii = Int_as_Object(i);
87 Object_foo(ii);
88
89 if (!nullable_Int_is_a_Int(ni))
90 printf("Instance ni is not a Int\n");
91 else {
92 int nni = nullable_Int_as_Int(ni);
93 Int_foo(nni);
94 }
95 `}
96
97 print "1"
98 callbacks_with_as_casts(new B, new B)
99 print "2"
100 callbacks_with_as_casts(new A, new B)
101 print "3"
102 callbacks_with_nullable_casts(new B, new B)
103 print "4"
104 callbacks_with_nullable_casts(new A, null)
105 print "5"
106 callbacks_with_failed_checks(new A, null)
107 print "6"
108 callbacks_with_primitives(1111, 2222, 3333)
109 print "7"
110 callbacks_with_primitives(new A, 5555, null)
111 print "8"