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