contrib/jwrapper: enable serialization of model
[nit.git] / contrib / jwrapper / src / jtype_converter.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2014 Frédéric Vachon <fredvac@gmail.com>
4 # Copyright 2015 Alexis Laferrière <alexis.laf@xymus.net>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # Services to convert java type to nit type and get casts if needed
19 module jtype_converter
20
21 import opts
22
23 redef class Sys
24 # Converter between Java and Nit type
25 var converter = new JavaTypeConverter is lazy
26
27 # Option to treat base Java objects as an equivalent to those in Nit?
28 #
29 # This concerns `Byte, Integer, Float, etc`.
30 var opt_cast_objects = new OptionBool("Convert base objects as their primitive equivalent", "-c")
31 end
32
33 class JavaTypeConverter
34
35 var type_map = new HashMap[String, String]
36 var param_cast_map = new HashMap[String, String]
37 var return_cast_map = new HashMap[String, String]
38
39 init
40 do
41 # Java type to nit type
42 type_map["byte"] = "Int"
43 type_map["short"] = "Int"
44 type_map["int"] = "Int"
45 type_map["long"] = "Int"
46 type_map["char"] = "Char"
47 type_map["float"] = "Float"
48 type_map["double"] = "Float"
49 type_map["boolean"] = "Bool"
50
51 # Cast if the type is given as a parameter
52 param_cast_map["byte"] = "(byte)"
53 param_cast_map["short"] = "(short)"
54 param_cast_map["float"] = "(float)"
55 param_cast_map["int"] = "(int)"
56
57 if opt_cast_objects.value then
58 type_map["Byte"] = "Int"
59 type_map["Short"] = "Int"
60 type_map["Integer"] = "Int"
61 type_map["Long"] = "Int"
62 type_map["Character"] = "Char"
63 type_map["Float"] = "Float"
64 type_map["Double"] = "Float"
65 type_map["Boolean"] = "Bool"
66 type_map["CharSequence"] = "JavaString"
67
68 param_cast_map["Byte"] = "(Byte)"
69 param_cast_map["Short"] = "(short)"
70 param_cast_map["Float"] = "(float)"
71 param_cast_map["Integer"] = "(int)"
72
73 # Cast if the type is given as a return value
74 return_cast_map["CharSequence"] = "(String)"
75 end
76 end
77
78 fun to_nit_type(java_type: String): nullable String
79 do
80 return self.type_map.get_or_null(java_type)
81 end
82
83 fun cast_as_param(java_type: String): String
84 do
85 return self.param_cast_map.get_or_default(java_type, "")
86 end
87
88 fun cast_as_return(java_type: String): String
89 do
90 return self.return_cast_map.get_or_default(java_type, "")
91 end
92 end