frontend: intro the serialization phase
[nit.git] / src / literal.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 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
17 # Parsing of literal values in the abstract syntax tree.
18 module literal
19
20 import parser
21 import toolcontext
22 import phase
23 import serialization_phase
24
25 redef class ToolContext
26 var literal_phase: Phase = new LiteralPhase(self, [serialization_phase])
27 end
28
29 private class LiteralPhase
30 super Phase
31
32 redef fun process_nmodule(nmodule) do nmodule.do_literal(toolcontext)
33 end
34
35 redef class AModule
36 # Visit the module to compute the real value of the literal-related node of the AST.
37 # Warnings and errors are displayed on the toolcontext.
38 fun do_literal(toolcontext: ToolContext)
39 do
40 var v = new LiteralVisitor(toolcontext)
41 v.enter_visit(self)
42 end
43 end
44
45 private class LiteralVisitor
46 super Visitor
47
48 var toolcontext: ToolContext
49
50 init(toolcontext: ToolContext)
51 do
52 self.toolcontext = toolcontext
53 end
54
55 redef fun visit(n)
56 do
57 n.accept_literal(self)
58 n.visit_all(self)
59 end
60 end
61
62 redef class ANode
63 private fun accept_literal(v: LiteralVisitor) do end
64 end
65
66 redef class AIntExpr
67 # The value of the literal int once computed.
68 var value: nullable Int
69 redef fun accept_literal(v)
70 do
71 self.value = self.n_number.text.to_i
72 end
73 end
74
75 redef class AFloatExpr
76 # The value of the literal float once computed.
77 var value: nullable Float
78 redef fun accept_literal(v)
79 do
80 self.value = self.n_float.text.to_f
81 end
82 end
83
84 redef class ACharExpr
85 # The value of the literal char once computed.
86 var value: nullable Char
87 redef fun accept_literal(v)
88 do
89 var txt = self.n_char.text.unescape_nit
90 if txt.length != 3 then
91 v.toolcontext.error(self.hot_location, "Invalid character literal {txt}")
92 return
93 end
94 self.value = txt[1]
95 end
96 end
97
98 redef class AStringFormExpr
99 # The value of the literal string once computed.
100 var value: nullable String
101 redef fun accept_literal(v)
102 do
103 var txt = self.n_string.text
104 var skip = 1
105 if txt[0] == txt[1] and txt.length >= 6 then skip = 3
106 self.value = txt.substring(skip, txt.length-(2*skip)).unescape_nit
107 end
108 end