Java Code Examples for org.antlr.v4.runtime.misc.Interval#of()

The following examples show how to use org.antlr.v4.runtime.misc.Interval#of() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Grammar.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static Map<Integer, Interval> getStateToGrammarRegionMap(GrammarRootAST ast, IntervalSet grammarTokenTypes) {
	Map<Integer, Interval> stateToGrammarRegionMap = new HashMap<Integer, Interval>();
	if ( ast==null ) return stateToGrammarRegionMap;

	List<GrammarAST> nodes = ast.getNodesWithType(grammarTokenTypes);
	for (GrammarAST n : nodes) {
		if (n.atnState != null) {
			Interval tokenRegion = Interval.of(n.getTokenStartIndex(), n.getTokenStopIndex());
			org.antlr.runtime.tree.Tree ruleNode = null;
			// RULEs, BLOCKs of transformed recursive rules point to original token interval
			switch ( n.getType() ) {
				case ANTLRParser.RULE :
					ruleNode = n;
					break;
				case ANTLRParser.BLOCK :
				case ANTLRParser.CLOSURE :
					ruleNode = n.getAncestor(ANTLRParser.RULE);
					break;
			}
			if ( ruleNode instanceof RuleAST ) {
				String ruleName = ((RuleAST) ruleNode).getRuleName();
				Rule r = ast.g.getRule(ruleName);
				if ( r instanceof LeftRecursiveRule ) {
					RuleAST originalAST = ((LeftRecursiveRule) r).getOriginalAST();
					tokenRegion = Interval.of(originalAST.getTokenStartIndex(), originalAST.getTokenStopIndex());
				}
			}
			stateToGrammarRegionMap.put(n.atnState.stateNumber, tokenRegion);
		}
	}
	return stateToGrammarRegionMap;
}
 
Example 2
Source File: InputPanel.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
	 * Show token information if the ctrl-key is down and mouse movement occurs
	 */
	public void showTokenInfoUponCtrlKey(Editor editor, PreviewState previewState, int offset) {
		Token tokenUnderCursor = ParsingUtils.getTokenUnderCursor(previewState, offset);
		if ( tokenUnderCursor==null ) {
			PreviewParser parser = (PreviewParser) previewState.parsingResult.parser;
			CommonTokenStream tokenStream = (CommonTokenStream) parser.getInputStream();
			tokenUnderCursor = ParsingUtils.getSkippedTokenUnderCursor(tokenStream, offset);
		}

		if ( tokenUnderCursor==null ) {
			return;
		}

//		System.out.println("token = "+tokenUnderCursor);
		String channelInfo = "";
		int channel = tokenUnderCursor.getChannel();
		if ( channel!=Token.DEFAULT_CHANNEL ) {
			String chNum = channel==Token.HIDDEN_CHANNEL ? "hidden" : String.valueOf(channel);
			channelInfo = ", Channel "+chNum;
		}
		JBColor color = JBColor.BLUE;
		String tokenInfo =
			String.format("#%d Type %s, Line %d:%d%s",
			              tokenUnderCursor.getTokenIndex(),
			              previewState.g.getTokenDisplayName(tokenUnderCursor.getType()),
			              tokenUnderCursor.getLine(),
			              tokenUnderCursor.getCharPositionInLine(),
			              channelInfo
			             );
		if ( channel==-1 ) {
			tokenInfo = "Skipped";
			color = JBColor.gray;
		}

		Interval sourceInterval = Interval.of(tokenUnderCursor.getStartIndex(),
		                                      tokenUnderCursor.getStopIndex()+1);
		highlightAndOfferHint(editor, offset, sourceInterval,
		                      color, EffectType.LINE_UNDERSCORE, tokenInfo);
	}
 
