1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.bnf; |
7 | |
8 | import java.util.ArrayList; |
9 | import java.util.HashMap; |
10 | import org.h2.util.New; |
11 | |
12 | /** |
13 | * Represents a sequence of BNF rules, or a list of alternative rules. |
14 | */ |
15 | public class RuleList implements Rule { |
16 | |
17 | private final boolean or; |
18 | private final ArrayList<Rule> list; |
19 | private boolean mapSet; |
20 | |
21 | public RuleList(Rule first, Rule next, boolean or) { |
22 | list = New.arrayList(); |
23 | if (first instanceof RuleList && ((RuleList) first).or == or) { |
24 | list.addAll(((RuleList) first).list); |
25 | } else { |
26 | list.add(first); |
27 | } |
28 | if (next instanceof RuleList && ((RuleList) next).or == or) { |
29 | list.addAll(((RuleList) next).list); |
30 | } else { |
31 | list.add(next); |
32 | } |
33 | this.or = or; |
34 | } |
35 | |
36 | @Override |
37 | public void accept(BnfVisitor visitor) { |
38 | visitor.visitRuleList(or, list); |
39 | } |
40 | |
41 | @Override |
42 | public void setLinks(HashMap<String, RuleHead> ruleMap) { |
43 | if (!mapSet) { |
44 | for (Rule r : list) { |
45 | r.setLinks(ruleMap); |
46 | } |
47 | mapSet = true; |
48 | } |
49 | } |
50 | |
51 | @Override |
52 | public boolean autoComplete(Sentence sentence) { |
53 | sentence.stopIfRequired(); |
54 | String old = sentence.getQuery(); |
55 | if (or) { |
56 | for (Rule r : list) { |
57 | sentence.setQuery(old); |
58 | if (r.autoComplete(sentence)) { |
59 | return true; |
60 | } |
61 | } |
62 | return false; |
63 | } |
64 | for (Rule r : list) { |
65 | if (!r.autoComplete(sentence)) { |
66 | sentence.setQuery(old); |
67 | return false; |
68 | } |
69 | } |
70 | return true; |
71 | } |
72 | |
73 | } |