src: new module annoation to help with annotations
[nit.git] / src / annotation.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Management and utilities on annotations
16 module annotation
17
18 import parser
19 import modelbuilder
20 import literal
21
22 redef class AAnnotation
23 # The name of the annotation
24 fun name: String
25 do
26 return n_atid.n_id.text
27 end
28
29 # Get the single argument of `self` as a `String`.
30 # Raise error and return null on any inconsistency.
31 fun arg_as_string(modelbuilder: ModelBuilder): nullable String
32 do
33 var args = n_args
34 if args.length == 1 then
35 var arg = args.first.as_string
36 if arg != null then return arg
37 end
38
39 modelbuilder.error(self, "Annotation error: \"{name}\" expects a single String as argument.")
40 return null
41 end
42
43 # Get the single argument of `self` as an `Int`.
44 # Raise error and return null on any inconsistency.
45 fun arg_as_int(modelbuilder: ModelBuilder): nullable Int
46 do
47 var args = n_args
48 if args.length == 1 then
49 var arg = args.first.as_int
50 if arg != null then return arg
51 end
52
53 modelbuilder.error(self, "Annotation error: \"{name}\" expects a single Int as argument.")
54 return null
55 end
56 end
57
58 redef class AAtArg
59 # Get `self` as a `String`.
60 # Return null if not a string.
61 fun as_string: nullable String
62 do
63 if not self isa AExprAtArg then return null
64 var nexpr = n_expr
65 if not nexpr isa AStringFormExpr then return null
66 return nexpr.value.as(not null)
67 end
68
69 # Get `self` as an `Int`.
70 # Return null if not an integer.
71 fun as_int: nullable Int
72 do
73 if not self isa AExprAtArg then return null
74 var nexpr = n_expr
75 if not nexpr isa AIntExpr then return null
76 return nexpr.value.as(not null)
77 end
78
79 # Get `self` as a single identifier.
80 # Return null if not a single identifier.
81 fun as_id: nullable String
82 do
83 if not self isa AExprAtArg then return null
84 var nexpr = n_expr
85 if not nexpr isa ACallExpr then return null
86 if not nexpr.n_expr isa AImplicitSelfExpr then return null
87 if not nexpr.n_args.n_exprs.is_empty then return null
88 return nexpr.n_id.text
89 end
90 end