Example 3
Source File: ShowAmbigTreesDialog.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void popupLookaheadTreesDialog(PreviewState previewState, LookaheadEventInfo lookaheadInfo) {
	// pop up subtrees for lookahead
	ShowAmbigTreesDialog dialog = new ShowAmbigTreesDialog();
	ParserInterpreter parser = (ParserInterpreter) previewState.parsingResult.parser;
	int startRuleIndex = parser.getRuleIndex(previewState.startRuleName);
	List<ParserRuleContext> lookaheadParseTrees =
		GrammarParserInterpreter.getLookaheadParseTrees(previewState.g,
		                                                parser,
		                                                parser.getTokenStream(),
		                                                startRuleIndex,
		                                                lookaheadInfo.decision,
		                                                lookaheadInfo.startIndex,
		                                                lookaheadInfo.stopIndex);
	if ( parser.getNumberOfSyntaxErrors()>0 ) {
		// should be no errors for ambiguities, unless original
		// input itself has errors. Just display error in this case.
		JBPanel errPanel = new JBPanel(new BorderLayout());
		errPanel.add(new JBLabel("Cannot display lookahead trees while there are syntax errors in your input."));
		dialog.treeScrollPane.setViewportView(errPanel);
		lookaheadParseTrees = null;
	}
	if ( lookaheadParseTrees!=null ) {
		Interval range = Interval.of(lookaheadInfo.startIndex, lookaheadInfo.stopIndex);
		String phrase = parser.getTokenStream().getText(range);
		if ( phrase.length()>MAX_PHRASE_WIDTH ) {
			phrase = phrase.substring(0, MAX_PHRASE_WIDTH)+"...";
		}
		String title = lookaheadParseTrees.size()+
			" Interpretations of Lookahead Phrase: "+
			phrase;
		dialog.ambigPhraseLabel.setText(title);
		dialog.setTrees(previewState, lookaheadParseTrees, title, lookaheadInfo.predictedAlt-1, false);
	}
	dialog.pack();
	dialog.setVisible(true);
}
 
Example 4
Source File: RangeUtils.java    From dcos-commons with Apache License 2.0 4 votes vote down vote up
private static Interval rangeToInterval(Range range) {
  return Interval.of((int) range.getBegin(), (int) range.getEnd());
}
 
Example 5
Source File: InputPanel.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
	 * Show tokens/region associated with parse tree parent of this token
	 * if the alt-key is down and mouse movement occurs.
	 */
	public void showParseRegion(EditorMouseEvent event, Editor editor,
	                            PreviewState previewState, int offset) {
		Token tokenUnderCursor = ParsingUtils.getTokenUnderCursor(previewState, offset);
		if ( tokenUnderCursor==null ) {
			return;
		}

		ParseTree tree = previewState.parsingResult.tree;
		TerminalNode nodeWithToken =
			(TerminalNode) ParsingUtils.getParseTreeNodeWithToken(tree, tokenUnderCursor);
		if ( nodeWithToken==null ) {
			// hidden token
			return;
		}

		PreviewParser parser = (PreviewParser) previewState.parsingResult.parser;
		CommonTokenStream tokenStream = (CommonTokenStream) parser.getInputStream();
		ParserRuleContext parent = (ParserRuleContext) nodeWithToken.getParent();
		Interval tokenInterval = parent.getSourceInterval();
		Token startToken = tokenStream.get(tokenInterval.a);
		Token stopToken = tokenStream.get(tokenInterval.b);
		Interval sourceInterval =
			Interval.of(startToken.getStartIndex(), stopToken.getStopIndex()+1);

		List<String> stack = parser.getRuleInvocationStack(parent);
		Collections.reverse(stack);

		if ( stack.size()>MAX_STACK_DISPLAY ) {
			// collapse contiguous dups to handle left-recursive stacks
			List<Pair<String, Integer>> smaller = new ArrayList<>();
			int last = 0;
			smaller.add(new Pair<>(stack.get(0), 1)); // init to having first element, count of 1
			for (int i = 1; i<stack.size(); i++) {
				String s = stack.get(i);
				if ( smaller.get(last).a.equals(s) ) {
					smaller.set(last, new Pair<>(s, smaller.get(last).b + 1));
				}
				else {
					smaller.add(new Pair<>(s, 1));
					last++;
				}
			}
			stack = new ArrayList<>();
			for ( Pair<String, Integer> pair : smaller ) {
				if ( pair.b>1 ) {
					stack.add(pair.a + "^" + pair.b);
				} else {
					stack.add(pair.a);
				}
			}
		}
		String stackS = Utils.join(stack.toArray(), "\n");
		highlightAndOfferHint(editor, offset, sourceInterval,
		                      JBColor.BLUE, EffectType.ROUNDED_BOX, stackS);


		// Code for a balloon.

//		JBPopupFactory popupFactory = JBPopupFactory.getInstance();
//		BalloonBuilder builder =
//		    popupFactory.createHtmlTextBalloonBuilder(Utils.join(stack.toArray(), "<br>"),
//												  MessageType.INFO, null);
//		builder.setHideOnClickOutside(true);
//		Balloon balloon = builder.createBalloon();
//		MouseEvent mouseEvent = event.getMouseEvent();
//		Point point = mouseEvent.getPoint();
//		point.translate(10, -15);
//		RelativePoint where = new RelativePoint(mouseEvent.getComponent(), point);
//		balloon.show(where, Balloon.Position.above);
	}