org.antlr.v4.runtime.tree.Tree Java Examples

The following examples show how to use org.antlr.v4.runtime.tree.Tree. 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: ShowAmbigTreesDialog.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void markFromRoots(final PreviewInterpreterRuleContext t, final PreviewInterpreterRuleContext u) {
	if ( t==null || u==null ) return;
	if ( !t.equals(u) ) return;
	t.reached = true;
	u.reached = true;
	int n = Math.min(t.getChildCount(), u.getChildCount());
	for (int i = 0; i<n; i++) { // for each leaf of t and u
		Tree tchild = t.getChild(i);
		Tree uchild = u.getChild(i);
		if ( !tchild.equals(uchild) ) {
			return; // don't consider other kids if ith doesn't match
		}
		if ( tchild instanceof PreviewInterpreterRuleContext &&
			uchild instanceof PreviewInterpreterRuleContext ) {
			markFromRoots((PreviewInterpreterRuleContext) tchild,
			              (PreviewInterpreterRuleContext) uchild);
		}
		else {
			return; // mismatched kids. should be caught above but...
		}
	}
}
 
Example #2
Source File: Trees.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Print out a whole tree in LISP form. Arg nodeTextProvider is used on the
 *  node payloads to get the text for the nodes.
 *
 *  @since 4.5.1
 */
public static String toStringTree(Tree t, TreeTextProvider nodeTextProvider) {
	if ( t==null ) return "null";
	String s = Utils.escapeWhitespace(nodeTextProvider.getText(t), false);
	if ( t.getChildCount()==0 ) return s;
	StringBuilder buf = new StringBuilder();
	buf.append("(");
	s = Utils.escapeWhitespace(nodeTextProvider.getText(t), false);
	buf.append(s);
	buf.append(' ');
	for (int i = 0; i<t.getChildCount(); i++) {
		if ( i>0 ) buf.append(' ');
		buf.append(toStringTree(t.getChild(i), nodeTextProvider));
	}
	buf.append(")");
	return buf.toString();
}
 
