001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.mappaint.mapcss;
003
004import java.awt.Color;
005import java.lang.annotation.ElementType;
006import java.lang.annotation.Retention;
007import java.lang.annotation.RetentionPolicy;
008import java.lang.annotation.Target;
009import java.lang.reflect.Array;
010import java.lang.reflect.InvocationTargetException;
011import java.lang.reflect.Method;
012import java.nio.charset.StandardCharsets;
013import java.util.ArrayList;
014import java.util.Arrays;
015import java.util.Collection;
016import java.util.Collections;
017import java.util.List;
018import java.util.TreeSet;
019import java.util.regex.Matcher;
020import java.util.regex.Pattern;
021import java.util.zip.CRC32;
022
023import org.openstreetmap.josm.Main;
024import org.openstreetmap.josm.actions.search.SearchCompiler;
025import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
026import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError;
027import org.openstreetmap.josm.data.osm.Node;
028import org.openstreetmap.josm.data.osm.OsmPrimitive;
029import org.openstreetmap.josm.data.osm.Way;
030import org.openstreetmap.josm.gui.mappaint.Cascade;
031import org.openstreetmap.josm.gui.mappaint.Environment;
032import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
033import org.openstreetmap.josm.gui.util.RotationAngle;
034import org.openstreetmap.josm.io.XmlWriter;
035import org.openstreetmap.josm.tools.AlphanumComparator;
036import org.openstreetmap.josm.tools.ColorHelper;
037import org.openstreetmap.josm.tools.Geometry;
038import org.openstreetmap.josm.tools.Predicates;
039import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
040import org.openstreetmap.josm.tools.Utils;
041
042/**
043 * Factory to generate Expressions.
044 *
045 * See {@link #createFunctionExpression}.
046 */
047public final class ExpressionFactory {
048
049    /**
050     * Marks functions which should be executed also when one or more arguments are null.
051     */
052    @Target(ElementType.METHOD)
053    @Retention(RetentionPolicy.RUNTIME)
054    static @interface NullableArguments {}
055
056    private static final List<Method> arrayFunctions = new ArrayList<>();
057    private static final List<Method> parameterFunctions = new ArrayList<>();
058    private static final List<Method> parameterFunctionsEnv = new ArrayList<>();
059
060    static {
061        for (Method m : Functions.class.getDeclaredMethods()) {
062            Class<?>[] paramTypes = m.getParameterTypes();
063            if (paramTypes.length == 1 && paramTypes[0].isArray()) {
064                arrayFunctions.add(m);
065            } else if (paramTypes.length >= 1 && paramTypes[0].equals(Environment.class)) {
066                parameterFunctionsEnv.add(m);
067            } else {
068                parameterFunctions.add(m);
069            }
070        }
071        try {
072            parameterFunctions.add(Math.class.getMethod("abs", float.class));
073            parameterFunctions.add(Math.class.getMethod("acos", double.class));
074            parameterFunctions.add(Math.class.getMethod("asin", double.class));
075            parameterFunctions.add(Math.class.getMethod("atan", double.class));
076            parameterFunctions.add(Math.class.getMethod("atan2", double.class, double.class));
077            parameterFunctions.add(Math.class.getMethod("ceil", double.class));
078            parameterFunctions.add(Math.class.getMethod("cos", double.class));
079            parameterFunctions.add(Math.class.getMethod("cosh", double.class));
080            parameterFunctions.add(Math.class.getMethod("exp", double.class));
081            parameterFunctions.add(Math.class.getMethod("floor", double.class));
082            parameterFunctions.add(Math.class.getMethod("log", double.class));
083            parameterFunctions.add(Math.class.getMethod("max", float.class, float.class));
084            parameterFunctions.add(Math.class.getMethod("min", float.class, float.class));
085            parameterFunctions.add(Math.class.getMethod("random"));
086            parameterFunctions.add(Math.class.getMethod("round", float.class));
087            parameterFunctions.add(Math.class.getMethod("signum", double.class));
088            parameterFunctions.add(Math.class.getMethod("sin", double.class));
089            parameterFunctions.add(Math.class.getMethod("sinh", double.class));
090            parameterFunctions.add(Math.class.getMethod("sqrt", double.class));
091            parameterFunctions.add(Math.class.getMethod("tan", double.class));
092            parameterFunctions.add(Math.class.getMethod("tanh", double.class));
093        } catch (NoSuchMethodException | SecurityException ex) {
094            throw new RuntimeException(ex);
095        }
096    }
097
098    private ExpressionFactory() {
099        // Hide default constructor for utils classes
100    }
101
102    /**
103     * List of functions that can be used in MapCSS expressions.
104     *
105     * First parameter can be of type {@link Environment} (if needed). This is
106     * automatically filled in by JOSM and the user only sees the remaining arguments.
107     * When one of the user supplied arguments cannot be converted the
108     * expected type or is null, the function is not called and it returns null
109     * immediately. Add the annotation {@link NullableArguments} to allow null arguments.
110     * Every method must be static.
111     */
112    @SuppressWarnings("UnusedDeclaration")
113    public static final class Functions {
114
115        private Functions() {
116            // Hide implicit public constructor for utility classes
117        }
118
119        /**
120         * Identity function for compatibility with MapCSS specification.
121         * @param o any object
122         * @return {@code o} unchanged
123         */
124        public static Object eval(Object o) {
125            return o;
126        }
127
128        /**
129         * Function associated to the numeric "+" operator.
130         * @param args arguments
131         * @return Sum of arguments
132         */
133        public static float plus(float... args) {
134            float res = 0;
135            for (float f : args) {
136                res += f;
137            }
138            return res;
139        }
140
141        /**
142         * Function associated to the numeric "-" operator.
143         * @param args arguments
144         * @return Substraction of arguments
145         */
146        public static Float minus(float... args) {
147            if (args.length == 0) {
148                return 0.0F;
149            }
150            if (args.length == 1) {
151                return -args[0];
152            }
153            float res = args[0];
154            for (int i = 1; i < args.length; ++i) {
155                res -= args[i];
156            }
157            return res;
158        }
159
160        /**
161         * Function associated to the numeric "*" operator.
162         * @param args arguments
163         * @return Multiplication of arguments
164         */
165        public static float times(float... args) {
166            float res = 1;
167            for (float f : args) {
168                res *= f;
169            }
170            return res;
171        }
172
173        /**
174         * Function associated to the numeric "/" operator.
175         * @param args arguments
176         * @return Division of arguments
177         */
178        public static Float divided_by(float... args) {
179            if (args.length == 0) {
180                return 1.0F;
181            }
182            float res = args[0];
183            for (int i = 1; i < args.length; ++i) {
184                if (args[i] == 0) {
185                    return null;
186                }
187                res /= args[i];
188            }
189            return res;
190        }
191
192        /**
193         * Creates a list of values, e.g., for the {@code dashes} property.
194         * @param args The values to put in a list
195         * @return list of values
196         * @see Arrays#asList(Object[])
197         */
198        public static List<Object> list(Object... args) {
199            return Arrays.asList(args);
200        }
201
202        /**
203         * Returns the number of elements in a list.
204         * @param lst the list
205         * @return length of the list
206         */
207        public static Integer count(List<?> lst) {
208            return lst.size();
209        }
210
211        /**
212         * Returns the first non-null object.
213         * The name originates from <a href="http://wiki.openstreetmap.org/wiki/MapCSS/0.2/eval">MapCSS standard</a>.
214         * @param args arguments
215         * @return the first non-null object
216         * @see Utils#firstNonNull(Object[])
217         */
218        @NullableArguments
219        public static Object any(Object... args) {
220            return Utils.firstNonNull(args);
221        }
222
223        /**
224         * Get the {@code n}th element of the list {@code lst} (counting starts at 0).
225         * @param lst list
226         * @param n index
227         * @return {@code n}th element of the list, or {@code null} if index out of range
228         * @since 5699
229         */
230        public static Object get(List<?> lst, float n) {
231            int idx = Math.round(n);
232            if (idx >= 0 && idx < lst.size()) {
233                return lst.get(idx);
234            }
235            return null;
236        }
237
238        /**
239         * Splits string {@code toSplit} at occurrences of the separator string {@code sep} and returns a list of matches.
240         * @param sep separator string
241         * @param toSplit string to split
242         * @return list of matches
243         * @see String#split(String)
244         * @since 5699
245         */
246        public static List<String> split(String sep, String toSplit) {
247            return Arrays.asList(toSplit.split(Pattern.quote(sep), -1));
248        }
249
250        /**
251         * Creates a color value with the specified amounts of {@code r}ed, {@code g}reen, {@code b}lue (arguments from 0.0 to 1.0)
252         * @param r the red component
253         * @param g the green component
254         * @param b the blue component
255         * @return color matching the given components
256         * @see Color#Color(float, float, float)
257         */
258        public static Color rgb(float r, float g, float b) {
259            try {
260                return new Color(r, g, b);
261            } catch (IllegalArgumentException e) {
262                return null;
263            }
264        }
265
266        /**
267         * Creates a color value with the specified amounts of {@code r}ed, {@code g}reen, {@code b}lue, {@code alpha}
268         * (arguments from 0.0 to 1.0)
269         * @param r the red component
270         * @param g the green component
271         * @param b the blue component
272         * @param alpha the alpha component
273         * @return color matching the given components
274         * @see Color#Color(float, float, float, float)
275         */
276        public static Color rgba(float r, float g, float b, float alpha) {
277            try {
278                return new Color(r, g, b, alpha);
279            } catch (IllegalArgumentException e) {
280                return null;
281            }
282        }
283
284        /**
285         * Create color from hsb color model. (arguments form 0.0 to 1.0)
286         * @param h hue
287         * @param s saturation
288         * @param b brightness
289         * @return the corresponding color
290         */
291        public static Color hsb_color(float h, float s, float b) {
292            try {
293                return Color.getHSBColor(h, s, b);
294            } catch (IllegalArgumentException e) {
295                return null;
296            }
297        }
298
299        /**
300         * Creates a color value from an HTML notation, i.e., {@code #rrggbb}.
301         * @param html HTML notation
302         * @return color matching the given notation
303         */
304        public static Color html2color(String html) {
305            return ColorHelper.html2color(html);
306        }
307
308        /**
309         * Computes the HTML notation ({@code #rrggbb}) for a color value).
310         * @param c color
311         * @return HTML notation matching the given color
312         */
313        public static String color2html(Color c) {
314            return ColorHelper.color2html(c);
315        }
316
317        /**
318         * Get the value of the red color channel in the rgb color model
319         * @param c color
320         * @return the red color channel in the range [0;1]
321         * @see java.awt.Color#getRed()
322         */
323        public static float red(Color c) {
324            return Utils.color_int2float(c.getRed());
325        }
326
327        /**
328         * Get the value of the green color channel in the rgb color model
329         * @param c color
330         * @return the green color channel in the range [0;1]
331         * @see java.awt.Color#getGreen()
332         */
333        public static float green(Color c) {
334            return Utils.color_int2float(c.getGreen());
335        }
336
337        /**
338         * Get the value of the blue color channel in the rgb color model
339         * @param c color
340         * @return the blue color channel in the range [0;1]
341         * @see java.awt.Color#getBlue()
342         */
343        public static float blue(Color c) {
344            return Utils.color_int2float(c.getBlue());
345        }
346
347        /**
348         * Get the value of the alpha channel in the rgba color model
349         * @param c color
350         * @return the alpha channel in the range [0;1]
351         * @see java.awt.Color#getAlpha()
352         */
353        public static float alpha(Color c) {
354            return Utils.color_int2float(c.getAlpha());
355        }
356
357        /**
358         * Assembles the strings to one.
359         * @param args arguments
360         * @return assembled string
361         * @see Utils#join
362         */
363        @NullableArguments
364        public static String concat(Object... args) {
365            return Utils.join("", Arrays.asList(args));
366        }
367
368        /**
369         * Assembles the strings to one, where the first entry is used as separator.
370         * @param args arguments. First one is used as separator
371         * @return assembled string
372         * @see Utils#join
373         */
374        @NullableArguments
375        public static String join(String... args) {
376            return Utils.join(args[0], Arrays.asList(args).subList(1, args.length));
377        }
378
379        /**
380         * Joins a list of {@code values} into a single string with fields separated by {@code separator}.
381         * @param separator the separator
382         * @param values collection of objects
383         * @return assembled string
384         * @see Utils#join
385         */
386        public static String join_list(final String separator, final List<String> values) {
387            return Utils.join(separator, values);
388        }
389
390        /**
391         * Returns the value of the property {@code key}, e.g., {@code prop("width")}.
392         * @param env the environment
393         * @param key the property key
394         * @return the property value
395         */
396        public static Object prop(final Environment env, String key) {
397            return prop(env, key, null);
398        }
399
400        /**
401         * Returns the value of the property {@code key} from layer {@code layer}.
402         * @param env the environment
403         * @param key the property key
404         * @param layer layer
405         * @return the property value
406         */
407        public static Object prop(final Environment env, String key, String layer) {
408            return env.getCascade(layer).get(key);
409        }
410
411        /**
412         * Determines whether property {@code key} is set.
413         * @param env the environment
414         * @param key the property key
415         * @return {@code true} if the property is set, {@code false} otherwise
416         */
417        public static Boolean is_prop_set(final Environment env, String key) {
418            return is_prop_set(env, key, null);
419        }
420
421        /**
422         * Determines whether property {@code key} is set on layer {@code layer}.
423         * @param env the environment
424         * @param key the property key
425         * @param layer layer
426         * @return {@code true} if the property is set, {@code false} otherwise
427         */
428        public static Boolean is_prop_set(final Environment env, String key, String layer) {
429            return env.getCascade(layer).containsKey(key);
430        }
431
432        /**
433         * Gets the value of the key {@code key} from the object in question.
434         * @param env the environment
435         * @param key the OSM key
436         * @return the value for given key
437         */
438        public static String tag(final Environment env, String key) {
439            return env.osm == null ? null : env.osm.get(key);
440        }
441
442        /**
443         * Gets the first non-null value of the key {@code key} from the object's parent(s).
444         * @param env the environment
445         * @param key the OSM key
446         * @return first non-null value of the key {@code key} from the object's parent(s)
447         */
448        public static String parent_tag(final Environment env, String key) {
449            if (env.parent == null) {
450                if (env.osm != null) {
451                    // we don't have a matched parent, so just search all referrers
452                    for (OsmPrimitive parent : env.osm.getReferrers()) {
453                        String value = parent.get(key);
454                        if (value != null) {
455                            return value;
456                        }
457                    }
458                }
459                return null;
460            }
461            return env.parent.get(key);
462        }
463
464        /**
465         * Gets a list of all non-null values of the key {@code key} from the object's parent(s).
466         *
467         * The values are sorted according to {@link AlphanumComparator}.
468         * @param env the environment
469         * @param key the OSM key
470         * @return a list of non-null values of the key {@code key} from the object's parent(s)
471         */
472        public static List<String> parent_tags(final Environment env, String key) {
473            if (env.parent == null) {
474                if (env.osm != null) {
475                    final Collection<String> tags = new TreeSet<>(AlphanumComparator.getInstance());
476                    // we don't have a matched parent, so just search all referrers
477                    for (OsmPrimitive parent : env.osm.getReferrers()) {
478                        String value = parent.get(key);
479                        if (value != null) {
480                            tags.add(value);
481                        }
482                    }
483                    return new ArrayList<>(tags);
484                }
485                return Collections.emptyList();
486            }
487            return Collections.singletonList(env.parent.get(key));
488        }
489
490        /**
491         * Gets the value of the key {@code key} from the object's child.
492         * @param env the environment
493         * @param key the OSM key
494         * @return the value of the key {@code key} from the object's child, or {@code null} if there is no child
495         */
496        public static String child_tag(final Environment env, String key) {
497            return env.child == null ? null : env.child.get(key);
498        }
499
500        /**
501         * Determines whether the object has a tag with the given key.
502         * @param env the environment
503         * @param key the OSM key
504         * @return {@code true} if the object has a tag with the given key, {@code false} otherwise
505         */
506        public static boolean has_tag_key(final Environment env, String key) {
507            return env.osm.hasKey(key);
508        }
509
510        /**
511         * Returns the index of node in parent way or member in parent relation.
512         * @param env the environment
513         * @return the index as float. Starts at 1
514         */
515        public static Float index(final Environment env) {
516            if (env.index == null) {
517                return null;
518            }
519            return new Float(env.index + 1);
520        }
521
522        /**
523         * Returns the role of current object in parent relation, or role of child if current object is a relation.
524         * @param env the environment
525         * @return role of current object in parent relation, or role of child if current object is a relation
526         * @see Environment#getRole()
527         */
528        public static String role(final Environment env) {
529            return env.getRole();
530        }
531
532        /**
533         * Returns the area of a closed way in square meters or {@code null}.
534         * @param env the environment
535         * @return the area of a closed way in square meters or {@code null}
536         * @see Geometry#closedWayArea(Way)
537         */
538        public static Float areasize(final Environment env) {
539            if (env.osm instanceof Way && ((Way) env.osm).isClosed()) {
540                return (float) Geometry.closedWayArea((Way) env.osm);
541            } else {
542                return null;
543            }
544        }
545
546        /**
547         * Returns the length of the way in metres or {@code null}.
548         * @param env the environment
549         * @return the length of the way in metres or {@code null}.
550         * @see Way#getLength()
551         */
552        public static Float waylength(final Environment env) {
553            if (env.osm instanceof Way) {
554                return (float) ((Way) env.osm).getLength();
555            } else {
556                return null;
557            }
558        }
559
560        /**
561         * Function associated to the logical "!" operator.
562         * @param b boolean value
563         * @return {@code true} if {@code !b}
564         */
565        public static boolean not(boolean b) {
566            return !b;
567        }
568
569        /**
570         * Function associated to the logical "&gt;=" operator.
571         * @param a first value
572         * @param b second value
573         * @return {@code true} if {@code a &gt;= b}
574         */
575        public static boolean greater_equal(float a, float b) {
576            return a >= b;
577        }
578
579        /**
580         * Function associated to the logical "&lt;=" operator.
581         * @param a first value
582         * @param b second value
583         * @return {@code true} if {@code a &lt;= b}
584         */
585        public static boolean less_equal(float a, float b) {
586            return a <= b;
587        }
588
589        /**
590         * Function associated to the logical "&gt;" operator.
591         * @param a first value
592         * @param b second value
593         * @return {@code true} if {@code a &gt; b}
594         */
595        public static boolean greater(float a, float b) {
596            return a > b;
597        }
598
599        /**
600         * Function associated to the logical "&lt;" operator.
601         * @param a first value
602         * @param b second value
603         * @return {@code true} if {@code a &lt; b}
604         */
605        public static boolean less(float a, float b) {
606            return a < b;
607        }
608
609        /**
610         * Converts an angle in degrees to radians.
611         * @param degree the angle in degrees
612         * @return the angle in radians
613         * @see Math#toRadians(double)
614         */
615        public static double degree_to_radians(double degree) {
616            return Math.toRadians(degree);
617        }
618
619        /**
620         * Converts an angle diven in cardinal directions to radians.
621         * The following values are supported: {@code n}, {@code north}, {@code ne}, {@code northeast},
622         * {@code e}, {@code east}, {@code se}, {@code southeast}, {@code s}, {@code south},
623         * {@code sw}, {@code southwest}, {@code w}, {@code west}, {@code nw}, {@code northwest}.
624         * @param cardinal the angle in cardinal directions.
625         * @return the angle in radians
626         * @see RotationAngle#parseCardinalRotation(String)
627         */
628        public static Double cardinal_to_radians(String cardinal) {
629            try {
630                return RotationAngle.parseCardinalRotation(cardinal);
631            } catch (IllegalArgumentException ignore) {
632                return null;
633            }
634        }
635
636        /**
637         * Determines if the objects {@code a} and {@code b} are equal.
638         * @param a First object
639         * @param b Second object
640         * @return {@code true} if objects are equal, {@code false} otherwise
641         * @see Object#equals(Object)
642         */
643        public static boolean equal(Object a, Object b) {
644            if (a.getClass() == b.getClass()) return a.equals(b);
645            if (a.equals(Cascade.convertTo(b, a.getClass()))) return true;
646            return b.equals(Cascade.convertTo(a, b.getClass()));
647        }
648
649        /**
650         * Determines if the objects {@code a} and {@code b} are not equal.
651         * @param a First object
652         * @param b Second object
653         * @return {@code false} if objects are equal, {@code true} otherwise
654         * @see Object#equals(Object)
655         */
656        public static boolean not_equal(Object a, Object b) {
657            return !equal(a, b);
658        }
659
660        /**
661         * Determines whether the JOSM search with {@code searchStr} applies to the object.
662         * @param env the environment
663         * @param searchStr the search string
664         * @return {@code true} if the JOSM search with {@code searchStr} applies to the object
665         * @see SearchCompiler
666         */
667        public static Boolean JOSM_search(final Environment env, String searchStr) {
668            Match m;
669            try {
670                m = SearchCompiler.compile(searchStr);
671            } catch (ParseError ex) {
672                return null;
673            }
674            return m.match(env.osm);
675        }
676
677        /**
678         * Obtains the JOSM'key {@link org.openstreetmap.josm.data.Preferences} string for key {@code key},
679         * and defaults to {@code def} if that is null.
680         * @param env the environment
681         * @param key Key in JOSM preference
682         * @param def Default value
683         * @return value for key, or default value if not found
684         */
685        public static String JOSM_pref(Environment env, String key, String def) {
686            return MapPaintStyles.getStyles().getPreferenceCached(key, def);
687        }
688
689        /**
690         * Tests if string {@code target} matches pattern {@code pattern}
691         * @param pattern The regex expression
692         * @param target The character sequence to be matched
693         * @return {@code true} if, and only if, the entire region sequence matches the pattern
694         * @see Pattern#matches(String, CharSequence)
695         * @since 5699
696         */
697        public static boolean regexp_test(String pattern, String target) {
698            return Pattern.matches(pattern, target);
699        }
700
701        /**
702         * Tests if string {@code target} matches pattern {@code pattern}
703         * @param pattern The regex expression
704         * @param target The character sequence to be matched
705         * @param flags a string that may contain "i" (case insensitive), "m" (multiline) and "s" ("dot all")
706         * @return {@code true} if, and only if, the entire region sequence matches the pattern
707         * @see Pattern#CASE_INSENSITIVE
708         * @see Pattern#DOTALL
709         * @see Pattern#MULTILINE
710         * @since 5699
711         */
712        public static boolean regexp_test(String pattern, String target, String flags) {
713            int f = 0;
714            if (flags.contains("i")) {
715                f |= Pattern.CASE_INSENSITIVE;
716            }
717            if (flags.contains("s")) {
718                f |= Pattern.DOTALL;
719            }
720            if (flags.contains("m")) {
721                f |= Pattern.MULTILINE;
722            }
723            return Pattern.compile(pattern, f).matcher(target).matches();
724        }
725
726        /**
727         * Tries to match string against pattern regexp and returns a list of capture groups in case of success.
728         * The first element (index 0) is the complete match (i.e. string).
729         * Further elements correspond to the bracketed parts of the regular expression.
730         * @param pattern The regex expression
731         * @param target The character sequence to be matched
732         * @param flags a string that may contain "i" (case insensitive), "m" (multiline) and "s" ("dot all")
733         * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
734         * @see Pattern#CASE_INSENSITIVE
735         * @see Pattern#DOTALL
736         * @see Pattern#MULTILINE
737         * @since 5701
738         */
739        public static List<String> regexp_match(String pattern, String target, String flags) {
740            int f = 0;
741            if (flags.contains("i")) {
742                f |= Pattern.CASE_INSENSITIVE;
743            }
744            if (flags.contains("s")) {
745                f |= Pattern.DOTALL;
746            }
747            if (flags.contains("m")) {
748                f |= Pattern.MULTILINE;
749            }
750            return Utils.getMatches(Pattern.compile(pattern, f).matcher(target));
751        }
752
753        /**
754         * Tries to match string against pattern regexp and returns a list of capture groups in case of success.
755         * The first element (index 0) is the complete match (i.e. string).
756         * Further elements correspond to the bracketed parts of the regular expression.
757         * @param pattern The regex expression
758         * @param target The character sequence to be matched
759         * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
760         * @since 5701
761         */
762        public static List<String> regexp_match(String pattern, String target) {
763            return Utils.getMatches(Pattern.compile(pattern).matcher(target));
764        }
765
766        /**
767         * Returns the OSM id of the current object.
768         * @param env the environment
769         * @return the OSM id of the current object
770         * @see OsmPrimitive#getUniqueId()
771         */
772        public static long osm_id(final Environment env) {
773            return env.osm.getUniqueId();
774        }
775
776        /**
777         * Translates some text for the current locale. The first argument is the text to translate,
778         * and the subsequent arguments are parameters for the string indicated by <code>{0}</code>, <code>{1}</code>, …
779         * @param args arguments
780         * @return the translated string
781         */
782        @NullableArguments
783        public static String tr(String... args) {
784            final String text = args[0];
785            System.arraycopy(args, 1, args, 0, args.length - 1);
786            return org.openstreetmap.josm.tools.I18n.tr(text, (Object[]) args);
787        }
788
789        /**
790         * Returns the substring of {@code s} starting at index {@code begin} (inclusive, 0-indexed).
791         * @param s The base string
792         * @param begin The start index
793         * @return the substring
794         * @see String#substring(int)
795         */
796        public static String substring(String s, /* due to missing Cascade.convertTo for int*/ float begin) {
797            return s == null ? null : s.substring((int) begin);
798        }
799
800        /**
801         * Returns the substring of {@code s} starting at index {@code begin} (inclusive)
802         * and ending at index {@code end}, (exclusive, 0-indexed).
803         * @param s The base string
804         * @param begin The start index
805         * @param end The end index
806         * @return the substring
807         * @see String#substring(int, int)
808         */
809        public static String substring(String s, float begin, float end) {
810            return s == null ? null : s.substring((int) begin, (int) end);
811        }
812
813        /**
814         * Replaces in {@code s} every {@code} target} substring by {@code replacement}.
815         * @param s The source string
816         * @param target The sequence of char values to be replaced
817         * @param replacement The replacement sequence of char values
818         * @return The resulting string
819         * @see String#replace(CharSequence, CharSequence)
820         */
821        public static String replace(String s, String target, String replacement) {
822            return s == null ? null : s.replace(target, replacement);
823        }
824
825        /**
826         * Percent-encode a string. (See https://en.wikipedia.org/wiki/Percent-encoding)
827         * This is especially useful for data urls, e.g.
828         * <code>concat("data:image/svg+xml,", URL_encode("&lt;svg&gt;...&lt;/svg&gt;"));</code>
829         * @param s arbitrary string
830         * @return the encoded string
831         */
832        public static String URL_encode(String s) {
833            return s == null ? null : Utils.encodeUrl(s);
834        }
835
836        /**
837         * XML-encode a string.
838         *
839         * Escapes special characters in xml. Alternative to using &lt;![CDATA[ ... ]]&gt; blocks.
840         * @param s arbitrary string
841         * @return the encoded string
842         */
843        public static String XML_encode(String s) {
844            return s == null ? null : XmlWriter.encode(s);
845        }
846
847        /**
848         * Calculates the CRC32 checksum from a string (based on RFC 1952).
849         * @param s the string
850         * @return long value from 0 to 2^32-1
851         */
852        public static long CRC32_checksum(String s) {
853            CRC32 cs = new CRC32();
854            cs.update(s.getBytes(StandardCharsets.UTF_8));
855            return cs.getValue();
856        }
857
858        /**
859         * check if there is right-hand traffic at the current location
860         * @param env the environment
861         * @return true if there is right-hand traffic
862         * @since 7193
863         */
864        public static boolean is_right_hand_traffic(Environment env) {
865            if (env.osm instanceof Node)
866                return RightAndLefthandTraffic.isRightHandTraffic(((Node) env.osm).getCoor());
867            return RightAndLefthandTraffic.isRightHandTraffic(env.osm.getBBox().getCenter());
868        }
869
870        /**
871         * Prints the object to the command line (for debugging purpose).
872         * @param o the object
873         * @return the same object, unchanged
874         */
875        @NullableArguments
876        public static Object print(Object o) {
877            System.out.print(o == null ? "none" : o.toString());
878            return o;
879        }
880
881        /**
882         * Prints the object to the command line, with new line at the end
883         * (for debugging purpose).
884         * @param o the object
885         * @return the same object, unchanged
886         */
887        @NullableArguments
888        public static Object println(Object o) {
889            System.out.println(o == null ? "none" : o.toString());
890            return o;
891        }
892
893        /**
894         * Get the number of tags for the current primitive.
895         * @param env the environment
896         * @return number of tags
897         */
898        public static int number_of_tags(Environment env) {
899            return env.osm.getNumKeys();
900        }
901
902        /**
903         * Get value of a setting.
904         * @param env the environment
905         * @param key setting key (given as layer identifier, e.g. setting::mykey {...})
906         * @return the value of the setting (calculated when the style is loaded)
907         */
908        public static Object setting(Environment env, String key) {
909            return env.source.settingValues.get(key);
910        }
911    }
912
913    /**
914     * Main method to create an function-like expression.
915     *
916     * @param name the name of the function or operator
917     * @param args the list of arguments (as expressions)
918     * @return the generated Expression. If no suitable function can be found,
919     * returns {@link NullExpression#INSTANCE}.
920     */
921    public static Expression createFunctionExpression(String name, List<Expression> args) {
922        if ("cond".equals(name) && args.size() == 3)
923            return new CondOperator(args.get(0), args.get(1), args.get(2));
924        else if ("and".equals(name))
925            return new AndOperator(args);
926        else if ("or".equals(name))
927            return new OrOperator(args);
928        else if ("length".equals(name) && args.size() == 1)
929            return new LengthFunction(args.get(0));
930        else if ("max".equals(name) && !args.isEmpty())
931            return new MinMaxFunction(args, true);
932        else if ("min".equals(name) && !args.isEmpty())
933            return new MinMaxFunction(args, false);
934
935        for (Method m : arrayFunctions) {
936            if (m.getName().equals(name))
937                return new ArrayFunction(m, args);
938        }
939        for (Method m : parameterFunctions) {
940            if (m.getName().equals(name) && args.size() == m.getParameterTypes().length)
941                return new ParameterFunction(m, args, false);
942        }
943        for (Method m : parameterFunctionsEnv) {
944            if (m.getName().equals(name) && args.size() == m.getParameterTypes().length-1)
945                return new ParameterFunction(m, args, true);
946        }
947        return NullExpression.INSTANCE;
948    }
949
950    /**
951     * Expression that always evaluates to null.
952     */
953    public static class NullExpression implements Expression {
954
955        /**
956         * The unique instance.
957         */
958        public static final NullExpression INSTANCE = new NullExpression();
959
960        @Override
961        public Object evaluate(Environment env) {
962            return null;
963        }
964    }
965
966    /**
967     * Conditional operator.
968     */
969    public static class CondOperator implements Expression {
970
971        private final Expression condition, firstOption, secondOption;
972
973        /**
974         * Constructs a new {@code CondOperator}.
975         * @param condition condition
976         * @param firstOption first option
977         * @param secondOption second option
978         */
979        public CondOperator(Expression condition, Expression firstOption, Expression secondOption) {
980            this.condition = condition;
981            this.firstOption = firstOption;
982            this.secondOption = secondOption;
983        }
984
985        @Override
986        public Object evaluate(Environment env) {
987            Boolean b = Cascade.convertTo(condition.evaluate(env), boolean.class);
988            if (b != null && b)
989                return firstOption.evaluate(env);
990            else
991                return secondOption.evaluate(env);
992        }
993    }
994
995    /**
996     * "And" logical operator.
997     */
998    public static class AndOperator implements Expression {
999
1000        private final List<Expression> args;
1001
1002        /**
1003         * Constructs a new {@code AndOperator}.
1004         * @param args arguments
1005         */
1006        public AndOperator(List<Expression> args) {
1007            this.args = args;
1008        }
1009
1010        @Override
1011        public Object evaluate(Environment env) {
1012            for (Expression arg : args) {
1013                Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class);
1014                if (b == null || !b) {
1015                    return Boolean.FALSE;
1016                }
1017            }
1018            return Boolean.TRUE;
1019        }
1020    }
1021
1022    /**
1023     * "Or" logical operator.
1024     */
1025    public static class OrOperator implements Expression {
1026
1027        private final List<Expression> args;
1028
1029        /**
1030         * Constructs a new {@code OrOperator}.
1031         * @param args arguments
1032         */
1033        public OrOperator(List<Expression> args) {
1034            this.args = args;
1035        }
1036
1037        @Override
1038        public Object evaluate(Environment env) {
1039            for (Expression arg : args) {
1040                Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class);
1041                if (b != null && b) {
1042                    return Boolean.TRUE;
1043                }
1044            }
1045            return Boolean.FALSE;
1046        }
1047    }
1048
1049    /**
1050     * Function to calculate the length of a string or list in a MapCSS eval expression.
1051     *
1052     * Separate implementation to support overloading for different argument types.
1053     *
1054     * The use for calculating the length of a list is deprecated, use
1055     * {@link Functions#count(java.util.List)} instead (see #10061).
1056     */
1057    public static class LengthFunction implements Expression {
1058
1059        private final Expression arg;
1060
1061        /**
1062         * Constructs a new {@code LengthFunction}.
1063         * @param args arguments
1064         */
1065        public LengthFunction(Expression args) {
1066            this.arg = args;
1067        }
1068
1069        @Override
1070        public Object evaluate(Environment env) {
1071            List<?> l = Cascade.convertTo(arg.evaluate(env), List.class);
1072            if (l != null)
1073                return l.size();
1074            String s = Cascade.convertTo(arg.evaluate(env), String.class);
1075            if (s != null)
1076                return s.length();
1077            return null;
1078        }
1079    }
1080
1081    /**
1082     * Computes the maximum/minimum value an arbitrary number of floats, or a list of floats.
1083     */
1084    public static class MinMaxFunction implements Expression {
1085
1086        private final List<Expression> args;
1087        private final boolean computeMax;
1088
1089        /**
1090         * Constructs a new {@code MinMaxFunction}.
1091         * @param args arguments
1092         * @param computeMax if {@code true}, compute max. If {@code false}, compute min
1093         */
1094        public MinMaxFunction(final List<Expression> args, final boolean computeMax) {
1095            this.args = args;
1096            this.computeMax = computeMax;
1097        }
1098
1099        public Float aggregateList(List<?> lst) {
1100            final List<Float> floats = Utils.transform(lst, new Utils.Function<Object, Float>() {
1101                @Override
1102                public Float apply(Object x) {
1103                    return Cascade.convertTo(x, float.class);
1104                }
1105            });
1106            final Collection<Float> nonNullList = Utils.filter(floats, Predicates.not(Predicates.isNull()));
1107            return computeMax ? Collections.max(nonNullList) : Collections.min(nonNullList);
1108        }
1109
1110        @Override
1111        public Object evaluate(final Environment env) {
1112            List<?> l = Cascade.convertTo(args.get(0).evaluate(env), List.class);
1113            if (args.size() != 1 || l == null)
1114                l = Utils.transform(args, new Utils.Function<Expression, Object>() {
1115                    @Override
1116                    public Object apply(Expression x) {
1117                        return x.evaluate(env);
1118                    }
1119                });
1120            return aggregateList(l);
1121        }
1122    }
1123
1124    /**
1125     * Function that takes a certain number of argument with specific type.
1126     *
1127     * Implementation is based on a Method object.
1128     * If any of the arguments evaluate to null, the result will also be null.
1129     */
1130    public static class ParameterFunction implements Expression {
1131
1132        private final Method m;
1133        private final boolean nullable;
1134        private final List<Expression> args;
1135        private final Class<?>[] expectedParameterTypes;
1136        private final boolean needsEnvironment;
1137
1138        /**
1139         * Constructs a new {@code ParameterFunction}.
1140         * @param m method
1141         * @param args arguments
1142         * @param needsEnvironment whether function needs environment
1143         */
1144        public ParameterFunction(Method m, List<Expression> args, boolean needsEnvironment) {
1145            this.m = m;
1146            this.nullable = m.getAnnotation(NullableArguments.class) != null;
1147            this.args = args;
1148            this.expectedParameterTypes = m.getParameterTypes();
1149            this.needsEnvironment = needsEnvironment;
1150        }
1151
1152        @Override
1153        public Object evaluate(Environment env) {
1154            Object[] convertedArgs;
1155
1156            if (needsEnvironment) {
1157                convertedArgs = new Object[args.size()+1];
1158                convertedArgs[0] = env;
1159                for (int i = 1; i < convertedArgs.length; ++i) {
1160                    convertedArgs[i] = Cascade.convertTo(args.get(i-1).evaluate(env), expectedParameterTypes[i]);
1161                    if (convertedArgs[i] == null && !nullable) {
1162                        return null;
1163                    }
1164                }
1165            } else {
1166                convertedArgs = new Object[args.size()];
1167                for (int i = 0; i < convertedArgs.length; ++i) {
1168                    convertedArgs[i] = Cascade.convertTo(args.get(i).evaluate(env), expectedParameterTypes[i]);
1169                    if (convertedArgs[i] == null && !nullable) {
1170                        return null;
1171                    }
1172                }
1173            }
1174            Object result = null;
1175            try {
1176                result = m.invoke(null, convertedArgs);
1177            } catch (IllegalAccessException | IllegalArgumentException ex) {
1178                throw new RuntimeException(ex);
1179            } catch (InvocationTargetException ex) {
1180                Main.error(ex);
1181                return null;
1182            }
1183            return result;
1184        }
1185
1186        @Override
1187        public String toString() {
1188            StringBuilder b = new StringBuilder("ParameterFunction~");
1189            b.append(m.getName()).append('(');
1190            for (int i = 0; i < args.size(); ++i) {
1191                if (i > 0) b.append(',');
1192                b.append(expectedParameterTypes[i]).append(' ').append(args.get(i));
1193            }
1194            b.append(')');
1195            return b.toString();
1196        }
1197    }
1198
1199    /**
1200     * Function that takes an arbitrary number of arguments.
1201     *
1202     * Currently, all array functions are static, so there is no need to
1203     * provide the environment, like it is done in {@link ParameterFunction}.
1204     * If any of the arguments evaluate to null, the result will also be null.
1205     */
1206    public static class ArrayFunction implements Expression {
1207
1208        private final Method m;
1209        private final boolean nullable;
1210        private final List<Expression> args;
1211        private final Class<?>[] expectedParameterTypes;
1212        private final Class<?> arrayComponentType;
1213
1214        /**
1215         * Constructs a new {@code ArrayFunction}.
1216         * @param m method
1217         * @param args arguments
1218         */
1219        public ArrayFunction(Method m, List<Expression> args) {
1220            this.m = m;
1221            this.nullable = m.getAnnotation(NullableArguments.class) != null;
1222            this.args = args;
1223            this.expectedParameterTypes = m.getParameterTypes();
1224            this.arrayComponentType = expectedParameterTypes[0].getComponentType();
1225        }
1226
1227        @Override
1228        public Object evaluate(Environment env) {
1229            Object[] convertedArgs = new Object[expectedParameterTypes.length];
1230            Object arrayArg = Array.newInstance(arrayComponentType, args.size());
1231            for (int i = 0; i < args.size(); ++i) {
1232                Object o = Cascade.convertTo(args.get(i).evaluate(env), arrayComponentType);
1233                if (o == null && !nullable) {
1234                    return null;
1235                }
1236                Array.set(arrayArg, i, o);
1237            }
1238            convertedArgs[0] = arrayArg;
1239
1240            Object result = null;
1241            try {
1242                result = m.invoke(null, convertedArgs);
1243            } catch (IllegalAccessException | IllegalArgumentException ex) {
1244                throw new RuntimeException(ex);
1245            } catch (InvocationTargetException ex) {
1246                Main.error(ex);
1247                return null;
1248            }
1249            return result;
1250        }
1251
1252        @Override
1253        public String toString() {
1254            StringBuilder b = new StringBuilder("ArrayFunction~");
1255            b.append(m.getName()).append('(');
1256            for (int i = 0; i < args.size(); ++i) {
1257                if (i > 0) b.append(',');
1258                b.append(arrayComponentType).append(' ').append(args.get(i));
1259            }
1260            b.append(')');
1261            return b.toString();
1262        }
1263    }
1264}