PageRenderTime 15ms CodeModel.GetById 2ms app.highlight 8ms RepoModel.GetById 2ms app.codeStats 0ms

/tags/release-0.1-rc2/hive/external/ql/src/java/org/apache/hadoop/hive/ql/lib/RuleRegExp.java

#
Java | 81 lines | 28 code | 9 blank | 44 comment | 3 complexity | 70367e71cefd04d77e253b47dc6cc1f0 MD5 | raw file
 1/**
 2 * Licensed to the Apache Software Foundation (ASF) under one
 3 * or more contributor license agreements.  See the NOTICE file
 4 * distributed with this work for additional information
 5 * regarding copyright ownership.  The ASF licenses this file
 6 * to you under the Apache License, Version 2.0 (the
 7 * "License"); you may not use this file except in compliance
 8 * with the License.  You may obtain a copy of the License at
 9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package org.apache.hadoop.hive.ql.lib;
20
21import java.util.Stack;
22import java.util.regex.Matcher;
23import java.util.regex.Pattern;
24
25import org.apache.hadoop.hive.ql.parse.SemanticException;
26
27/**
28 * Rule interface for Nodes Used in Node dispatching to dispatch process/visitor
29 * functions for Nodes.
30 */
31public class RuleRegExp implements Rule {
32
33  private final String ruleName;
34  private final Pattern pattern;
35
36  /**
37   * The rule specified by the regular expression. Note that, the regular
38   * expression is specified in terms of Node name. For eg: TS.*RS -> means
39   * TableScan Node followed by anything any number of times followed by
40   * ReduceSink
41   * 
42   * @param ruleName
43   *          name of the rule
44   * @param regExp
45   *          regular expression for the rule
46   **/
47  public RuleRegExp(String ruleName, String regExp) {
48    this.ruleName = ruleName;
49    pattern = Pattern.compile(regExp);
50  }
51
52  /**
53   * This function returns the cost of the rule for the specified stack. Lower
54   * the cost, the better the rule is matched
55   * 
56   * @param stack
57   *          Node stack encountered so far
58   * @return cost of the function
59   * @throws SemanticException
60   */
61  public int cost(Stack<Node> stack) throws SemanticException {
62    int numElems = (stack != null ? stack.size() : 0);
63    String name = new String();
64    for (int pos = numElems - 1; pos >= 0; pos--) {
65      name = stack.get(pos).getName() + "%" + name;
66      Matcher m = pattern.matcher(name);
67      if (m.matches()) {
68        return m.group().length();
69      }
70    }
71
72    return -1;
73  }
74
75  /**
76   * @return the name of the Node
77   **/
78  public String getName() {
79    return ruleName;
80  }
81}