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

Last change on this file since 7064 was 7064, checked in by bastiK, 10 years ago

see #9691 - add back reverted optimization [7056] (modified so it is thread safe)

File size: 20.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.validation.tests;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.Reader;
9import java.util.ArrayList;
10import java.util.Arrays;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.Iterator;
15import java.util.LinkedHashMap;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.regex.Matcher;
20import java.util.regex.Pattern;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.command.ChangePropertyCommand;
24import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
25import org.openstreetmap.josm.command.Command;
26import org.openstreetmap.josm.command.SequenceCommand;
27import org.openstreetmap.josm.data.osm.OsmPrimitive;
28import org.openstreetmap.josm.data.osm.Tag;
29import org.openstreetmap.josm.data.validation.FixableTestError;
30import org.openstreetmap.josm.data.validation.Severity;
31import org.openstreetmap.josm.data.validation.Test;
32import org.openstreetmap.josm.data.validation.TestError;
33import org.openstreetmap.josm.gui.mappaint.Environment;
34import org.openstreetmap.josm.gui.mappaint.MultiCascade;
35import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
36import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
37import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
38import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
39import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
40import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
41import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
42import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
43import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
44import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
45import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
46import org.openstreetmap.josm.io.MirroredInputStream;
47import org.openstreetmap.josm.io.UTFInputStreamReader;
48import org.openstreetmap.josm.tools.CheckParameterUtil;
49import org.openstreetmap.josm.tools.Predicate;
50import org.openstreetmap.josm.tools.Utils;
51
52/**
53 * MapCSS-based tag checker/fixer.
54 * @since 6506
55 */
56public class MapCSSTagChecker extends Test.TagTest {
57
58 /**
59 * The preference key for tag checker source entries.
60 * @since 6670
61 */
62 public static final String ENTRIES_PREF_KEY = "validator." + MapCSSTagChecker.class.getName() + ".entries";
63
64 /**
65 * Constructs a new {@code MapCSSTagChecker}.
66 */
67 public MapCSSTagChecker() {
68 super(tr("Tag checker (MapCSS based)"), tr("This test checks for errors in tag keys and values."));
69 }
70
71 final List<TagCheck> checks = new ArrayList<>();
72
73 static class TagCheck implements Predicate<OsmPrimitive> {
74 protected final MapCSSRule rule;
75 protected final List<PrimitiveToTag> change = new ArrayList<>();
76 protected final Map<String, String> keyChange = new LinkedHashMap<>();
77 protected final List<String> alternatives = new ArrayList<>();
78 protected final Map<Instruction.AssignmentInstruction, Severity> errors = new HashMap<>();
79 protected final Map<String, Boolean> assertions = new HashMap<>();
80
81 TagCheck(MapCSSRule rule) {
82 this.rule = rule;
83 }
84
85 /**
86 * A function mapping the matched {@link OsmPrimitive} to a {@link Tag}.
87 */
88 abstract static class PrimitiveToTag implements Utils.Function<OsmPrimitive, Tag> {
89
90 private PrimitiveToTag() {
91 // Hide implicit public constructor for utility class
92 }
93
94 /**
95 * Creates a new mapping from an {@code MapCSS} object.
96 * In case of an {@link Expression}, that is evaluated on the matched {@link OsmPrimitive}.
97 * In case of a {@link String}, that is "compiled" to a {@link Tag} instance.
98 */
99 static PrimitiveToTag ofMapCSSObject(final Object obj, final boolean keyOnly) {
100 if (obj instanceof Expression) {
101 return new PrimitiveToTag() {
102 @Override
103 public Tag apply(OsmPrimitive p) {
104 final String s = (String) ((Expression) obj).evaluate(new Environment().withPrimitive(p));
105 return keyOnly? new Tag(s) : Tag.ofString(s);
106 }
107 };
108 } else if (obj instanceof String) {
109 final Tag tag = keyOnly ? new Tag((String) obj) : Tag.ofString((String) obj);
110 return new PrimitiveToTag() {
111 @Override
112 public Tag apply(OsmPrimitive ignore) {
113 return tag;
114 }
115 };
116 } else {
117 return null;
118 }
119 }
120 }
121
122 static TagCheck ofMapCSSRule(final MapCSSRule rule) {
123 final TagCheck check = new TagCheck(rule);
124 boolean containsSetClassExpression = false;
125 for (Instruction i : rule.declaration.instructions) {
126 if (i instanceof Instruction.AssignmentInstruction) {
127 final Instruction.AssignmentInstruction ai = (Instruction.AssignmentInstruction) i;
128 if (ai.isSetInstruction) {
129 containsSetClassExpression = true;
130 continue;
131 }
132 final String val = ai.val instanceof Expression
133 ? (String) ((Expression) ai.val).evaluate(new Environment())
134 : ai.val instanceof String
135 ? (String) ai.val
136 : null;
137 if (ai.key.startsWith("throw")) {
138 final Severity severity = Severity.valueOf(ai.key.substring("throw".length()).toUpperCase());
139 check.errors.put(ai, severity);
140 } else if ("fixAdd".equals(ai.key)) {
141 final PrimitiveToTag toTag = PrimitiveToTag.ofMapCSSObject(ai.val, false);
142 check.change.add(toTag);
143 } else if ("fixRemove".equals(ai.key)) {
144 CheckParameterUtil.ensureThat(!(ai.val instanceof String) || !val.contains("="), "Unexpected '='. Please only specify the key to remove!");
145 final PrimitiveToTag toTag = PrimitiveToTag.ofMapCSSObject(ai.val, true);
146 check.change.add(toTag);
147 } else if ("fixChangeKey".equals(ai.key) && val != null) {
148 CheckParameterUtil.ensureThat(val.contains("=>"), "Separate old from new key by '=>'!");
149 final String[] x = val.split("=>", 2);
150 check.keyChange.put(Tag.removeWhiteSpaces(x[0]), Tag.removeWhiteSpaces(x[1]));
151 } else if ("suggestAlternative".equals(ai.key) && val != null) {
152 check.alternatives.add(val);
153 } else if ("assertMatch".equals(ai.key) && val != null) {
154 check.assertions.put(val, true);
155 } else if ("assertNoMatch".equals(ai.key) && val != null) {
156 check.assertions.put(val, false);
157 } else {
158 throw new RuntimeException("Cannot add instruction " + ai.key + ": " + ai.val + "!");
159 }
160 }
161 }
162 if (check.errors.isEmpty() && !containsSetClassExpression) {
163 throw new RuntimeException("No throwError/throwWarning/throwOther given! You should specify a validation error message for " + rule.selector);
164 } else if (check.errors.size() > 1) {
165 throw new RuntimeException("More than one throwError/throwWarning/throwOther given! You should specify a single validation error message for " + rule.selector);
166 }
167 return check;
168 }
169
170 static List<TagCheck> readMapCSS(Reader css) throws ParseException {
171 CheckParameterUtil.ensureParameterNotNull(css, "css");
172 return readMapCSS(new MapCSSParser(css));
173 }
174
175 static List<TagCheck> readMapCSS(MapCSSParser css) throws ParseException {
176 CheckParameterUtil.ensureParameterNotNull(css, "css");
177 final MapCSSStyleSource source = new MapCSSStyleSource("");
178 css.sheet(source);
179 assert source.getErrors().isEmpty();
180 // Ignore "meta" rule(s) from external rules of JOSM wiki
181 removeMetaRules(source);
182 return new ArrayList<>(Utils.transform(source.rules, new Utils.Function<MapCSSRule, TagCheck>() {
183 @Override
184 public TagCheck apply(MapCSSRule x) {
185 return TagCheck.ofMapCSSRule(x);
186 }
187 }));
188 }
189
190 private static void removeMetaRules(MapCSSStyleSource source) {
191 for (Iterator<MapCSSRule> it = source.rules.iterator(); it.hasNext(); ) {
192 MapCSSRule x = it.next();
193 if (x.selector instanceof GeneralSelector) {
194 GeneralSelector gs = (GeneralSelector) x.selector;
195 if ("meta".equals(gs.base) && gs.getConditions().isEmpty()) {
196 it.remove();
197 }
198 }
199 }
200 }
201
202 @Override
203 public boolean evaluate(OsmPrimitive primitive) {
204 // Tests whether the primitive contains a deprecated tag which is represented by this MapCSSTagChecker.
205 return whichSelectorMatchesPrimitive(primitive) != null;
206 }
207
208 Selector whichSelectorMatchesPrimitive(OsmPrimitive primitive) {
209 return whichSelectorMatchesEnvironment(new Environment().withPrimitive(primitive));
210 }
211
212 Selector whichSelectorMatchesEnvironment(Environment env) {
213 env.clearSelectorMatchingInformation();
214 if (rule.selector.matches(env)) {
215 return rule.selector;
216 }
217 return null;
218 }
219
220 /**
221 * Determines the {@code index}-th key/value/tag (depending on {@code type}) of the
222 * {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector}.
223 */
224 static String determineArgument(Selector.GeneralSelector matchingSelector, int index, String type) {
225 try {
226 final Condition c = matchingSelector.getConditions().get(index);
227 final Tag tag = c instanceof Condition.KeyCondition
228 ? ((Condition.KeyCondition) c).asTag()
229 : c instanceof Condition.SimpleKeyValueCondition
230 ? ((Condition.SimpleKeyValueCondition) c).asTag()
231 : c instanceof Condition.KeyValueCondition
232 ? ((Condition.KeyValueCondition) c).asTag()
233 : null;
234 if (tag == null) {
235 return null;
236 } else if ("key".equals(type)) {
237 return tag.getKey();
238 } else if ("value".equals(type)) {
239 return tag.getValue();
240 } else if ("tag".equals(type)) {
241 return tag.toString();
242 }
243 } catch (IndexOutOfBoundsException ignore) {
244 Main.debug(ignore.getMessage());
245 }
246 return null;
247 }
248
249 /**
250 * Replaces occurrences of {@code {i.key}}, {@code {i.value}}, {@code {i.tag}} in {@code s} by the corresponding
251 * key/value/tag of the {@code index}-th {@link Condition} of {@code matchingSelector}.
252 */
253 static String insertArguments(Selector matchingSelector, String s) {
254 if (s != null && matchingSelector instanceof Selector.ChildOrParentSelector) {
255 return insertArguments(((Selector.ChildOrParentSelector)matchingSelector).right, s);
256 } else if (s == null || !(matchingSelector instanceof GeneralSelector)) {
257 return s;
258 }
259 final Matcher m = Pattern.compile("\\{(\\d+)\\.(key|value|tag)\\}").matcher(s);
260 final StringBuffer sb = new StringBuffer();
261 while (m.find()) {
262 final String argument = determineArgument((Selector.GeneralSelector) matchingSelector, Integer.parseInt(m.group(1)), m.group(2));
263 try {
264 m.appendReplacement(sb, String.valueOf(argument));
265 } catch (IndexOutOfBoundsException e) {
266 Main.error(tr("Unable to replace argument {0} in {1}: {2}", argument, sb, e.getMessage()));
267 }
268 }
269 m.appendTail(sb);
270 return sb.toString();
271 }
272
273 /**
274 * Constructs a fix in terms of a {@link org.openstreetmap.josm.command.Command} for the {@link OsmPrimitive}
275 * if the error is fixable, or {@code null} otherwise.
276 *
277 * @param p the primitive to construct the fix for
278 * @return the fix or {@code null}
279 */
280 Command fixPrimitive(OsmPrimitive p) {
281 if (change.isEmpty() && keyChange.isEmpty()) {
282 return null;
283 }
284 final Selector matchingSelector = whichSelectorMatchesPrimitive(p);
285 Collection<Command> cmds = new LinkedList<>();
286 for (PrimitiveToTag toTag : change) {
287 final Tag tag = toTag.apply(p);
288 final String key = insertArguments(matchingSelector, tag.getKey());
289 final String value = insertArguments(matchingSelector, tag.getValue());
290 cmds.add(new ChangePropertyCommand(p, key, value));
291 }
292 for (Map.Entry<String, String> i : keyChange.entrySet()) {
293 final String oldKey = insertArguments(matchingSelector, i.getKey());
294 final String newKey = insertArguments(matchingSelector, i.getValue());
295 cmds.add(new ChangePropertyKeyCommand(p, oldKey, newKey));
296 }
297 return new SequenceCommand(tr("Fix of {0}", getDescriptionForMatchingSelector(p, matchingSelector)), cmds);
298 }
299
300 /**
301 * Constructs a (localized) message for this deprecation check.
302 *
303 * @return a message
304 */
305 String getMessage(OsmPrimitive p) {
306 if (errors.isEmpty()) {
307 // Return something to avoid NPEs
308 return rule.declaration.toString();
309 } else {
310 final Object val = errors.keySet().iterator().next().val;
311 return String.valueOf(
312 val instanceof Expression
313 ? ((Expression) val).evaluate(new Environment().withPrimitive(p))
314 : val
315 );
316 }
317 }
318
319 /**
320 * Constructs a (localized) description for this deprecation check.
321 *
322 * @return a description (possibly with alternative suggestions)
323 * @see #getDescriptionForMatchingSelector
324 */
325 String getDescription(OsmPrimitive p) {
326 if (alternatives.isEmpty()) {
327 return getMessage(p);
328 } else {
329 /* I18N: {0} is the test error message and {1} is an alternative */
330 return tr("{0}, use {1} instead", getMessage(p), Utils.join(tr(" or "), alternatives));
331 }
332 }
333
334 /**
335 * Constructs a (localized) description for this deprecation check
336 * where any placeholders are replaced by values of the matched selector.
337 *
338 * @return a description (possibly with alternative suggestions)
339 */
340 String getDescriptionForMatchingSelector(OsmPrimitive p, Selector matchingSelector) {
341 return insertArguments(matchingSelector, getDescription(p));
342 }
343
344 Severity getSeverity() {
345 return errors.isEmpty() ? null : errors.values().iterator().next();
346 }
347
348 @Override
349 public String toString() {
350 return getDescription(null);
351 }
352
353 /**
354 * Constructs a {@link TestError} for the given primitive, or returns null if the primitive does not give rise to an error.
355 *
356 * @param p the primitive to construct the error for
357 * @return an instance of {@link TestError}, or returns null if the primitive does not give rise to an error.
358 */
359 TestError getErrorForPrimitive(OsmPrimitive p) {
360 final Environment env = new Environment().withPrimitive(p);
361 return getErrorForPrimitive(p, whichSelectorMatchesEnvironment(env), env);
362 }
363
364 TestError getErrorForPrimitive(OsmPrimitive p, Selector matchingSelector, Environment env) {
365 if (matchingSelector != null && !errors.isEmpty()) {
366 final Command fix = fixPrimitive(p);
367 final String description = getDescriptionForMatchingSelector(p, matchingSelector);
368 final List<OsmPrimitive> primitives;
369 if (env.child != null) {
370 primitives = Arrays.asList(p, env.child);
371 } else {
372 primitives = Collections.singletonList(p);
373 }
374 if (fix != null) {
375 return new FixableTestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives, fix);
376 } else {
377 return new TestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives);
378 }
379 } else {
380 return null;
381 }
382 }
383 }
384
385 static class MapCSSTagCheckerAndRule extends MapCSSTagChecker {
386 public final MapCSSRule rule;
387
388 MapCSSTagCheckerAndRule(MapCSSRule rule) {
389 this.rule = rule;
390 }
391
392 @Override
393 public boolean equals(Object obj) {
394 return super.equals(obj)
395 || (obj instanceof TagCheck && rule.equals(((TagCheck) obj).rule))
396 || (obj instanceof MapCSSRule && rule.equals(obj));
397 }
398 }
399
400 /**
401 * Obtains all {@link TestError}s for the {@link OsmPrimitive} {@code p}.
402 */
403 public Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity) {
404 final ArrayList<TestError> r = new ArrayList<>();
405 final Environment env = new Environment(p, new MultiCascade(), Environment.DEFAULT_LAYER, null);
406 for (TagCheck check : checks) {
407 if (Severity.OTHER.equals(check.getSeverity()) && !includeOtherSeverity) {
408 continue;
409 }
410 final Selector selector = check.whichSelectorMatchesEnvironment(env);
411 if (selector != null) {
412 check.rule.execute(env);
413 final TestError error = check.getErrorForPrimitive(p, selector, env);
414 if (error != null) {
415 error.setTester(new MapCSSTagCheckerAndRule(check.rule));
416 r.add(error);
417 }
418 }
419 }
420 return r;
421 }
422
423 /**
424 * Visiting call for primitives.
425 *
426 * @param p The primitive to inspect.
427 */
428 @Override
429 public void check(OsmPrimitive p) {
430 errors.addAll(getErrorsForPrimitive(p, ValidatorPreference.PREF_OTHER.get()));
431 }
432
433 /**
434 * Adds a new MapCSS config file from the given {@code Reader}.
435 * @param css The reader
436 * @throws ParseException if the config file does not match MapCSS syntax
437 */
438 public void addMapCSS(Reader css) throws ParseException {
439 checks.addAll(TagCheck.readMapCSS(css));
440 }
441
442 @Override
443 public synchronized void initialize() throws Exception {
444 checks.clear();
445 for (String i : new ValidatorTagCheckerRulesPreference.RulePrefHelper().getActiveUrls()) {
446 try {
447 if (i.startsWith("resource:")) {
448 Main.debug(tr("Adding {0} to tag checker", i));
449 } else {
450 Main.info(tr("Adding {0} to tag checker", i));
451 }
452 try (MirroredInputStream s = new MirroredInputStream(i)) {
453 addMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
454 }
455 } catch (IOException ex) {
456 Main.warn(tr("Failed to add {0} to tag checker", i));
457 Main.warn(ex, false);
458 } catch (Exception ex) {
459 Main.warn(tr("Failed to add {0} to tag checker", i));
460 Main.warn(ex);
461 }
462 }
463 }
464}
Note: See TracBrowser for help on using the repository browser.