aboutsummaryrefslogtreecommitdiffstats
path: root/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/ScriptParser.java
blob: ec9329c3c292e1d4d63fd3ab560d2f1a63dc8400 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.indexinglanguage;

import com.yahoo.javacc.FastCharStream;
import com.yahoo.vespa.indexinglanguage.expressions.Expression;
import com.yahoo.vespa.indexinglanguage.expressions.ScriptExpression;
import com.yahoo.vespa.indexinglanguage.expressions.StatementExpression;
import com.yahoo.vespa.indexinglanguage.parser.CharStream;
import com.yahoo.vespa.indexinglanguage.parser.IndexingParser;
import com.yahoo.vespa.indexinglanguage.parser.ParseException;
import com.yahoo.vespa.indexinglanguage.parser.TokenMgrException;

/**
 * @author Simon Thoresen Hult
 */
public final class ScriptParser {

    public static Expression parseExpression(ScriptParserContext config) throws ParseException {
        return parse(config, parser -> parser.root());
    }

    public static ScriptExpression parseScript(ScriptParserContext config) throws ParseException {
        return parse(config, parser -> parser.script());
    }

    public static StatementExpression parseStatement(ScriptParserContext config) throws ParseException {
        return parse(config, parser -> {
            try {
                return parser.statement();
            }
            catch (TokenMgrException e) {
                throw new ParseException(e.getMessage());
            }
        });
    }

    private interface ParserMethod<T extends Expression> {

        T call(IndexingParser parser) throws ParseException;
    }

    private static <T extends Expression> T parse(ScriptParserContext context, ParserMethod<T> method)
            throws ParseException {
        CharStream input = context.getInputStream();
        IndexingParser parser = new IndexingParser(input);
        parser.setAnnotatorConfig(context.getAnnotatorConfig());
        parser.setDefaultFieldName(context.getDefaultFieldName());
        parser.setLinguistics(context.getLinguistcs());
        parser.setEmbedders(context.getEmbedders());
        try {
            return method.call(parser);
        } catch (ParseException e) {
            if (!(input instanceof FastCharStream)) {
                throw e;
            }
            throw new ParseException(((FastCharStream)input).formatException(e.getMessage()));
        } finally {
            if (parser.token != null && parser.token.next != null) {
                input.backup(parser.token.next.image.length());
            }
        }
    }

}