source: josm/trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java@ 14468

Last change on this file since 14468 was 14421, checked in by GerdP, 5 years ago

fix fix #16982, now really

  • Property svn:eol-style set to native
File size: 36.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.validation.tests;
3
4import static org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.FixCommand.evaluateObject;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.io.BufferedReader;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.Reader;
11import java.io.StringReader;
12import java.text.MessageFormat;
13import java.util.ArrayList;
14import java.util.Arrays;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.HashMap;
18import java.util.HashSet;
19import java.util.LinkedHashMap;
20import java.util.LinkedHashSet;
21import java.util.LinkedList;
22import java.util.List;
23import java.util.Locale;
24import java.util.Map;
25import java.util.Objects;
26import java.util.Optional;
27import java.util.Set;
28import java.util.function.Predicate;
29import java.util.regex.Matcher;
30import java.util.regex.Pattern;
31
32import org.openstreetmap.josm.command.ChangePropertyCommand;
33import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
34import org.openstreetmap.josm.command.Command;
35import org.openstreetmap.josm.command.DeleteCommand;
36import org.openstreetmap.josm.command.SequenceCommand;
37import org.openstreetmap.josm.data.osm.DataSet;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.osm.OsmUtils;
40import org.openstreetmap.josm.data.osm.Tag;
41import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
42import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
43import org.openstreetmap.josm.data.validation.OsmValidator;
44import org.openstreetmap.josm.data.validation.Severity;
45import org.openstreetmap.josm.data.validation.Test;
46import org.openstreetmap.josm.data.validation.TestError;
47import org.openstreetmap.josm.gui.mappaint.Environment;
48import org.openstreetmap.josm.gui.mappaint.Keyword;
49import org.openstreetmap.josm.gui.mappaint.MultiCascade;
50import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
51import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.ClassCondition;
52import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
53import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
54import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
55import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule.Declaration;
56import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
57import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
58import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.AbstractSelector;
59import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
60import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
61import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
62import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.TokenMgrError;
63import org.openstreetmap.josm.io.CachedFile;
64import org.openstreetmap.josm.io.FileWatcher;
65import org.openstreetmap.josm.io.IllegalDataException;
66import org.openstreetmap.josm.io.UTFInputStreamReader;
67import org.openstreetmap.josm.spi.preferences.Config;
68import org.openstreetmap.josm.tools.CheckParameterUtil;
69import org.openstreetmap.josm.tools.I18n;
70import org.openstreetmap.josm.tools.Logging;
71import org.openstreetmap.josm.tools.MultiMap;
72import org.openstreetmap.josm.tools.Utils;
73
74/**
75 * MapCSS-based tag checker/fixer.
76 * @since 6506
77 */
78public class MapCSSTagChecker extends Test.TagTest {
79
80 /**
81 * A grouped MapCSSRule with multiple selectors for a single declaration.
82 * @see MapCSSRule
83 */
84 public static class GroupedMapCSSRule {
85 /** MapCSS selectors **/
86 public final List<Selector> selectors;
87 /** MapCSS declaration **/
88 public final Declaration declaration;
89
90 /**
91 * Constructs a new {@code GroupedMapCSSRule}.
92 * @param selectors MapCSS selectors
93 * @param declaration MapCSS declaration
94 */
95 public GroupedMapCSSRule(List<Selector> selectors, Declaration declaration) {
96 this.selectors = selectors;
97 this.declaration = declaration;
98 }
99
100 @Override
101 public int hashCode() {
102 return Objects.hash(selectors, declaration);
103 }
104
105 @Override
106 public boolean equals(Object obj) {
107 if (this == obj) return true;
108 if (obj == null || getClass() != obj.getClass()) return false;
109 GroupedMapCSSRule that = (GroupedMapCSSRule) obj;
110 return Objects.equals(selectors, that.selectors) &&
111 Objects.equals(declaration, that.declaration);
112 }
113
114 @Override
115 public String toString() {
116 return "GroupedMapCSSRule [selectors=" + selectors + ", declaration=" + declaration + ']';
117 }
118 }
119
120 /**
121 * The preference key for tag checker source entries.
122 * @since 6670
123 */
124 public static final String ENTRIES_PREF_KEY = "validator." + MapCSSTagChecker.class.getName() + ".entries";
125
126 /**
127 * Constructs a new {@code MapCSSTagChecker}.
128 */
129 public MapCSSTagChecker() {
130 super(tr("Tag checker (MapCSS based)"), tr("This test checks for errors in tag keys and values."));
131 }
132
133 /**
134 * Represents a fix to a validation test. The fixing {@link Command} can be obtained by {@link #createCommand(OsmPrimitive, Selector)}.
135 */
136 @FunctionalInterface
137 interface FixCommand {
138 /**
139 * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to evaluate placeholders
140 * (cf. {@link MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}).
141 * @param p OSM primitive
142 * @param matchingSelector matching selector
143 * @return fix command
144 */
145 Command createCommand(OsmPrimitive p, Selector matchingSelector);
146
147 /**
148 * Checks that object is either an {@link Expression} or a {@link String}.
149 * @param obj object to check
150 * @throws IllegalArgumentException if object is not an {@code Expression} or a {@code String}
151 */
152 static void checkObject(final Object obj) {
153 CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String,
154 () -> "instance of Exception or String expected, but got " + obj);
155 }
156
157 /**
158 * Evaluates given object as {@link Expression} or {@link String} on the matched {@link OsmPrimitive} and {@code matchingSelector}.
159 * @param obj object to evaluate ({@link Expression} or {@link String})
160 * @param p OSM primitive
161 * @param matchingSelector matching selector
162 * @return result string
163 */
164 static String evaluateObject(final Object obj, final OsmPrimitive p, final Selector matchingSelector) {
165 final String s;
166 if (obj instanceof Expression) {
167 s = (String) ((Expression) obj).evaluate(new Environment(p));
168 } else if (obj instanceof String) {
169 s = (String) obj;
170 } else {
171 return null;
172 }
173 return TagCheck.insertArguments(matchingSelector, s, p);
174 }
175
176 /**
177 * Creates a fixing command which executes a {@link ChangePropertyCommand} on the specified tag.
178 * @param obj object to evaluate ({@link Expression} or {@link String})
179 * @return created fix command
180 */
181 static FixCommand fixAdd(final Object obj) {
182 checkObject(obj);
183 return new FixCommand() {
184 @Override
185 public 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 * Creates a fixing command which executes a {@link ChangePropertyCommand} to delete the specified key.
199 * @param obj object to evaluate ({@link Expression} or {@link String})
200 * @return created fix command
201 */
202 static FixCommand fixRemove(final Object obj) {
203 checkObject(obj);
204 return new FixCommand() {
205 @Override
206 public Command createCommand(OsmPrimitive p, Selector matchingSelector) {
207 final String key = evaluateObject(obj, p, matchingSelector);
208 return new ChangePropertyCommand(p, key, "");
209 }
210
211 @Override
212 public String toString() {
213 return "fixRemove: " + obj;
214 }
215 };
216 }
217
218 /**
219 * Creates a fixing command which executes a {@link ChangePropertyKeyCommand} on the specified keys.
220 * @param oldKey old key
221 * @param newKey new key
222 * @return created fix command
223 */
224 static FixCommand fixChangeKey(final String oldKey, final String newKey) {
225 return new FixCommand() {
226 @Override
227 public Command createCommand(OsmPrimitive p, Selector matchingSelector) {
228 return new ChangePropertyKeyCommand(p,
229 TagCheck.insertArguments(matchingSelector, oldKey, p),
230 TagCheck.insertArguments(matchingSelector, newKey, p));
231 }
232
233 @Override
234 public String toString() {
235 return "fixChangeKey: " + oldKey + " => " + newKey;
236 }
237 };
238 }
239 }
240
241 final MultiMap<String, TagCheck> checks = new MultiMap<>();
242
243 /**
244 * Result of {@link TagCheck#readMapCSS}
245 * @since 8936
246 */
247 public static class ParseResult {
248 /** Checks successfully parsed */
249 public final List<TagCheck> parseChecks;
250 /** Errors that occurred during parsing */
251 public final Collection<Throwable> parseErrors;
252
253 /**
254 * Constructs a new {@code ParseResult}.
255 * @param parseChecks Checks successfully parsed
256 * @param parseErrors Errors that occurred during parsing
257 */
258 public ParseResult(List<TagCheck> parseChecks, Collection<Throwable> parseErrors) {
259 this.parseChecks = parseChecks;
260 this.parseErrors = parseErrors;
261 }
262 }
263
264 /**
265 * Tag check.
266 */
267 public static class TagCheck implements Predicate<OsmPrimitive> {
268 /** The selector of this {@code TagCheck} */
269 protected final GroupedMapCSSRule rule;
270 /** Commands to apply in order to fix a matching primitive */
271 protected final List<FixCommand> fixCommands = new ArrayList<>();
272 /** Tags (or arbitraty strings) of alternatives to be presented to the user */
273 protected final List<String> alternatives = new ArrayList<>();
274 /** An {@link org.openstreetmap.josm.gui.mappaint.mapcss.Instruction.AssignmentInstruction}-{@link Severity} pair.
275 * Is evaluated on the matching primitive to give the error message. Map is checked to contain exactly one element. */
276 protected final Map<Instruction.AssignmentInstruction, Severity> errors = new HashMap<>();
277 /** Unit tests */
278 protected final Map<String, Boolean> assertions = new HashMap<>();
279 /** MapCSS Classes to set on matching primitives */
280 protected final Set<String> setClassExpressions = new HashSet<>();
281 /** Denotes whether the object should be deleted for fixing it */
282 protected boolean deletion;
283 /** A string used to group similar tests */
284 protected String group;
285
286 TagCheck(GroupedMapCSSRule rule) {
287 this.rule = rule;
288 }
289
290 private static final String POSSIBLE_THROWS = possibleThrows();
291
292 static final String possibleThrows() {
293 StringBuilder sb = new StringBuilder();
294 for (Severity s : Severity.values()) {
295 if (sb.length() > 0) {
296 sb.append('/');
297 }
298 sb.append("throw")
299 .append(s.name().charAt(0))
300 .append(s.name().substring(1).toLowerCase(Locale.ENGLISH));
301 }
302 return sb.toString();
303 }
304
305 static TagCheck ofMapCSSRule(final GroupedMapCSSRule rule) throws IllegalDataException {
306 final TagCheck check = new TagCheck(rule);
307 for (Instruction i : rule.declaration.instructions) {
308 if (i instanceof Instruction.AssignmentInstruction) {
309 final Instruction.AssignmentInstruction ai = (Instruction.AssignmentInstruction) i;
310 if (ai.isSetInstruction) {
311 check.setClassExpressions.add(ai.key);
312 continue;
313 }
314 try {
315 final String val = ai.val instanceof Expression
316 ? Optional.of(((Expression) ai.val).evaluate(new Environment())).map(Object::toString).orElse(null)
317 : ai.val instanceof String
318 ? (String) ai.val
319 : ai.val instanceof Keyword
320 ? ((Keyword) ai.val).val
321 : null;
322 if (ai.key.startsWith("throw")) {
323 try {
324 check.errors.put(ai, Severity.valueOf(ai.key.substring("throw".length()).toUpperCase(Locale.ENGLISH)));
325 } catch (IllegalArgumentException e) {
326 Logging.log(Logging.LEVEL_WARN,
327 "Unsupported "+ai.key+" instruction. Allowed instructions are "+POSSIBLE_THROWS+'.', e);
328 }
329 } else if ("fixAdd".equals(ai.key)) {
330 check.fixCommands.add(FixCommand.fixAdd(ai.val));
331 } else if ("fixRemove".equals(ai.key)) {
332 CheckParameterUtil.ensureThat(!(ai.val instanceof String) || !(val != null && val.contains("=")),
333 "Unexpected '='. Please only specify the key to remove in: " + ai);
334 check.fixCommands.add(FixCommand.fixRemove(ai.val));
335 } else if (val != null && "fixChangeKey".equals(ai.key)) {
336 CheckParameterUtil.ensureThat(val.contains("=>"), "Separate old from new key by '=>'!");
337 final String[] x = val.split("=>", 2);
338 check.fixCommands.add(FixCommand.fixChangeKey(Utils.removeWhiteSpaces(x[0]), Utils.removeWhiteSpaces(x[1])));
339 } else if (val != null && "fixDeleteObject".equals(ai.key)) {
340 CheckParameterUtil.ensureThat("this".equals(val), "fixDeleteObject must be followed by 'this'");
341 check.deletion = true;
342 } else if (val != null && "suggestAlternative".equals(ai.key)) {
343 check.alternatives.add(val);
344 } else if (val != null && "assertMatch".equals(ai.key)) {
345 check.assertions.put(val, Boolean.TRUE);
346 } else if (val != null && "assertNoMatch".equals(ai.key)) {
347 check.assertions.put(val, Boolean.FALSE);
348 } else if (val != null && "group".equals(ai.key)) {
349 check.group = val;
350 } else {
351 throw new IllegalDataException("Cannot add instruction " + ai.key + ": " + ai.val + '!');
352 }
353 } catch (IllegalArgumentException e) {
354 throw new IllegalDataException(e);
355 }
356 }
357 }
358 if (check.errors.isEmpty() && check.setClassExpressions.isEmpty()) {
359 throw new IllegalDataException(
360 "No "+POSSIBLE_THROWS+" given! You should specify a validation error message for " + rule.selectors);
361 } else if (check.errors.size() > 1) {
362 throw new IllegalDataException(
363 "More than one "+POSSIBLE_THROWS+" given! You should specify a single validation error message for "
364 + rule.selectors);
365 }
366 return check;
367 }
368
369 static ParseResult readMapCSS(Reader css) throws ParseException {
370 CheckParameterUtil.ensureParameterNotNull(css, "css");
371
372 final MapCSSStyleSource source = new MapCSSStyleSource("");
373 final MapCSSParser preprocessor = new MapCSSParser(css, MapCSSParser.LexicalState.PREPROCESSOR);
374 final StringReader mapcss = new StringReader(preprocessor.pp_root(source));
375 final MapCSSParser parser = new MapCSSParser(mapcss, MapCSSParser.LexicalState.DEFAULT);
376 parser.sheet(source);
377 // Ignore "meta" rule(s) from external rules of JOSM wiki
378 source.removeMetaRules();
379 // group rules with common declaration block
380 Map<Declaration, List<Selector>> g = new LinkedHashMap<>();
381 for (MapCSSRule rule : source.rules) {
382 if (!g.containsKey(rule.declaration)) {
383 List<Selector> sels = new ArrayList<>();
384 sels.add(rule.selector);
385 g.put(rule.declaration, sels);
386 } else {
387 g.get(rule.declaration).add(rule.selector);
388 }
389 }
390 List<TagCheck> parseChecks = new ArrayList<>();
391 for (Map.Entry<Declaration, List<Selector>> map : g.entrySet()) {
392 try {
393 parseChecks.add(TagCheck.ofMapCSSRule(
394 new GroupedMapCSSRule(map.getValue(), map.getKey())));
395 } catch (IllegalDataException e) {
396 Logging.error("Cannot add MapCss rule: "+e.getMessage());
397 source.logError(e);
398 }
399 }
400 return new ParseResult(parseChecks, source.getErrors());
401 }
402
403 @Override
404 public boolean test(OsmPrimitive primitive) {
405 // Tests whether the primitive contains a deprecated tag which is represented by this MapCSSTagChecker.
406 return whichSelectorMatchesPrimitive(primitive) != null;
407 }
408
409 Selector whichSelectorMatchesPrimitive(OsmPrimitive primitive) {
410 return whichSelectorMatchesEnvironment(new Environment(primitive));
411 }
412
413 Selector whichSelectorMatchesEnvironment(Environment env) {
414 for (Selector i : rule.selectors) {
415 env.clearSelectorMatchingInformation();
416 if (i.matches(env)) {
417 return i;
418 }
419 }
420 return null;
421 }
422
423 /**
424 * Determines the {@code index}-th key/value/tag (depending on {@code type}) of the
425 * {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector}.
426 * @param matchingSelector matching selector
427 * @param index index
428 * @param type selector type ("key", "value" or "tag")
429 * @param p OSM primitive
430 * @return argument value, can be {@code null}
431 */
432 static String determineArgument(Selector.GeneralSelector matchingSelector, int index, String type, OsmPrimitive p) {
433 try {
434 final Condition c = matchingSelector.getConditions().get(index);
435 final Tag tag = c instanceof Condition.ToTagConvertable
436 ? ((Condition.ToTagConvertable) c).asTag(p)
437 : null;
438 if (tag == null) {
439 return null;
440 } else if ("key".equals(type)) {
441 return tag.getKey();
442 } else if ("value".equals(type)) {
443 return tag.getValue();
444 } else if ("tag".equals(type)) {
445 return tag.toString();
446 }
447 } catch (IndexOutOfBoundsException ignore) {
448 Logging.debug(ignore);
449 }
450 return null;
451 }
452
453 /**
454 * Replaces occurrences of <code>{i.key}</code>, <code>{i.value}</code>, <code>{i.tag}</code> in {@code s} by the corresponding
455 * key/value/tag of the {@code index}-th {@link Condition} of {@code matchingSelector}.
456 * @param matchingSelector matching selector
457 * @param s any string
458 * @param p OSM primitive
459 * @return string with arguments inserted
460 */
461 static String insertArguments(Selector matchingSelector, String s, OsmPrimitive p) {
462 if (s != null && matchingSelector instanceof Selector.ChildOrParentSelector) {
463 return insertArguments(((Selector.ChildOrParentSelector) matchingSelector).right, s, p);
464 } else if (s == null || !(matchingSelector instanceof GeneralSelector)) {
465 return s;
466 }
467 final Matcher m = Pattern.compile("\\{(\\d+)\\.(key|value|tag)\\}").matcher(s);
468 final StringBuffer sb = new StringBuffer();
469 while (m.find()) {
470 final String argument = determineArgument((Selector.GeneralSelector) matchingSelector,
471 Integer.parseInt(m.group(1)), m.group(2), p);
472 try {
473 // Perform replacement with null-safe + regex-safe handling
474 m.appendReplacement(sb, String.valueOf(argument).replace("^(", "").replace(")$", ""));
475 } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
476 Logging.log(Logging.LEVEL_ERROR, tr("Unable to replace argument {0} in {1}: {2}", argument, sb, e.getMessage()), e);
477 }
478 }
479 m.appendTail(sb);
480 return sb.toString();
481 }
482
483 /**
484 * Constructs a fix in terms of a {@link org.openstreetmap.josm.command.Command} for the {@link OsmPrimitive}
485 * if the error is fixable, or {@code null} otherwise.
486 *
487 * @param p the primitive to construct the fix for
488 * @return the fix or {@code null}
489 */
490 Command fixPrimitive(OsmPrimitive p) {
491 if (fixCommands.isEmpty() && !deletion) {
492 return null;
493 }
494 try {
495 final Selector matchingSelector = whichSelectorMatchesPrimitive(p);
496 Collection<Command> cmds = new LinkedList<>();
497 for (FixCommand fixCommand : fixCommands) {
498 cmds.add(fixCommand.createCommand(p, matchingSelector));
499 }
500 if (deletion && !p.isDeleted()) {
501 cmds.add(new DeleteCommand(p));
502 }
503 return new SequenceCommand(tr("Fix of {0}", getDescriptionForMatchingSelector(p, matchingSelector)), cmds);
504 } catch (IllegalArgumentException e) {
505 Logging.error(e);
506 return null;
507 }
508 }
509
510 /**
511 * Constructs a (localized) message for this deprecation check.
512 * @param p OSM primitive
513 *
514 * @return a message
515 */
516 String getMessage(OsmPrimitive p) {
517 if (errors.isEmpty()) {
518 // Return something to avoid NPEs
519 return rule.declaration.toString();
520 } else {
521 final Object val = errors.keySet().iterator().next().val;
522 return String.valueOf(
523 val instanceof Expression
524 ? ((Expression) val).evaluate(new Environment(p))
525 : val
526 );
527 }
528 }
529
530 /**
531 * Constructs a (localized) description for this deprecation check.
532 * @param p OSM primitive
533 *
534 * @return a description (possibly with alternative suggestions)
535 * @see #getDescriptionForMatchingSelector
536 */
537 String getDescription(OsmPrimitive p) {
538 if (alternatives.isEmpty()) {
539 return getMessage(p);
540 } else {
541 /* I18N: {0} is the test error message and {1} is an alternative */
542 return tr("{0}, use {1} instead", getMessage(p), Utils.join(tr(" or "), alternatives));
543 }
544 }
545
546 /**
547 * Constructs a (localized) description for this deprecation check
548 * where any placeholders are replaced by values of the matched selector.
549 *
550 * @param matchingSelector matching selector
551 * @param p OSM primitive
552 * @return a description (possibly with alternative suggestions)
553 */
554 String getDescriptionForMatchingSelector(OsmPrimitive p, Selector matchingSelector) {
555 return insertArguments(matchingSelector, getDescription(p), p);
556 }
557
558 Severity getSeverity() {
559 return errors.isEmpty() ? null : errors.values().iterator().next();
560 }
561
562 @Override
563 public String toString() {
564 return getDescription(null);
565 }
566
567 /**
568 * Constructs a {@link TestError} for the given primitive, or returns null if the primitive does not give rise to an error.
569 *
570 * @param p the primitive to construct the error for
571 * @return an instance of {@link TestError}, or returns null if the primitive does not give rise to an error.
572 */
573 TestError getErrorForPrimitive(OsmPrimitive p) {
574 final Environment env = new Environment(p);
575 return getErrorForPrimitive(p, whichSelectorMatchesEnvironment(env), env, null);
576 }
577
578 TestError getErrorForPrimitive(OsmPrimitive p, Selector matchingSelector, Environment env, Test tester) {
579 if (matchingSelector != null && !errors.isEmpty()) {
580 final Command fix = fixPrimitive(p);
581 final String description = getDescriptionForMatchingSelector(p, matchingSelector);
582 final String description1 = group == null ? description : group;
583 final String description2 = group == null ? null : description;
584 final List<OsmPrimitive> primitives;
585 if (env.child instanceof OsmPrimitive) {
586 primitives = Arrays.asList(p, (OsmPrimitive) env.child);
587 } else {
588 primitives = Collections.singletonList(p);
589 }
590 final TestError.Builder error = TestError.builder(tester, getSeverity(), 3000)
591 .messageWithManuallyTranslatedDescription(description1, description2, matchingSelector.toString())
592 .primitives(primitives);
593 if (fix != null) {
594 return error.fix(() -> fix).build();
595 } else {
596 return error.build();
597 }
598 } else {
599 return null;
600 }
601 }
602
603 /**
604 * Returns the set of tagchecks on which this check depends on.
605 * @param schecks the collection of tagcheks to search in
606 * @return the set of tagchecks on which this check depends on
607 * @since 7881
608 */
609 public Set<TagCheck> getTagCheckDependencies(Collection<TagCheck> schecks) {
610 Set<TagCheck> result = new HashSet<>();
611 Set<String> classes = getClassesIds();
612 if (schecks != null && !classes.isEmpty()) {
613 for (TagCheck tc : schecks) {
614 if (this.equals(tc)) {
615 continue;
616 }
617 for (String id : tc.setClassExpressions) {
618 if (classes.contains(id)) {
619 result.add(tc);
620 break;
621 }
622 }
623 }
624 }
625 return result;
626 }
627
628 /**
629 * Returns the list of ids of all MapCSS classes referenced in the rule selectors.
630 * @return the list of ids of all MapCSS classes referenced in the rule selectors
631 * @since 7881
632 */
633 public Set<String> getClassesIds() {
634 Set<String> result = new HashSet<>();
635 for (Selector s : rule.selectors) {
636 if (s instanceof AbstractSelector) {
637 for (Condition c : ((AbstractSelector) s).getConditions()) {
638 if (c instanceof ClassCondition) {
639 result.add(((ClassCondition) c).id);
640 }
641 }
642 }
643 }
644 return result;
645 }
646 }
647
648 static class MapCSSTagCheckerAndRule extends MapCSSTagChecker {
649 public final GroupedMapCSSRule rule;
650
651 MapCSSTagCheckerAndRule(GroupedMapCSSRule rule) {
652 this.rule = rule;
653 }
654
655 @Override
656 public synchronized boolean equals(Object obj) {
657 return super.equals(obj)
658 || (obj instanceof TagCheck && rule.equals(((TagCheck) obj).rule))
659 || (obj instanceof GroupedMapCSSRule && rule.equals(obj));
660 }
661
662 @Override
663 public synchronized int hashCode() {
664 return Objects.hash(super.hashCode(), rule);
665 }
666
667 @Override
668 public String toString() {
669 return "MapCSSTagCheckerAndRule [rule=" + rule + ']';
670 }
671 }
672
673 /**
674 * Obtains all {@link TestError}s for the {@link OsmPrimitive} {@code p}.
675 * @param p The OSM primitive
676 * @param includeOtherSeverity if {@code true}, errors of severity {@link Severity#OTHER} (info) will also be returned
677 * @return all errors for the given primitive, with or without those of "info" severity
678 */
679 public synchronized Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity) {
680 return getErrorsForPrimitive(p, includeOtherSeverity, checks.values());
681 }
682
683 private static Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity,
684 Collection<Set<TagCheck>> checksCol) {
685 final List<TestError> r = new ArrayList<>();
686 final Environment env = new Environment(p, new MultiCascade(), Environment.DEFAULT_LAYER, null);
687 for (Set<TagCheck> schecks : checksCol) {
688 for (TagCheck check : schecks) {
689 boolean ignoreError = Severity.OTHER == check.getSeverity() && !includeOtherSeverity;
690 // Do not run "information" level checks if not wanted, unless they also set a MapCSS class
691 if (ignoreError && check.setClassExpressions.isEmpty()) {
692 continue;
693 }
694 final Selector selector = check.whichSelectorMatchesEnvironment(env);
695 if (selector != null) {
696 check.rule.declaration.execute(env);
697 if (!ignoreError && !check.errors.isEmpty()) {
698 final TestError error = check.getErrorForPrimitive(p, selector, env, new MapCSSTagCheckerAndRule(check.rule));
699 if (error != null) {
700 r.add(error);
701 }
702 }
703 }
704 }
705 }
706 return r;
707 }
708
709 /**
710 * Visiting call for primitives.
711 *
712 * @param p The primitive to inspect.
713 */
714 @Override
715 public void check(OsmPrimitive p) {
716 errors.addAll(getErrorsForPrimitive(p, ValidatorPrefHelper.PREF_OTHER.get()));
717 }
718
719 /**
720 * Adds a new MapCSS config file from the given URL.
721 * @param url The unique URL of the MapCSS config file
722 * @return List of tag checks and parsing errors, or null
723 * @throws ParseException if the config file does not match MapCSS syntax
724 * @throws IOException if any I/O error occurs
725 * @since 7275
726 */
727 public synchronized ParseResult addMapCSS(String url) throws ParseException, IOException {
728 CheckParameterUtil.ensureParameterNotNull(url, "url");
729 ParseResult result;
730 try (CachedFile cache = new CachedFile(url);
731 InputStream zip = cache.findZipEntryInputStream("validator.mapcss", "");
732 InputStream s = zip != null ? zip : cache.getInputStream();
733 Reader reader = new BufferedReader(UTFInputStreamReader.create(s))) {
734 if (zip != null)
735 I18n.addTexts(cache.getFile());
736 result = TagCheck.readMapCSS(reader);
737 checks.remove(url);
738 checks.putAll(url, result.parseChecks);
739 // Check assertions, useful for development of local files
740 if (Config.getPref().getBoolean("validator.check_assert_local_rules", false) && Utils.isLocalUrl(url)) {
741 for (String msg : checkAsserts(result.parseChecks)) {
742 Logging.warn(msg);
743 }
744 }
745 }
746 return result;
747 }
748
749 @Override
750 public synchronized void initialize() throws Exception {
751 checks.clear();
752 for (SourceEntry source : new ValidatorPrefHelper().get()) {
753 if (!source.active) {
754 continue;
755 }
756 String i = source.url;
757 try {
758 if (!i.startsWith("resource:")) {
759 Logging.info(tr("Adding {0} to tag checker", i));
760 } else if (Logging.isDebugEnabled()) {
761 Logging.debug(tr("Adding {0} to tag checker", i));
762 }
763 addMapCSS(i);
764 if (Config.getPref().getBoolean("validator.auto_reload_local_rules", true) && source.isLocal()) {
765 FileWatcher.getDefaultInstance().registerSource(source);
766 }
767 } catch (IOException | IllegalStateException | IllegalArgumentException ex) {
768 Logging.warn(tr("Failed to add {0} to tag checker", i));
769 Logging.log(Logging.LEVEL_WARN, ex);
770 } catch (ParseException | TokenMgrError ex) {
771 Logging.warn(tr("Failed to add {0} to tag checker", i));
772 Logging.warn(ex);
773 }
774 }
775 }
776
777 /**
778 * Checks that rule assertions are met for the given set of TagChecks.
779 * @param schecks The TagChecks for which assertions have to be checked
780 * @return A set of error messages, empty if all assertions are met
781 * @since 7356
782 */
783 public Set<String> checkAsserts(final Collection<TagCheck> schecks) {
784 Set<String> assertionErrors = new LinkedHashSet<>();
785 final DataSet ds = new DataSet();
786 for (final TagCheck check : schecks) {
787 Logging.debug("Check: {0}", check);
788 for (final Map.Entry<String, Boolean> i : check.assertions.entrySet()) {
789 Logging.debug("- Assertion: {0}", i);
790 final OsmPrimitive p = OsmUtils.createPrimitive(i.getKey());
791 // Build minimal ordered list of checks to run to test the assertion
792 List<Set<TagCheck>> checksToRun = new ArrayList<>();
793 Set<TagCheck> checkDependencies = check.getTagCheckDependencies(schecks);
794 if (!checkDependencies.isEmpty()) {
795 checksToRun.add(checkDependencies);
796 }
797 checksToRun.add(Collections.singleton(check));
798 // Add primitive to dataset to avoid DataIntegrityProblemException when evaluating selectors
799 ds.addPrimitive(p);
800 final Collection<TestError> pErrors = getErrorsForPrimitive(p, true, checksToRun);
801 Logging.debug("- Errors: {0}", pErrors);
802 @SuppressWarnings({"EqualsBetweenInconvertibleTypes", "EqualsIncompatibleType"})
803 final boolean isError = pErrors.stream().anyMatch(e -> e.getTester().equals(check.rule));
804 if (isError != i.getValue()) {
805 final String error = MessageFormat.format("Expecting test ''{0}'' (i.e., {1}) to {2} {3} (i.e., {4})",
806 check.getMessage(p), check.rule.selectors, i.getValue() ? "match" : "not match", i.getKey(), p.getKeys());
807 assertionErrors.add(error);
808 }
809 ds.removePrimitive(p);
810 }
811 }
812 return assertionErrors;
813 }
814
815 @Override
816 public synchronized int hashCode() {
817 return Objects.hash(super.hashCode(), checks);
818 }
819
820 @Override
821 public synchronized boolean equals(Object obj) {
822 if (this == obj) return true;
823 if (obj == null || getClass() != obj.getClass()) return false;
824 if (!super.equals(obj)) return false;
825 MapCSSTagChecker that = (MapCSSTagChecker) obj;
826 return Objects.equals(checks, that.checks);
827 }
828
829 /**
830 * Reload tagchecker rule.
831 * @param rule tagchecker rule to reload
832 * @since 12825
833 */
834 public static void reloadRule(SourceEntry rule) {
835 MapCSSTagChecker tagChecker = OsmValidator.getTest(MapCSSTagChecker.class);
836 if (tagChecker != null) {
837 try {
838 tagChecker.addMapCSS(rule.url);
839 } catch (IOException | ParseException | TokenMgrError e) {
840 Logging.warn(e);
841 }
842 }
843 }
844}
Note: See TracBrowser for help on using the repository browser.