The Unified and Autonomous Development Platform
midwork
robin shine052b0631f0b1
diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.javaindex b3151ad0e5..7da725b00e 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.java@@ -1,83 +1,37 @@package com.pmease.commons.antlr.codeassist;-import java.io.IOException;-import java.io.InputStream;import java.io.Serializable;-import java.lang.reflect.Constructor;-import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;import java.util.Collections;-import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;-import java.util.UUID;-import javax.annotation.Nullable;--import org.antlr.v4.runtime.ANTLRInputStream;-import org.antlr.v4.runtime.BailErrorStrategy;-import org.antlr.v4.runtime.CharStream;-import org.antlr.v4.runtime.CommonTokenStream;import org.antlr.v4.runtime.Lexer;import org.antlr.v4.runtime.Token;-import org.antlr.v4.runtime.tree.TerminalNode;-import org.apache.tika.io.IOUtils;import com.google.common.base.Preconditions;import com.google.common.collect.Sets;-import com.pmease.commons.antlr.ANTLRv4Lexer;-import com.pmease.commons.antlr.ANTLRv4Parser;-import com.pmease.commons.antlr.ANTLRv4Parser.AlternativeContext;-import com.pmease.commons.antlr.ANTLRv4Parser.AtomContext;-import com.pmease.commons.antlr.ANTLRv4Parser.BlockContext;-import com.pmease.commons.antlr.ANTLRv4Parser.EbnfContext;-import com.pmease.commons.antlr.ANTLRv4Parser.EbnfSuffixContext;-import com.pmease.commons.antlr.ANTLRv4Parser.ElementContext;-import com.pmease.commons.antlr.ANTLRv4Parser.GrammarSpecContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LabeledAltContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LabeledElementContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LabeledLexerElementContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LexerAltContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LexerAtomContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LexerBlockContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LexerElementContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LexerRuleBlockContext;-import com.pmease.commons.antlr.ANTLRv4Parser.LexerRuleSpecContext;-import com.pmease.commons.antlr.ANTLRv4Parser.ModeSpecContext;-import com.pmease.commons.antlr.ANTLRv4Parser.NotSetContext;-import com.pmease.commons.antlr.ANTLRv4Parser.ParserRuleSpecContext;-import com.pmease.commons.antlr.ANTLRv4Parser.RuleBlockContext;-import com.pmease.commons.antlr.ANTLRv4Parser.RuleSpecContext;-import com.pmease.commons.antlr.ANTLRv4Parser.SetElementContext;-import com.pmease.commons.antlr.AntlrUtils;import com.pmease.commons.antlr.codeassist.ElementSpec.Multiplicity;import com.pmease.commons.antlr.codeassist.parse.EarleyParser;-import com.pmease.commons.antlr.codeassist.parse.ParentedElement;-import com.pmease.commons.antlr.codeassist.parse.ParseNode;-import com.pmease.commons.antlr.codeassist.parse.ParseState;-import com.pmease.commons.antlr.codeassist.parse.ParsedElement;+import com.pmease.commons.antlr.codeassist.parse.Element;+import com.pmease.commons.antlr.codeassist.parse.Node;+import com.pmease.commons.antlr.codeassist.parse.State;import com.pmease.commons.util.StringUtils;public abstract class CodeAssist implements Serializable {private static final long serialVersionUID = 1L;-- private final Class<? extends Lexer> lexerClass;-- private transient Constructor<? extends Lexer> lexerCtor;-- private final Map<String, RuleSpec> rules = new HashMap<>();-- private final Map<String, Integer> tokenTypesByLiteral = new HashMap<>();- private final Map<String, Integer> tokenTypesByRule = new HashMap<>();-- private final Set<String> blockRuleNames = new HashSet<>();+ private final Grammar grammar;+ public CodeAssist(Grammar grammar) {+ this.grammar = grammar;+ }+/*** Code assist constructor* @param lexerClass@@ -85,8 +39,7 @@ public abstract class CodeAssist implements Serializable {* grammar files and token file will be derived from the lexer class*/public CodeAssist(Class<? extends Lexer> lexerClass) {- this(lexerClass, new String[]{AntlrUtils.getDefaultGrammarFile(lexerClass)},- AntlrUtils.getDefaultTokenFile(lexerClass));+ this(new Grammar(lexerClass));}/**@@ -100,324 +53,11 @@ public abstract class CodeAssist implements Serializable {* generated tokens file in class path, relative to class path root*/public CodeAssist(Class<? extends Lexer> lexerClass, String grammarFiles[], String tokenFile) {- this.lexerClass = lexerClass;- tokenTypesByRule.put("EOF", Token.EOF);-- try (InputStream is = getClass().getClassLoader().getResourceAsStream(tokenFile)) {- for (String line: IOUtils.readLines(is)) {- String key = StringUtils.substringBeforeLast(line, "=");- Integer value = Integer.valueOf(StringUtils.substringAfterLast(line, "="));- if (key.startsWith("'"))- tokenTypesByLiteral.put(key.substring(1, key.length()-1), value);- else- tokenTypesByRule.put(key, value);- }- } catch (IOException e) {- throw new RuntimeException(e);- }-- for (String grammarFile: grammarFiles) {- try (InputStream is = getClass().getClassLoader().getResourceAsStream(grammarFile)) {- ANTLRv4Lexer lexer = new ANTLRv4Lexer(new ANTLRInputStream(is));- CommonTokenStream tokens = new CommonTokenStream(lexer);- ANTLRv4Parser parser = new ANTLRv4Parser(tokens);- parser.removeErrorListeners();- parser.setErrorHandler(new BailErrorStrategy());- GrammarSpecContext grammarSpecContext = parser.grammarSpec();- for (RuleSpecContext ruleSpecContext: grammarSpecContext.rules().ruleSpec()) {- RuleSpec rule = newRule(ruleSpecContext);- rules.put(rule.getName(), rule);- }- for (ModeSpecContext modeSpecContext: grammarSpecContext.modeSpec()) {- for (LexerRuleSpecContext lexerRuleSpecContext: modeSpecContext.lexerRuleSpec()) {- RuleSpec rule = newRule(lexerRuleSpecContext);- rules.put(rule.getName(), rule);- }- }- } catch (IOException e) {- throw new RuntimeException(e);- }- }- }-- private Constructor<? extends Lexer> getLexerCtor() {- if (lexerCtor == null) {- try {- lexerCtor = lexerClass.getConstructor(CharStream.class);- } catch (NoSuchMethodException | SecurityException e) {- throw new RuntimeException(e);- }- }- return lexerCtor;- }-- private RuleSpec newRule(RuleSpecContext ruleSpecContext) {- ParserRuleSpecContext parserRuleSpecContext = ruleSpecContext.parserRuleSpec();- if (parserRuleSpecContext != null) {- String name = parserRuleSpecContext.RULE_REF().getText();- List<AlternativeSpec> alternatives = new ArrayList<>();- RuleBlockContext ruleBlockContext = parserRuleSpecContext.ruleBlock();- for (LabeledAltContext labeledAltContext: ruleBlockContext.ruleAltList().labeledAlt())- alternatives.add(newAltenative(labeledAltContext));- return new RuleSpec(name, alternatives);- } else {- return newRule(ruleSpecContext.lexerRuleSpec());- }- }-- private RuleSpec newRule(LexerRuleSpecContext lexerRuleSpecContext) {- String name;- List<AlternativeSpec> alternatives = new ArrayList<>();- name = lexerRuleSpecContext.TOKEN_REF().getText();- LexerRuleBlockContext lexerRuleBlockContext = lexerRuleSpecContext.lexerRuleBlock();- for (LexerAltContext lexerAltContext: lexerRuleBlockContext.lexerAltList().lexerAlt())- alternatives.add(newAltenative(lexerAltContext));- return new RuleSpec(name, alternatives);- }-- private AlternativeSpec newAltenative(LexerAltContext lexerAltContext) {- List<ElementSpec> elements = new ArrayList<>();- if (lexerAltContext.lexerElements() != null) {- for (LexerElementContext lexerElementContext: lexerAltContext.lexerElements().lexerElement()) {- ElementSpec element = newElement(lexerElementContext);- if (element != null)- elements.add(element);- }- }-- return new AlternativeSpec(null, elements);- }-- private AlternativeSpec newAltenative(LabeledAltContext labeledAltContext) {- String label;- if (labeledAltContext.id() != null)- label = labeledAltContext.id().getText();- else- label = null;-- return newAltenative(label, labeledAltContext.alternative());- }-- @Nullable- private ElementSpec newElement(LexerElementContext lexerElementContext) {- LabeledLexerElementContext labeledLexerElementContext = lexerElementContext.labeledLexerElement();- if (labeledLexerElementContext != null) {- String label = labeledLexerElementContext.id().getText();- LexerAtomContext lexerAtomContext = labeledLexerElementContext.lexerAtom();- if (lexerAtomContext != null)- return newElement(label, lexerAtomContext, lexerElementContext.ebnfSuffix());- else- return newElement(label, labeledLexerElementContext.block(), lexerElementContext.ebnfSuffix());- } else if (lexerElementContext.lexerAtom() != null) {- return newElement(null, lexerElementContext.lexerAtom(), lexerElementContext.ebnfSuffix());- } else if (lexerElementContext.lexerBlock() != null) {- return newElement(null, lexerElementContext.lexerBlock(), lexerElementContext.ebnfSuffix());- } else {- return null;- }- }-- private AlternativeSpec newAltenative(@Nullable String label, AlternativeContext alternativeContext) {- List<ElementSpec> elements = new ArrayList<>();- for (ElementContext elementContext: alternativeContext.element()) {- ElementSpec element = newElement(elementContext);- if (element != null)- elements.add(element);- }-- return new AlternativeSpec(label, elements);- }-- @Nullable- private ElementSpec newElement(ElementContext elementContext) {- LabeledElementContext labeledElementContext = elementContext.labeledElement();- if (labeledElementContext != null) {- String label = labeledElementContext.id().getText();- AtomContext atomContext = labeledElementContext.atom();- if (atomContext != null)- return newElement(label, atomContext, elementContext.ebnfSuffix());- else- return newElement(label, labeledElementContext.block(), elementContext.ebnfSuffix());- } else if (elementContext.atom() != null) {- return newElement(null, elementContext.atom(), elementContext.ebnfSuffix());- } else if (elementContext.ebnf() != null) {- return newElement(elementContext.ebnf());- } else {- return null;- }- }-- @Nullable- private ElementSpec newElement(String label, AtomContext atomContext, EbnfSuffixContext ebnfSuffixContext) {- Multiplicity multiplicity = newMultiplicity(ebnfSuffixContext);- if (atomContext.terminal() != null) {- if (atomContext.terminal().TOKEN_REF() != null) {- String ruleName = atomContext.terminal().TOKEN_REF().getText();- int tokenType = tokenTypesByRule.get(ruleName);- if (tokenType != Token.EOF)- return new LexerRuleRefElementSpec(this ,label, multiplicity, tokenType, ruleName);- else- return null;- } else {- String literal = getLiteral(atomContext.terminal().STRING_LITERAL());- int tokenType = tokenTypesByLiteral.get(literal);- return new LiteralElementSpec(label, multiplicity, tokenType, literal);- }- } else if (atomContext.ruleref() != null) {- return new RuleRefElementSpec(this, label, multiplicity, atomContext.ruleref().RULE_REF().getText());- } else if (atomContext.notSet() != null) {- return new NotTokenElementSpec(this, label, multiplicity, getNegativeTokenTypes(atomContext.notSet()));- } else if (atomContext.DOT() != null) {- return new AnyTokenElementSpec(label, multiplicity);- } else {- throw new IllegalStateException();- }- }-- private String getLiteral(TerminalNode terminal) {- String literal = terminal.getText();- return literal.substring(1, literal.length()-1);- }-- @Nullable- private ElementSpec newElement(String label, LexerAtomContext lexerAtomContext, EbnfSuffixContext ebnfSuffixContext) {- Multiplicity multiplicity = newMultiplicity(ebnfSuffixContext);- if (lexerAtomContext.terminal() != null) {- if (lexerAtomContext.terminal().TOKEN_REF() != null) {- String ruleName = lexerAtomContext.terminal().TOKEN_REF().getText();- Integer tokenType = tokenTypesByRule.get(ruleName);- if (tokenType == null) // fragment rule- tokenType = 0;- if (tokenType != Token.EOF)- return new LexerRuleRefElementSpec(this, label, multiplicity, tokenType, ruleName);- else- return null;- } else {- String literal = getLiteral(lexerAtomContext.terminal().STRING_LITERAL());- Integer tokenType = tokenTypesByLiteral.get(literal);- if (tokenType == null)- tokenType = 0;- return new LiteralElementSpec(label, multiplicity, tokenType, literal);- }- } else if (lexerAtomContext.RULE_REF() != null) {- return new RuleRefElementSpec(this, label, multiplicity, lexerAtomContext.RULE_REF().getText());- } else if (lexerAtomContext.notSet() != null- || lexerAtomContext.DOT() != null- || lexerAtomContext.LEXER_CHAR_SET()!=null- || lexerAtomContext.range() != null) {- // Use AnyTokenElementSpec here to as it does not affect our code assist analysis- return new AnyTokenElementSpec(label, multiplicity);- } else {- throw new IllegalStateException();- }- }-- private Set<Integer> getNegativeTokenTypes(NotSetContext notSetContext) {- Set<Integer> negativeTokenTypes = new HashSet<>();- if (notSetContext.setElement() != null) {- negativeTokenTypes.add(getTokenType(notSetContext.setElement()));- } else {- for (SetElementContext setElementContext: notSetContext.blockSet().setElement())- negativeTokenTypes.add(getTokenType(setElementContext));- }- return negativeTokenTypes;- }-- private int getTokenType(SetElementContext setElementContext) {- Integer tokenType;- if (setElementContext.STRING_LITERAL() != null)- tokenType = tokenTypesByLiteral.get(getLiteral(setElementContext.STRING_LITERAL()));- else if (setElementContext.TOKEN_REF() != null)- tokenType = tokenTypesByRule.get(setElementContext.TOKEN_REF().getText());- else- tokenType = null;- if (tokenType != null)- return tokenType;- else- throw new IllegalStateException();- }-- private Multiplicity newMultiplicity(@Nullable EbnfSuffixContext ebnfSuffixContext) {- if (ebnfSuffixContext != null) {- if (ebnfSuffixContext.STAR() != null)- return Multiplicity.ZERO_OR_MORE;- else if (ebnfSuffixContext.PLUS() != null)- return Multiplicity.ONE_OR_MORE;- else- return Multiplicity.ZERO_OR_ONE;- } else {- return Multiplicity.ONE;- }- }-- private ElementSpec newElement(@Nullable String label, BlockContext blockContext, @Nullable EbnfSuffixContext ebnfSuffixContext) {- List<AlternativeSpec> alternatives = new ArrayList<>();- for (AlternativeContext alternativeContext: blockContext.altList().alternative())- alternatives.add(newAltenative(null, alternativeContext));- String ruleName = UUID.randomUUID().toString();- blockRuleNames.add(ruleName);- RuleSpec rule = new RuleSpec(ruleName, alternatives);- rules.put(ruleName, rule);- return new RuleRefElementSpec(this, label, newMultiplicity(ebnfSuffixContext), ruleName);- }-- private ElementSpec newElement(@Nullable String label, LexerBlockContext lexerBlockContext, @Nullable EbnfSuffixContext ebnfSuffixContext) {- List<AlternativeSpec> alternatives = new ArrayList<>();- for (LexerAltContext lexerAltContext: lexerBlockContext.lexerAltList().lexerAlt())- alternatives.add(newAltenative(lexerAltContext));- String ruleName = UUID.randomUUID().toString();- blockRuleNames.add(ruleName);- RuleSpec rule = new RuleSpec(ruleName, alternatives);- rules.put(ruleName, rule);- return new RuleRefElementSpec(this, label, newMultiplicity(ebnfSuffixContext), ruleName);- }-- private ElementSpec newElement(EbnfContext ebnfContext) {- if (ebnfContext.blockSuffix() != null)- return newElement(null, ebnfContext.block(), ebnfContext.blockSuffix().ebnfSuffix());- else- return newElement(null, ebnfContext.block(), null);- }-- public boolean isBlockRule(String ruleName) {- return blockRuleNames.contains(ruleName);- }-- @Nullable- public String getTokenNameByType(int tokenType) {- for (Map.Entry<String, Integer> entry: tokenTypesByRule.entrySet()) {- if (entry.getValue() == tokenType)- return entry.getKey();- }- return null;- }-- @Nullable- public RuleSpec getRule(String ruleName) {- return rules.get(ruleName);- }-- public final List<Token> lex(String content) {- try {- List<Token> tokens = new ArrayList<>();- Lexer lexer = getLexerCtor().newInstance(new ANTLRInputStream(content));- lexer.removeErrorListeners();- Token token = lexer.nextToken();- while (token.getType() != Token.EOF) {- if (token.getChannel() == Token.DEFAULT_CHANNEL)- tokens.add(token);- token = lexer.nextToken();- }-- return tokens;- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException- | InvocationTargetException e) {- throw new RuntimeException(e);- }+ this(new Grammar(lexerClass, grammarFiles, tokenFile));}public List<InputCompletion> suggest(InputStatus inputStatus, String ruleName) {- RuleSpec rule = Preconditions.checkNotNull(getRule(ruleName));+ RuleSpec rule = Preconditions.checkNotNull(grammar.getRule(ruleName));String inputContent = inputStatus.getContent();List<InputCompletion> inputSuggestions = new ArrayList<>();@@ -466,17 +106,17 @@ public abstract class CodeAssist implements Serializable {for (ElementCompletion each: value) {content = inputContent.substring(0, each.getReplaceBegin()) + each.getReplaceContent();ParentedElement parentElement = each.getExpectingElement().getParent();- ElementSpec elementSpec = each.getExpectingElement().getElement().getSpec();+ ElementSpec elementSpec = each.getExpectingElement().getSpec();for (String mandatory: getMandatoriesAfter(parentElement, elementSpec)) {String prevContent = content;content += mandatory;- if (tokenTypesByLiteral.containsKey(mandatory)) {+ if (grammar.getTokenTypeByLiteral(mandatory) != null) {/** if mandatory can be appended without space, the last token* position should remain unchanged in concatenated content*/- List<Token> tokens = lex(content);+ List<Token> tokens = grammar.lex(content);if (!tokens.isEmpty()) {Token lastToken = tokens.get(tokens.size()-1);if (lastToken.getStartIndex() != content.length() - mandatory.length()@@ -515,7 +155,7 @@ public abstract class CodeAssist implements Serializable {// we skip existing mandatory tokens in current inputString contentAfterCaret = content.substring(caret);ParentedElement parentElement = completion.getExpectingElement().getParent();- ElementSpec elementSpec = completion.getExpectingElement().getElement().getSpec();+ ElementSpec elementSpec = completion.getExpectingElement().getSpec();caret += skipMandatories(contentAfterCaret, getMandatoriesAfter(parentElement, elementSpec));}} else {@@ -542,36 +182,64 @@ public abstract class CodeAssist implements Serializable {return inputSuggestions;}- private ParentedElement getElementExpectingTerminal(ParentedElement parent, ParsedElement element) {+ private ParentedElement getElementExpectingTerminal(ParentedElement parent, Element element) {parent = new ParentedElement(parent, element);- ParseNode node = element.getNode();+ Node node = element.getNode();if (node != null) {- element = node.getParsedElements().get(node.getParsedElements().size()-1);+ element = node.getElements().get(node.getElements().size()-1);return getElementExpectingTerminal(parent, element);} else {return parent;}}+ private List<Element> assumeCompleted(EarleyParser parser, Node node, int endTokenIndex) {+ List<Element> rootElements = new ArrayList<>();+ if (node.getBeginTokenIndex() == 0 && node.getRuleSpec().getName().equals(parser.getRule().getName())) {+ rootElements.add(new Element(parser, null, endTokenIndex, node));+ } else {+ State startState = parser.getStates().get(node.getBeginTokenIndex());+ for (Node startNode: startState.getNodes()) {+ if (!startNode.isCompleted()) {+ ElementSpec nextElement = startNode.getExpectedElementSpec();+ if (nextElement instanceof RuleRefElementSpec) {+ RuleRefElementSpec ruleRefElement = (RuleRefElementSpec) nextElement;+ if (ruleRefElement.getRuleName().equals(node.getRuleSpec().getName())) {+ List<Element> elements = new ArrayList<>(startNode.getElements());+ elements.add(new Element(parser, ruleRefElement, endTokenIndex, node));+ Node parentNode = new Node(startNode.getBeginTokenIndex(),+ startNode.getRuleSpec(), startNode.getAlternativeSpecIndex(),+ startNode.getExpectedElementSpecIndex(),+ startNode.isExpectedElementSpecMatchedOnce(),+ elements);+ rootElements.addAll(assumeCompleted(parser, parentNode, endTokenIndex));+ }+ }+ }+ }+ }+ return rootElements;+ }+private void fillSuggestions(List<ElementSuggestion> suggestions, EarleyParser parser,- ParseState state, InputStatus inputStatus) {- for (ParseNode node: state.getNodesExpectingTerminal()) {- List<ParsedElement> rootElements = parser.assumeCompleted(node, state.getNextTokenIndex());+ State state, InputStatus inputStatus) {+ for (Node node: state.getNodesExpectingTerminal()) {+ List<Element> rootElements = assumeCompleted(parser, node, state.getEndTokenIndex());String matchWith;- if (state.getNextTokenIndex() != 0) {- int stopIndex = parser.getTokens().get(state.getNextTokenIndex()-1).getStopIndex()+1;+ if (state.getEndTokenIndex() != 0) {+ int stopIndex = parser.getTokens().get(state.getEndTokenIndex()-1).getStopIndex()+1;matchWith = inputStatus.getContent().substring(stopIndex, inputStatus.getCaret());} else {matchWith = inputStatus.getContentBeforeCaret();}matchWith = StringUtils.trimStart(matchWith);- for (ParsedElement rootElement: rootElements) {+ for (Element rootElement: rootElements) {List<ParentedElement> expectingElements = new ArrayList<>();ParentedElement expectingElement = getElementExpectingTerminal(null, rootElement);expectingElements.add(expectingElement);expectingElement = expectingElement.getParent();while (expectingElement != null) {- if (expectingElement.getElement().getNode().getParsedElements().size() == 1) {+ if (expectingElement.getNode().getElements().size() == 1) {expectingElements.add(expectingElement);expectingElement = expectingElement.getParent();} else {@@ -597,11 +265,11 @@ public abstract class CodeAssist implements Serializable {List<ElementSuggestion> suggestions = new ArrayList<>();- List<Token> tokens = lex(inputStatus.getContentBeforeCaret());+ List<Token> tokens = grammar.lex(inputStatus.getContentBeforeCaret());EarleyParser parser = new EarleyParser(spec, tokens);if (parser.getStates().size() >= 1) {- ParseState lastState = parser.getStates().get(parser.getStates().size()-1);+ State lastState = parser.getStates().get(parser.getStates().size()-1);fillSuggestions(suggestions, parser, lastState, inputStatus);}@@ -618,7 +286,7 @@ public abstract class CodeAssist implements Serializable {* suggest the user to quote the value.*/if (parser.getStates().size() >= 2) {- ParseState stateBeforeLast = parser.getStates().get(parser.getStates().size()-2);+ State stateBeforeLast = parser.getStates().get(parser.getStates().size()-2);fillSuggestions(suggestions, parser, stateBeforeLast, inputStatus);}@@ -627,7 +295,7 @@ public abstract class CodeAssist implements Serializable {int replaceStart = inputStatus.getCaret() - suggestion.getMatchWith().length();int replaceEnd = inputStatus.getCaret();String contentAfterReplaceStart = inputContent.substring(replaceStart);- tokens = lex(contentAfterReplaceStart);+ tokens = grammar.lex(contentAfterReplaceStart);/** if input around the caret matches spec of the suggestion, we then replace@@ -635,7 +303,7 @@ public abstract class CodeAssist implements Serializable {* suggested content*/if (!tokens.isEmpty() && tokens.get(0).getStartIndex() == 0) {- ElementSpec elementSpec = (ElementSpec) suggestion.getExpectingElement().getElement().getSpec();+ ElementSpec elementSpec = (ElementSpec) suggestion.getExpectingElement().getSpec();int matchDistance = elementSpec.getMatchDistance(tokens);if (matchDistance > 0) {int charIndex = tokens.get(matchDistance-1).getStopIndex()+1;@@ -647,10 +315,10 @@ public abstract class CodeAssist implements Serializable {String before = inputContent.substring(0, replaceStart);for (InputSuggestion inputSuggestion: suggestion.getInputSuggestions()) {- int nextTokenIndex = suggestion.getExpectingElement().getElement().getNextTokenIndex();+ int nextTokenIndex = suggestion.getExpectingElement().getEndTokenIndex();if (nextTokenIndex != 0) {Token lastToken = parser.getTokens().get(nextTokenIndex-1);- tokens = lex(before + inputSuggestion.getContent());+ tokens = grammar.lex(before + inputSuggestion.getContent());/** ignore the suggestion if we can not append the suggested content directly.* This normally indicates that a space is required before the suggestion,@@ -718,10 +386,10 @@ public abstract class CodeAssist implements Serializable {List<String> literals = new ArrayList<>();if (parentElement != null && elementSpec != null&& (elementSpec.getMultiplicity() == Multiplicity.ONE || elementSpec.getMultiplicity() == Multiplicity.ZERO_OR_ONE)) {- AlternativeSpec alternativeSpec = parentElement.getElement().getNode().getAlternativeSpec();+ AlternativeSpec alternativeSpec = parentElement.getNode().getAlternativeSpec();int specIndex = alternativeSpec.getElements().indexOf(elementSpec);if (specIndex == alternativeSpec.getElements().size()-1) {- elementSpec = parentElement.getElement().getSpec();+ elementSpec = parentElement.getSpec();parentElement = parentElement.getParent();return getMandatoriesAfter(parentElement, elementSpec);} else {@@ -738,6 +406,10 @@ public abstract class CodeAssist implements Serializable {return literals;}+ public Grammar getGrammar() {+ return grammar;+ }+protected abstract List<InputSuggestion> suggest(ParentedElement element, String matchWith);}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementCompletion.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementCompletion.javaindex 89df2521b4..6a2342154e 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementCompletion.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementCompletion.java@@ -1,7 +1,5 @@package com.pmease.commons.antlr.codeassist;-import com.pmease.commons.antlr.codeassist.parse.ParentedElement;-public class ElementCompletion extends InputCompletion {private static final long serialVersionUID = 1L;diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementSuggestion.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementSuggestion.javaindex 7c282f0ca6..f30c110d09 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementSuggestion.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ElementSuggestion.java@@ -2,8 +2,6 @@ package com.pmease.commons.antlr.codeassist;import java.util.List;-import com.pmease.commons.antlr.codeassist.parse.ParentedElement;-public class ElementSuggestion {private final ParentedElement expectingElement;diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/Grammar.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/Grammar.javanew file mode 100644index 0000000000..ccf77198d9--- /dev/null+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/Grammar.java@@ -0,0 +1,414 @@+package com.pmease.commons.antlr.codeassist;++import java.io.IOException;+import java.io.InputStream;+import java.io.Serializable;+import java.lang.reflect.Constructor;+import java.lang.reflect.InvocationTargetException;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.UUID;++import javax.annotation.Nullable;++import org.antlr.v4.runtime.ANTLRInputStream;+import org.antlr.v4.runtime.BailErrorStrategy;+import org.antlr.v4.runtime.CharStream;+import org.antlr.v4.runtime.CommonTokenStream;+import org.antlr.v4.runtime.Lexer;+import org.antlr.v4.runtime.Token;+import org.antlr.v4.runtime.tree.TerminalNode;+import org.apache.tika.io.IOUtils;++import com.pmease.commons.antlr.ANTLRv4Lexer;+import com.pmease.commons.antlr.ANTLRv4Parser;+import com.pmease.commons.antlr.ANTLRv4Parser.AlternativeContext;+import com.pmease.commons.antlr.ANTLRv4Parser.AtomContext;+import com.pmease.commons.antlr.ANTLRv4Parser.BlockContext;+import com.pmease.commons.antlr.ANTLRv4Parser.EbnfContext;+import com.pmease.commons.antlr.ANTLRv4Parser.EbnfSuffixContext;+import com.pmease.commons.antlr.ANTLRv4Parser.ElementContext;+import com.pmease.commons.antlr.ANTLRv4Parser.GrammarSpecContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LabeledAltContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LabeledElementContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LabeledLexerElementContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LexerAltContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LexerAtomContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LexerBlockContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LexerElementContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LexerRuleBlockContext;+import com.pmease.commons.antlr.ANTLRv4Parser.LexerRuleSpecContext;+import com.pmease.commons.antlr.ANTLRv4Parser.ModeSpecContext;+import com.pmease.commons.antlr.ANTLRv4Parser.NotSetContext;+import com.pmease.commons.antlr.ANTLRv4Parser.ParserRuleSpecContext;+import com.pmease.commons.antlr.ANTLRv4Parser.RuleBlockContext;+import com.pmease.commons.antlr.ANTLRv4Parser.RuleSpecContext;+import com.pmease.commons.antlr.ANTLRv4Parser.SetElementContext;+import com.pmease.commons.antlr.AntlrUtils;+import com.pmease.commons.antlr.codeassist.ElementSpec.Multiplicity;+import com.pmease.commons.util.StringUtils;++public class Grammar implements Serializable {++ private static final long serialVersionUID = 1L;++ private final Class<? extends Lexer> lexerClass;++ private transient Constructor<? extends Lexer> lexerCtor;++ private final Map<String, RuleSpec> rules = new HashMap<>();++ private final Map<String, Integer> tokenTypesByLiteral = new HashMap<>();++ private final Map<String, Integer> tokenTypesByRule = new HashMap<>();++ private final Set<String> blockRuleNames = new HashSet<>();++ /**+ * Code assist constructor+ * @param lexerClass+ * lexer class to be used to lex code. Other required information such as+ * grammar files and token file will be derived from the lexer class+ */+ public Grammar(Class<? extends Lexer> lexerClass) {+ this(lexerClass, new String[]{AntlrUtils.getDefaultGrammarFile(lexerClass)},+ AntlrUtils.getDefaultTokenFile(lexerClass));+ }++ /**+ * Code assist constructor.+ *+ * @param lexerClass+ * lexer class to be used to lex code+ * @param grammarFiles+ * grammar files in class path, relative to class path root+ * @param tokenFile+ * generated tokens file in class path, relative to class path root+ */+ public Grammar(Class<? extends Lexer> lexerClass, String grammarFiles[], String tokenFile) {+ this.lexerClass = lexerClass;+ tokenTypesByRule.put("EOF", Token.EOF);++ try (InputStream is = getClass().getClassLoader().getResourceAsStream(tokenFile)) {+ for (String line: IOUtils.readLines(is)) {+ String key = StringUtils.substringBeforeLast(line, "=");+ Integer value = Integer.valueOf(StringUtils.substringAfterLast(line, "="));+ if (key.startsWith("'"))+ tokenTypesByLiteral.put(key.substring(1, key.length()-1), value);+ else+ tokenTypesByRule.put(key, value);+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }++ for (String grammarFile: grammarFiles) {+ try (InputStream is = getClass().getClassLoader().getResourceAsStream(grammarFile)) {+ ANTLRv4Lexer lexer = new ANTLRv4Lexer(new ANTLRInputStream(is));+ CommonTokenStream tokens = new CommonTokenStream(lexer);+ ANTLRv4Parser parser = new ANTLRv4Parser(tokens);+ parser.removeErrorListeners();+ parser.setErrorHandler(new BailErrorStrategy());+ GrammarSpecContext grammarSpecContext = parser.grammarSpec();+ for (RuleSpecContext ruleSpecContext: grammarSpecContext.rules().ruleSpec()) {+ RuleSpec rule = newRule(ruleSpecContext);+ rules.put(rule.getName(), rule);+ }+ for (ModeSpecContext modeSpecContext: grammarSpecContext.modeSpec()) {+ for (LexerRuleSpecContext lexerRuleSpecContext: modeSpecContext.lexerRuleSpec()) {+ RuleSpec rule = newRule(lexerRuleSpecContext);+ rules.put(rule.getName(), rule);+ }+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ }++ private Constructor<? extends Lexer> getLexerCtor() {+ if (lexerCtor == null) {+ try {+ lexerCtor = lexerClass.getConstructor(CharStream.class);+ } catch (NoSuchMethodException | SecurityException e) {+ throw new RuntimeException(e);+ }+ }+ return lexerCtor;+ }++ private RuleSpec newRule(RuleSpecContext ruleSpecContext) {+ ParserRuleSpecContext parserRuleSpecContext = ruleSpecContext.parserRuleSpec();+ if (parserRuleSpecContext != null) {+ String name = parserRuleSpecContext.RULE_REF().getText();+ List<AlternativeSpec> alternatives = new ArrayList<>();+ RuleBlockContext ruleBlockContext = parserRuleSpecContext.ruleBlock();+ for (LabeledAltContext labeledAltContext: ruleBlockContext.ruleAltList().labeledAlt())+ alternatives.add(newAltenative(labeledAltContext));+ return new RuleSpec(name, alternatives);+ } else {+ return newRule(ruleSpecContext.lexerRuleSpec());+ }+ }++ private RuleSpec newRule(LexerRuleSpecContext lexerRuleSpecContext) {+ String name;+ List<AlternativeSpec> alternatives = new ArrayList<>();+ name = lexerRuleSpecContext.TOKEN_REF().getText();+ LexerRuleBlockContext lexerRuleBlockContext = lexerRuleSpecContext.lexerRuleBlock();+ for (LexerAltContext lexerAltContext: lexerRuleBlockContext.lexerAltList().lexerAlt())+ alternatives.add(newAltenative(lexerAltContext));+ return new RuleSpec(name, alternatives);+ }++ private AlternativeSpec newAltenative(LexerAltContext lexerAltContext) {+ List<ElementSpec> elements = new ArrayList<>();+ if (lexerAltContext.lexerElements() != null) {+ for (LexerElementContext lexerElementContext: lexerAltContext.lexerElements().lexerElement()) {+ ElementSpec element = newElement(lexerElementContext);+ if (element != null)+ elements.add(element);+ }+ }++ return new AlternativeSpec(null, elements);+ }++ private AlternativeSpec newAltenative(LabeledAltContext labeledAltContext) {+ String label;+ if (labeledAltContext.id() != null)+ label = labeledAltContext.id().getText();+ else+ label = null;++ return newAltenative(label, labeledAltContext.alternative());+ }++ @Nullable+ private ElementSpec newElement(LexerElementContext lexerElementContext) {+ LabeledLexerElementContext labeledLexerElementContext = lexerElementContext.labeledLexerElement();+ if (labeledLexerElementContext != null) {+ String label = labeledLexerElementContext.id().getText();+ LexerAtomContext lexerAtomContext = labeledLexerElementContext.lexerAtom();+ if (lexerAtomContext != null)+ return newElement(label, lexerAtomContext, lexerElementContext.ebnfSuffix());+ else+ return newElement(label, labeledLexerElementContext.block(), lexerElementContext.ebnfSuffix());+ } else if (lexerElementContext.lexerAtom() != null) {+ return newElement(null, lexerElementContext.lexerAtom(), lexerElementContext.ebnfSuffix());+ } else if (lexerElementContext.lexerBlock() != null) {+ return newElement(null, lexerElementContext.lexerBlock(), lexerElementContext.ebnfSuffix());+ } else {+ return null;+ }+ }++ private AlternativeSpec newAltenative(@Nullable String label, AlternativeContext alternativeContext) {+ List<ElementSpec> elements = new ArrayList<>();+ for (ElementContext elementContext: alternativeContext.element()) {+ ElementSpec element = newElement(elementContext);+ if (element != null)+ elements.add(element);+ }++ return new AlternativeSpec(label, elements);+ }++ @Nullable+ private ElementSpec newElement(ElementContext elementContext) {+ LabeledElementContext labeledElementContext = elementContext.labeledElement();+ if (labeledElementContext != null) {+ String label = labeledElementContext.id().getText();+ AtomContext atomContext = labeledElementContext.atom();+ if (atomContext != null)+ return newElement(label, atomContext, elementContext.ebnfSuffix());+ else+ return newElement(label, labeledElementContext.block(), elementContext.ebnfSuffix());+ } else if (elementContext.atom() != null) {+ return newElement(null, elementContext.atom(), elementContext.ebnfSuffix());+ } else if (elementContext.ebnf() != null) {+ return newElement(elementContext.ebnf());+ } else {+ return null;+ }+ }++ @Nullable+ private ElementSpec newElement(String label, AtomContext atomContext, EbnfSuffixContext ebnfSuffixContext) {+ Multiplicity multiplicity = newMultiplicity(ebnfSuffixContext);+ if (atomContext.terminal() != null) {+ if (atomContext.terminal().TOKEN_REF() != null) {+ String ruleName = atomContext.terminal().TOKEN_REF().getText();+ int tokenType = tokenTypesByRule.get(ruleName);+ if (tokenType != Token.EOF)+ return new LexerRuleRefElementSpec(this ,label, multiplicity, tokenType, ruleName);+ else+ return null;+ } else {+ String literal = getLiteral(atomContext.terminal().STRING_LITERAL());+ int tokenType = tokenTypesByLiteral.get(literal);+ return new LiteralElementSpec(label, multiplicity, tokenType, literal);+ }+ } else if (atomContext.ruleref() != null) {+ return new RuleRefElementSpec(this, label, multiplicity, atomContext.ruleref().RULE_REF().getText());+ } else if (atomContext.notSet() != null) {+ return new NotTokenElementSpec(this, label, multiplicity, getNegativeTokenTypes(atomContext.notSet()));+ } else if (atomContext.DOT() != null) {+ return new AnyTokenElementSpec(label, multiplicity);+ } else {+ throw new IllegalStateException();+ }+ }++ private String getLiteral(TerminalNode terminal) {+ String literal = terminal.getText();+ return literal.substring(1, literal.length()-1);+ }++ @Nullable+ private ElementSpec newElement(String label, LexerAtomContext lexerAtomContext, EbnfSuffixContext ebnfSuffixContext) {+ Multiplicity multiplicity = newMultiplicity(ebnfSuffixContext);+ if (lexerAtomContext.terminal() != null) {+ if (lexerAtomContext.terminal().TOKEN_REF() != null) {+ String ruleName = lexerAtomContext.terminal().TOKEN_REF().getText();+ Integer tokenType = tokenTypesByRule.get(ruleName);+ if (tokenType == null) // fragment rule+ tokenType = 0;+ if (tokenType != Token.EOF)+ return new LexerRuleRefElementSpec(this, label, multiplicity, tokenType, ruleName);+ else+ return null;+ } else {+ String literal = getLiteral(lexerAtomContext.terminal().STRING_LITERAL());+ Integer tokenType = tokenTypesByLiteral.get(literal);+ if (tokenType == null)+ tokenType = 0;+ return new LiteralElementSpec(label, multiplicity, tokenType, literal);+ }+ } else if (lexerAtomContext.RULE_REF() != null) {+ return new RuleRefElementSpec(this, label, multiplicity, lexerAtomContext.RULE_REF().getText());+ } else if (lexerAtomContext.notSet() != null+ || lexerAtomContext.DOT() != null+ || lexerAtomContext.LEXER_CHAR_SET()!=null+ || lexerAtomContext.range() != null) {+ // Use AnyTokenElementSpec here to as it does not affect our code assist analysis+ return new AnyTokenElementSpec(label, multiplicity);+ } else {+ throw new IllegalStateException();+ }+ }++ private Set<Integer> getNegativeTokenTypes(NotSetContext notSetContext) {+ Set<Integer> negativeTokenTypes = new HashSet<>();+ if (notSetContext.setElement() != null) {+ negativeTokenTypes.add(getTokenType(notSetContext.setElement()));+ } else {+ for (SetElementContext setElementContext: notSetContext.blockSet().setElement())+ negativeTokenTypes.add(getTokenType(setElementContext));+ }+ return negativeTokenTypes;+ }++ private int getTokenType(SetElementContext setElementContext) {+ Integer tokenType;+ if (setElementContext.STRING_LITERAL() != null)+ tokenType = tokenTypesByLiteral.get(getLiteral(setElementContext.STRING_LITERAL()));+ else if (setElementContext.TOKEN_REF() != null)+ tokenType = tokenTypesByRule.get(setElementContext.TOKEN_REF().getText());+ else+ tokenType = null;+ if (tokenType != null)+ return tokenType;+ else+ throw new IllegalStateException();+ }++ private Multiplicity newMultiplicity(@Nullable EbnfSuffixContext ebnfSuffixContext) {+ if (ebnfSuffixContext != null) {+ if (ebnfSuffixContext.STAR() != null)+ return Multiplicity.ZERO_OR_MORE;+ else if (ebnfSuffixContext.PLUS() != null)+ return Multiplicity.ONE_OR_MORE;+ else+ return Multiplicity.ZERO_OR_ONE;+ } else {+ return Multiplicity.ONE;+ }+ }++ private ElementSpec newElement(@Nullable String label, BlockContext blockContext, @Nullable EbnfSuffixContext ebnfSuffixContext) {+ List<AlternativeSpec> alternatives = new ArrayList<>();+ for (AlternativeContext alternativeContext: blockContext.altList().alternative())+ alternatives.add(newAltenative(null, alternativeContext));+ String ruleName = UUID.randomUUID().toString();+ blockRuleNames.add(ruleName);+ RuleSpec rule = new RuleSpec(ruleName, alternatives);+ rules.put(ruleName, rule);+ return new RuleRefElementSpec(this, label, newMultiplicity(ebnfSuffixContext), ruleName);+ }++ private ElementSpec newElement(@Nullable String label, LexerBlockContext lexerBlockContext, @Nullable EbnfSuffixContext ebnfSuffixContext) {+ List<AlternativeSpec> alternatives = new ArrayList<>();+ for (LexerAltContext lexerAltContext: lexerBlockContext.lexerAltList().lexerAlt())+ alternatives.add(newAltenative(lexerAltContext));+ String ruleName = UUID.randomUUID().toString();+ blockRuleNames.add(ruleName);+ RuleSpec rule = new RuleSpec(ruleName, alternatives);+ rules.put(ruleName, rule);+ return new RuleRefElementSpec(this, label, newMultiplicity(ebnfSuffixContext), ruleName);+ }++ private ElementSpec newElement(EbnfContext ebnfContext) {+ if (ebnfContext.blockSuffix() != null)+ return newElement(null, ebnfContext.block(), ebnfContext.blockSuffix().ebnfSuffix());+ else+ return newElement(null, ebnfContext.block(), null);+ }++ public boolean isBlockRule(String ruleName) {+ return blockRuleNames.contains(ruleName);+ }++ @Nullable+ public String getTokenNameByType(int tokenType) {+ for (Map.Entry<String, Integer> entry: tokenTypesByRule.entrySet()) {+ if (entry.getValue() == tokenType)+ return entry.getKey();+ }+ return null;+ }++ @Nullable+ public Integer getTokenTypeByLiteral(String literal) {+ return tokenTypesByLiteral.get(literal);+ }++ @Nullable+ public RuleSpec getRule(String ruleName) {+ return rules.get(ruleName);+ }++ public final List<Token> lex(String content) {+ try {+ List<Token> tokens = new ArrayList<>();+ Lexer lexer = getLexerCtor().newInstance(new ANTLRInputStream(content));+ lexer.removeErrorListeners();+ Token token = lexer.nextToken();+ while (token.getType() != Token.EOF) {+ if (token.getChannel() == Token.DEFAULT_CHANNEL)+ tokens.add(token);+ token = lexer.nextToken();+ }++ return tokens;+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException+ | InvocationTargetException e) {+ throw new RuntimeException(e);+ }+ }++}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/LexerRuleRefElementSpec.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/LexerRuleRefElementSpec.javaindex 251879d0d1..2cc3cd4278 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/LexerRuleRefElementSpec.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/LexerRuleRefElementSpec.java@@ -12,7 +12,7 @@ public class LexerRuleRefElementSpec extends TerminalElementSpec {private static final long serialVersionUID = 1L;- private final CodeAssist codeAssist;+ private final Grammar grammar;private final int tokenType;@@ -20,11 +20,11 @@ public class LexerRuleRefElementSpec extends TerminalElementSpec {private transient Optional<RuleSpec> rule;- public LexerRuleRefElementSpec(CodeAssist codeAssist, String label, Multiplicity multiplicity,+ public LexerRuleRefElementSpec(Grammar grammar, String label, Multiplicity multiplicity,int tokenType, String ruleName) {super(label, multiplicity);- this.codeAssist = codeAssist;+ this.grammar = grammar;this.tokenType = tokenType;this.ruleName = ruleName;}@@ -35,7 +35,7 @@ public class LexerRuleRefElementSpec extends TerminalElementSpec {public RuleSpec getRule() {if (rule == null)- rule = Optional.fromNullable(codeAssist.getRule(ruleName));+ rule = Optional.fromNullable(grammar.getRule(ruleName));return rule.orNull();}@@ -79,7 +79,7 @@ public class LexerRuleRefElementSpec extends TerminalElementSpec {@Overrideprotected String toStringOnce() {- if (codeAssist.isBlockRule(ruleName))+ if (grammar.isBlockRule(ruleName))return "(" + Preconditions.checkNotNull(getRule()) + ")";elsereturn ruleName;diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/NotTokenElementSpec.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/NotTokenElementSpec.javaindex 5a3bc075ba..f60312dc33 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/NotTokenElementSpec.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/NotTokenElementSpec.java@@ -12,15 +12,15 @@ public class NotTokenElementSpec extends TerminalElementSpec {private static final long serialVersionUID = 1L;- private final CodeAssist codeAssist;+ private final Grammar grammar;private final Set<Integer> notTokenTypes;- public NotTokenElementSpec(CodeAssist codeAssist, String label,+ public NotTokenElementSpec(Grammar grammar, String label,Multiplicity multiplicity, Set<Integer> notTokenTypes) {super(label, multiplicity);- this.codeAssist = codeAssist;+ this.grammar = grammar;this.notTokenTypes = notTokenTypes;}@@ -37,7 +37,7 @@ public class NotTokenElementSpec extends TerminalElementSpec {protected String toStringOnce() {List<String> notTokenNames = new ArrayList<>();for (int notTokenType: notTokenTypes)- notTokenNames.add(Preconditions.checkNotNull(codeAssist.getTokenNameByType(notTokenType)));+ notTokenNames.add(Preconditions.checkNotNull(grammar.getTokenNameByType(notTokenType)));return StringUtils.join(notTokenNames, " ");}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParentedElement.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ParentedElement.javasimilarity index 61%rename from commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParentedElement.javarename to commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ParentedElement.javaindex cc45508f5a..5c54c61be3 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParentedElement.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/ParentedElement.java@@ -1,31 +1,28 @@-package com.pmease.commons.antlr.codeassist.parse;+package com.pmease.commons.antlr.codeassist;import javax.annotation.Nullable;-public class ParentedElement {+import com.pmease.commons.antlr.codeassist.parse.Element;++public class ParentedElement extends Element {private final ParentedElement parent;- private final ParsedElement element;-- public ParentedElement(@Nullable ParentedElement parent, ParsedElement element) {+ public ParentedElement(@Nullable ParentedElement parent, Element element) {+ super(element.getParser(), element.getSpec(), element.getEndTokenIndex(), element.getNode());+this.parent = parent;- this.element = element;}public ParentedElement getParent() {return parent;}- public ParsedElement getElement() {- return element;- }-@Nullablepublic ParentedElement findParentByLabel(String label) {ParentedElement current = parent;while (current != null) {- if (label.equals(current.element.getLabel()))+ if (label.equals(current.getLabel()))return current;current = current.parent;}@@ -36,7 +33,7 @@ public class ParentedElement {public ParentedElement findParentByRule(String ruleName) {ParentedElement current = parent;while (current != null) {- if (ruleName.equals(current.element.getNode().getRuleSpec().getName()))+ if (ruleName.equals(current.getNode().getRuleSpec().getName()))return current;current = current.parent;}@@ -49,5 +46,5 @@ public class ParentedElement {elsereturn parent.getRoot();}-+}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/RuleRefElementSpec.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/RuleRefElementSpec.javaindex 450e97a2d7..6b032428cd 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/RuleRefElementSpec.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/RuleRefElementSpec.java@@ -14,22 +14,22 @@ public class RuleRefElementSpec extends ElementSpec {private static final long serialVersionUID = 1L;- private final CodeAssist codeAssist;+ private final Grammar grammar;private final String ruleName;private transient RuleSpec rule;- public RuleRefElementSpec(CodeAssist codeAssist, String label, Multiplicity multiplicity, String ruleName) {+ public RuleRefElementSpec(Grammar grammar, String label, Multiplicity multiplicity, String ruleName) {super(label, multiplicity);- this.codeAssist = codeAssist;+ this.grammar = grammar;this.ruleName = ruleName;}public RuleSpec getRule() {if (rule == null)- rule = Preconditions.checkNotNull(codeAssist.getRule(ruleName));+ rule = Preconditions.checkNotNull(grammar.getRule(ruleName));return rule;}@@ -74,7 +74,7 @@ public class RuleRefElementSpec extends ElementSpec {@Overrideprotected String toStringOnce() {- if (codeAssist.isBlockRule(ruleName))+ if (grammar.isBlockRule(ruleName))return "(" + Preconditions.checkNotNull(getRule()) + ")";elsereturn ruleName;@@ -82,7 +82,7 @@ public class RuleRefElementSpec extends ElementSpec {@Overridepublic int getMatchDistance(List<Token> tokens) {- return new EarleyParser(getRule(), tokens).getMatchDistance();+ return new EarleyParser(getRule(), tokens).getEndOfMatch();}}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/SurroundingAware.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/SurroundingAware.javaindex 0bba1560bf..988692477f 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/SurroundingAware.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/SurroundingAware.java@@ -7,20 +7,20 @@ import org.antlr.v4.runtime.Token;public abstract class SurroundingAware {- private final CodeAssist codeAssist;+ private final Grammar grammar;private final String prefix;private final String suffix;- public SurroundingAware(CodeAssist codeAssist, String prefix, String suffix) {- this.codeAssist = codeAssist;+ public SurroundingAware(Grammar grammar, String prefix, String suffix) {+ this.grammar = grammar;this.prefix = prefix;this.suffix = suffix;}private boolean matches(ElementSpec spec, String content) {- List<Token> tokens = codeAssist.lex(content);+ List<Token> tokens = grammar.lex(content);int start;int stop;if (tokens.isEmpty()) {diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/EarleyParser.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/EarleyParser.javaindex bd5031dac4..64984d2cd5 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/EarleyParser.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/EarleyParser.java@@ -5,6 +5,8 @@ import java.util.HashSet;import java.util.List;import java.util.Set;+import javax.annotation.Nullable;+import org.antlr.v4.runtime.Token;import com.google.common.collect.Lists;@@ -22,41 +24,41 @@ public class EarleyParser {private int tokenIndex = 0;- private final List<ParseState> states = new ArrayList<>();+ private final List<State> states = new ArrayList<>();public EarleyParser(RuleSpec rule, List<Token> tokens) {this.rule = rule;this.tokens = tokens;- Set<ParseNode> nodes = new HashSet<>();+ Set<Node> nodes = new HashSet<>();for (int i=0; i<rule.getAlternatives().size(); i++)- nodes.add(new ParseNode(tokenIndex, rule, i, 0, false, new ArrayList<ParsedElement>()));+ nodes.add(new Node(tokenIndex, rule, i, 0, false, new ArrayList<Element>()));while (!nodes.isEmpty()) {- ParseState state = new ParseState(tokenIndex, nodes);+ State state = new State(tokenIndex, nodes);states.add(state);- for (ParseNode node: Lists.newArrayList(state.getNodes()))+ for (Node node: Lists.newArrayList(state.getNodes()))process(node, state);if (tokenIndex == tokens.size())break;nodes = new HashSet<>();- for (ParseNode node: state.getNodes())+ for (Node node: state.getNodes())scan(node, nodes);tokenIndex++;}}- private void process(ParseNode node, ParseState state) {+ private void process(Node node, State state) {if (!node.isCompleted()) { // predictElementSpec nextElement = node.getElementSpecs().get(node.getExpectedElementSpecIndex());if (nextElement instanceof RuleRefElementSpec) {RuleRefElementSpec ruleRefElement = (RuleRefElementSpec) nextElement;RuleSpec elementRule = ruleRefElement.getRule();for (int i=0; i<elementRule.getAlternatives().size(); i++) {- ParseNode predictedNode = new ParseNode(tokenIndex,- elementRule, i, 0, false, new ArrayList<ParsedElement>());+ Node predictedNode = new Node(tokenIndex,+ elementRule, i, 0, false, new ArrayList<Element>());if (state.addNode(predictedNode))process(predictedNode, state);}@@ -64,33 +66,33 @@ public class EarleyParser {if (nextElement.getMultiplicity() == Multiplicity.ZERO_OR_MORE|| nextElement.getMultiplicity() == Multiplicity.ZERO_OR_ONE|| node.isExpectedElementSpecMatchedOnce()) {- ParseNode advancedNode = new ParseNode(node.getStartTokenIndex(), node.getRuleSpec(),+ Node advancedNode = new Node(node.getBeginTokenIndex(), node.getRuleSpec(),node.getAlternativeSpecIndex(), node.getExpectedElementSpecIndex()+1, false,- new ArrayList<>(node.getParsedElements()));+ new ArrayList<>(node.getElements()));if (state.addNode(advancedNode))process(advancedNode, state);}} else { // complete- ParseState startState = states.get(node.getStartTokenIndex());- for (ParseNode startNode: startState.getNodes()) {+ State startState = states.get(node.getBeginTokenIndex());+ for (Node startNode: startState.getNodes()) {if (!startNode.isCompleted()) {ElementSpec nextElement = startNode.getExpectedElementSpec();if (nextElement instanceof RuleRefElementSpec) {RuleRefElementSpec ruleRefElement = (RuleRefElementSpec) nextElement;if (ruleRefElement.getRuleName().equals(node.getRuleSpec().getName())) {- ParseNode advancedNode;- List<ParsedElement> parsedElements = new ArrayList<>(startNode.getParsedElements());- if (!node.getParsedElements().isEmpty())- parsedElements.add(new ParsedElement(ruleRefElement, state.getNextTokenIndex(), node));+ Node advancedNode;+ List<Element> elements = new ArrayList<>(startNode.getElements());+ if (!node.getElements().isEmpty())+ elements.add(new Element(this, ruleRefElement, state.getEndTokenIndex(), node));if (nextElement.getMultiplicity() == Multiplicity.ONE|| nextElement.getMultiplicity() == Multiplicity.ZERO_OR_ONE) {- advancedNode = new ParseNode(startNode.getStartTokenIndex(),+ advancedNode = new Node(startNode.getBeginTokenIndex(),startNode.getRuleSpec(), startNode.getAlternativeSpecIndex(),- startNode.getExpectedElementSpecIndex()+1, false, parsedElements);+ startNode.getExpectedElementSpecIndex()+1, false, elements);} else {- advancedNode = new ParseNode(startNode.getStartTokenIndex(),+ advancedNode = new Node(startNode.getBeginTokenIndex(),startNode.getRuleSpec(), startNode.getAlternativeSpecIndex(),- startNode.getExpectedElementSpecIndex(), true, parsedElements);+ startNode.getExpectedElementSpecIndex(), true, elements);}if (state.addNode(advancedNode))process(advancedNode, state);@@ -101,31 +103,31 @@ public class EarleyParser {}}- private void scan(ParseNode node, Set<ParseNode> nextNodes) {+ private void scan(Node node, Set<Node> nextNodes) {if (!node.isCompleted()) {ElementSpec nextElement = node.getElementSpecs().get(node.getExpectedElementSpecIndex());int tokenType = tokens.get(tokenIndex).getType();if ((nextElement instanceof TerminalElementSpec)&& ((TerminalElementSpec)nextElement).isToken(tokenType)) {- ParseNode scanNode;- List<ParsedElement> parsedElements = new ArrayList<>(node.getParsedElements());- parsedElements.add(new ParsedElement(nextElement, tokenIndex+1, null));+ Node scanNode;+ List<Element> elements = new ArrayList<>(node.getElements());+ elements.add(new Element(this, nextElement, tokenIndex+1, null));if (nextElement.getMultiplicity() == Multiplicity.ONE|| nextElement.getMultiplicity() == Multiplicity.ZERO_OR_ONE) {- scanNode = new ParseNode(node.getStartTokenIndex(), node.getRuleSpec(),+ scanNode = new Node(node.getBeginTokenIndex(), node.getRuleSpec(),node.getAlternativeSpecIndex(), node.getExpectedElementSpecIndex()+1,- false, parsedElements);+ false, elements);} else {- scanNode = new ParseNode(node.getStartTokenIndex(), node.getRuleSpec(),+ scanNode = new Node(node.getBeginTokenIndex(), node.getRuleSpec(),node.getAlternativeSpecIndex(), node.getExpectedElementSpecIndex(),- true, parsedElements);+ true, elements);}nextNodes.add(scanNode);}}}- public List<ParseState> getStates() {+ public List<State> getStates() {return states;}@@ -137,48 +139,41 @@ public class EarleyParser {return tokens;}- public Set<ParseNode> getMatches() {+ public Set<Node> getMatches() {if (states.size() == tokens.size()+1)return states.get(tokens.size()).getMatches(rule.getName());elsereturn new HashSet<>();}- public int getMatchDistance() {+ public boolean matches() {+ return !getMatches().isEmpty();+ }++ @Nullable+ public Token getLastMatchedToken() {+ int endOfMatch = getEndOfMatch();+ if (endOfMatch > 0)+ return tokens.get(endOfMatch-1);+ else+ return null;+ }++ public List<Token> getMatchedTokens() {+ int endOfMatch = getEndOfMatch();+ if (endOfMatch > 0)+ return tokens.subList(0, endOfMatch);+ else+ return new ArrayList<>();+ }++ public int getEndOfMatch() {for (int i=states.size()-1; i>=0; i--) {- ParseState state = states.get(i);+ State state = states.get(i);if (!state.getMatches(rule.getName()).isEmpty())return i;}return -1;}- public List<ParsedElement> assumeCompleted(ParseNode node, int stopTokenIndex) {- List<ParsedElement> rootElements = new ArrayList<>();- if (node.getStartTokenIndex() == 0 && node.getRuleSpec().getName().equals(rule.getName())) {- rootElements.add(new ParsedElement(null, stopTokenIndex, node));- } else {- ParseState startState = states.get(node.getStartTokenIndex());- for (ParseNode startNode: startState.getNodes()) {- if (!startNode.isCompleted()) {- ElementSpec nextElement = startNode.getExpectedElementSpec();- if (nextElement instanceof RuleRefElementSpec) {- RuleRefElementSpec ruleRefElement = (RuleRefElementSpec) nextElement;- if (ruleRefElement.getRuleName().equals(node.getRuleSpec().getName())) {- List<ParsedElement> parsedElements = new ArrayList<>(startNode.getParsedElements());- parsedElements.add(new ParsedElement(ruleRefElement, stopTokenIndex, node));- ParseNode parentNode = new ParseNode(startNode.getStartTokenIndex(),- startNode.getRuleSpec(), startNode.getAlternativeSpecIndex(),- startNode.getExpectedElementSpecIndex(),- startNode.isExpectedElementSpecMatchedOnce(),- parsedElements);- rootElements.addAll(assumeCompleted(parentNode, stopTokenIndex));- }- }- }- }- }- return rootElements;- }-}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/Element.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/Element.javanew file mode 100644index 0000000000..1120260812--- /dev/null+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/Element.java@@ -0,0 +1,124 @@+package com.pmease.commons.antlr.codeassist.parse;++import java.util.ArrayList;+import java.util.List;++import javax.annotation.Nullable;++import org.antlr.v4.runtime.Token;++import com.pmease.commons.antlr.codeassist.ElementSpec;++public class Element {++ private final ElementSpec spec;++ private final int endTokenIndex;++ private final Node node;++ private final EarleyParser parser;++ public Element(EarleyParser parser, @Nullable ElementSpec spec, int endTokenIndex, @Nullable Node node) {+ this.parser = parser;+ this.spec = spec;+ this.endTokenIndex = endTokenIndex;+ this.node = node;+ }++ @Nullable+ public ElementSpec getSpec() {+ return spec;+ }++ public boolean isRoot() {+ return spec == null;+ }++ public boolean isTerminal() {+ return node == null;+ }++ @Nullable+ public String getLabel() {+ return spec!=null?spec.getLabel():null;+ }++ public int getEndTokenIndex() {+ return endTokenIndex;+ }++ @Nullable+ public Node getNode() {+ return node;+ }++ public List<Token> getMatchedTokens() {+ if (node != null)+ return parser.getTokens().subList(node.getBeginTokenIndex(), endTokenIndex);+ else+ return parser.getTokens().subList(endTokenIndex-1, endTokenIndex);+ }++ @Nullable+ public Token getFirstMatchedToken() {+ if (node != null) {+ if (endTokenIndex > node.getBeginTokenIndex())+ return parser.getTokens().get(node.getBeginTokenIndex());+ else+ return null;+ } else {+ return parser.getTokens().get(endTokenIndex-1);+ }+ }++ @Nullable+ public Token getLastMatchedToken() {+ if (node != null) {+ if (endTokenIndex > node.getBeginTokenIndex())+ return parser.getTokens().get(endTokenIndex-1);+ else+ return null;+ } else {+ return parser.getTokens().get(endTokenIndex-1);+ }+ }++ public String getMatchedText() {+ StringBuilder builder = new StringBuilder();+ for (Token token: getMatchedTokens())+ builder.append(token.getText());+ return builder.toString();+ }++ public List<Element> getChildrenByLabel(String label, boolean recursive) {+ List<Element> children = new ArrayList<>();+ if (node != null) {+ for (Element child: node.getElements()) {+ if (label.equals(child.getLabel()))+ children.add(child);+ if (recursive)+ children.addAll(child.getChildrenByLabel(label, recursive));+ }+ }+ return children;+ }++ public List<Element> getChildrenByRule(String ruleName, boolean recursive) {+ List<Element> children = new ArrayList<>();+ if (node != null) {+ for (Element child: node.getElements()) {+ if (ruleName.equals(child.getNode().getRuleSpec().getName()))+ children.add(child);+ if (recursive)+ children.addAll(child.getChildrenByRule(ruleName, recursive));+ }+ }+ return children;+ }++ public EarleyParser getParser() {+ return parser;+ }++}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParseNode.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/Node.javasimilarity index 79%rename from commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParseNode.javarename to commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/Node.javaindex 55ddb2f54d..e6f0e8f47b 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParseNode.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/Node.java@@ -11,9 +11,9 @@ import com.pmease.commons.antlr.codeassist.AlternativeSpec;import com.pmease.commons.antlr.codeassist.ElementSpec;import com.pmease.commons.antlr.codeassist.RuleSpec;-public class ParseNode {+public class Node {- private final int startTokenIndex;+ private final int beginTokenIndex;private final RuleSpec ruleSpec;@@ -23,24 +23,24 @@ public class ParseNode {private final boolean expectedElementSpecMatchedOnce;- private final List<ParsedElement> parsedElements;+ private final List<Element> elements;private transient AlternativeSpec alternativeSpec;private transient List<ElementSpec> elementSpecs;- public ParseNode(int startTokenIndex, RuleSpec ruleSpec, int alternativeSpecIndex, int nextElementSpecIndex,- boolean nextElementSpecMatchedOnce, List<ParsedElement> parsedElements) {- this.startTokenIndex = startTokenIndex;+ public Node(int beginTokenIndex, RuleSpec ruleSpec, int alternativeSpecIndex, int nextElementSpecIndex,+ boolean nextElementSpecMatchedOnce, List<Element> elements) {+ this.beginTokenIndex = beginTokenIndex;this.ruleSpec = ruleSpec;this.alternativeSpecIndex = alternativeSpecIndex;this.expectedElementSpecIndex = nextElementSpecIndex;this.expectedElementSpecMatchedOnce = nextElementSpecMatchedOnce;- this.parsedElements = parsedElements;+ this.elements = elements;}- public int getStartTokenIndex() {- return startTokenIndex;+ public int getBeginTokenIndex() {+ return beginTokenIndex;}public RuleSpec getRuleSpec() {@@ -67,8 +67,8 @@ public class ParseNode {return getElementSpecs().get(expectedElementSpecIndex);}- public List<ParsedElement> getParsedElements() {- return parsedElements;+ public List<Element> getElements() {+ return elements;}public AlternativeSpec getAlternativeSpec() {@@ -89,30 +89,30 @@ public class ParseNode {@Overridepublic boolean equals(Object other) {- if (!(other instanceof ParseNode))+ if (!(other instanceof Node))return false;if (this == other)return true;- ParseNode otherNode = (ParseNode) other;+ Node otherNode = (Node) other;return new EqualsBuilder()- .append(startTokenIndex, otherNode.startTokenIndex)+ .append(beginTokenIndex, otherNode.beginTokenIndex).append(ruleSpec.getName(), otherNode.ruleSpec.getName()).append(alternativeSpecIndex, otherNode.alternativeSpecIndex).append(expectedElementSpecIndex, otherNode.expectedElementSpecIndex).append(expectedElementSpecMatchedOnce, otherNode.expectedElementSpecMatchedOnce)- .append(parsedElements, otherNode.parsedElements)+ .append(elements, otherNode.elements).isEquals();}@Overridepublic int hashCode() {return new HashCodeBuilder(17, 37)- .append(startTokenIndex)+ .append(beginTokenIndex).append(ruleSpec.getName()).append(alternativeSpecIndex).append(expectedElementSpecIndex).append(expectedElementSpecMatchedOnce)- .append(parsedElements)+ .append(elements).toHashCode();}@@ -125,7 +125,7 @@ public class ParseNode {for (int i=expectedElementSpecIndex; i<getElementSpecs().size(); i++)buffer.append(getElementSpecs().get(i)).append(" ");- return ruleSpec.getName() + " -> " + buffer.toString() + ": " + startTokenIndex;+ return ruleSpec.getName() + " -> " + buffer.toString() + ": " + beginTokenIndex;}}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParsedElement.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParsedElement.javadeleted file mode 100644index 1139e57c4c..0000000000--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParsedElement.java+++ /dev/null@@ -1,86 +0,0 @@-package com.pmease.commons.antlr.codeassist.parse;--import java.util.ArrayList;-import java.util.List;--import javax.annotation.Nullable;--import org.antlr.v4.runtime.Token;--import com.pmease.commons.antlr.codeassist.ElementSpec;--public class ParsedElement {-- private final ElementSpec spec;-- private final int nextTokenIndex;-- private final ParseNode node;-- public ParsedElement(@Nullable ElementSpec spec, int nextTokenIndex, @Nullable ParseNode node) {- this.spec = spec;- this.nextTokenIndex = nextTokenIndex;- this.node = node;- }-- @Nullable- public ElementSpec getSpec() {- return spec;- }-- public boolean isRoot() {- return spec == null;- }-- public boolean isTerminal() {- return node == null;- }-- @Nullable- public String getLabel() {- return spec!=null?spec.getLabel():null;- }-- public int getNextTokenIndex() {- return nextTokenIndex;- }-- @Nullable- public ParseNode getNode() {- return node;- }-- public List<Token> getParsedTokens(List<Token> tokens) {- if (node != null)- return tokens.subList(node.getStartTokenIndex(), nextTokenIndex);- else- return tokens.subList(nextTokenIndex, nextTokenIndex+1);- }-- public List<ParsedElement> getChildrenByLabel(String label, boolean recursive) {- List<ParsedElement> children = new ArrayList<>();- if (node != null) {- for (ParsedElement child: node.getParsedElements()) {- if (label.equals(child.getLabel()))- children.add(child);- if (recursive)- children.addAll(child.getChildrenByLabel(label, recursive));- }- }- return children;- }-- public List<ParsedElement> getChildrenByRule(String ruleName, boolean recursive) {- List<ParsedElement> children = new ArrayList<>();- if (node != null) {- for (ParsedElement child: node.getParsedElements()) {- if (ruleName.equals(child.getNode().getRuleSpec().getName()))- children.add(child);- if (recursive)- children.addAll(child.getChildrenByRule(ruleName, recursive));- }- }- return children;- }--}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/RuleCompletion.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/RuleCompletion.javaindex 7ddf015c7d..f582f5f6d1 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/RuleCompletion.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/RuleCompletion.java@@ -7,26 +7,26 @@ public class RuleCompletion {private final String ruleName;- private final int fromStreamIndex;+ private final int beginTokenIndex;- private final int toStreamIndex;+ private final int endTokenIndex;- public RuleCompletion(String ruleName, int fromStreamIndex, int toStreamIndex) {+ public RuleCompletion(String ruleName, int beginTokenIndex, int endTokenIndex) {this.ruleName = ruleName;- this.fromStreamIndex = fromStreamIndex;- this.toStreamIndex = toStreamIndex;+ this.beginTokenIndex = beginTokenIndex;+ this.endTokenIndex = endTokenIndex;}public String getRuleName() {return ruleName;}- public int getFromStreamIndex() {- return fromStreamIndex;+ public int getBeginTokenIndex() {+ return beginTokenIndex;}- public int getToStreamIndex() {- return toStreamIndex;+ public int getEndTokenIndex() {+ return endTokenIndex;}@Override@@ -35,11 +35,11 @@ public class RuleCompletion {return false;if (this == other)return true;- RuleCompletion otherSpan = (RuleCompletion) other;+ RuleCompletion otherCompletion = (RuleCompletion) other;return new EqualsBuilder()- .append(ruleName, otherSpan.ruleName)- .append(fromStreamIndex, otherSpan.fromStreamIndex)- .append(toStreamIndex, otherSpan.toStreamIndex)+ .append(ruleName, otherCompletion.ruleName)+ .append(beginTokenIndex, otherCompletion.beginTokenIndex)+ .append(endTokenIndex, otherCompletion.endTokenIndex).isEquals();}@@ -47,8 +47,8 @@ public class RuleCompletion {public int hashCode() {return new HashCodeBuilder(17, 37).append(ruleName)- .append(fromStreamIndex)- .append(toStreamIndex)+ .append(beginTokenIndex)+ .append(endTokenIndex).toHashCode();}diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParseState.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/State.javasimilarity index 61%rename from commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParseState.javarename to commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/State.javaindex 64bc25bb30..907fde84bc 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/ParseState.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/parse/State.java@@ -8,37 +8,37 @@ import javax.annotation.Nullable;import com.pmease.commons.antlr.codeassist.ElementSpec;import com.pmease.commons.antlr.codeassist.TerminalElementSpec;-public class ParseState {+public class State {- private final int nextTokenIndex;+ private final int endTokenIndex;- private final Set<ParseNode> nodes;+ private final Set<Node> nodes;private Set<RuleCompletion> ruleCompletions = new HashSet<>();- public Set<ParseNode> getNodes() {+ public Set<Node> getNodes() {return nodes;}- public ParseState(int tokenIndex, Set<ParseNode> nodes) {- this.nextTokenIndex = tokenIndex;+ public State(int tokenIndex, Set<Node> nodes) {+ this.endTokenIndex = tokenIndex;this.nodes = nodes;- for (ParseNode node: nodes) {+ for (Node node: nodes) {if (node.isCompleted())- ruleCompletions.add(new RuleCompletion(node.getRuleSpec().getName(), node.getStartTokenIndex(), tokenIndex));+ ruleCompletions.add(new RuleCompletion(node.getRuleSpec().getName(), node.getBeginTokenIndex(), tokenIndex));}}@Nullable- private RuleCompletion getRuleCompletion(ParseNode node) {+ private RuleCompletion getRuleCompletion(Node node) {if (node.isCompleted())- return new RuleCompletion(node.getRuleSpec().getName(), node.getStartTokenIndex(), nextTokenIndex);+ return new RuleCompletion(node.getRuleSpec().getName(), node.getBeginTokenIndex(), endTokenIndex);elsereturn null;}- public boolean addNode(ParseNode node) {+ public boolean addNode(Node node) {if (!nodes.contains(node)) {RuleCompletion ruleCompletion = getRuleCompletion(node);if (ruleCompletion != null) {@@ -55,24 +55,24 @@ public class ParseState {return false;}- public int getNextTokenIndex() {- return nextTokenIndex;+ public int getEndTokenIndex() {+ return endTokenIndex;}- public Set<ParseNode> getMatches(String ruleName) {- Set<ParseNode> matches = new HashSet<>();- for (ParseNode node: nodes) {+ public Set<Node> getMatches(String ruleName) {+ Set<Node> matches = new HashSet<>();+ for (Node node: nodes) {if (node.getRuleSpec().getName().equals(ruleName)- && node.getStartTokenIndex() == 0 && node.isCompleted()) {+ && node.getBeginTokenIndex() == 0 && node.isCompleted()) {matches.add(node);}}return matches;}- public Set<ParseNode> getNodesExpectingTerminal() {- Set<ParseNode> nodesExpectingTerminal = new HashSet<>();- for (ParseNode node: nodes) {+ public Set<Node> getNodesExpectingTerminal() {+ Set<Node> nodesExpectingTerminal = new HashSet<>();+ for (Node node: nodes) {ElementSpec expectingSpec = node.getExpectedElementSpec();if (expectingSpec instanceof TerminalElementSpec)nodesExpectingTerminal.add(node);@@ -83,7 +83,7 @@ public class ParseState {@Overridepublic String toString() {StringBuffer buffer = new StringBuffer();- for (ParseNode node: nodes)+ for (Node node: nodes)buffer.append(node).append("\n");return buffer.toString();}diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/parse/EarleyParserTest.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/parse/EarleyParserTest.javaindex 2f1de7781c..f2821118f3 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/parse/EarleyParserTest.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/parse/EarleyParserTest.java@@ -1,34 +1,33 @@package com.pmease.commons.antlr.codeassist.parse;-import java.util.List;+import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertTrue;-import org.antlr.v4.runtime.Token;import org.junit.Test;-import com.pmease.commons.antlr.codeassist.CodeAssist;-import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;-import com.pmease.commons.antlr.codeassist.RuleSpec;+import com.pmease.commons.antlr.codeassist.Grammar;+import com.pmease.commons.antlr.codeassist.test.CodeAssistTest1Lexer;import com.pmease.commons.antlr.codeassist.test.CodeAssistTest4Lexer;public class EarleyParserTest {+ private Grammar grammar;++ private boolean matches(String ruleName, String text) {+ return new EarleyParser(grammar.getRule(ruleName), grammar.lex(text)).matches();+ }+@Testpublic void test() {- CodeAssist assist = new CodeAssist(CodeAssistTest4Lexer.class) {-- private static final long serialVersionUID = 1L;-- @Override- protected List<InputSuggestion> suggest(ParseTree parseTree, Node elementNode, String matchWith) {- return null;- }-- };- List<Token> tokens = assist.lex("cd");- RuleSpec rule = assist.getRule("a");- System.out.println(new EarleyParser(rule, tokens).getMatches().size());+ grammar = new Grammar(CodeAssistTest1Lexer.class);+ assertTrue(matches("notRealAmbiguity", "cd"));++ grammar = new Grammar(CodeAssistTest4Lexer.class);+ assertTrue(matches("expr", "(1+2)+3"));+ assertTrue(matches("expr", "1+(2*3)"));+ assertFalse(matches("expr", "(1+2)+"));+ assertFalse(matches("expr", "1(2*3)"));+ assertFalse(matches("expr", "1/2+3)"));}}diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest1.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest1.javaindex 2ad707dffa..d2d86c677e 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest1.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest1.java@@ -1,6 +1,6 @@package com.pmease.commons.antlr.codeassist.test;-import static org.junit.Assert.*;+import static org.junit.Assert.assertEquals;import java.util.ArrayList;import java.util.List;@@ -11,8 +11,7 @@ import com.pmease.commons.antlr.codeassist.CodeAssist;import com.pmease.commons.antlr.codeassist.InputCompletion;import com.pmease.commons.antlr.codeassist.InputStatus;import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;public class CodeAssistTest1 {@@ -21,7 +20,7 @@ public class CodeAssistTest1 {private static final long serialVersionUID = 1L;@Override- protected List<InputSuggestion> suggest(ParseTree parseTree, Node elementNode, String matchWith) {+ protected List<InputSuggestion> suggest(ParentedElement element, String matchWith) {return null;}@@ -57,8 +56,6 @@ public class CodeAssistTest1 {suggestions = suggest(new InputStatus("cd "), "mandatories");assertEquals(1, suggestions.size());assertEquals("cd ef g h:9", suggestions.get(0).toString());-- assertTrue(codeAssist.getRule("notRealAmbiguity").getMatchDistance("o p q"));}}diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.javaindex 879a77e189..968649e6f7 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.java@@ -12,8 +12,7 @@ import com.pmease.commons.antlr.codeassist.InputCompletion;import com.pmease.commons.antlr.codeassist.InputStatus;import com.pmease.commons.antlr.codeassist.InputSuggestion;import com.pmease.commons.antlr.codeassist.LexerRuleRefElementSpec;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;import com.pmease.commons.antlr.codeassist.SurroundingAware;public class CodeAssistTest2 {@@ -25,16 +24,16 @@ public class CodeAssistTest2 {private static final long serialVersionUID = 1L;@Override- protected List<InputSuggestion> suggest(final ParseTree parseTree, Node elementNode, String matchWith) {- if (elementNode.getSpec() instanceof LexerRuleRefElementSpec) {- LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) elementNode.getSpec();+ protected List<InputSuggestion> suggest(final ParentedElement element, String matchWith) {+ if (element.getSpec() instanceof LexerRuleRefElementSpec) {+ LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) element.getSpec();if (spec.getRuleName().equals("Value")) {- return new SurroundingAware(codeAssist, "(", ")") {+ return new SurroundingAware(codeAssist.getGrammar(), "(", ")") {@Overrideprotected List<InputSuggestion> match(String matchWith) {List<InputSuggestion> suggestions = new ArrayList<>();- if (parseTree.getLastNode().getToken().getType() == CodeAssistTest2Lexer.BRANCH) {+ if (element.getRoot().getLastMatchedToken().getType() == CodeAssistTest2Lexer.BRANCH) {for (String value: BRANCHS) {if (value.toLowerCase().contains(matchWith.toLowerCase()))suggestions.add(new InputSuggestion(value));@@ -43,7 +42,7 @@ public class CodeAssistTest2 {return suggestions;}- }.suggest(elementNode, matchWith);+ }.suggest(element.getSpec(), matchWith);}}return null;diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest3.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest3.javaindex ebca173423..daf832e027 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest3.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest3.java@@ -1,20 +1,20 @@package com.pmease.commons.antlr.codeassist.test;+import static org.junit.Assert.assertEquals;+import java.util.ArrayList;import java.util.List;import org.junit.Test;-import static org.junit.Assert.*;import com.pmease.commons.antlr.codeassist.CodeAssist;import com.pmease.commons.antlr.codeassist.InputCompletion;import com.pmease.commons.antlr.codeassist.InputStatus;import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;import com.pmease.commons.antlr.codeassist.RuleRefElementSpec;import com.pmease.commons.antlr.codeassist.SurroundingAware;-import com.pmease.commons.antlr.codeassist.TokenNode;+import com.pmease.commons.antlr.codeassist.parse.Element;public class CodeAssistTest3 {@@ -25,18 +25,17 @@ public class CodeAssistTest3 {private static final long serialVersionUID = 1L;@Override- protected List<InputSuggestion> suggest(final ParseTree parseTree, Node elementNode, String matchWith) {- if (elementNode.getSpec() instanceof RuleRefElementSpec) {- RuleRefElementSpec spec = (RuleRefElementSpec) elementNode.getSpec();+ protected List<InputSuggestion> suggest(final ParentedElement element, String matchWith) {+ if (element.getSpec() instanceof RuleRefElementSpec) {+ RuleRefElementSpec spec = (RuleRefElementSpec) element.getSpec();if (spec.getRuleName().equals("value")) {- return new SurroundingAware(codeAssist, "\"", "\"") {+ return new SurroundingAware(codeAssist.getGrammar(), "\"", "\"") {@Overrideprotected List<InputSuggestion> match(String matchWith) {List<InputSuggestion> suggestions = new ArrayList<>();- Node criteria = parseTree.findParentByRuleName(parseTree.getLastNode(), "criteria");- TokenNode tokenNode = parseTree.getFirstTokenNode(criteria);- if (tokenNode.getToken().getText().equals("author")) {+ Element criteriaElement = element.findParentByRule("criteria");+ if (criteriaElement.getFirstMatchedToken().getText().equals("author")) {for (String value: AUTHORS) {if (value.toLowerCase().contains(matchWith.toLowerCase()))suggestions.add(new InputSuggestion(value));@@ -45,7 +44,7 @@ public class CodeAssistTest3 {return suggestions;}- }.suggest(elementNode, matchWith);+ }.suggest(element.getSpec(), matchWith);}}return null;diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest4.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest4.javaindex 62505aff51..ebc4f70249 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest4.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest4.java@@ -1,8 +1,6 @@package com.pmease.commons.antlr.codeassist.test;import static org.junit.Assert.assertEquals;-import static org.junit.Assert.assertFalse;-import static org.junit.Assert.assertTrue;import java.util.ArrayList;import java.util.List;@@ -13,8 +11,7 @@ import com.pmease.commons.antlr.codeassist.CodeAssist;import com.pmease.commons.antlr.codeassist.InputCompletion;import com.pmease.commons.antlr.codeassist.InputStatus;import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;public class CodeAssistTest4 {@@ -23,7 +20,7 @@ public class CodeAssistTest4 {private static final long serialVersionUID = 1L;@Override- protected List<InputSuggestion> suggest(final ParseTree parseTree, Node elementNode, String matchWith) {+ protected List<InputSuggestion> suggest(ParentedElement element, String matchWith) {return null;}@@ -65,12 +62,6 @@ public class CodeAssistTest4 {assertEquals("5+:2", suggestions.get(2).toString());assertEquals("5-:2", suggestions.get(3).toString());assertEquals("5;:2", suggestions.get(4).toString());-- assertTrue(codeAssist.getRule("expr").getMatchDistance("(1+2)+3"));- assertTrue(codeAssist.getRule("expr").getMatchDistance("1+(2*3)"));- assertFalse(codeAssist.getRule("expr").getMatchDistance("(1+2)+"));- assertFalse(codeAssist.getRule("expr").getMatchDistance("1(2*3)"));- assertFalse(codeAssist.getRule("expr").getMatchDistance("1/2+3)"));}}diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest5.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest5.javaindex 26ac86e948..e3e43d3946 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest5.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest5.java@@ -17,9 +17,9 @@ import com.pmease.commons.antlr.codeassist.InputStatus;import com.pmease.commons.antlr.codeassist.InputSuggestion;import com.pmease.commons.antlr.codeassist.LexerRuleRefElementSpec;import com.pmease.commons.antlr.codeassist.LiteralElementSpec;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;import com.pmease.commons.antlr.codeassist.RuleRefElementSpec;+import com.pmease.commons.antlr.codeassist.parse.Element;/*** This test case uses MySQL select grammar.@@ -53,8 +53,8 @@ public class CodeAssistTest5 {private static final long serialVersionUID = 1L;@Override- protected List<InputSuggestion> suggest(final ParseTree parseTree, Node elementNode, String matchWith) {- ElementSpec spec = (ElementSpec) elementNode.getSpec();+ protected List<InputSuggestion> suggest(final ParentedElement element, String matchWith) {+ ElementSpec spec = element.getSpec();if (spec instanceof RuleRefElementSpec) {RuleRefElementSpec ruleElementSpec = (RuleRefElementSpec) spec;if (ruleElementSpec.getRuleName().equals("schema_name")) {@@ -69,11 +69,11 @@ public class CodeAssistTest5 {LexerRuleRefElementSpec lexerRuleRefElementSpec = (LexerRuleRefElementSpec) spec;if ("tableName".equals(lexerRuleRefElementSpec.getLabel())) {List<InputSuggestion> suggestions = new ArrayList<>();- Node columnNameNode = parseTree.findParentByRuleName(parseTree.getLastNode(), "column_name");+ Element columnNameElement = element.findParentByRule("column_name");String schemaName;- List<Node> schemaNameNodes = parseTree.getChildrenByRuleName(columnNameNode, "schema_name", true);- if (!schemaNameNodes.isEmpty())- schemaName = parseTree.getText(schemaNameNodes.get(0));+ List<Element> schemaNameElements = columnNameElement.getChildrenByRule("schema_name", true);+ if (!schemaNameElements.isEmpty())+ schemaName = schemaNameElements.get(0).getMatchedText();elseschemaName = DEFAULT_SCHEMA;if (SCHEMA_TABLES.containsKey(schemaName)) {@@ -85,10 +85,10 @@ public class CodeAssistTest5 {return suggestions;} else if ("columnName".equals(lexerRuleRefElementSpec.getLabel())) {List<InputSuggestion> suggestions = new ArrayList<>();- Node columnNameNode = parseTree.findParentByRuleName(parseTree.getLastNode(), "column_name");- List<Node> tableNameNodes = parseTree.getChildrenByLabel(columnNameNode, "tableName", true);- if (!tableNameNodes.isEmpty()) {- String tableName = parseTree.getText(tableNameNodes.get(0));+ Element columnNameElement = element.getRoot().findParentByRule("column_name");+ List<Element> tableNameElements = columnNameElement.getChildrenByLabel("tableName", true);+ if (!tableNameElements.isEmpty()) {+ String tableName = tableNameElements.get(0).getMatchedText();if (TABLE_COLUMNS.containsKey(tableName)) {for (String columnName: TABLE_COLUMNS.get(tableName)) {if (columnName.startsWith(matchWith))diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.javaindex 1a2bf0e7d3..1bca349249 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.java@@ -19,13 +19,11 @@ import org.antlr.v4.runtime.Token;import org.antlr.v4.runtime.TokenStream;import com.pmease.commons.antlr.AntlrUtils;-import com.pmease.commons.antlr.codeassist.AssistStream;import com.pmease.commons.antlr.codeassist.CodeAssist;import com.pmease.commons.antlr.codeassist.InputCompletion;import com.pmease.commons.antlr.codeassist.InputStatus;import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;import com.pmease.commons.util.StringUtils;@SuppressWarnings("serial")@@ -64,8 +62,8 @@ public abstract class ANTLRAssistBehavior extends InputAssistBehavior {codeAssist = new CodeAssist(lexerClass, grammarFiles, tokenFile) {@Override- protected List<InputSuggestion> suggest(ParseTree parseTree, Node elementNode, String matchWith) {- return ANTLRAssistBehavior.this.suggest(parseTree, elementNode, matchWith);+ protected List<InputSuggestion> suggest(ParentedElement element, String matchWith) {+ return ANTLRAssistBehavior.this.suggest(element, matchWith);}};@@ -170,11 +168,11 @@ public abstract class ANTLRAssistBehavior extends InputAssistBehavior {@Overrideprotected int getAnchor(String content) {- AssistStream stream = codeAssist.lex(content);- if (stream.isEof()) {+ List<Token> tokens = codeAssist.getGrammar().lex(content);+ if (tokens.isEmpty()) {return 0;} else {- Token lastToken = stream.getToken(stream.size()-1);+ Token lastToken = tokens.get(tokens.size()-1);String contentAfterLastToken = content.substring(lastToken.getStopIndex()+1);if (contentAfterLastToken.length() > 0) {contentAfterLastToken = StringUtils.trimStart(contentAfterLastToken);@@ -185,7 +183,6 @@ public abstract class ANTLRAssistBehavior extends InputAssistBehavior {}}- protected abstract List<InputSuggestion> suggest(ParseTree parseTree,- Node elementNode, String matchWith);+ protected abstract List<InputSuggestion> suggest(ParentedElement element, String matchWith);}diff --git a/gitplex.product/src/test/java/gitplex/product/Test.java b/gitplex.product/src/test/java/gitplex/product/Test.javaindex eeaaf69c06..51ece49798 100644--- a/gitplex.product/src/test/java/gitplex/product/Test.java+++ b/gitplex.product/src/test/java/gitplex/product/Test.java@@ -5,10 +5,7 @@ import java.util.List;import org.antlr.v4.runtime.Token;-import com.pmease.commons.antlr.codeassist.CodeAssist;-import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.Grammar;import com.pmease.commons.antlr.codeassist.RuleSpec;import com.pmease.commons.antlr.codeassist.parse.EarleyParser;import com.pmease.commons.lang.extractors.java.JavaLexer;@@ -17,20 +14,11 @@ public class Test {@org.junit.Testpublic void test() throws IOException {- CodeAssist assist = new CodeAssist(JavaLexer.class) {-- private static final long serialVersionUID = 1L;-- @Override- protected List<InputSuggestion> suggest(ParseTree parseTree, Node elementNode, String matchWith) {- return null;- }-- };- List<Token> tokens = assist.lex("1");- RuleSpec rule = assist.getRule("compilationUnit");+ Grammar grammar = new Grammar(JavaLexer.class);+ List<Token> tokens = grammar.lex("1");+ RuleSpec rule = grammar.getRule("compilationUnit");EarleyParser parser = new EarleyParser(rule, tokens);- System.out.println(parser.getMatches().size());+ System.out.println(parser.matches());}}\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/QueryAssistBehavior.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/QueryAssistBehavior.javaindex 79e0b93d0b..b4dcb6363b 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/QueryAssistBehavior.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/commit/QueryAssistBehavior.java@@ -7,8 +7,7 @@ import com.google.common.collect.Lists;import com.pmease.commons.antlr.codeassist.InputSuggestion;import com.pmease.commons.antlr.codeassist.LexerRuleRefElementSpec;import com.pmease.commons.antlr.codeassist.LiteralElementSpec;-import com.pmease.commons.antlr.codeassist.Node;-import com.pmease.commons.antlr.codeassist.ParseTree;+import com.pmease.commons.antlr.codeassist.ParentedElement;import com.pmease.commons.antlr.codeassist.SurroundingAware;import com.pmease.commons.wicket.behavior.inputassist.ANTLRAssistBehavior;@@ -22,16 +21,16 @@ public class QueryAssistBehavior extends ANTLRAssistBehavior {}@Override- protected List<InputSuggestion> suggest(final ParseTree parseTree, Node elementNode, String matchWith) {- if (elementNode.getSpec() instanceof LexerRuleRefElementSpec) {- LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) elementNode.getSpec();+ protected List<InputSuggestion> suggest(final ParentedElement element, String matchWith) {+ if (element.getSpec() instanceof LexerRuleRefElementSpec) {+ LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) element.getSpec();if (spec.getRuleName().equals("Value")) {- return new SurroundingAware(codeAssist, "(", ")") {+ return new SurroundingAware(codeAssist.getGrammar(), "(", ")") {@Overrideprotected List<InputSuggestion> match(String matchWith) {List<InputSuggestion> suggestions = new ArrayList<>();- if (parseTree.getLastNode().getToken().getType() == CommitQueryParser.BRANCH) {+ if (element.getRoot().getLastMatchedToken().getType() == CommitQueryParser.BRANCH) {for (String value: BRANCHS) {if (value.toLowerCase().contains(matchWith.toLowerCase()))suggestions.add(new InputSuggestion(value));@@ -40,10 +39,10 @@ public class QueryAssistBehavior extends ANTLRAssistBehavior {return suggestions;}- }.suggest(elementNode, matchWith);+ }.suggest(element.getSpec(), matchWith);}- } else if (elementNode.getSpec() instanceof LiteralElementSpec) {- LiteralElementSpec spec = (LiteralElementSpec) elementNode.getSpec();+ } else if (element.getSpec() instanceof LiteralElementSpec) {+ LiteralElementSpec spec = (LiteralElementSpec) element.getSpec();if (spec.getLiteral().toLowerCase().startsWith(matchWith.toLowerCase())) {String description;switch (spec.getLiteral()) {