All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.leeonky.interpreter.TokenSpec Maven / Gradle / Ivy

The newest version!
package com.github.leeonky.interpreter;

import java.util.Set;
import java.util.function.Predicate;

import static com.github.leeonky.util.function.When.when;

public class TokenSpec {
    private final Predicate startsWith;
    private final Set excluded;
    private final TriplePredicate endsWith;
    private boolean trimStart = false;
    private Predicate predicate = token -> true;

    private TokenSpec(Predicate startsWith, Set excluded,
                      TriplePredicate endsWith) {
        this.startsWith = startsWith;
        this.excluded = excluded;
        this.endsWith = endsWith;
    }

    public static TokenSpec tokenSpec(Predicate startsWith, Set excluded,
                                      TriplePredicate endsWith) {
        return new TokenSpec(startsWith, excluded, endsWith);
    }

    public static TokenSpec tokenSpec(Predicate startsWith, Set excluded, Set delimiters) {
        return tokenSpec(startsWith, excluded, (code, position, size) -> delimiters.contains(code.charAt(position)));
    }

    public TokenSpec trimStart() {
        trimStart = true;
        return this;
    }

    public TokenSpec predicate(Predicate predicate) {
        this.predicate = predicate;
        return this;
    }

    public , N extends Node, C extends RuntimeContext,
            O extends Operator, S extends Procedure> TokenScanner scanner() {
        return sourceCode -> sourceCode.tryFetch(() -> when(sourceCode.startsWith(startsWith)).optional(() -> {
            Token token = TokenScanner.tokenScanner(trimStart, endsWith).scan(sourceCode);
            return !excluded.contains(token.getContent()) && predicate.test(token) ? token : null;
        }));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy