1 5 package org.h2.bnf; 6 7 import java.util.HashMap ; 8 9 import org.h2.util.StringUtils; 10 11 public class RuleElement implements Rule { 12 13 private boolean keyword; 14 private String name; 15 private Rule link; 16 private int type; 17 private String topic; 18 19 public RuleElement(String name, boolean keyword, String topic) { 20 this.name = name; 21 this.topic = topic; 22 this.keyword = keyword; 23 this.type = Sentence.CONTEXT; 24 } 25 26 public RuleElement(String name, String topic) { 27 this.name = name; 28 this.topic = topic; 29 if(name.length()==1 || name.equals(StringUtils.toUpperEnglish(name))) { 30 keyword = true; 31 } 32 topic = StringUtils.toLowerEnglish(topic); 33 this.type = topic.startsWith("function") ? Sentence.FUNCTION : Sentence.KEYWORD; 34 } 35 36 public RuleElement merge(RuleElement rule) { 37 return new RuleElement(name + " " + rule.name, topic); 38 } 39 40 public String random(Bnf config, int level) { 41 if(keyword) { 42 return name.length() > 1 ? " " + name + " " : name; 43 } 44 if(link != null) { 45 return link.random(config, level+1); 46 } 47 throw new Error (">>>" + name + "<<<"); 48 } 49 50 public String name() { 51 return name; 52 } 53 54 public Rule last() { 55 return this; 56 } 57 58 public void setLinks(HashMap ruleMap) { 59 if(link != null) { 60 link.setLinks(ruleMap); 61 } 62 if(keyword) { 63 return; 64 } 65 for(int i=0; i<name.length() && link == null; i++) { 66 String test = StringUtils.toLowerEnglish(name.substring(i)); 67 RuleHead r = (RuleHead)ruleMap.get(test); 68 if(r != null) { 69 link = r.rule; 70 return; 71 } 72 } 73 if(link == null) { 74 throw new Error (">>>" + name + "<<<"); 75 } 76 } 77 78 public String matchRemove(String query, Sentence sentence) { 79 if(sentence.stop()) { 80 return null; 81 } 82 if(query.length()==0) { 83 return null; 84 } 85 if(keyword) { 86 String up = StringUtils.toUpperEnglish(query); 87 if(up.startsWith(name)) { 88 query = query.substring(name.length()); 89 while(!name.equals("_") && query.length()>0 && Character.isWhitespace(query.charAt(0))) { 90 query = query.substring(1); 91 } 92 return query; 93 } 94 return null; 95 } else { 96 query = link.matchRemove(query, sentence); 97 if(query != null && !name.startsWith("@") && (link.name() == null || !link.name().startsWith("@"))) { 98 while(query.length()>0 && Character.isWhitespace(query.charAt(0))) { 99 query = query.substring(1); 100 } 101 } 102 return query; 103 } 104 } 105 106 public void addNextTokenList(String query, Sentence sentence) { 107 if(sentence.stop()) { 108 return; 109 } 110 if(keyword) { 111 String q = query.trim(); 112 String up = StringUtils.toUpperEnglish(q); 113 if(q.length() == 0 || name.startsWith(up)) { 114 if(q.length() < name.length()) { 115 sentence.add(name, name.substring(q.length()), type); 116 } 117 } 118 return; 119 } 120 link.addNextTokenList(query, sentence); 121 } 122 123 public boolean isKeyword() { 124 return keyword; 125 } 126 127 } 128 | Popular Tags |