Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2010 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.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
19 import com.google.javascript.jscomp.regex.RegExpTree;
20 import com.google.javascript.rhino.Token;
21 import com.google.javascript.rhino.Node;
22
23 /**
24 * Look for references to the global RegExp object that would cause
25 * regular expressions to be unoptimizable, and checks that regular expressions
26 * are syntactically valid.
27 *
28 * @author [email protected] (John Lenz)
29 */
30 class CheckRegExp extends AbstractPostOrderCallback implements CompilerPass {
31
32 static final DiagnosticType REGEXP_REFERENCE =
33 DiagnosticType.warning("JSC_REGEXP_REFERENCE",
34 "References to the global RegExp object prevents " +
35 "optimization of regular expressions.");
36 static final DiagnosticType MALFORMED_REGEXP = DiagnosticType.warning(
37 "JSC_MALFORMED_REGEXP",
38 "Malformed Regular Expression: {0}");
39
40 private final AbstractCompiler compiler;
41 private boolean globalRegExpPropertiesUsed = false;
42
43 public boolean isGlobalRegExpPropertiesUsed() {
44 return globalRegExpPropertiesUsed;
45 }
46
47 public CheckRegExp(AbstractCompiler compiler) {
48 this.compiler = compiler;
49 }
50
51 @Override
52 public void process(Node externs, Node root) {
53 NodeTraversal.traverse(compiler, root, this);
54 }
55
56 @Override
57 public void visit(NodeTraversal t, Node n, Node parent) {
58 if (NodeUtil.isReferenceName(n)) {
59 String name = n.getString();
60 if (name.equals("RegExp") && t.getScope().getVar(name) == null) {
61 int parentType = parent.getType();
62 boolean first = (n == parent.getFirstChild());
63 if (!((parentType == Token.NEW && first)
64 || (parentType == Token.CALL && first)
65 || (parentType == Token.INSTANCEOF && !first))) {
66 t.report(n, REGEXP_REFERENCE);
67 globalRegExpPropertiesUsed = true;
68 }
69 }
70
71 // Check the syntax of regular expression patterns.
72 } else if (n.isRegExp()) {
73 String pattern = n.getFirstChild().getString();
74 String flags = n.getChildCount() == 2
75 ? n.getLastChild().getString() : "";
76 try {
77 RegExpTree.parseRegExp(pattern, flags);
78 } catch (IllegalArgumentException ex) {
79 t.report(n, MALFORMED_REGEXP, ex.getMessage());
80 }
81 }
82 }
83 }