1 // Copyright 2011 Google Inc. All Rights Reserved.
3 package com
.google
.appengine
.api
.search
.query
;
5 import org
.antlr
.runtime
.ANTLRStringStream
;
6 import org
.antlr
.runtime
.RecognitionException
;
7 import org
.antlr
.runtime
.TokenRewriteStream
;
8 import org
.antlr
.runtime
.tree
.CommonTree
;
9 import org
.antlr
.runtime
.tree
.CommonTreeAdaptor
;
12 * A generator of AST representation of a query. This class uses the given factory
13 * to produce a query parser which parses user specified query. If successful it
14 * returns the root of an AST representing the parsed query.
17 public class QueryTreeBuilder
{
19 private QueryParserFactory parserFactory
;
20 private final CommonTreeAdaptor adaptor
= new CommonTreeAdaptor();
22 public QueryTreeBuilder() {
23 this.parserFactory
= new QueryParserFactory();
26 public QueryTreeBuilder(QueryParserFactory parserFactory
) {
27 this.parserFactory
= parserFactory
;
31 * Parses the user query and returns a CommonTree.
33 * @param query the user query to be parsed
34 * @return a CommonTree constructed from the query
35 * @throws RecognitionException if the user query is invalid
36 * @throws NullPointerException if query is null
38 public CommonTree
parse(String query
) throws RecognitionException
{
40 throw new NullPointerException("query must not be null");
42 String trimmed
= query
.trim();
43 if (trimmed
.isEmpty()) {
44 return (CommonTree
) adaptor
.nil();
46 ANTLRStringStream stream
= new ANTLRStringStream(query
);
47 QueryLexer lexer
= new QueryLexer(stream
);
48 TokenRewriteStream tokens
= new TokenRewriteStream(lexer
);
49 QueryParser parser
= parserFactory
.newParser(tokens
);
50 return (CommonTree
) parser
.query().getTree();