aboutsummaryrefslogtreecommitdiffstats
path: root/predicate-search-core/src/main/java/com/yahoo/document/predicate/Predicate.java
blob: fb8d5a032675a3bf768efe455aad60b0c5d5bfd1 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;

import com.yahoo.document.predicate.parser.PredicateLexer;
import com.yahoo.document.predicate.parser.PredicateParser;
import com.yahoo.text.Ascii;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;

import java.nio.charset.StandardCharsets;

/**
 * @author Simon Thoresen Hult
 */
public abstract class Predicate implements Cloneable {

    private final static char QUOTE_CHAR = '\'';
    private final static Ascii.Encoder ASCII_ENCODER = Ascii.newEncoder(StandardCharsets.UTF_8, QUOTE_CHAR);
    private final static Ascii.Decoder ASCII_DECODER = Ascii.newDecoder(StandardCharsets.UTF_8);

    @Override
    public Predicate clone() throws CloneNotSupportedException {
        return (Predicate)super.clone();
    }

    @Override
    public final String toString() {
        StringBuilder out = new StringBuilder();
        appendTo(out);
        return out.toString();
    }

    protected abstract void appendTo(StringBuilder out);

    protected static void appendQuotedTo(String str, StringBuilder out) {
        String encoded = asciiEncode(str);
        if (requiresQuote(encoded)) {
            out.append(QUOTE_CHAR).append(encoded).append(QUOTE_CHAR);
        } else {
            out.append(str);
        }
    }

    private static boolean requiresQuote(String str) {
        for (int i = 0, len = str.length(); i < len; i = str.offsetByCodePoints(i, 1)) {
            int c = str.codePointAt(i);
            if (c == Ascii.ESCAPE_CHAR || !Character.isLetterOrDigit(c)) {
                return true;
            }
        }
        return false;
    }

    public static String asciiEncode(String str) {
        return ASCII_ENCODER.encode(str);
    }

    public static String asciiDecode(String str) {
        return ASCII_DECODER.decode(str);
    }

    public static Predicate fromBinary(byte[] buf) {
        return BinaryFormat.decode(buf);
    }

    public static Predicate fromString(String str) {
        ANTLRStringStream input = new ANTLRStringStream(str);
        PredicateLexer lexer = new PredicateLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        PredicateParser parser = new PredicateParser(tokens);
        try {
            return parser.predicate();
        } catch (RecognitionException e) {
            throw new IllegalArgumentException(e);
        }
    }

}