1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package cz.zcu.mre.sparkle.tools.sparqlValidation;
21
22 import cz.zcu.mre.sparkle.tools.SparqlParser;
23 import org.antlr.v4.runtime.*;
24 import org.antlr.v4.runtime.atn.ATNState;
25 import org.antlr.v4.runtime.atn.RuleTransition;
26 import org.antlr.v4.runtime.atn.Transition;
27 import org.antlr.v4.runtime.misc.IntervalSet;
28 import org.antlr.v4.runtime.misc.ParseCancellationException;
29 import java.util.*;
30
31
32
33
34
35
36
37
38 public class SparqlValidationSyntaxErrorListener
39 extends BaseErrorListener {
40
41 private final List<SyntaxError> syntaxErrorList;
42
43 public SparqlValidationSyntaxErrorListener() {
44 syntaxErrorList = new ArrayList<>();
45 }
46
47 @Override
48 public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
49 String msg, RecognitionException e) throws ParseCancellationException {
50
51 if (e == null) {
52 e = new InlineRecognitionException(msg, recognizer, ((Parser) recognizer).getInputStream(),
53 ((Parser) recognizer).getContext(), (Token) offendingSymbol);
54 }
55
56
57
58
59
60
61
62
63
64
65
66
67
68 SyntaxError error = new SyntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e);
69
70
71
72
73
74
75
76
77
78 if (!syntaxErrorList.contains(error)) {
79 syntaxErrorList.add(error);
80 }
81 }
82
83
84
85
86
87
88
89
90
91
92
93 public Set<String> nextRulesOrTokens(Parser recognizer, ATNState state, Set<ATNState> seen, SyntaxError error) {
94 Set<String> result = new LinkedHashSet<>();
95
96 if (!seen.add(state)) {
97 return result;
98 }
99
100 for (Transition t : state.getTransitions()) {
101 if (t instanceof RuleTransition) {
102 result.add(recognizer.getRuleNames()[((RuleTransition) t).ruleIndex]);
103 } else if (t.isEpsilon()) {
104 result.addAll(nextRulesOrTokens(recognizer, t.target, seen, error));
105 } else {
106 IntervalSet label = t.label();
107 if (label != null) {
108 if (label.toList().contains((Integer) SparqlParser.AS)) {
109 error.getExpectedTokens().addAll(label);
110 }
111 result.add(label.toString(recognizer.getVocabulary()));
112 }
113 }
114 }
115 return result;
116 }
117
118 public List<SyntaxError> getSyntaxErrorList() {
119 return syntaxErrorList;
120 }
121
122 static class InlineRecognitionException
123 extends RecognitionException {
124
125 InlineRecognitionException(String message, Recognizer<?, ?> recognizer,
126 IntStream input, ParserRuleContext ctx, Token offendingToken) {
127
128 super(message, recognizer, input, ctx);
129 this.setOffendingToken(offendingToken);
130 }
131 }
132
133 }