Debian Codegraph @

src/com/google/javascript/jscomp/ClosureRewriteClass.java

raw symbols SCIP
1 /*
2 * Copyright 2012 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.google.javascript.jscomp;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.collect.Lists;
20 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.JSDocInfo;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.Token;
25
26 import java.util.List;
27
28 /**
29 * Rewrites "goog.defineClass" into a form that is suitable for
30 * type checking and dead code elimination.
31 *
32 * @author [email protected] (John Lenz)
33 */
34 class ClosureRewriteClass extends AbstractPostOrderCallback
35 implements HotSwapCompilerPass {
36
37 // Errors
38 static final DiagnosticType GOOG_CLASS_TARGET_INVALID = DiagnosticType.error(
39 "JSC_GOOG_CLASS_TARGET_INVALID",
40 "Unsupported class definition expression.");
41
42 static final DiagnosticType GOOG_CLASS_SUPER_CLASS_NOT_VALID = DiagnosticType.error(
43 "JSC_GOOG_CLASS_SUPER_CLASS_NOT_VALID",
44 "The super class must be null or a valid name reference");
45
46 static final DiagnosticType GOOG_CLASS_DESCRIPTOR_NOT_VALID = DiagnosticType.error(
47 "JSC_GOOG_CLASS_DESCRIPTOR_NOT_VALID",
48 "The class descriptor must be an object literal");
49
50 static final DiagnosticType GOOG_CLASS_CONSTRUCTOR_MISING = DiagnosticType.error(
51 "JSC_GOOG_CLASS_CONSTRUCTOR_MISING",
52 "The constructor expression is missing for the class descriptor");
53
54 static final DiagnosticType GOOG_CLASS_STATICS_NOT_VALID = DiagnosticType.error(
55 "JSC_GOOG_CLASS_STATICS_NOT_VALID",
56 "The class statics descriptor must be an object or function literal");
57
58 static final DiagnosticType GOOG_CLASS_UNEXPECTED_PARAMS = DiagnosticType.error(
59 "JSC_GOOG_CLASS_UNEXPECTED_PARAMS",
60 "The class definition has too many arguments.");
61
62 private final AbstractCompiler compiler;
63
64 public ClosureRewriteClass(AbstractCompiler compiler) {
65 this.compiler = compiler;
66 }
67
68 @Override
69 public void process(Node externs, Node root) {
70 NodeTraversal.traverse(compiler, root, this);
71 }
72
73 @Override
74 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
75 this.compiler.process(this);
76
77 }
78
79 @Override
80 public void visit(NodeTraversal t, Node n, Node parent) {
81 if (n.isCall() && isGoogDefineClass(n)) {
82 if (!validateUsage(n)) {
83 compiler.report(JSError.make(n, GOOG_CLASS_TARGET_INVALID));
84 }
85 }
86 maybeRewriteClassDefinition(n);
87 }
88
89 private boolean validateUsage(Node n) {
90 // There are only three valid usage patterns for of goog.defineClass
91 // var ClassName = googDefineClass
92 // namespace.ClassName = googDefineClass
93 // and within an objectlit, used by the goog.defineClass.
94 Node parent = n.getParent();
95 switch (parent.getType()) {
96 case Token.NAME:
97 return true;
98 case Token.ASSIGN:
99 return n == parent.getLastChild() && parent.getParent().isExprResult();
100 case Token.STRING_KEY:
101 return isContainedInGoogDefineClass(parent);
102 }
103 return false;
104 }
105
106 private boolean isContainedInGoogDefineClass(Node n) {
107 while (n != null) {
108 n = n.getParent();
109 if (n.isCall()) {
110 if (isGoogDefineClass(n)) {
111 return true;
112 }
113 } else if (!n.isObjectLit() && !n.isStringKey()) {
114 break;
115 }
116 }
117 return false;
118 }
119
120 private void maybeRewriteClassDefinition(Node n) {
121 if (n.isVar()) {
122 Node target = n.getFirstChild();
123 Node value = target.getFirstChild();
124 maybeRewriteClassDefinition(n, target, value);
125 } else if (NodeUtil.isExprAssign(n)) {
126 Node assign = n.getFirstChild();
127 Node target = assign.getFirstChild();
128 Node value = assign.getLastChild();
129 maybeRewriteClassDefinition(n, target, value);
130 }
131 }
132
133 private void maybeRewriteClassDefinition(
134 Node n, Node target, Node value) {
135 if (isGoogDefineClass(value)) {
136 if (!target.isQualifiedName()) {
137 compiler.report(JSError.make(n, GOOG_CLASS_TARGET_INVALID));
138 }
139 ClassDefinition def = extractClassDefinition(target, value);
140 if (def != null) {
141 value.detachFromParent();
142 target.detachFromParent();
143 rewriteGoogDefineClass(n, def);
144 }
145 }
146 }
147
148 private static class MemberDefinition {
149 final JSDocInfo info;
150 final Node name;
151 final Node value;
152
153 MemberDefinition(JSDocInfo info, Node name, Node value) {
154 this.info = info;
155 this.name = name;
156 this.value = value;
157 }
158 }
159
160 private final class ClassDefinition {
161 final Node name;
162 final Node superClass;
163 final MemberDefinition constructor;
164 final List<MemberDefinition> staticProps;
165 final List<MemberDefinition> props;
166 final Node classModifier;
167
168 ClassDefinition(
169 Node name,
170 Node superClass,
171 MemberDefinition constructor,
172 List<MemberDefinition> staticProps,
173 List<MemberDefinition> props,
174 Node classModifier) {
175 this.name = name;
176 this.superClass = superClass;
177 this.constructor = constructor;
178 this.staticProps = staticProps;
179 this.props = props;
180 this.classModifier = classModifier;
181 }
182 }
183
184 /**
185 * Validates the class definition and if valid, destructively extracts
186 * the class definition from the AST.
187 */
188 private ClassDefinition extractClassDefinition(
189 Node targetName, Node callNode) {
190
191 // name = goog.defineClass(superClass, {...}, [modifier, ...])
192 Node superClass = NodeUtil.getArgumentForCallOrNew(callNode, 0);
193 if (superClass == null ||
194 (!superClass.isNull() && !superClass.isQualifiedName())) {
195 compiler.report(JSError.make(callNode, GOOG_CLASS_SUPER_CLASS_NOT_VALID));
196 return null;
197 }
198 if (NodeUtil.isNullOrUndefined(superClass)) {
199 superClass = null;
200 }
201
202 Node description = NodeUtil.getArgumentForCallOrNew(callNode, 1);
203 if (description == null
204 || !description.isObjectLit()
205 || !validateObjLit(description)) {
206 // report bad class definition
207 compiler.report(JSError.make(callNode, GOOG_CLASS_DESCRIPTOR_NOT_VALID));
208 return null;
209 }
210
211 int paramCount = callNode.getChildCount() -1;
212 if (paramCount > 2) {
213 compiler.report(JSError.make(callNode, GOOG_CLASS_UNEXPECTED_PARAMS));
214 return null;
215 }
216
217 Node constructor = extractProperty(description, "constructor");
218 if (constructor == null) {
219 // report missing constructor
220 compiler.report(JSError.make(description, GOOG_CLASS_CONSTRUCTOR_MISING));
221 return null;
222 }
223 JSDocInfo info = NodeUtil.getBestJSDocInfo(constructor);
224
225 Node classModifier = null;
226 Node statics = null;
227 Node staticsProp = extractProperty(description, "statics");
228 if (staticsProp != null) {
229 if (staticsProp.isObjectLit() && validateObjLit(staticsProp)) {
230 statics = staticsProp;
231 } else if (staticsProp.isFunction()) {
232 classModifier = staticsProp;
233 } else {
234 compiler.report(
235 JSError.make(staticsProp, GOOG_CLASS_STATICS_NOT_VALID));
236 return null;
237 }
238 }
239
240 if (statics == null) {
241 statics = IR.objectlit();
242 }
243
244 // Ok, now rip apart the definition into its component pieces.
245 // Remove the "special" property key nodes.
246 maybeDetach(constructor.getParent());
247 maybeDetach(statics.getParent());
248 if (classModifier != null) {
249 maybeDetach(classModifier.getParent());
250 }
251 ClassDefinition def = new ClassDefinition(
252 targetName,
253 maybeDetach(superClass),
254 new MemberDefinition(info, null, maybeDetach(constructor)),
255 objectLitToList(maybeDetach(statics)),
256 objectLitToList(description),
257 maybeDetach(classModifier));
258 return def;
259 }
260
261 private Node maybeDetach(Node node) {
262 if (node != null && node.getParent() != null) {
263 node.detachFromParent();
264 }
265 return node;
266 }
267
268 // Only unquoted plain properties are currently supported.
269 private boolean validateObjLit(Node objlit) {
270 for (Node key : objlit.children()) {
271 if (!key.isStringKey() || key.isQuotedString()) {
272 return false;
273 }
274 }
275 return true;
276 }
277
278 /**
279 * @return The first property in the objlit that matches the key.
280 */
281 private Node extractProperty(Node objlit, String keyName) {
282 for (Node keyNode : objlit.children()) {
283 if (keyNode.getString().equals(keyName)) {
284 return keyNode.isStringKey() ? keyNode.getFirstChild() : null;
285 }
286 }
287 return null;
288 }
289
290 private List<MemberDefinition> objectLitToList(
291 Node objlit) {
292 List<MemberDefinition> result = Lists.newArrayList();
293 for (Node keyNode : objlit.children()) {
294 result.add(
295 new MemberDefinition(
296 NodeUtil.getBestJSDocInfo(keyNode),
297 keyNode,
298 keyNode.removeFirstChild()));
299 }
300 objlit.detachChildren();
301 return result;
302 }
303
304 private void rewriteGoogDefineClass(Node exprRoot, ClassDefinition cls) {
305
306 // For simplicity add everything into a block, before adding it to the AST.
307 Node block = IR.block();
308
309 if (exprRoot.isVar()) {
310 // example: var ctr = function(){}
311 block.addChildToBack(
312 IR.var(
313 cls.name.cloneTree(), cls.constructor.value)
314 .srcref(exprRoot).setJSDocInfo(cls.constructor.info));
315 } else {
316 // example: ns.ctr = function(){}
317 block.addChildToBack(
318 fixupSrcref(IR.exprResult(
319 IR.assign(
320 cls.name.cloneTree(), cls.constructor.value)
321 .srcref(exprRoot).setJSDocInfo(cls.constructor.info)
322 .srcref(exprRoot))).setJSDocInfo(cls.constructor.info));
323 }
324
325 if (cls.superClass != null) {
326 // example: goog.inherits(ctr, superClass)
327 block.addChildToBack(
328 fixupSrcref(IR.exprResult(
329 IR.call(
330 NodeUtil.newQualifiedNameNode(
331 compiler.getCodingConvention(), "goog.inherits")
332 .srcrefTree(cls.superClass),
333 cls.name.cloneTree(),
334 cls.superClass.cloneTree()).srcref(cls.superClass))));
335 }
336
337 for (MemberDefinition def : cls.staticProps) {
338 // example: ctr.prop = value
339 block.addChildToBack(
340 fixupSrcref(IR.exprResult(
341 fixupSrcref(IR.assign(
342 IR.getprop(cls.name.cloneTree(),
343 IR.string(def.name.getString()).srcref(def.name))
344 .srcref(def.name),
345 def.value)).setJSDocInfo(def.info))));
346 // Handle inner class definitions.
347 maybeRewriteClassDefinition(block.getLastChild());
348 }
349
350 for (MemberDefinition def : cls.props) {
351 // example: ctr.prototype.prop = value
352 block.addChildToBack(
353 fixupSrcref(IR.exprResult(
354 fixupSrcref(IR.assign(
355 IR.getprop(
356 fixupSrcref(IR.getprop(cls.name.cloneTree(),
357 IR.string("prototype").srcref(def.name))),
358 IR.string(def.name.getString()).srcref(def.name))
359 .srcref(def.name),
360 def.value)).setJSDocInfo(def.info))));
361 // Handle inner class definitions.
362 maybeRewriteClassDefinition(block.getLastChild());
363 }
364
365 if (cls.classModifier != null) {
366 // example: modifier(ctr)
367 block.addChildToBack(
368 IR.exprResult(
369 fixupFreeCall(
370 IR.call(
371 cls.classModifier,
372 cls.name.cloneTree())
373 .srcref(cls.classModifier)))
374 .srcref(cls.classModifier));
375 }
376
377 exprRoot.getParent().replaceChild(exprRoot, block);
378 compiler.reportCodeChange();
379 }
380
381 private Node fixupSrcref(Node node) {
382 node.srcref(node.getFirstChild());
383 return node;
384 }
385
386 private Node fixupFreeCall(Node call) {
387 Preconditions.checkState(call.isCall());
388 call.putBooleanProp(Node.FREE_CALL, true);
389 return call;
390 }
391
392 /**
393 * @return Whether the call represents a class definition.
394 */
395 private boolean isGoogDefineClass(Node value) {
396 if (value != null && value.isCall()) {
397 String targetName = value.getFirstChild().getQualifiedName();
398 return ("goog.defineClass".equals(targetName) ||
399 "goog.labs.classdef.defineClass".equals(targetName));
400 }
401 return false;
402 }
403 }