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 import modelbuilder
#FIXME useless
26 redef class ToolContext
27 var literal_phase
: Phase = new LiteralPhase(self, null)
30 private class LiteralPhase
33 redef fun process_nmodule
(nmodule
) do nmodule
.do_literal
(toolcontext
)
37 # Visit the module to compute the real value of the literal-related node of the AST.
38 # Warnings and errors are displayed on the toolcontext.
39 fun do_literal
(toolcontext
: ToolContext)
41 var v
= new LiteralVisitor(toolcontext
)
46 private class LiteralVisitor
49 var toolcontext
: ToolContext
51 init(toolcontext
: ToolContext)
53 self.toolcontext
= toolcontext
58 n
.accept_literal
(self)
64 private fun accept_literal
(v
: LiteralVisitor) do end
68 # The value of the literal int once computed.
69 var value
: nullable Int
70 redef fun accept_literal
(v
)
72 self.value
= self.n_number
.text
.to_i
76 redef class AFloatExpr
77 # The value of the literal float once computed.
78 var value
: nullable Float
79 redef fun accept_literal
(v
)
81 self.value
= self.n_float
.text
.to_f
86 # The value of the literal char once computed.
87 var value
: nullable Char
88 redef fun accept_literal
(v
)
90 var txt
= self.n_char
.text
.unescape_nit
91 if txt
.length
!= 3 then
92 v
.toolcontext
.error
(self.hot_location
, "Invalid character literal {txt}")
99 redef class AStringFormExpr
100 # The value of the literal string once computed.
101 var value
: nullable String
102 redef fun accept_literal
(v
)
104 var txt
= self.n_string
.text
106 if txt
[0] == txt
[1] and txt
.length
>= 6 then skip
= 3
107 self.value
= txt
.substring
(skip
, txt
.length-
(2*skip
)).unescape_nit
112 # Return a string where Nit escape sequences are transformed.
116 # print s.length # -> 2
117 # var u = s.unescape_nit
118 # print s.length # -> 1
119 # print s[0].ascii # -> 10 (the ASCII value of the "new line" character)
120 fun unescape_nit
: String
122 var res
= new Buffer.with_capacity
(self.length
)
123 var was_slash
= false
125 if not was_slash
then
136 else if c
== 'r' then
138 else if c
== 't' then
140 else if c
== '0' then