ni_nitdoc: added fast copy past utility to signatures.
[nit.git] / src / cached.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 # Implementation of the method-related annotation `cached`
16 #
17 # Note this module can be used as a reference on how to implements
18 # complex annotation that modify both the model and the AST of a Nit program
19 module cached
20
21 import modelize_property
22 import parser_util
23 import simple_misc_analysis
24
25 redef class ToolContext
26 var cached_phase: Phase = new CachedPhase(self, [modelize_property_phase])
27 end
28
29 private class CachedPhase
30 super Phase
31
32 init(toolcontext, depends)
33 do
34 # FIXME The phase has to be executed just after `modelize_property_phase`
35 # But there is no simple way to express this
36 # So, for the moment, I just looked at the linearization and see what phase is after `modelize_property_phase`
37 # And inserted before it
38 toolcontext.phases.add_edge(toolcontext.simple_misc_analysis_phase, self)
39 end
40
41 redef fun process_annotated_node(npropdef, nat)
42 do
43 # Skip if we are not interested
44 if nat.n_atid.n_id.text != "cached" then return
45
46 # Do some validity checks and print errors if the annotation is used incorrectly
47 var modelbuilder = toolcontext.modelbuilder
48
49 if not npropdef isa AConcreteMethPropdef then
50 modelbuilder.error(npropdef, "Syntax error: only a function can be cached.")
51 return
52 end
53
54 var mpropdef = npropdef.mpropdef.as(not null)
55
56 var mtype = mpropdef.msignature.return_mtype
57 if mtype == null then
58 modelbuilder.error(npropdef, "Syntax error: only a function can be cached.")
59 return
60 end
61
62 if not npropdef.n_signature.n_params.is_empty then
63 modelbuilder.error(npropdef, "Syntax error: only a function without arguments can be cached.")
64 return
65 end
66
67 # OK, let we do some meta-programming...
68
69 var location = npropdef.location
70 var name = mpropdef.mproperty.name
71 var nclassdef = npropdef.parent.as(AStdClassdef)
72 var mclassdef = nclassdef.mclassdef.as(not null)
73
74 # Create a new private attribute to store the cache
75 var cache_mpropdef = new MAttributeDef(mclassdef, new MAttribute(mclassdef, "@{name}<cache>", private_visibility), location)
76 cache_mpropdef.static_mtype = mtype.as_nullable
77
78 # Create another new private attribute to store the boolean «is the function cached?»
79 # The point is to manage the case where `null' is a genuine return value of the method
80 var is_cached_mpropdef = new MAttributeDef(mclassdef, new MAttribute(mclassdef, "@{name}<is_cached>", private_visibility), location)
81 is_cached_mpropdef.static_mtype = mclassdef.mmodule.get_primitive_class("Bool").mclass_type
82 # FIXME? Because there is a default value ("false") a real propdef is required
83 var is_cached_npropdef = toolcontext.parse_propdef("var is_cached = false").as(AAttrPropdef)
84 associate_propdef(is_cached_mpropdef, is_cached_npropdef)
85
86 # Create a new private method to do the real work
87 var real_mpropdef = new MMethodDef(mclassdef, new MMethod(mclassdef, "{name}<real>", private_visibility), location)
88 real_mpropdef.msignature = mpropdef.msignature
89 # FIXME: Again, if the engine require a real propdef even if it is empty
90 var real_npropdef = toolcontext.parse_propdef("fun real do end").as(AConcreteMethPropdef)
91 associate_propdef(real_mpropdef, real_npropdef)
92 # Note: the body is set at the last line of this function
93
94 # Save the original body
95 var real_body = npropdef.n_block.as(not null)
96
97 # Replace the original body with a new body that do the proxy'n'cache work
98 var proxy_body = toolcontext.parse_stmts("if self._is_cached then return self._cache.as(not null)\nvar res = call_real\nself._cache_write = res\nself._is_cached_write = true\nreturn res")
99 real_body.replace_with(proxy_body)
100
101 # Do some transformation on the identifiers used on the proxy body so that correct entities are designated
102 # FIXME: we just trick the following phases into associating by name some tokens with some model-entities
103 # But this is bad at at least two levels
104 # - we already know the real model-entities, so why doing latter the association and not now?
105 # - associating by names may cause a useless fragility (name-conflicts, etc.)
106 proxy_body.collect_tokens_by_text("_is_cached").first.text = is_cached_mpropdef.mproperty.name
107 proxy_body.collect_tokens_by_text("_is_cached_write").first.text = is_cached_mpropdef.mproperty.name
108 proxy_body.collect_tokens_by_text("_cache").first.text = cache_mpropdef.mproperty.name
109 proxy_body.collect_tokens_by_text("_cache_write").first.text = cache_mpropdef.mproperty.name
110 proxy_body.collect_tokens_by_text("call_real").first.text = real_mpropdef.mproperty.name
111
112 # FIXME a last transformation cannot be done yet. So, the call to `super` (ASuperExpr) is broken in cached methods.
113
114 # Give the original body to the private real methoddef
115 real_npropdef.n_block.replace_with(real_body)
116 end
117
118 # Detach `n` from its original AST and attach it to `m` (and its related AST)
119 # `n' must not be already attached to an existing model entity
120 # `m' must not be already attached to an existing AST node
121 fun associate_propdef(m: MPropDef, n: APropdef)
122 do
123 # FIXME: the model-AST relations **must** be rationalized:
124 # * 1- fragility: the risk of inconsistencies is too hight
125 # * 2- complexity: there is too much paths to access the same things
126
127 # Easy attach
128 assert n.mpropdef == null
129 n.mpropdef = m
130
131 # Required to so that look-for implementation works
132 assert not toolcontext.modelbuilder.mpropdef2npropdef.has_key(m)
133 toolcontext.modelbuilder.mpropdef2npropdef[m] = n
134
135 var mclassdef = m.mclassdef
136 var nclassdef = toolcontext.modelbuilder.mclassdef2nclassdef[mclassdef]
137 # Sanity checks
138 assert nclassdef.mclassdef == mclassdef
139
140 # Required so that some visit can use nclassdef as a context # FIXME it is ugly
141 n.parent = nclassdef
142
143 # Required so that propdef are visited in visitors
144 if not nclassdef.n_propdefs.has(n) then nclassdef.n_propdefs.add(n)
145 end
146 end