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

Last change on this file since 10672 was 10672, checked in by Don-vip, 8 years ago

see #12472 - fix "UnsynchronizedOverridesSynchronized" warnings

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