Example #3
Source File: TreeLayoutAdaptor.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Iterator<Tree> iterator() {
	return new Iterator<Tree>() {
		private int i = 0;

		@Override
		public boolean hasNext() {
			return tree.getChildCount() > i;
		}

		@Override
		public Tree next() {
			if (!hasNext())
				throw new NoSuchElementException();

			return tree.getChild(i++);
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	};
}
 
Example #4
Source File: TreeLayoutAdaptor.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Iterator<Tree> iterator() {
	return new Iterator<Tree>() {
		private int i = tree.getChildCount();

		@Override
		public boolean hasNext() {
			return i > 0;
		}

		@Override
		public Tree next() {
			if (!hasNext())
				throw new NoSuchElementException();

			return tree.getChild(--i);
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	};
}
 
Example #5
Source File: TreePostScriptGenerator.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void generateEdges(Tree parent) {
		if (!getTree().isLeaf(parent)) {
			Rectangle2D.Double parentBounds = getBoundsOfNode(parent);
//			System.out.println("%% parent("+getText(parent)+")="+parentBounds);
			double x1 = parentBounds.getCenterX();
			double y1 = parentBounds.y;
			for (Tree child : getChildren(parent)) {
				Rectangle2D.Double childBounds = getBoundsOfNode(child);
//				System.out.println("%% child("+getText(child)+")="+childBounds);
				double x2 = childBounds.getCenterX();
				double y2 = childBounds.getMaxY();
				doc.line(x1, y1, x2, y2);
				generateEdges(child);
			}
		}
	}
 
Example #6
Source File: HierarchyViewer.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void selectNodeAtOffset(int offset) {
	if (!scrollFromSource) {
		return;
	}
	DefaultMutableTreeNode root = (DefaultMutableTreeNode) myTree.getModel().getRoot();
	if ( root==null ) {
		return; // probably because the grammar is not valid
	}
	Tree tree = (Tree) root.getUserObject();

	if (tree instanceof ParseTree) {
		DefaultMutableTreeNode atOffset = getNodeAtOffset(root, offset);

		if (atOffset != null) {
			TreePath path = new TreePath(atOffset.getPath());
			myTree.getSelectionModel().setSelectionPath(path);
			myTree.scrollPathToVisible(path);
		}
	}
}
 
Example #7
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void setTree(Tree root) {
	if ( root!=null ) {
		boolean useIdentity = true; // compare node identity
		this.treeLayout =
			new TreeLayout<Tree>(getTreeLayoutAdaptor(root),
								 new TreeViewer.VariableExtentProvide(this),
								 new DefaultConfiguration<Tree>(gapBetweenLevels,
																gapBetweenNodes),
								 useIdentity);
		// Let the UI display this new AST.
		updatePreferredSize();
	}
	else {
		this.treeLayout = null;
		repaint();
	}
}
 
Example #8
Source File: HierarchyViewer.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private MutableTreeNode wrap(final Tree tree) {
	if (tree == null) {
		return null;
	}
	DefaultMutableTreeNode root = new DefaultMutableTreeNode(tree) {
		@Override
		public String toString() {
			return treeTextProvider.getText((Tree) getUserObject());
		}


	};

	for (int i = 0; i < tree.getChildCount(); i++) {
		root.add(wrap(tree.getChild(i)));
	}
	return root;
}
 
Example #9
Source File: TreePostScriptGenerator.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public double getHeight(Tree tree) {
	String s = getText(tree);
	double h =
		doc.getLineHeight() + nodeHeightPaddingAbove + nodeHeightPaddingBelow;
	String[] lines = s.split("\n");
	return h * lines.length;
}
 
Example #10
Source File: HierarchyViewer.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
HierarchyViewer(Tree tree, PreviewPanel previewPanel) {
	this.previewPanel = previewPanel;

	setupComponents();
	setupTree(tree);

	myTree.addMouseListener(new MouseAdapter() {
		@Override
		public void mouseClicked(MouseEvent e) {
			if (e.getButton() == MouseEvent.BUTTON1) {
				onClick(e);
			}
		}
	});
}
 
Example #11
Source File: DocumentTree.java    From smartcheck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return rule nodes
 */
default Map<Node, Tree> ruleNodes() {
    return this.elements().entrySet().stream().collect(
            HashMap::new,
            (map, entry) -> map.put(
                    entry.getValue(), entry.getKey()
            ),
            Map::putAll
    );
}
 
Example #12
Source File: ShowAmbigTreesDialog.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
	 * Given two trees, t and u, compare them starting from the leaves and the decision root
	 * Tree t is considered the "truth" and we are comparing u to it. That
	 * means u might contain fewer in-range leaves. t's leaves should be
	 * start..stop indexes.
	 */
	public static void mark(final PreviewInterpreterRuleContext t,
							final PreviewInterpreterRuleContext u) {
		// First mark from roots down
		markFromRoots(t, u);

		// Get leaves so we can do a difference between the trees starting at the bottom and top
		List<TerminalNode> tleaves = ParsingUtils.getAllLeaves(t);
		List<TerminalNode> uleaves = ParsingUtils.getAllLeaves(u);

		int firstTleafTokenIndex = tleaves.isEmpty() ? -1 : tleaves.get(0).getSymbol().getTokenIndex();
		int firstUleafTokenIndex = uleaves.isEmpty() ? -1 : uleaves.get(0).getSymbol().getTokenIndex();
		final int first = Math.max(firstTleafTokenIndex, firstUleafTokenIndex);

		// filter so we start in same place
		tleaves = Utils.filter(tleaves, tree -> ((Token) tree.getPayload()).getTokenIndex()>=first);
		uleaves = Utils.filter(uleaves, tree -> ((Token) tree.getPayload()).getTokenIndex()>=first);
		int n = Math.min(tleaves.size(), uleaves.size());
		for (int i = 0; i<n; i++) { // for each leaf in t and u
			Tree tleaf = tleaves.get(i);
			Tree uleaf = uleaves.get(i);
			List<? extends Tree> tancestors = ParsingUtils.getAncestors(tleaf);
			List<? extends Tree> uancestors = ParsingUtils.getAncestors(uleaf);
			int a = 0;
			int nta = tancestors.size();
			int nua = uancestors.size();
			PreviewInterpreterRuleContext tancestor;
			PreviewInterpreterRuleContext uancestor;
			while ( a<nta && a<nua ) { // walk ancestor chain for each leaf until not equal
				tancestor = (PreviewInterpreterRuleContext) tancestors.get(a);
				uancestor = (PreviewInterpreterRuleContext) uancestors.get(a);
				if ( !tancestor.equals(uancestor) ) break;
				tancestor.reached = true;
				uancestor.reached = true;
//				if (tancestor == t || uancestor == u)
//					break; // stop if we hit incoming root nodes
				a++;
			}
		}
	}
 
Example #13
Source File: Trees.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Save this tree in a postscript file using a particular font name and size */
public static void save(Tree t,
                        List<String> ruleNames, String fileName,
                        String fontName, int fontSize)
throws IOException
{
	writePS(t, ruleNames, fileName, fontName, fontSize);
}
 
Example #14
Source File: UberTreeViewer.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void paintBox(Graphics g, Tree tree) {
	customPaintBox(g, tree);

	Rectangle2D.Double box = getBoundsOfNode(tree);
	if ( tree instanceof PreviewInterpreterRuleContext ) {
		PreviewInterpreterRuleContext ctx = (PreviewInterpreterRuleContext)tree;
		if ( highlightUnreachedNodes && !ctx.reached ) {
			g.setColor(JBColor.orange);
			g.drawRoundRect((int) box.x, (int) box.y, (int) box.width - 1,
							(int) box.height - 1, arcSize, arcSize);
		}
	}
}
 
Example #15
Source File: VisitSiblingLists.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void enterEveryRule(ParserRuleContext ctx) {
	// Find sibling lists that are children of this parent node
	Set<Class> completed = new HashSet<>(); // only count sibling list for each subtree type once
	for (int i = 0; i<ctx.getChildCount(); i++) {
		ParseTree child = ctx.getChild(i);

		if ( completed.contains(child.getClass()) ) continue; // avoid counting repeatedly
		completed.add(child.getClass());
		if ( child instanceof TerminalNode ) continue; // tokens are separators at most not siblings

		// found subtree child
		List<? extends ParserRuleContext> siblings =
			ctx.getRuleContexts(((ParserRuleContext) child).getClass());
		if ( siblings.size()>1 ) { // we found a list
			// check for separator by looking between first two siblings (assume all are same)
			ParserRuleContext first = siblings.get(0);
			ParserRuleContext second = siblings.get(1);
			List<Tree> children = Trees.getChildren(ctx);

			int firstIndex = children.indexOf(first);
			int secondIndex = children.indexOf(second);

			if ( firstIndex+1 == secondIndex ) continue; // nothing between first and second so no separator

			ParseTree between = ctx.getChild(firstIndex+1);
			if ( between instanceof TerminalNode ) { // is it a token?
				Token separator = ((TerminalNode) between).getSymbol();
				visitNonSingletonWithSeparator(ctx, siblings, separator);
			}
		}
	}
}
 
Example #16
Source File: AltLabelTextProvider.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public String getText(Tree node) {
	if ( node instanceof PreviewInterpreterRuleContext) {
		PreviewInterpreterRuleContext inode = (PreviewInterpreterRuleContext)node;
		Rule r = g.getRule(inode.getRuleIndex());
		String[] altLabels = getAltLabels(r);
		String name = r.name;
		int outerAltNum = inode.getOuterAltNum();
		if ( altLabels!=null ) {
			if ( outerAltNum>=0 && outerAltNum<altLabels.length ) {
				return name+":"+altLabels[outerAltNum];
			}
			else {
				return name;
			}
		}
		else if ( r.getOriginalNumberOfAlts()>1 ) {
			return name + ":" +outerAltNum;
		}
		else {
			return name; // don't display an alternative number if there's only one
		}
	} else if (node instanceof TerminalNode) {
		return getLabelForToken( ((TerminalNode)node).getSymbol() );
	}
	return Trees.getNodeText(node, Arrays.asList(parser.getRuleNames()));
}
 
Example #17
Source File: Trees.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String getPS(Tree t, List<String> ruleNames,
						   String fontName, int fontSize)
{
	TreePostScriptGenerator psgen =
		new TreePostScriptGenerator(ruleNames, t, fontName, fontSize);
	return psgen.getPS();
}
 
Example #18
Source File: TreeUtils.java    From proleap-vb6-parser with MIT License 5 votes vote down vote up
/**
 * @see org.antlr.v4.runtime.tree.Trees.toStringTree(Tree, Parser)
 */
public static String toStringTree(final Tree t, final Parser recog) {
	final String[] ruleNames = recog != null ? recog.getRuleNames() : null;
	final List<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null;

	return toStringTree(t, ruleNamesList, 0);
}
 
Example #19
Source File: HierarchyViewer.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void setupTree(Tree tree) {
	setTree(tree);

	DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
	renderer.setOpenIcon(Icons.PARSER_RULE);
	renderer.setClosedIcon(Icons.PARSER_RULE);
	renderer.setLeafIcon(Icons.LEXER_RULE);
	myTree.setCellRenderer(renderer);
}
 
Example #20
Source File: TreeUtils.java    From proleap-vb6-parser with MIT License 5 votes vote down vote up
/**
 * @see org.antlr.v4.runtime.tree.Trees.toStringTree(Tree, List<String>)
 */
public static String toStringTree(final Tree t, final List<String> ruleNames, final int depth) {
	String s = Utils.escapeWhitespace(Trees.getNodeText(t, ruleNames), false);

	if (t.getChildCount() == 0) {
		return s;
	}

	final StringBuilder buf = new StringBuilder();

	if (depth > 0) {
		buf.append(NEWLINE);
	}

	buf.append(indent(depth));
	buf.append("(");
	s = Utils.escapeWhitespace(Trees.getNodeText(t, ruleNames), false);
	buf.append(s);
	buf.append(' ');

	for (int i = 0; i < t.getChildCount(); i++) {
		if (i > 0) {
			buf.append(' ');
		}

		buf.append(toStringTree(t.getChild(i), ruleNames, depth + 1));
	}

	buf.append(")");

	return buf.toString();
}
 
Example #21
Source File: TreePostScriptGenerator.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TreePostScriptGenerator(List<String> ruleNames, Tree root,
							   String fontName, int fontSize)
{
	this.root = root;
	setTreeTextProvider(new TreeViewer.DefaultTreeTextProvider(ruleNames));
	doc = new PostScriptDocument(fontName, fontSize);
	boolean compareNodeIdentities = true;
	this.treeLayout =
		new TreeLayout<Tree>(getTreeLayoutAdaptor(root),
							 new VariableExtentProvide(),
							 new DefaultConfiguration<Tree>(gapBetweenLevels,
															gapBetweenNodes,
															Configuration.Location.Bottom),
                                compareNodeIdentities);
}
 
Example #22
Source File: TreePostScriptGenerator.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public String getPS() {
	// generate the edges and boxes (with text)
	generateEdges(getTree().getRoot());
	for (Tree node : treeLayout.getNodeBounds().keySet()) {
		generateNode(node);
	}

	Dimension size = treeLayout.getBounds().getBounds().getSize();
	doc.boundingBox(size.width, size.height);
	doc.close();
	return doc.getPS();
}
 
Example #23
Source File: Tool.java    From bookish with MIT License 5 votes vote down vote up
/** check all references to entities in all files
 * track list of entity refs for each paragraph
 */
public void verifyAllEntityRefs(Artifact artifact) {
	for (ChapDocInfo doc : artifact.docs) {
		Collection<ParseTree> refNodes =
			XPath.findAll(doc.tree, "//REF", doc.parser);
		for (ParseTree t : refNodes) {
			String label = stripQuotes(t.getText());
			EntityDef d = doc.getEntity(label);
			if ( d==null ) {
				Token tok = ((TerminalNode) t).getSymbol();
				System.err.printf("%s line %d:%d unknown label '%s'\n",
				                  doc.getSourceName(),
				                  tok.getLine(),
				                  tok.getCharPositionInLine(),
				                  label);
				continue;
			}
			d.refCount++;
			List<? extends Tree> ancestors = Trees.getAncestors(t);
			Tree p = ParrtCollections.findLast(ancestors, (Tree a) -> a instanceof BookishParser.ParagraphContext);
			// track all side items ref'd within this paragraph
			if ( d.refCount==1 && p!=null && d.isSideItem() ) {
				// for first ref, annotate paragraph if this ref is inside a paragraph
				((BookishParser.ParagraphContext)p).entitiesRefd.add(d);
			}
		}
	}
}
 
Example #24
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public double getWidth(Tree tree) {
	FontMetrics fontMetrics = viewer.getFontMetrics(viewer.font);
	String s = viewer.getText(tree);
	int w = fontMetrics.stringWidth(s) + viewer.nodeWidthPadding*2;
	return w;
}
 
Example #25
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public double getHeight(Tree tree) {
	FontMetrics fontMetrics = viewer.getFontMetrics(viewer.font);
	int h = fontMetrics.getHeight() + viewer.nodeHeightPadding*2;
	String s = viewer.getText(tree);
	String[] lines = s.split("\n");
	return h * lines.length;
}
 
Example #26
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TreeViewer(List<String> ruleNames, Tree tree) {
	setRuleNames(ruleNames);
	if ( tree!=null ) {
		setTree(tree);
	}
	setFont(font);
}
 
Example #27
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void paintEdges(Graphics g, Tree parent) {
	if (!getTree().isLeaf(parent)) {
           BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND,
                   BasicStroke.JOIN_ROUND);
           ((Graphics2D)g).setStroke(stroke);

		Rectangle2D.Double parentBounds = getBoundsOfNode(parent);
		double x1 = parentBounds.getCenterX();
		double y1 = parentBounds.getMaxY();
		for (Tree child : getTree().getChildren(parent)) {
			Rectangle2D.Double childBounds = getBoundsOfNode(child);
			double x2 = childBounds.getCenterX();
			double y2 = childBounds.getMinY();
			if (getUseCurvedEdges()) {
				CubicCurve2D c = new CubicCurve2D.Double();
				double ctrlx1 = x1;
				double ctrly1 = (y1+y2)/2;
				double ctrlx2 = x2;
				double ctrly2 = y1;
				c.setCurve(x1, y1, ctrlx1, ctrly1, ctrlx2, ctrly2, x2, y2);
				((Graphics2D) g).draw(c);
			} else {
				g.drawLine((int) x1, (int) y1,
						   (int) x2, (int) y2);
			}
			paintEdges(g, child);
		}
	}
}
 
Example #28
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
	public void paint(Graphics g) {
		super.paint(g);

		if ( treeLayout==null ) {
			return;
		}

		Graphics2D g2 = (Graphics2D)g;
		// anti-alias the lines
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
      						RenderingHints.VALUE_ANTIALIAS_ON);

		// Anti-alias the text
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                         	RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

//		AffineTransform at = g2.getTransform();
//        g2.scale(
//            (double) this.getWidth() / 400,
//            (double) this.getHeight() / 400);
//
//		g2.setTransform(at);

		paintEdges(g, getTree().getRoot());

		// paint the boxes
		for (Tree Tree : treeLayout.getNodeBounds().keySet()) {
			paintBox(g, Tree);
		}
	}
 
Example #29
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected int getHighlightedNodeIndex(Tree node) {
	if ( highlightedNodes==null ) return -1;
	for (int i = 0; i < highlightedNodes.size(); i++) {
		Tree t = highlightedNodes.get(i);
		if ( t == node ) return i;
	}
	return -1;
}
 
Example #30
Source File: TreeViewer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void removeHighlightedNodes(Collection<Tree> nodes) {
	if ( highlightedNodes!=null ) {
		// only remove exact objects defined by ==, not equals()
		for (Tree t : nodes) {
			int i = getHighlightedNodeIndex(t);
			if ( i>=0 ) highlightedNodes.remove(i);
		}
	}
}