001/* 002 * PlotSquared, a land and world management plugin for Minecraft. 003 * Copyright (C) IntellectualSites <https://intellectualsites.com> 004 * Copyright (C) IntellectualSites team and contributors 005 * 006 * This program is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with this program. If not, see <https://www.gnu.org/licenses/>. 018 */ 019package com.plotsquared.core.util; 020 021import com.sk89q.worldedit.internal.expression.Expression; 022import org.checkerframework.checker.nullness.qual.NonNull; 023 024/** 025 * An expression that can be evaluated. 026 * Evaluation is thread-safe. 027 * This is a wrapper for {@link Expression}. 028 */ 029public class PlotExpression { 030 031 private final Expression expression; 032 private final Object lock = new Object(); 033 034 private PlotExpression(final @NonNull String rawExpression, final @NonNull String @NonNull [] variableNames) { 035 this.expression = Expression.compile(rawExpression, variableNames); 036 } 037 038 /** 039 * Compiles an expression from a string. 040 * 041 * @param expression the expression to compile. 042 * @param variableNames the variables that can be set in {@link #evaluate(double...)}. 043 * @return the compiled expression. 044 */ 045 public static @NonNull PlotExpression compile( 046 final @NonNull String expression, 047 final @NonNull String @NonNull ... variableNames 048 ) { 049 return new PlotExpression(expression, variableNames); 050 } 051 052 /** 053 * Evaluates the expression with the given variable values. 054 * 055 * @param values the values to set the variables to. 056 * @return the result of the evaluation. 057 */ 058 public double evaluate(double... values) { 059 double evaluate; 060 // synchronization is likely the best option in terms of memory and cpu consumption 061 synchronized (this.lock) { 062 evaluate = this.expression.evaluate(values); 063 } 064 return evaluate; 065 } 066 067}