001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.validation.tests;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.BufferedReader;
007import java.io.IOException;
008import java.io.InputStream;
009import java.io.Reader;
010import java.io.StringReader;
011import java.text.MessageFormat;
012import java.util.ArrayList;
013import java.util.Arrays;
014import java.util.Collection;
015import java.util.Collections;
016import java.util.HashMap;
017import java.util.HashSet;
018import java.util.Iterator;
019import java.util.LinkedHashMap;
020import java.util.LinkedHashSet;
021import java.util.LinkedList;
022import java.util.List;
023import java.util.Locale;
024import java.util.Map;
025import java.util.Set;
026import java.util.regex.Matcher;
027import java.util.regex.Pattern;
028
029import org.openstreetmap.josm.Main;
030import org.openstreetmap.josm.command.ChangePropertyCommand;
031import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
032import org.openstreetmap.josm.command.Command;
033import org.openstreetmap.josm.command.DeleteCommand;
034import org.openstreetmap.josm.command.SequenceCommand;
035import org.openstreetmap.josm.data.osm.DataSet;
036import org.openstreetmap.josm.data.osm.OsmPrimitive;
037import org.openstreetmap.josm.data.osm.OsmUtils;
038import org.openstreetmap.josm.data.osm.Tag;
039import org.openstreetmap.josm.data.validation.FixableTestError;
040import org.openstreetmap.josm.data.validation.Severity;
041import org.openstreetmap.josm.data.validation.Test;
042import org.openstreetmap.josm.data.validation.TestError;
043import org.openstreetmap.josm.gui.mappaint.Environment;
044import org.openstreetmap.josm.gui.mappaint.Keyword;
045import org.openstreetmap.josm.gui.mappaint.MultiCascade;
046import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
047import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.ClassCondition;
048import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
049import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
050import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
051import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule.Declaration;
052import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
053import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
054import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.AbstractSelector;
055import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
056import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
057import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
058import org.openstreetmap.josm.gui.preferences.SourceEntry;
059import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
060import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
061import org.openstreetmap.josm.io.CachedFile;
062import org.openstreetmap.josm.io.IllegalDataException;
063import org.openstreetmap.josm.io.UTFInputStreamReader;
064import org.openstreetmap.josm.tools.CheckParameterUtil;
065import org.openstreetmap.josm.tools.MultiMap;
066import org.openstreetmap.josm.tools.Predicate;
067import org.openstreetmap.josm.tools.Utils;
068
069/**
070 * MapCSS-based tag checker/fixer.
071 * @since 6506
072 */
073public class MapCSSTagChecker extends Test.TagTest {
074
075    /**
076     * A grouped MapCSSRule with multiple selectors for a single declaration.
077     * @see MapCSSRule
078     */
079    public static class GroupedMapCSSRule {
080        /** MapCSS selectors **/
081        public final List<Selector> selectors;
082        /** MapCSS declaration **/
083        public final Declaration declaration;
084
085        /**
086         * Constructs a new {@code GroupedMapCSSRule}.
087         * @param selectors MapCSS selectors
088         * @param declaration MapCSS declaration
089         */
090        public GroupedMapCSSRule(List<Selector> selectors, Declaration declaration) {
091            this.selectors = selectors;
092            this.declaration = declaration;
093        }
094
095        @Override
096        public int hashCode() {
097            final int prime = 31;
098            int result = 1;
099            result = prime * result + ((declaration == null) ? 0 : declaration.hashCode());
100            result = prime * result + ((selectors == null) ? 0 : selectors.hashCode());
101            return result;
102        }
103
104        @Override
105        public boolean equals(Object obj) {
106            if (this == obj)
107                return true;
108            if (obj == null)
109                return false;
110            if (!(obj instanceof GroupedMapCSSRule))
111                return false;
112            GroupedMapCSSRule other = (GroupedMapCSSRule) obj;
113            if (declaration == null) {
114                if (other.declaration != null)
115                    return false;
116            } else if (!declaration.equals(other.declaration))
117                return false;
118            if (selectors == null) {
119                if (other.selectors != null)
120                    return false;
121            } else if (!selectors.equals(other.selectors))
122                return false;
123            return true;
124        }
125
126        @Override
127        public String toString() {
128            return "GroupedMapCSSRule [selectors=" + selectors + ", declaration=" + declaration + ']';
129        }
130    }
131
132    /**
133     * The preference key for tag checker source entries.
134     * @since 6670
135     */
136    public static final String ENTRIES_PREF_KEY = "validator." + MapCSSTagChecker.class.getName() + ".entries";
137
138    /**
139     * Constructs a new {@code MapCSSTagChecker}.
140     */
141    public MapCSSTagChecker() {
142        super(tr("Tag checker (MapCSS based)"), tr("This test checks for errors in tag keys and values."));
143    }
144
145    /**
146     * Represents a fix to a validation test. The fixing {@link Command} can be obtained by {@link #createCommand(OsmPrimitive, Selector)}.
147     */
148    abstract static class FixCommand {
149        /**
150         * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to evaluate placeholders
151         * (cf. {@link MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}).
152         * @param p OSM primitive
153         * @param matchingSelector  matching selector
154         * @return fix command
155         */
156        abstract Command createCommand(final OsmPrimitive p, final Selector matchingSelector);
157
158        private static void checkObject(final Object obj) {
159            CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String,
160                    "instance of Exception or String expected, but got " + obj);
161        }
162
163        /**
164         * Evaluates given object as {@link Expression} or {@link String} on the matched {@link OsmPrimitive} and {@code matchingSelector}.
165         */
166        private static String evaluateObject(final Object obj, final OsmPrimitive p, final Selector matchingSelector) {
167            final String s;
168            if (obj instanceof Expression) {
169                s = (String) ((Expression) obj).evaluate(new Environment(p));
170            } else if (obj instanceof String) {
171                s = (String) obj;
172            } else {
173                return null;
174            }
175            return TagCheck.insertArguments(matchingSelector, s, p);
176        }
177
178        /**
179         * Creates a fixing command which executes a {@link ChangePropertyCommand} on the specified tag.
180         */
181        static FixCommand fixAdd(final Object obj) {
182            checkObject(obj);
183            return new FixCommand() {
184                @Override
185                Command createCommand(OsmPrimitive p, Selector matchingSelector) {
186                    final Tag tag = Tag.ofString(evaluateObject(obj, p, matchingSelector));
187                    return new ChangePropertyCommand(p, tag.getKey(), tag.getValue());
188                }
189
190                @Override
191                public String toString() {
192                    return "fixAdd: " + obj;
193                }
194            };
195
196        }
197
198        /**
199         * Creates a fixing command which executes a {@link ChangePropertyCommand} to delete the specified key.
200         */
201        static FixCommand fixRemove(final Object obj) {
202            checkObject(obj);
203            return new FixCommand() {
204                @Override
205                Command createCommand(OsmPrimitive p, Selector matchingSelector) {
206                    final String key = evaluateObject(obj, p, matchingSelector);
207                    return new ChangePropertyCommand(p, key, "");
208                }
209
210                @Override
211                public String toString() {
212                    return "fixRemove: " + obj;
213                }
214            };
215        }
216
217        /**
218         * Creates a fixing command which executes a {@link ChangePropertyKeyCommand} on the specified keys.
219         */
220        static FixCommand fixChangeKey(final String oldKey, final String newKey) {
221            return new FixCommand() {
222                @Override
223                Command createCommand(OsmPrimitive p, Selector matchingSelector) {
224                    return new ChangePropertyKeyCommand(p,
225                            TagCheck.insertArguments(matchingSelector, oldKey, p),
226                            TagCheck.insertArguments(matchingSelector, newKey, p));
227                }
228
229                @Override
230                public String toString() {
231                    return "fixChangeKey: " + oldKey + " => " + newKey;
232                }
233            };
234        }
235    }
236
237    final MultiMap<String, TagCheck> checks = new MultiMap<>();
238
239    /**
240     * Result of {@link TagCheck#readMapCSS}
241     * @since 8936
242     */
243    public static class ParseResult {
244        /** Checks successfully parsed */
245        public final List<TagCheck> parseChecks;
246        /** Errors that occured during parsing */
247        public final Collection<Throwable> parseErrors;
248
249        /**
250         * Constructs a new {@code ParseResult}.
251         * @param parseChecks Checks successfully parsed
252         * @param parseErrors Errors that occured during parsing
253         */
254        public ParseResult(List<TagCheck> parseChecks, Collection<Throwable> parseErrors) {
255            this.parseChecks = parseChecks;
256            this.parseErrors = parseErrors;
257        }
258    }
259
260    public static class TagCheck implements Predicate<OsmPrimitive> {
261        protected final GroupedMapCSSRule rule;
262        protected final List<FixCommand> fixCommands = new ArrayList<>();
263        protected final List<String> alternatives = new ArrayList<>();
264        protected final Map<Instruction.AssignmentInstruction, Severity> errors = new HashMap<>();
265        protected final Map<String, Boolean> assertions = new HashMap<>();
266        protected final Set<String> setClassExpressions = new HashSet<>();
267        protected boolean deletion;
268
269        TagCheck(GroupedMapCSSRule rule) {
270            this.rule = rule;
271        }
272
273        private static final String POSSIBLE_THROWS = possibleThrows();
274
275        static final String possibleThrows() {
276            StringBuilder sb = new StringBuilder();
277            for (Severity s : Severity.values()) {
278                if (sb.length() > 0) {
279                    sb.append('/');
280                }
281                sb.append("throw")
282                .append(s.name().charAt(0))
283                .append(s.name().substring(1).toLowerCase(Locale.ENGLISH));
284            }
285            return sb.toString();
286        }
287
288        static TagCheck ofMapCSSRule(final GroupedMapCSSRule rule) throws IllegalDataException {
289            final TagCheck check = new TagCheck(rule);
290            for (Instruction i : rule.declaration.instructions) {
291                if (i instanceof Instruction.AssignmentInstruction) {
292                    final Instruction.AssignmentInstruction ai = (Instruction.AssignmentInstruction) i;
293                    if (ai.isSetInstruction) {
294                        check.setClassExpressions.add(ai.key);
295                        continue;
296                    }
297                    final String val = ai.val instanceof Expression
298                            ? (String) ((Expression) ai.val).evaluate(new Environment())
299                            : ai.val instanceof String
300                            ? (String) ai.val
301                            : ai.val instanceof Keyword
302                            ? ((Keyword) ai.val).val
303                            : null;
304                    if (ai.key.startsWith("throw")) {
305                        try {
306                            final Severity severity = Severity.valueOf(ai.key.substring("throw".length()).toUpperCase(Locale.ENGLISH));
307                            check.errors.put(ai, severity);
308                        } catch (IllegalArgumentException e) {
309                            Main.warn("Unsupported "+ai.key+" instruction. Allowed instructions are "+POSSIBLE_THROWS);
310                        }
311                    } else if ("fixAdd".equals(ai.key)) {
312                        check.fixCommands.add(FixCommand.fixAdd(ai.val));
313                    } else if ("fixRemove".equals(ai.key)) {
314                        CheckParameterUtil.ensureThat(!(ai.val instanceof String) || !(val != null && val.contains("=")),
315                                "Unexpected '='. Please only specify the key to remove!");
316                        check.fixCommands.add(FixCommand.fixRemove(ai.val));
317                    } else if ("fixChangeKey".equals(ai.key) && val != null) {
318                        CheckParameterUtil.ensureThat(val.contains("=>"), "Separate old from new key by '=>'!");
319                        final String[] x = val.split("=>", 2);
320                        check.fixCommands.add(FixCommand.fixChangeKey(Tag.removeWhiteSpaces(x[0]), Tag.removeWhiteSpaces(x[1])));
321                    } else if ("fixDeleteObject".equals(ai.key) && val != null) {
322                        CheckParameterUtil.ensureThat("this".equals(val), "fixDeleteObject must be followed by 'this'");
323                        check.deletion = true;
324                    } else if ("suggestAlternative".equals(ai.key) && val != null) {
325                        check.alternatives.add(val);
326                    } else if ("assertMatch".equals(ai.key) && val != null) {
327                        check.assertions.put(val, Boolean.TRUE);
328                    } else if ("assertNoMatch".equals(ai.key) && val != null) {
329                        check.assertions.put(val, Boolean.FALSE);
330                    } else {
331                        throw new IllegalDataException("Cannot add instruction " + ai.key + ": " + ai.val + '!');
332                    }
333                }
334            }
335            if (check.errors.isEmpty() && check.setClassExpressions.isEmpty()) {
336                throw new IllegalDataException(
337                        "No "+POSSIBLE_THROWS+" given! You should specify a validation error message for " + rule.selectors);
338            } else if (check.errors.size() > 1) {
339                throw new IllegalDataException(
340                        "More than one "+POSSIBLE_THROWS+" given! You should specify a single validation error message for "
341                                + rule.selectors);
342            }
343            return check;
344        }
345
346        static ParseResult readMapCSS(Reader css) throws ParseException {
347            CheckParameterUtil.ensureParameterNotNull(css, "css");
348
349            final MapCSSStyleSource source = new MapCSSStyleSource("");
350            final MapCSSParser preprocessor = new MapCSSParser(css, MapCSSParser.LexicalState.PREPROCESSOR);
351
352            css = new StringReader(preprocessor.pp_root(source));
353            final MapCSSParser parser = new MapCSSParser(css, MapCSSParser.LexicalState.DEFAULT);
354            parser.sheet(source);
355            Collection<Throwable> parseErrors = source.getErrors();
356            assert parseErrors.isEmpty();
357            // Ignore "meta" rule(s) from external rules of JOSM wiki
358            removeMetaRules(source);
359            // group rules with common declaration block
360            Map<Declaration, List<Selector>> g = new LinkedHashMap<>();
361            for (MapCSSRule rule : source.rules) {
362                if (!g.containsKey(rule.declaration)) {
363                    List<Selector> sels = new ArrayList<>();
364                    sels.add(rule.selector);
365                    g.put(rule.declaration, sels);
366                } else {
367                    g.get(rule.declaration).add(rule.selector);
368                }
369            }
370            List<TagCheck> parseChecks = new ArrayList<>();
371            for (Map.Entry<Declaration, List<Selector>> map : g.entrySet()) {
372                try {
373                    parseChecks.add(TagCheck.ofMapCSSRule(
374                            new GroupedMapCSSRule(map.getValue(), map.getKey())));
375                } catch (IllegalDataException e) {
376                    Main.error("Cannot add MapCss rule: "+e.getMessage());
377                    parseErrors.add(e);
378                }
379            }
380            return new ParseResult(parseChecks, parseErrors);
381        }
382
383        private static void removeMetaRules(MapCSSStyleSource source) {
384            for (Iterator<MapCSSRule> it = source.rules.iterator(); it.hasNext();) {
385                MapCSSRule x = it.next();
386                if (x.selector instanceof GeneralSelector) {
387                    GeneralSelector gs = (GeneralSelector) x.selector;
388                    if ("meta".equals(gs.base) && gs.getConditions().isEmpty()) {
389                        it.remove();
390                    }
391                }
392            }
393        }
394
395        @Override
396        public boolean evaluate(OsmPrimitive primitive) {
397            // Tests whether the primitive contains a deprecated tag which is represented by this MapCSSTagChecker.
398            return whichSelectorMatchesPrimitive(primitive) != null;
399        }
400
401        Selector whichSelectorMatchesPrimitive(OsmPrimitive primitive) {
402            return whichSelectorMatchesEnvironment(new Environment(primitive));
403        }
404
405        Selector whichSelectorMatchesEnvironment(Environment env) {
406            for (Selector i : rule.selectors) {
407                env.clearSelectorMatchingInformation();
408                if (i.matches(env)) {
409                    return i;
410                }
411            }
412            return null;
413        }
414
415        /**
416         * Determines the {@code index}-th key/value/tag (depending on {@code type}) of the
417         * {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector}.
418         */
419        static String determineArgument(Selector.GeneralSelector matchingSelector, int index, String type, OsmPrimitive p) {
420            try {
421                final Condition c = matchingSelector.getConditions().get(index);
422                final Tag tag = c instanceof Condition.KeyCondition
423                        ? ((Condition.KeyCondition) c).asTag(p)
424                        : c instanceof Condition.SimpleKeyValueCondition
425                        ? ((Condition.SimpleKeyValueCondition) c).asTag()
426                        : c instanceof Condition.KeyValueCondition
427                        ? ((Condition.KeyValueCondition) c).asTag()
428                        : null;
429                if (tag == null) {
430                    return null;
431                } else if ("key".equals(type)) {
432                    return tag.getKey();
433                } else if ("value".equals(type)) {
434                    return tag.getValue();
435                } else if ("tag".equals(type)) {
436                    return tag.toString();
437                }
438            } catch (IndexOutOfBoundsException ignore) {
439                if (Main.isDebugEnabled()) {
440                    Main.debug(ignore.getMessage());
441                }
442            }
443            return null;
444        }
445
446        /**
447         * Replaces occurrences of <code>{i.key}</code>, <code>{i.value}</code>, <code>{i.tag}</code> in {@code s} by the corresponding
448         * key/value/tag of the {@code index}-th {@link Condition} of {@code matchingSelector}.
449         */
450        static String insertArguments(Selector matchingSelector, String s, OsmPrimitive p) {
451            if (s != null && matchingSelector instanceof Selector.ChildOrParentSelector) {
452                return insertArguments(((Selector.ChildOrParentSelector) matchingSelector).right, s, p);
453            } else if (s == null || !(matchingSelector instanceof GeneralSelector)) {
454                return s;
455            }
456            final Matcher m = Pattern.compile("\\{(\\d+)\\.(key|value|tag)\\}").matcher(s);
457            final StringBuffer sb = new StringBuffer();
458            while (m.find()) {
459                final String argument = determineArgument((Selector.GeneralSelector) matchingSelector,
460                        Integer.parseInt(m.group(1)), m.group(2), p);
461                try {
462                    // Perform replacement with null-safe + regex-safe handling
463                    m.appendReplacement(sb, String.valueOf(argument).replace("^(", "").replace(")$", ""));
464                } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
465                    Main.error(tr("Unable to replace argument {0} in {1}: {2}", argument, sb, e.getMessage()));
466                }
467            }
468            m.appendTail(sb);
469            return sb.toString();
470        }
471
472        /**
473         * Constructs a fix in terms of a {@link org.openstreetmap.josm.command.Command} for the {@link OsmPrimitive}
474         * if the error is fixable, or {@code null} otherwise.
475         *
476         * @param p the primitive to construct the fix for
477         * @return the fix or {@code null}
478         */
479        Command fixPrimitive(OsmPrimitive p) {
480            if (fixCommands.isEmpty() && !deletion) {
481                return null;
482            }
483            final Selector matchingSelector = whichSelectorMatchesPrimitive(p);
484            Collection<Command> cmds = new LinkedList<>();
485            for (FixCommand fixCommand : fixCommands) {
486                cmds.add(fixCommand.createCommand(p, matchingSelector));
487            }
488            if (deletion) {
489                cmds.add(new DeleteCommand(p));
490            }
491            return new SequenceCommand(tr("Fix of {0}", getDescriptionForMatchingSelector(p, matchingSelector)), cmds);
492        }
493
494        /**
495         * Constructs a (localized) message for this deprecation check.
496         *
497         * @return a message
498         */
499        String getMessage(OsmPrimitive p) {
500            if (errors.isEmpty()) {
501                // Return something to avoid NPEs
502                return rule.declaration.toString();
503            } else {
504                final Object val = errors.keySet().iterator().next().val;
505                return String.valueOf(
506                        val instanceof Expression
507                                ? ((Expression) val).evaluate(new Environment(p))
508                                : val
509                );
510            }
511        }
512
513        /**
514         * Constructs a (localized) description for this deprecation check.
515         *
516         * @return a description (possibly with alternative suggestions)
517         * @see #getDescriptionForMatchingSelector
518         */
519        String getDescription(OsmPrimitive p) {
520            if (alternatives.isEmpty()) {
521                return getMessage(p);
522            } else {
523                /* I18N: {0} is the test error message and {1} is an alternative */
524                return tr("{0}, use {1} instead", getMessage(p), Utils.join(tr(" or "), alternatives));
525            }
526        }
527
528        /**
529         * Constructs a (localized) description for this deprecation check
530         * where any placeholders are replaced by values of the matched selector.
531         *
532         * @return a description (possibly with alternative suggestions)
533         */
534        String getDescriptionForMatchingSelector(OsmPrimitive p, Selector matchingSelector) {
535            return insertArguments(matchingSelector, getDescription(p), p);
536        }
537
538        Severity getSeverity() {
539            return errors.isEmpty() ? null : errors.values().iterator().next();
540        }
541
542        @Override
543        public String toString() {
544            return getDescription(null);
545        }
546
547        /**
548         * Constructs a {@link TestError} for the given primitive, or returns null if the primitive does not give rise to an error.
549         *
550         * @param p the primitive to construct the error for
551         * @return an instance of {@link TestError}, or returns null if the primitive does not give rise to an error.
552         */
553        TestError getErrorForPrimitive(OsmPrimitive p) {
554            final Environment env = new Environment(p);
555            return getErrorForPrimitive(p, whichSelectorMatchesEnvironment(env), env);
556        }
557
558        TestError getErrorForPrimitive(OsmPrimitive p, Selector matchingSelector, Environment env) {
559            if (matchingSelector != null && !errors.isEmpty()) {
560                final Command fix = fixPrimitive(p);
561                final String description = getDescriptionForMatchingSelector(p, matchingSelector);
562                final List<OsmPrimitive> primitives;
563                if (env.child != null) {
564                    primitives = Arrays.asList(p, env.child);
565                } else {
566                    primitives = Collections.singletonList(p);
567                }
568                if (fix != null) {
569                    return new FixableTestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives, fix);
570                } else {
571                    return new TestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives);
572                }
573            } else {
574                return null;
575            }
576        }
577
578        /**
579         * Returns the set of tagchecks on which this check depends on.
580         * @param schecks the collection of tagcheks to search in
581         * @return the set of tagchecks on which this check depends on
582         * @since 7881
583         */
584        public Set<TagCheck> getTagCheckDependencies(Collection<TagCheck> schecks) {
585            Set<TagCheck> result = new HashSet<MapCSSTagChecker.TagCheck>();
586            Set<String> classes = getClassesIds();
587            if (schecks != null && !classes.isEmpty()) {
588                for (TagCheck tc : schecks) {
589                    if (this.equals(tc)) {
590                        continue;
591                    }
592                    for (String id : tc.setClassExpressions) {
593                        if (classes.contains(id)) {
594                            result.add(tc);
595                            break;
596                        }
597                    }
598                }
599            }
600            return result;
601        }
602
603        /**
604         * Returns the list of ids of all MapCSS classes referenced in the rule selectors.
605         * @return the list of ids of all MapCSS classes referenced in the rule selectors
606         * @since 7881
607         */
608        public Set<String> getClassesIds() {
609            Set<String> result = new HashSet<>();
610            for (Selector s : rule.selectors) {
611                if (s instanceof AbstractSelector) {
612                    for (Condition c : ((AbstractSelector) s).getConditions()) {
613                        if (c instanceof ClassCondition) {
614                            result.add(((ClassCondition) c).id);
615                        }
616                    }
617                }
618            }
619            return result;
620        }
621    }
622
623    static class MapCSSTagCheckerAndRule extends MapCSSTagChecker {
624        public final GroupedMapCSSRule rule;
625
626        MapCSSTagCheckerAndRule(GroupedMapCSSRule rule) {
627            this.rule = rule;
628        }
629
630        @Override
631        public boolean equals(Object obj) {
632            return super.equals(obj)
633                    || (obj instanceof TagCheck && rule.equals(((TagCheck) obj).rule))
634                    || (obj instanceof GroupedMapCSSRule && rule.equals(obj));
635        }
636
637        @Override
638        public int hashCode() {
639            final int prime = 31;
640            int result = super.hashCode();
641            result = prime * result + ((rule == null) ? 0 : rule.hashCode());
642            return result;
643        }
644
645        @Override
646        public String toString() {
647            return "MapCSSTagCheckerAndRule [rule=" + rule + ']';
648        }
649    }
650
651    /**
652     * Obtains all {@link TestError}s for the {@link OsmPrimitive} {@code p}.
653     * @param p The OSM primitive
654     * @param includeOtherSeverity if {@code true}, errors of severity {@link Severity#OTHER} (info) will also be returned
655     * @return all errors for the given primitive, with or without those of "info" severity
656     */
657    public synchronized Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity) {
658        return getErrorsForPrimitive(p, includeOtherSeverity, checks.values());
659    }
660
661    private static Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity,
662            Collection<Set<TagCheck>> checksCol) {
663        final List<TestError> r = new ArrayList<>();
664        final Environment env = new Environment(p, new MultiCascade(), Environment.DEFAULT_LAYER, null);
665        for (Set<TagCheck> schecks : checksCol) {
666            for (TagCheck check : schecks) {
667                if (Severity.OTHER.equals(check.getSeverity()) && !includeOtherSeverity) {
668                    continue;
669                }
670                final Selector selector = check.whichSelectorMatchesEnvironment(env);
671                if (selector != null) {
672                    check.rule.declaration.execute(env);
673                    final TestError error = check.getErrorForPrimitive(p, selector, env);
674                    if (error != null) {
675                        error.setTester(new MapCSSTagCheckerAndRule(check.rule));
676                        r.add(error);
677                    }
678                }
679            }
680        }
681        return r;
682    }
683
684    /**
685     * Visiting call for primitives.
686     *
687     * @param p The primitive to inspect.
688     */
689    @Override
690    public void check(OsmPrimitive p) {
691        errors.addAll(getErrorsForPrimitive(p, ValidatorPreference.PREF_OTHER.get()));
692    }
693
694    /**
695     * Adds a new MapCSS config file from the given URL.
696     * @param url The unique URL of the MapCSS config file
697     * @return List of tag checks and parsing errors, or null
698     * @throws ParseException if the config file does not match MapCSS syntax
699     * @throws IOException if any I/O error occurs
700     * @since 7275
701     */
702    public synchronized ParseResult addMapCSS(String url) throws ParseException, IOException {
703        CheckParameterUtil.ensureParameterNotNull(url, "url");
704        CachedFile cache = new CachedFile(url);
705        InputStream zip = cache.findZipEntryInputStream("validator.mapcss", "");
706        ParseResult result;
707        try (InputStream s = zip != null ? zip : cache.getInputStream()) {
708            result = TagCheck.readMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
709            checks.remove(url);
710            checks.putAll(url, result.parseChecks);
711            // Check assertions, useful for development of local files
712            if (Main.pref.getBoolean("validator.check_assert_local_rules", false) && Utils.isLocalUrl(url)) {
713                for (String msg : checkAsserts(result.parseChecks)) {
714                    Main.warn(msg);
715                }
716            }
717        }
718        return result;
719    }
720
721    @Override
722    public synchronized void initialize() throws Exception {
723        checks.clear();
724        for (SourceEntry source : new ValidatorTagCheckerRulesPreference.RulePrefHelper().get()) {
725            if (!source.active) {
726                continue;
727            }
728            String i = source.url;
729            try {
730                if (!i.startsWith("resource:")) {
731                    Main.info(tr("Adding {0} to tag checker", i));
732                } else if (Main.isDebugEnabled()) {
733                    Main.debug(tr("Adding {0} to tag checker", i));
734                }
735                addMapCSS(i);
736                if (Main.pref.getBoolean("validator.auto_reload_local_rules", true) && source.isLocal()) {
737                    try {
738                        Main.fileWatcher.registerValidatorRule(source);
739                    } catch (IOException e) {
740                        Main.error(e);
741                    }
742                }
743            } catch (IOException ex) {
744                Main.warn(tr("Failed to add {0} to tag checker", i));
745                Main.warn(ex, false);
746            } catch (Exception ex) {
747                Main.warn(tr("Failed to add {0} to tag checker", i));
748                Main.warn(ex);
749            }
750        }
751    }
752
753    /**
754     * Checks that rule assertions are met for the given set of TagChecks.
755     * @param schecks The TagChecks for which assertions have to be checked
756     * @return A set of error messages, empty if all assertions are met
757     * @since 7356
758     */
759    public Set<String> checkAsserts(final Collection<TagCheck> schecks) {
760        Set<String> assertionErrors = new LinkedHashSet<>();
761        final DataSet ds = new DataSet();
762        for (final TagCheck check : schecks) {
763            if (Main.isDebugEnabled()) {
764                Main.debug("Check: "+check);
765            }
766            for (final Map.Entry<String, Boolean> i : check.assertions.entrySet()) {
767                if (Main.isDebugEnabled()) {
768                    Main.debug("- Assertion: "+i);
769                }
770                final OsmPrimitive p = OsmUtils.createPrimitive(i.getKey());
771                // Build minimal ordered list of checks to run to test the assertion
772                List<Set<TagCheck>> checksToRun = new ArrayList<Set<TagCheck>>();
773                Set<TagCheck> checkDependencies = check.getTagCheckDependencies(schecks);
774                if (!checkDependencies.isEmpty()) {
775                    checksToRun.add(checkDependencies);
776                }
777                checksToRun.add(Collections.singleton(check));
778                // Add primitive to dataset to avoid DataIntegrityProblemException when evaluating selectors
779                ds.addPrimitive(p);
780                final Collection<TestError> pErrors = getErrorsForPrimitive(p, true, checksToRun);
781                if (Main.isDebugEnabled()) {
782                    Main.debug("- Errors: "+pErrors);
783                }
784                final boolean isError = Utils.exists(pErrors, new Predicate<TestError>() {
785                    @Override
786                    public boolean evaluate(TestError e) {
787                        //noinspection EqualsBetweenInconvertibleTypes
788                        return e.getTester().equals(check.rule);
789                    }
790                });
791                if (isError != i.getValue()) {
792                    final String error = MessageFormat.format("Expecting test ''{0}'' (i.e., {1}) to {2} {3} (i.e., {4})",
793                            check.getMessage(p), check.rule.selectors, i.getValue() ? "match" : "not match", i.getKey(), p.getKeys());
794                    assertionErrors.add(error);
795                }
796                ds.removePrimitive(p);
797            }
798        }
799        return assertionErrors;
800    }
801
802    @Override
803    public synchronized int hashCode() {
804        final int prime = 31;
805        int result = super.hashCode();
806        result = prime * result + ((checks == null) ? 0 : checks.hashCode());
807        return result;
808    }
809
810    @Override
811    public synchronized boolean equals(Object obj) {
812        if (this == obj)
813            return true;
814        if (!super.equals(obj))
815            return false;
816        if (!(obj instanceof MapCSSTagChecker))
817            return false;
818        MapCSSTagChecker other = (MapCSSTagChecker) obj;
819        if (checks == null) {
820            if (other.checks != null)
821                return false;
822        } else if (!checks.equals(other.checks))
823            return false;
824        return true;
825    }
826}