Debian Codegraph @

rhino/src/org/mozilla/javascript/ast/FunctionNode.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.ast;
8
9 import org.mozilla.javascript.Node;
10 import org.mozilla.javascript.Token;
11
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17
18 /**
19 * A JavaScript function declaration or expression.<p>
20 * Node type is {@link Token#FUNCTION}.<p>
21 *
22 * <pre><i>FunctionDeclaration</i> :
23 * <b>function</b> Identifier ( FormalParameterListopt ) { FunctionBody }
24 * <i>FunctionExpression</i> :
25 * <b>function</b> Identifieropt ( FormalParameterListopt ) { FunctionBody }
26 * <i>FormalParameterList</i> :
27 * Identifier
28 * FormalParameterList , Identifier
29 * <i>FunctionBody</i> :
30 * SourceElements
31 * <i>Program</i> :
32 * SourceElements
33 * <i>SourceElements</i> :
34 * SourceElement
35 * SourceElements SourceElement
36 * <i>SourceElement</i> :
37 * Statement
38 * FunctionDeclaration</pre>
39 *
40 * JavaScript 1.8 introduces "function closures" of the form
41 * <pre>function ([params] ) Expression</pre>
42 *
43 * In this case the FunctionNode node will have no body but will have an
44 * expression.
45 */
46 public class FunctionNode extends ScriptNode {
47
48 /**
49 * There are three types of functions that can be defined. The first
50 * is a function statement. This is a function appearing as a top-level
51 * statement (i.e., not nested inside some other statement) in either a
52 * script or a function.<p>
53 *
54 * The second is a function expression, which is a function appearing in
55 * an expression except for the third type, which is...<p>
56 *
57 * The third type is a function expression where the expression is the
58 * top-level expression in an expression statement.<p>
59 *
60 * The three types of functions have different treatment and must be
61 * distinguished.<p>
62 */
63 public static final int FUNCTION_STATEMENT = 1;
64 public static final int FUNCTION_EXPRESSION = 2;
65 public static final int FUNCTION_EXPRESSION_STATEMENT = 3;
66 public static final int ARROW_FUNCTION = 4;
67
68 public static enum Form { FUNCTION, GETTER, SETTER, METHOD }
69
70 private static final List<AstNode> NO_PARAMS =
71 Collections.unmodifiableList(new ArrayList<AstNode>());
72
73 private Name functionName;
74 private List<AstNode> params;
75 private AstNode body;
76 private boolean isExpressionClosure;
77 private Form functionForm = Form.FUNCTION;
78 private int lp = -1;
79 private int rp = -1;
80
81 // codegen variables
82 private int functionType;
83 private boolean needsActivation;
84 private boolean isGenerator;
85 private List<Node> generatorResumePoints;
86 private Map<Node,int[]> liveLocals;
87 private AstNode memberExprNode;
88
89 {
90 type = Token.FUNCTION;
91 }
92
93 public FunctionNode() {
94 }
95
96 public FunctionNode(int pos) {
97 super(pos);
98 }
99
100 public FunctionNode(int pos, Name name) {
101 super(pos);
102 setFunctionName(name);
103 }
104
105 /**
106 * Returns function name
107 * @return function name, {@code null} for anonymous functions
108 */
109 public Name getFunctionName() {
110 return functionName;
111 }
112
113 /**
114 * Sets function name, and sets its parent to this node.
115 * @param name function name, {@code null} for anonymous functions
116 */
117 public void setFunctionName(Name name) {
118 functionName = name;
119 if (name != null)
120 name.setParent(this);
121 }
122
123 /**
124 * Returns the function name as a string
125 * @return the function name, {@code ""} if anonymous
126 */
127 public String getName() {
128 return functionName != null ? functionName.getIdentifier() : "";
129 }
130
131 /**
132 * Returns the function parameter list
133 * @return the function parameter list. Returns an immutable empty
134 * list if there are no parameters.
135 */
136 public List<AstNode> getParams() {
137 return params != null ? params : NO_PARAMS;
138 }
139
140 /**
141 * Sets the function parameter list, and sets the parent for
142 * each element of the list.
143 * @param params the function parameter list, or {@code null} if no params
144 */
145 public void setParams(List<AstNode> params) {
146 if (params == null) {
147 this.params = null;
148 } else {
149 if (this.params != null)
150 this.params.clear();
151 for (AstNode param : params)
152 addParam(param);
153 }
154 }
155
156 /**
157 * Adds a parameter to the function parameter list.
158 * Sets the parent of the param node to this node.
159 * @param param the parameter
160 * @throws IllegalArgumentException if param is {@code null}
161 */
162 public void addParam(AstNode param) {
163 assertNotNull(param);
164 if (params == null) {
165 params = new ArrayList<AstNode>();
166 }
167 params.add(param);
168 param.setParent(this);
169 }
170
171 /**
172 * Returns true if the specified {@link AstNode} node is a parameter
173 * of this Function node. This provides a way during AST traversal
174 * to disambiguate the function name node from the parameter nodes.
175 */
176 public boolean isParam(AstNode node) {
177 return params == null ? false : params.contains(node);
178 }
179
180 /**
181 * Returns function body. Normally a {@link Block}, but can be a plain
182 * {@link AstNode} if it's a function closure.
183 *
184 * @return the body. Can be {@code null} only if the AST is malformed.
185 */
186 public AstNode getBody() {
187 return body;
188 }
189
190 /**
191 * Sets function body, and sets its parent to this node.
192 * Also sets the encoded source bounds based on the body bounds.
193 * Assumes the function node absolute position has already been set,
194 * and the body node's absolute position and length are set.<p>
195 *
196 * @param body function body. Its parent is set to this node, and its
197 * position is updated to be relative to this node.
198 *
199 * @throws IllegalArgumentException if body is {@code null}
200 */
201 public void setBody(AstNode body) {
202 assertNotNull(body);
203 this.body = body;
204 if (Boolean.TRUE.equals(body.getProp(Node.EXPRESSION_CLOSURE_PROP))) {
205 setIsExpressionClosure(true);
206 }
207 int absEnd = body.getPosition() + body.getLength();
208 body.setParent(this);
209 this.setLength(absEnd - this.position);
210 setEncodedSourceBounds(this.position, absEnd);
211 }
212
213 /**
214 * Returns left paren position, -1 if missing
215 */
216 public int getLp() {
217 return lp;
218 }
219
220 /**
221 * Sets left paren position
222 */
223 public void setLp(int lp) {
224 this.lp = lp;
225 }
226
227 /**
228 * Returns right paren position, -1 if missing
229 */
230 public int getRp() {
231 return rp;
232 }
233
234 /**
235 * Sets right paren position
236 */
237 public void setRp(int rp) {
238 this.rp = rp;
239 }
240
241 /**
242 * Sets both paren positions
243 */
244 public void setParens(int lp, int rp) {
245 this.lp = lp;
246 this.rp = rp;
247 }
248
249 /**
250 * Returns whether this is a 1.8 function closure
251 */
252 public boolean isExpressionClosure() {
253 return isExpressionClosure;
254 }
255
256 /**
257 * Sets whether this is a 1.8 function closure
258 */
259 public void setIsExpressionClosure(boolean isExpressionClosure) {
260 this.isExpressionClosure = isExpressionClosure;
261 }
262
263 /**
264 * Return true if this function requires an Ecma-262 Activation object.
265 * The Activation object is implemented by
266 * {@link org.mozilla.javascript.NativeCall}, and is fairly expensive
267 * to create, so when possible, the interpreter attempts to use a plain
268 * call frame instead.
269 *
270 * @return true if this function needs activation. It could be needed
271 * if there is a lexical closure, or in a number of other situations.
272 */
273 public boolean requiresActivation() {
274 return needsActivation;
275 }
276
277 public void setRequiresActivation() {
278 needsActivation = true;
279 }
280
281 public boolean isGenerator() {
282 return isGenerator;
283 }
284
285 public void setIsGenerator() {
286 isGenerator = true;
287 }
288
289 public void addResumptionPoint(Node target) {
290 if (generatorResumePoints == null)
291 generatorResumePoints = new ArrayList<Node>();
292 generatorResumePoints.add(target);
293 }
294
295 public List<Node> getResumptionPoints() {
296 return generatorResumePoints;
297 }
298
299 public Map<Node,int[]> getLiveLocals() {
300 return liveLocals;
301 }
302
303 public void addLiveLocals(Node node, int[] locals) {
304 if (liveLocals == null)
305 liveLocals = new HashMap<Node,int[]>();
306 liveLocals.put(node, locals);
307 }
308
309 @Override
310 public int addFunction(FunctionNode fnNode) {
311 int result = super.addFunction(fnNode);
312 if (getFunctionCount() > 0) {
313 needsActivation = true;
314 }
315 return result;
316 }
317
318 /**
319 * Returns the function type (statement, expr, statement expr)
320 */
321 public int getFunctionType() {
322 return functionType;
323 }
324
325 public void setFunctionType(int type) {
326 functionType = type;
327 }
328
329 public boolean isMethod() {
330 return functionForm == Form.GETTER || functionForm == Form.SETTER || functionForm == Form.METHOD;
331 }
332
333 public boolean isGetterMethod() {
334 return functionForm == Form.GETTER;
335 }
336
337 public boolean isSetterMethod() {
338 return functionForm == Form.SETTER;
339 }
340
341 public boolean isNormalMethod() {
342 return functionForm == Form.METHOD;
343 }
344
345 public void setFunctionIsGetterMethod() {
346 functionForm = Form.GETTER;
347 }
348
349 public void setFunctionIsSetterMethod() {
350 functionForm = Form.SETTER;
351 }
352
353 public void setFunctionIsNormalMethod() {
354 functionForm = Form.METHOD;
355 }
356
357 /**
358 * Rhino supports a nonstandard Ecma extension that allows you to
359 * say, for instance, function a.b.c(arg1, arg) {...}, and it will
360 * be rewritten at codegen time to: a.b.c = function(arg1, arg2) {...}
361 * If we detect an expression other than a simple Name in the position
362 * where a function name was expected, we record that expression here.
363 * <p>
364 * This extension is only available by setting the CompilerEnv option
365 * "isAllowMemberExprAsFunctionName" in the Parser.
366 */
367 public void setMemberExprNode(AstNode node) {
368 memberExprNode = node;
369 if (node != null)
370 node.setParent(this);
371 }
372
373 public AstNode getMemberExprNode() {
374 return memberExprNode;
375 }
376
377 @Override
378 public String toSource(int depth) {
379 StringBuilder sb = new StringBuilder();
380 boolean isArrow = functionType == ARROW_FUNCTION;
381 if (!isMethod()) {
382 sb.append(makeIndent(depth));
383 if (!isArrow) {
384 sb.append("function");
385 }
386 }
387 if (functionName != null) {
388 sb.append(" ");
389 sb.append(functionName.toSource(0));
390 }
391 if (params == null) {
392 sb.append("() ");
393 } else if (isArrow && lp == -1) {
394 // no paren
395 printList(params, sb);
396 sb.append(" ");
397 } else {
398 sb.append("(");
399 printList(params, sb);
400 sb.append(") ");
401 }
402 if (isArrow) {
403 sb.append("=> ");
404 }
405 if (isExpressionClosure) {
406 AstNode body = getBody();
407 if (body.getLastChild() instanceof ReturnStatement) {
408 // omit "return" keyword, just print the expression
409 body = ((ReturnStatement) body.getLastChild()).getReturnValue();
410 sb.append(body.toSource(0));
411 if (functionType == FUNCTION_STATEMENT) {
412 sb.append(";");
413 }
414 } else {
415 // should never happen
416 sb.append(" ");
417 sb.append(body.toSource(0));
418 }
419 } else {
420 sb.append(getBody().toSource(depth).trim());
421 }
422 if (functionType == FUNCTION_STATEMENT || isMethod()) {
423 sb.append("\n");
424 }
425 return sb.toString();
426 }
427
428 /**
429 * Visits this node, the function name node if supplied,
430 * the parameters, and the body. If there is a member-expr node,
431 * it is visited last.
432 */
433 @Override
434 public void visit(NodeVisitor v) {
435 if (v.visit(this)) {
436 if (functionName != null) {
437 functionName.visit(v);
438 }
439 for (AstNode param : getParams()) {
440 param.visit(v);
441 }
442 getBody().visit(v);
443 if (!isExpressionClosure) {
444 if (memberExprNode != null) {
445 memberExprNode.visit(v);
446 }
447 }
448 }
449 }
450 }