1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Parsing of literal values in the abstract syntax tree.
24 redef class ToolContext
25 var literal_phase
: Phase = new LiteralPhase(self, null)
28 private class LiteralPhase
31 redef fun process_nmodule
(nmodule
) do nmodule
.do_literal
(toolcontext
)
35 # Visit the module to compute the real value of the literal-related node of the AST.
36 # Warnings and errors are displayed on the toolcontext.
37 fun do_literal
(toolcontext
: ToolContext)
39 var v
= new LiteralVisitor(toolcontext
)
44 private class LiteralVisitor
47 var toolcontext
: ToolContext
49 init(toolcontext
: ToolContext)
51 self.toolcontext
= toolcontext
56 n
.accept_literal
(self)
62 private fun accept_literal
(v
: LiteralVisitor) do end
66 # The value of the literal int once computed.
67 var value
: nullable Int
70 redef class ADecIntExpr
71 redef fun accept_literal
(v
)
73 self.value
= self.n_number
.text
.to_i
77 redef class AHexIntExpr
78 redef fun accept_literal
(v
)
80 self.value
= self.n_hex_number
.text
.substring_from
(2).to_hex
84 redef class AFloatExpr
85 # The value of the literal float once computed.
86 var value
: nullable Float
87 redef fun accept_literal
(v
)
89 self.value
= self.n_float
.text
.to_f
94 # The value of the literal char once computed.
95 var value
: nullable Char
96 redef fun accept_literal
(v
)
98 var txt
= self.n_char
.text
.unescape_nit
99 if txt
.length
!= 3 then
100 v
.toolcontext
.error
(self.hot_location
, "Invalid character literal {txt}")
103 self.value
= txt
.chars
[1]
107 redef class AStringFormExpr
108 # The value of the literal string once computed.
109 var value
: nullable String
110 redef fun accept_literal
(v
)
112 var txt
= self.n_string
.text
115 if txt
.chars
[0] == txt
.chars
[1] and txt
.length
>= 6 then
118 if txt
.chars
[0] == '"' and txt
.chars
[3] == '\n' then behead
= 4 # ignore first \n in """
120 self.value
= txt
.substring
(behead
, txt
.length
- behead
- betail
).unescape_nit