misc/vim: inform the user when no results are found
[nit.git] / examples / extern_methods.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012-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 # This module illustrates some uses of the FFI, specifically
18 # how to use extern methods. Which means to implement a Nit method in C.
19 module extern_methods
20
21 redef enum Int
22 # Returns self'th fibonnaci number
23 # implemented here in C for optimization purposes
24 fun fib : Int import fib `{
25 if ( recv < 2 )
26 return recv;
27 else
28 return Int_fib( recv-1 ) + Int_fib( recv-2 );
29 `}
30
31 # System call to sleep for "self" seconds
32 fun sleep `{
33 sleep( recv );
34 `}
35
36 # Return atan2l( self, x ) from libmath
37 fun atan_with( x : Int ) : Float `{
38 return atan2( recv, x );
39 `}
40
41 # This method callback to Nit methods from C code
42 # It will use from C code:
43 # * the local fib method
44 # * the + operator, a method of Int
45 # * to_s, a method of all objects
46 # * String.to_cstring, a method of String to return an equivalent char*
47 fun foo import fib, +, to_s, String.to_cstring `{
48 long recv_fib = Int_fib( recv );
49 long recv_plus_fib = Int__plus( recv, recv_fib );
50
51 String nit_string = Int_to_s( recv_plus_fib );
52 char *c_string = String_to_cstring( nit_string );
53
54 printf( "from C: self + fib(self) = %s\n", c_string );
55 `}
56
57 # Equivalent to foo but written in pure Nit
58 fun bar do print "from Nit: self + fib(self) = {self+self.fib}"
59 end
60
61 print 12.fib
62
63 print "sleeping 1 second..."
64 1.sleep
65
66 print 100.atan_with( 200 )
67 8.foo
68 8.bar
69