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

de.larsgrefer.sass.embedded.functions.HostFunction Maven / Gradle / Ivy

There is a newer version: 4.0.0-m2
Show newest version
package de.larsgrefer.sass.embedded.functions;

import com.sass_lang.embedded_protocol.Value;
import lombok.Getter;
import lombok.With;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author Lars Grefer
 * @see de.larsgrefer.sass.embedded.SassCompiler#registerFunction(HostFunction)
 * @see HostFunctionFactory
 */
@Getter
public abstract class HostFunction {

    private static final Random hostFunctionIds = new Random();

    private final int id = Math.abs(hostFunctionIds.nextInt());

    private final String name;

    private final List arguments;

    private final String signature;

    protected HostFunction(String name, List arguments) {
        this.name = name;
        this.arguments = Collections.unmodifiableList(arguments);
        this.signature = prepareSignature();
    }

    @Nonnull
    public abstract Value invoke(List arguments) throws Throwable;

    private String prepareSignature() {
        String functionName = getName();

        return functionName + getArguments().stream()
                .map(Argument::getSassSignature)
                .collect(Collectors.joining(", ", "(", ")"));
    }

    @lombok.Value
    @With
    public static class Argument {
        String name;

        @Nullable
        String defaultValue;

        public String getSassSignature() {
            String signature = "$" + name;

            if (defaultValue != null) {
                signature += ": " + defaultValue;
            }
            return signature;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy