| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.bnf; |
| 7 |
|
| 8 |
import java.io.ByteArrayInputStream; |
| 9 |
import java.io.IOException; |
| 10 |
import java.io.InputStreamReader; |
| 11 |
import java.io.Reader; |
| 12 |
import java.nio.charset.StandardCharsets; |
| 13 |
import java.sql.ResultSet; |
| 14 |
import java.sql.SQLException; |
| 15 |
import java.util.ArrayList; |
| 16 |
import java.util.HashMap; |
| 17 |
import java.util.StringTokenizer; |
| 18 |
import org.h2.bnf.context.DbContextRule; |
| 19 |
import org.h2.command.dml.Help; |
| 20 |
import org.h2.tools.Csv; |
| 21 |
import org.h2.util.StringUtils; |
| 22 |
import org.h2.util.Utils; |
| 23 |
|
| 24 |
/** |
| 25 |
* This class can read a file that is similar to BNF (Backus-Naur form). |
| 26 |
* It is made specially to support SQL grammar. |
| 27 |
*/ |
| 28 |
public class Bnf { |
| 29 |
|
| 30 |
/** |
| 31 |
* The rule map. The key is lowercase, and all spaces |
| 32 |
* are replaces with underscore. |
| 33 |
*/ |
| 34 |
private final HashMap<String, RuleHead> ruleMap = new HashMap<>(); |
| 35 |
private String syntax; |
| 36 |
private String currentToken; |
| 37 |
private String[] tokens; |
| 38 |
private char firstChar; |
| 39 |
private int index; |
| 40 |
private Rule lastRepeat; |
| 41 |
private ArrayList<RuleHead> statements; |
| 42 |
private String currentTopic; |
| 43 |
|
| 44 |
/** |
| 45 |
* Create an instance using the grammar specified in the CSV file. |
| 46 |
* |
| 47 |
* @param csv if not specified, the help.csv is used |
| 48 |
* @return a new instance |
| 49 |
* @throws SQLException on failure |
| 50 |
* @throws IOException on failure |
| 51 |
*/ |
| 52 |
public static Bnf getInstance(Reader csv) throws SQLException, IOException { |
| 53 |
Bnf bnf = new Bnf(); |
| 54 |
if (csv == null) { |
| 55 |
byte[] data = Utils.getResource("/org/h2/res/help.csv"); |
| 56 |
csv = new InputStreamReader(new ByteArrayInputStream(data), StandardCharsets.UTF_8); |
| 57 |
} |
| 58 |
bnf.parse(csv); |
| 59 |
return bnf; |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Add an alias for a rule. |
| 64 |
* |
| 65 |
* @param name for example "procedure" |
| 66 |
* @param replacement for example "@func@" |
| 67 |
*/ |
| 68 |
public void addAlias(String name, String replacement) { |
| 69 |
RuleHead head = ruleMap.get(replacement); |
| 70 |
ruleMap.put(name, head); |
| 71 |
} |
| 72 |
|
| 73 |
private void addFixedRule(String name, int fixedType) { |
| 74 |
Rule rule = new RuleFixed(fixedType); |
| 75 |
addRule(name, "Fixed", rule); |
| 76 |
} |
| 77 |
|
| 78 |
private RuleHead addRule(String topic, String section, Rule rule) { |
| 79 |
RuleHead head = new RuleHead(section, topic, rule); |
| 80 |
String key = StringUtils.toLowerEnglish(topic.trim().replace(' ', '_')); |
| 81 |
if (ruleMap.putIfAbsent(key, head) != null) { |
| 82 |
throw new AssertionError("already exists: " + topic); |
| 83 |
} |
| 84 |
return head; |
| 85 |
} |
| 86 |
|
| 87 |
private void parse(Reader reader) throws SQLException, IOException { |
| 88 |
Rule functions = null; |
| 89 |
statements = new ArrayList<>(); |
| 90 |
Csv csv = new Csv(); |
| 91 |
csv.setLineCommentCharacter('#'); |
| 92 |
ResultSet rs = csv.read(reader, null); |
| 93 |
while (rs.next()) { |
| 94 |
String section = rs.getString("SECTION").trim(); |
| 95 |
if (section.startsWith("System")) { |
| 96 |
continue; |
| 97 |
} |
| 98 |
String topic = rs.getString("TOPIC"); |
| 99 |
syntax = Help.stripAnnotationsFromSyntax(rs.getString("SYNTAX")); |
| 100 |
currentTopic = section; |
| 101 |
tokens = tokenize(); |
| 102 |
index = 0; |
| 103 |
Rule rule = parseRule(); |
| 104 |
if (section.startsWith("Command")) { |
| 105 |
rule = new RuleList(rule, new RuleElement(";\n\n", currentTopic), false); |
| 106 |
} |
| 107 |
RuleHead head = addRule(topic, section, rule); |
| 108 |
if (section.startsWith("Function")) { |
| 109 |
if (functions == null) { |
| 110 |
functions = rule; |
| 111 |
} else { |
| 112 |
functions = new RuleList(rule, functions, true); |
| 113 |
} |
| 114 |
} else if (section.startsWith("Commands")) { |
| 115 |
statements.add(head); |
| 116 |
} |
| 117 |
} |
| 118 |
addRule("@func@", "Function", functions); |
| 119 |
addFixedRule("@ymd@", RuleFixed.YMD); |
| 120 |
addFixedRule("@hms@", RuleFixed.HMS); |
| 121 |
addFixedRule("@nanos@", RuleFixed.NANOS); |
| 122 |
addFixedRule("anything_except_single_quote", RuleFixed.ANY_EXCEPT_SINGLE_QUOTE); |
| 123 |
addFixedRule("single_character", RuleFixed.ANY_EXCEPT_SINGLE_QUOTE); |
| 124 |
addFixedRule("anything_except_double_quote", RuleFixed.ANY_EXCEPT_DOUBLE_QUOTE); |
| 125 |
addFixedRule("anything_until_end_of_line", RuleFixed.ANY_UNTIL_EOL); |
| 126 |
addFixedRule("anything_until_comment_start_or_end", RuleFixed.ANY_UNTIL_END); |
| 127 |
addFixedRule("anything_except_two_dollar_signs", RuleFixed.ANY_EXCEPT_2_DOLLAR); |
| 128 |
addFixedRule("anything", RuleFixed.ANY_WORD); |
| 129 |
addFixedRule("@hex_start@", RuleFixed.HEX_START); |
| 130 |
addFixedRule("@octal_start@", RuleFixed.OCTAL_START); |
| 131 |
addFixedRule("@binary_start@", RuleFixed.BINARY_START); |
| 132 |
addFixedRule("@concat@", RuleFixed.CONCAT); |
| 133 |
addFixedRule("@az_@", RuleFixed.AZ_UNDERSCORE); |
| 134 |
addFixedRule("@af@", RuleFixed.AF); |
| 135 |
addFixedRule("@digit@", RuleFixed.DIGIT); |
| 136 |
addFixedRule("@open_bracket@", RuleFixed.OPEN_BRACKET); |
| 137 |
addFixedRule("@close_bracket@", RuleFixed.CLOSE_BRACKET); |
| 138 |
addFixedRule("json_text", RuleFixed.JSON_TEXT); |
| 139 |
Rule digit = ruleMap.get("digit").getRule(); |
| 140 |
ruleMap.get("number").setRule(new RuleList(digit, new RuleOptional(new RuleRepeat(digit, false)), false)); |
| 141 |
} |
| 142 |
|
| 143 |
/** |
| 144 |
* Parse the syntax and let the rule call the visitor. |
| 145 |
* |
| 146 |
* @param visitor the visitor |
| 147 |
* @param s the syntax to parse |
| 148 |
*/ |
| 149 |
public void visit(BnfVisitor visitor, String s) { |
| 150 |
this.syntax = s; |
| 151 |
tokens = tokenize(); |
| 152 |
index = 0; |
| 153 |
Rule rule = parseRule(); |
| 154 |
rule.setLinks(ruleMap); |
| 155 |
rule.accept(visitor); |
| 156 |
} |
| 157 |
|
| 158 |
/** |
| 159 |
* Check whether the statement starts with a whitespace. |
| 160 |
* |
| 161 |
* @param s the statement |
| 162 |
* @return if the statement is not empty and starts with a whitespace |
| 163 |
*/ |
| 164 |
public static boolean startWithSpace(String s) { |
| 165 |
return s.length() > 0 && Character.isWhitespace(s.charAt(0)); |
| 166 |
} |
| 167 |
|
| 168 |
/** |
| 169 |
* Convert convert ruleLink to rule_link. |
| 170 |
* |
| 171 |
* @param token the token |
| 172 |
* @return the rule map key |
| 173 |
*/ |
| 174 |
public static String getRuleMapKey(String token) { |
| 175 |
StringBuilder buff = new StringBuilder(); |
| 176 |
for (int i = 0, l = token.length(); i < l; i++) { |
| 177 |
char ch = token.charAt(i); |
| 178 |
if (Character.isUpperCase(ch)) { |
| 179 |
buff.append('_').append(Character.toLowerCase(ch)); |
| 180 |
} else { |
| 181 |
buff.append(ch); |
| 182 |
} |
| 183 |
} |
| 184 |
return buff.toString(); |
| 185 |
} |
| 186 |
|
| 187 |
/** |
| 188 |
* Get the rule head for the given title. |
| 189 |
* |
| 190 |
* @param title the title |
| 191 |
* @return the rule head, or null |
| 192 |
*/ |
| 193 |
public RuleHead getRuleHead(String title) { |
| 194 |
return ruleMap.get(title); |
| 195 |
} |
| 196 |
|
| 197 |
private Rule parseRule() { |
| 198 |
read(); |
| 199 |
return parseOr(); |
| 200 |
} |
| 201 |
|
| 202 |
private Rule parseOr() { |
| 203 |
Rule r = parseList(); |
| 204 |
if (firstChar == '|') { |
| 205 |
read(); |
| 206 |
r = new RuleList(r, parseOr(), true); |
| 207 |
} |
| 208 |
lastRepeat = r; |
| 209 |
return r; |
| 210 |
} |
| 211 |
|
| 212 |
private Rule parseList() { |
| 213 |
Rule r = parseToken(); |
| 214 |
if (firstChar != '|' && firstChar != ']' && firstChar != '}' |
| 215 |
&& firstChar != 0) { |
| 216 |
r = new RuleList(r, parseList(), false); |
| 217 |
} |
| 218 |
lastRepeat = r; |
| 219 |
return r; |
| 220 |
} |
| 221 |
|
| 222 |
private RuleExtension parseExtension(boolean compatibility) { |
| 223 |
read(); |
| 224 |
Rule r; |
| 225 |
if (firstChar == '[') { |
| 226 |
read(); |
| 227 |
r = parseOr(); |
| 228 |
r = new RuleOptional(r); |
| 229 |
if (firstChar != ']') { |
| 230 |
throw new AssertionError("expected ], got " + currentToken + " syntax:" + syntax); |
| 231 |
} |
| 232 |
} else if (firstChar == '{') { |
| 233 |
read(); |
| 234 |
r = parseOr(); |
| 235 |
if (firstChar != '}') { |
| 236 |
throw new AssertionError("expected }, got " + currentToken + " syntax:" + syntax); |
| 237 |
} |
| 238 |
} else { |
| 239 |
r = parseOr(); |
| 240 |
} |
| 241 |
return new RuleExtension(r, compatibility); |
| 242 |
} |
| 243 |
|
| 244 |
private Rule parseToken() { |
| 245 |
Rule r; |
| 246 |
if ((firstChar >= 'A' && firstChar <= 'Z') |
| 247 |
|| (firstChar >= 'a' && firstChar <= 'z')) { |
| 248 |
// r = new RuleElement(currentToken+ " syntax:" + syntax); |
| 249 |
r = new RuleElement(currentToken, currentTopic); |
| 250 |
} else if (firstChar == '[') { |
| 251 |
read(); |
| 252 |
r = parseOr(); |
| 253 |
r = new RuleOptional(r); |
| 254 |
if (firstChar != ']') { |
| 255 |
throw new AssertionError("expected ], got " + currentToken + " syntax:" + syntax); |
| 256 |
} |
| 257 |
} else if (firstChar == '{') { |
| 258 |
read(); |
| 259 |
r = parseOr(); |
| 260 |
if (firstChar != '}') { |
| 261 |
throw new AssertionError("expected }, got " + currentToken + " syntax:" + syntax); |
| 262 |
} |
| 263 |
} else if (firstChar == '@') { |
| 264 |
if ("@commaDots@".equals(currentToken)) { |
| 265 |
r = new RuleList(new RuleElement(",", currentTopic), lastRepeat, false); |
| 266 |
r = new RuleRepeat(r, true); |
| 267 |
} else if ("@dots@".equals(currentToken)) { |
| 268 |
r = new RuleRepeat(lastRepeat, false); |
| 269 |
} else if ("@c@".equals(currentToken)) { |
| 270 |
r = parseExtension(true); |
| 271 |
} else if ("@h2@".equals(currentToken)) { |
| 272 |
r = parseExtension(false); |
| 273 |
} else { |
| 274 |
r = new RuleElement(currentToken, currentTopic); |
| 275 |
} |
| 276 |
} else { |
| 277 |
r = new RuleElement(currentToken, currentTopic); |
| 278 |
} |
| 279 |
lastRepeat = r; |
| 280 |
read(); |
| 281 |
return r; |
| 282 |
} |
| 283 |
|
| 284 |
private void read() { |
| 285 |
if (index < tokens.length) { |
| 286 |
currentToken = tokens[index++]; |
| 287 |
firstChar = currentToken.charAt(0); |
| 288 |
} else { |
| 289 |
currentToken = ""; |
| 290 |
firstChar = 0; |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
@Override |
| 295 |
public String toString() { |
| 296 |
StringBuilder builder = new StringBuilder(); |
| 297 |
for (int i = 0; i < index; i++) { |
| 298 |
builder.append(tokens[i]).append(' '); |
| 299 |
} |
| 300 |
builder.append("[*]"); |
| 301 |
for (int i = index; i < tokens.length; i++) { |
| 302 |
builder.append(' ').append(tokens[i]); |
| 303 |
} |
| 304 |
return builder.toString(); |
| 305 |
} |
| 306 |
|
| 307 |
private String[] tokenize() { |
| 308 |
ArrayList<String> list = new ArrayList<>(); |
| 309 |
syntax = StringUtils.replaceAll(syntax, "yyyy-MM-dd", "@ymd@"); |
| 310 |
syntax = StringUtils.replaceAll(syntax, "hh:mm:ss", "@hms@"); |
| 311 |
syntax = StringUtils.replaceAll(syntax, "hh:mm", "@hms@"); |
| 312 |
syntax = StringUtils.replaceAll(syntax, "mm:ss", "@hms@"); |
| 313 |
syntax = StringUtils.replaceAll(syntax, "nnnnnnnnn", "@nanos@"); |
| 314 |
syntax = StringUtils.replaceAll(syntax, "function", "@func@"); |
| 315 |
syntax = StringUtils.replaceAll(syntax, "0x", "@hexStart@"); |
| 316 |
syntax = StringUtils.replaceAll(syntax, "0o", "@octalStart@"); |
| 317 |
syntax = StringUtils.replaceAll(syntax, "0b", "@binaryStart@"); |
| 318 |
syntax = StringUtils.replaceAll(syntax, ",...", "@commaDots@"); |
| 319 |
syntax = StringUtils.replaceAll(syntax, "...", "@dots@"); |
| 320 |
syntax = StringUtils.replaceAll(syntax, "||", "@concat@"); |
| 321 |
syntax = StringUtils.replaceAll(syntax, "a-z|_", "@az_@"); |
| 322 |
syntax = StringUtils.replaceAll(syntax, "A-Z|_", "@az_@"); |
| 323 |
syntax = StringUtils.replaceAll(syntax, "A-F", "@af@"); |
| 324 |
syntax = StringUtils.replaceAll(syntax, "0-9", "@digit@"); |
| 325 |
syntax = StringUtils.replaceAll(syntax, "'['", "@openBracket@"); |
| 326 |
syntax = StringUtils.replaceAll(syntax, "']'", "@closeBracket@"); |
| 327 |
StringTokenizer tokenizer = getTokenizer(syntax); |
| 328 |
while (tokenizer.hasMoreTokens()) { |
| 329 |
String s = tokenizer.nextToken(); |
| 330 |
// avoid duplicate strings |
| 331 |
s = StringUtils.cache(s); |
| 332 |
if (s.length() == 1) { |
| 333 |
if (" \r\n".indexOf(s.charAt(0)) >= 0) { |
| 334 |
continue; |
| 335 |
} |
| 336 |
} |
| 337 |
list.add(s); |
| 338 |
} |
| 339 |
return list.toArray(new String[0]); |
| 340 |
} |
| 341 |
|
| 342 |
/** |
| 343 |
* Get the list of tokens that can follow. |
| 344 |
* This is the main autocomplete method. |
| 345 |
* The returned map for the query 'S' may look like this: |
| 346 |
* <pre> |
| 347 |
* key: 1#SELECT, value: ELECT |
| 348 |
* key: 1#SET, value: ET |
| 349 |
* </pre> |
| 350 |
* |
| 351 |
* @param query the start of the statement |
| 352 |
* @return the map of possible token types / tokens |
| 353 |
*/ |
| 354 |
public HashMap<String, String> getNextTokenList(String query) { |
| 355 |
Sentence sentence = new Sentence(); |
| 356 |
sentence.setQuery(query); |
| 357 |
try { |
| 358 |
for (RuleHead head : statements) { |
| 359 |
if (!head.getSection().startsWith("Commands")) { |
| 360 |
continue; |
| 361 |
} |
| 362 |
sentence.start(); |
| 363 |
if (head.getRule().autoComplete(sentence)) { |
| 364 |
break; |
| 365 |
} |
| 366 |
} |
| 367 |
} catch (IllegalStateException e) { |
| 368 |
// ignore |
| 369 |
} |
| 370 |
return sentence.getNext(); |
| 371 |
} |
| 372 |
|
| 373 |
/** |
| 374 |
* Cross-link all statements with each other. |
| 375 |
* This method is called after updating the topics. |
| 376 |
*/ |
| 377 |
public void linkStatements() { |
| 378 |
for (RuleHead r : ruleMap.values()) { |
| 379 |
r.getRule().setLinks(ruleMap); |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
/** |
| 384 |
* Update a topic with a context specific rule. |
| 385 |
* This is used for autocomplete support. |
| 386 |
* |
| 387 |
* @param topic the topic |
| 388 |
* @param rule the database context rule |
| 389 |
*/ |
| 390 |
public void updateTopic(String topic, DbContextRule rule) { |
| 391 |
topic = StringUtils.toLowerEnglish(topic); |
| 392 |
RuleHead head = ruleMap.get(topic); |
| 393 |
if (head == null) { |
| 394 |
head = new RuleHead("db", topic, rule); |
| 395 |
ruleMap.put(topic, head); |
| 396 |
statements.add(head); |
| 397 |
} else { |
| 398 |
head.setRule(rule); |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
/** |
| 403 |
* Get the list of possible statements. |
| 404 |
* |
| 405 |
* @return the list of statements |
| 406 |
*/ |
| 407 |
public ArrayList<RuleHead> getStatements() { |
| 408 |
return statements; |
| 409 |
} |
| 410 |
|
| 411 |
/** |
| 412 |
* Get the tokenizer for the given syntax. |
| 413 |
* |
| 414 |
* @param s the syntax |
| 415 |
* @return the tokenizer |
| 416 |
*/ |
| 417 |
public static StringTokenizer getTokenizer(String s) { |
| 418 |
return new StringTokenizer(s, " [](){}|.,\r\n<>:-+*/=\"!'$", true); |
| 419 |
} |
| 420 |
|
| 421 |
} |