Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.javascript.jscomp.NodeTraversal.Callback;
22 import com.google.javascript.rhino.Node;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26
27 /**
28 * Moves top-level function declarations to the top.
29 *
30 * Enable this pass if a try catch block wraps the output after compilation,
31 * and the output runs on Firefox because function declarations are only
32 * defined when reached inside a try catch block on Firefox.
33 *
34 * On Firefox, this code works:
35 *
36 * var g = f;
37 * function f() {}
38 *
39 * but this code does not work:
40 *
41 * try {
42 * var g = f;
43 * function f() {}
44 * } catch(e) {}
45 *
46 */
47 class MoveFunctionDeclarations implements Callback, CompilerPass {
48 private final AbstractCompiler compiler;
49 private final Map<JSModule, List<Node>> functions;
50
51 MoveFunctionDeclarations(AbstractCompiler compiler) {
52 this.compiler = compiler;
53 functions = Maps.newHashMap();
54 }
55
56 @Override
57 public void process(Node externs, Node root) {
58 NodeTraversal.traverse(compiler, root, this);
59 for (Entry<JSModule, List<Node>> entry : functions.entrySet()) {
60 JSModule module = entry.getKey();
61 Node addingRoot = compiler.getNodeForCodeInsertion(module);
62 for (Node n : Lists.reverse(entry.getValue())) {
63 addingRoot.addChildToFront(n);
64 }
65 }
66 }
67
68 @Override
69 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
70 Node gramps = n.getAncestor(2);
71 return gramps == null || !gramps.isScript();
72 }
73
74 @Override
75 public void visit(NodeTraversal t, Node n, Node parent) {
76 if (parent == null || !parent.isScript()) {
77 return;
78 }
79
80 if (NodeUtil.isFunctionDeclaration(n)) {
81 parent.removeChild(n);
82 compiler.reportCodeChange();
83
84 JSModule module = t.getModule();
85 List<Node> moduleFunctions = functions.get(module);
86 if (moduleFunctions == null) {
87 moduleFunctions = Lists.newArrayList();
88 functions.put(module, moduleFunctions);
89 }
90 moduleFunctions.add(n);
91 }
92 }
93 }