Debian Codegraph @

src/com/google/javascript/jscomp/AngularPass.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
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.Lists;
21 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
22
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.JSDocInfo;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27
28 import java.util.ArrayList;
29 import java.util.List;
30
31 /**
32 * Compiler pass for AngularJS-specific needs. Generates {@code $inject} \
33 * properties for functions (class constructors, wrappers, etc) annotated with
34 * @ngInject.
35 *
36 * <p>For example, the following code:</p>
37 * <pre>{@code
38 *
39 * /** @ngInject * /
40 * function Controller(dependency1, dependency2) {
41 * // do something
42 * }
43 *
44 * }</pre>
45 *
46 * <p>will be transformed into:
47 * <pre>{@code
48 *
49 * function Controller(dependency1, dependency2) {
50 * // do something
51 * }
52 * Controller.$inject = ['dependency1', 'dependency2'];
53 *
54 * }</pre>
55 *
56 * <p> This pass also supports assignments of function expressions to variables
57 * like:
58 * <pre>{@code
59 *
60 * /** @ngInject * /
61 * var filter = function(a, b) {};
62 *
63 * var ns = {};
64 * /** @ngInject * /
65 * ns.method = function(a,b,c) {};
66 *
67 * /** @ngInject * /
68 * var shorthand = ns.method2 = function(a,b,c,) {}
69 *
70 * }</pre>
71 */
72 class AngularPass extends AbstractPostOrderCallback implements CompilerPass {
73 final AbstractCompiler compiler;
74
75 /** Nodes annotated with @ngInject */
76 private List<NodeContext> injectables = new ArrayList<NodeContext>();
77
78 public AngularPass(AbstractCompiler compiler) {
79 this.compiler = compiler;
80 }
81
82 public static final String INJECT_PROPERTY_NAME = "$inject";
83
84 static final DiagnosticType INJECT_IN_NON_GLOBAL_OR_BLOCK_ERROR =
85 DiagnosticType.error("JSC_INJECT_IN_NON_GLOBAL_OR_BLOCK_ERROR",
86 "@ngInject only applies to functions defined in blocks or " +
87 "global scope.");
88
89 static final DiagnosticType INJECT_NON_FUNCTION_ERROR =
90 DiagnosticType.error("JSC_INJECT_NON_FUNCTION_ERROR",
91 "@ngInject can only be used when defining a function or " +
92 "assigning a function expression.");
93
94 static final DiagnosticType FUNCTION_NAME_ERROR =
95 DiagnosticType.error("JSC_FUNCTION_NAME_ERROR",
96 "Unable to determine target function name for @ngInject.");
97
98 @Override
99 public void process(Node externs, Node root) {
100 // Traverses AST looking for nodes annotated with @ngInject.
101 NodeTraversal.traverse(compiler, root, this);
102 CodingConvention convention = compiler.getCodingConvention();
103 boolean codeChanged = false;
104 // iterates through annotated nodes adding $inject property to elements.
105 for (NodeContext entry : injectables) {
106 String name = entry.getName();
107 Node fn = entry.getFunctionNode();
108 List<Node> dependencies = createDependenciesList(fn);
109 // skips entry if it does have any dependencies.
110 if (dependencies.size() == 0) {
111 continue;
112 }
113 Node dependenciesArray = IR.arraylit(dependencies.toArray(
114 new Node[dependencies.size()]));
115 // creates `something.$inject = ['param1', 'param2']` node.
116 Node statement = IR.exprResult(
117 IR.assign(
118 IR.getelem(
119 NodeUtil.newQualifiedNameNode(convention, name),
120 IR.string(INJECT_PROPERTY_NAME)),
121 dependenciesArray
122 )
123 );
124 // adds `something.$inject = [...]` node after the annotated node.
125 Node target = entry.getTarget();
126 target.getParent().addChildAfter(statement, target);
127 codeChanged = true;
128 }
129 if (codeChanged) {
130 compiler.reportCodeChange();
131 }
132 }
133
134 /**
135 * Given a FUNCTION node returns array of STRING nodes representing function
136 * parameters.
137 * @param n the FUNCTION node.
138 * @return STRING nodes.
139 */
140 private List<Node> createDependenciesList(Node n) {
141 Preconditions.checkArgument(n.isFunction());
142 Node params = NodeUtil.getFunctionParameters(n);
143 if (params != null) {
144 return createStringsFromParamList(params);
145 }
146 return Lists.newArrayList();
147 }
148
149 /**
150 * Given a PARAM_LIST node creates an array of corresponding STRING nodes.
151 * @param params PARAM_LIST node.
152 * @return array of STRING nodes.
153 */
154 private List<Node> createStringsFromParamList(Node params) {
155 Node param = params.getFirstChild();
156 ArrayList<Node> names = Lists.newArrayList();
157 while (param != null && param.isName()) {
158 names.add(IR.string(param.getString()).srcref(param));
159 param = param.getNext();
160 }
161 return names;
162 }
163
164 @Override
165 public void visit(NodeTraversal t, Node n, Node parent) {
166 JSDocInfo docInfo = n.getJSDocInfo();
167 if (docInfo != null && docInfo.isNgInject()) {
168 addNode(n, t);
169 }
170 }
171
172 /**
173 * Add node to the list of injectables.
174 * @param n node to add.
175 * @param t node traversal instance.
176 */
177 private void addNode(Node n, NodeTraversal t) {
178 Node target = null;
179 Node fn = null;
180 String name = null;
181
182 switch (n.getType()) {
183 // handles assignment cases like:
184 // a = function() {}
185 // a = b = c = function() {}
186 case Token.ASSIGN:
187 name = n.getFirstChild().getQualifiedName();
188 // last node of chained assignment.
189 fn = n;
190 while (fn.isAssign()) {
191 fn = fn.getLastChild();
192 }
193 target = n.getParent();
194 break;
195
196 // handles function case:
197 // function fnName() {}
198 case Token.FUNCTION:
199 name = NodeUtil.getFunctionName(n);
200 fn = n;
201 target = n;
202 break;
203
204 // handles var declaration cases like:
205 // var a = function() {}
206 // var a = b = function() {}
207 case Token.VAR:
208 name = n.getFirstChild().getString();
209 // looks for a function node.
210 fn = getDeclarationRValue(n);
211 target = n;
212 break;
213 }
214 // checks that the declaration took place in a block or in a global scope.
215 if (!target.getParent().isScript() && !target.getParent().isBlock()) {
216 compiler.report(t.makeError(n, INJECT_IN_NON_GLOBAL_OR_BLOCK_ERROR));
217 return;
218 }
219 // checks that it is a function declaration.
220 if (fn == null || !fn.isFunction()) {
221 compiler.report(t.makeError(n, INJECT_NON_FUNCTION_ERROR));
222 return;
223 }
224 // checks that name is present, which must always be the case unless the
225 // compiler allowed a syntax error or a dangling anonymous function
226 // expression.
227 Preconditions.checkNotNull(name);
228 // registers the node.
229 injectables.add(new NodeContext(name, n, fn, target));
230 }
231
232 /**
233 * Given a VAR node (variable declaration) returns the node of initial value.
234 *
235 * <pre>{@code
236 * var x; // null
237 * var y = "value"; // STRING "value" node
238 * var z = x = y = function() {}; // FUNCTION node
239 * }</pre>
240 * @param n VAR node.
241 * @return the assigned intial value, or the rightmost rvalue of an assignment
242 * chain, or null.
243 */
244 private Node getDeclarationRValue(Node n) {
245 Preconditions.checkNotNull(n);
246 Preconditions.checkArgument(n.isVar());
247 n = n.getFirstChild().getFirstChild();
248 if (n == null) {
249 return null;
250 }
251 while (n.isAssign()) {
252 n = n.getLastChild();
253 }
254 return n;
255 }
256
257 class NodeContext {
258 /** Name of the function/object. */
259 private String name;
260 /** Node jsDoc is attached to. */
261 private Node node;
262 /** Function node */
263 private Node functionNode;
264 /** Node after which to inject the new code */
265 private Node target;
266
267 public NodeContext(String name, Node node, Node functionNode, Node target) {
268 this.name = name;
269 this.node = node;
270 this.functionNode = functionNode;
271 this.target = target;
272 }
273
274 /**
275 * @return the name.
276 */
277 public String getName() {
278 return name;
279 }
280
281 /**
282 * @return the node.
283 */
284 public Node getNode() {
285 return node;
286 }
287
288 /**
289 * @return the context.
290 */
291 public Node getFunctionNode() {
292 return functionNode;
293 }
294
295 /**
296 * @return the context.
297 */
298 public Node getTarget() {
299 return target;
300 }
301 }
302 }