Search in sources :

Example 16 with Tree

use of org.antlr.v4.runtime.tree.Tree in project antlr4 by antlr.

the class GrammarDependencies method analyse.

private void analyse(File grammarFile, Collection<File> grammarFiles, Tool tool) {
    GrammarRootAST grammar = tool.parseGrammar(grammarFile.getAbsolutePath());
    if (grammar == null)
        return;
    for (GrammarAST importDecl : grammar.getAllChildrenWithType(ANTLRParser.IMPORT)) {
        Tree id = importDecl.getFirstChildWithType(ANTLRParser.ID);
        // being reported by the ANTLR tool
        if (id != null) {
            String grammarPath = getRelativePath(grammarFile);
            graph.addEdge(id.getText() + ".g4", grammarPath);
        }
    }
    for (GrammarAST options : grammar.getAllChildrenWithType(ANTLRParser.OPTIONS)) {
        for (int i = 0, count = options.getChildCount(); i < count; i++) {
            Tree option = options.getChild(i);
            if (option.getType() == ANTLRParser.ASSIGN) {
                String key = option.getChild(0).getText();
                String value = option.getChild(1).getText();
                if ("tokenVocab".equals(key)) {
                    String name = stripQuotes(value);
                    // the grammar name may be qualified, but we resolve the path anyway
                    String grammarName = stripPath(name);
                    String grammarPath = MojoUtils.findSourceSubdir(sourceDirectory, grammarFile);
                    File depGrammarFile = resolve(grammarName, grammarPath);
                    // (files probably reside in the root directory anyway with such a configuration )
                    if (packageName != null)
                        grammarPath = packageName;
                    graph.addEdge(getRelativePath(depGrammarFile), grammarPath + grammarFile.getName());
                }
            }
        }
    }
}
Also used : GrammarRootAST(org.antlr.v4.tool.ast.GrammarRootAST) GrammarAST(org.antlr.v4.tool.ast.GrammarAST) Tree(org.antlr.runtime.tree.Tree) File(java.io.File)

Example 17 with Tree

use of org.antlr.v4.runtime.tree.Tree in project antlr4 by antlr.

the class TreeViewer method paintBox.

protected void paintBox(Graphics g, Tree tree) {
    Rectangle2D.Double box = getBoundsOfNode(tree);
    // draw the box in the background
    boolean ruleFailedAndMatchedNothing = false;
    if (tree instanceof ParserRuleContext) {
        ParserRuleContext ctx = (ParserRuleContext) tree;
        ruleFailedAndMatchedNothing = ctx.exception != null && ctx.stop != null && ctx.stop.getTokenIndex() < ctx.start.getTokenIndex();
    }
    if (isHighlighted(tree) || boxColor != null || tree instanceof ErrorNode || ruleFailedAndMatchedNothing) {
        if (isHighlighted(tree))
            g.setColor(highlightedBoxColor);
        else if (tree instanceof ErrorNode || ruleFailedAndMatchedNothing)
            g.setColor(LIGHT_RED);
        else
            g.setColor(boxColor);
        g.fillRoundRect((int) box.x, (int) box.y, (int) box.width - 1, (int) box.height - 1, arcSize, arcSize);
    }
    if (borderColor != null) {
        g.setColor(borderColor);
        g.drawRoundRect((int) box.x, (int) box.y, (int) box.width - 1, (int) box.height - 1, arcSize, arcSize);
    }
    // draw the text on top of the box (possibly multiple lines)
    g.setColor(textColor);
    String s = getText(tree);
    String[] lines = s.split("\n");
    FontMetrics m = getFontMetrics(font);
    int x = (int) box.x + arcSize / 2 + nodeWidthPadding;
    int y = (int) box.y + m.getAscent() + m.getLeading() + 1 + nodeHeightPadding;
    for (int i = 0; i < lines.length; i++) {
        text(g, lines[i], x, y);
        y += m.getHeight();
    }
}
Also used : ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) Rectangle2D(java.awt.geom.Rectangle2D) ErrorNode(org.antlr.v4.runtime.tree.ErrorNode)

Example 18 with Tree

use of org.antlr.v4.runtime.tree.Tree in project antlr4 by antlr.

the class TreeViewer method showInDialog.

protected static JFrame showInDialog(final TreeViewer viewer) {
    final JFrame dialog = new JFrame();
    dialog.setTitle("Parse Tree Inspector");
    final Preferences prefs = Preferences.userNodeForPackage(TreeViewer.class);
    // Make new content panes
    final Container mainPane = new JPanel(new BorderLayout(5, 5));
    final Container contentPane = new JPanel(new BorderLayout(0, 0));
    contentPane.setBackground(Color.white);
    // Wrap viewer in scroll pane
    JScrollPane scrollPane = new JScrollPane(viewer);
    // Make the scrollpane (containing the viewer) the center component
    contentPane.add(scrollPane, BorderLayout.CENTER);
    JPanel wrapper = new JPanel(new FlowLayout());
    // Add button to bottom
    JPanel bottomPanel = new JPanel(new BorderLayout(0, 0));
    contentPane.add(bottomPanel, BorderLayout.SOUTH);
    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
        }
    });
    wrapper.add(ok);
    // Add an export-to-png button right of the "OK" button
    JButton png = new JButton("Export as PNG");
    png.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            generatePNGFile(viewer, dialog);
        }
    });
    wrapper.add(png);
    bottomPanel.add(wrapper, BorderLayout.SOUTH);
    // Add scale slider
    double lastKnownViewerScale = prefs.getDouble(DIALOG_VIEWER_SCALE_PREFS_KEY, viewer.getScale());
    viewer.setScale(lastKnownViewerScale);
    int sliderValue = (int) ((lastKnownViewerScale - 1.0) * 1000);
    final JSlider scaleSlider = new JSlider(JSlider.HORIZONTAL, -999, 1000, sliderValue);
    scaleSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            int v = scaleSlider.getValue();
            viewer.setScale(v / 1000.0 + 1.0);
        }
    });
    bottomPanel.add(scaleSlider, BorderLayout.CENTER);
    // Add a JTree representing the parser tree of the input.
    JPanel treePanel = new JPanel(new BorderLayout(5, 5));
    // An "empty" icon that will be used for the JTree's nodes.
    Icon empty = new EmptyIcon();
    UIManager.put("Tree.closedIcon", empty);
    UIManager.put("Tree.openIcon", empty);
    UIManager.put("Tree.leafIcon", empty);
    Tree parseTreeRoot = viewer.getTree().getRoot();
    TreeNodeWrapper nodeRoot = new TreeNodeWrapper(parseTreeRoot, viewer);
    fillTree(nodeRoot, parseTreeRoot, viewer);
    final JTree tree = new JTree(nodeRoot);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            JTree selectedTree = (JTree) e.getSource();
            TreePath path = selectedTree.getSelectionPath();
            if (path != null) {
                TreeNodeWrapper treeNode = (TreeNodeWrapper) path.getLastPathComponent();
                // Set the clicked AST.
                viewer.setTree((Tree) treeNode.getUserObject());
            }
        }
    });
    treePanel.add(new JScrollPane(tree));
    // Create the pane for both the JTree and the AST
    final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treePanel, contentPane);
    mainPane.add(splitPane, BorderLayout.CENTER);
    dialog.setContentPane(mainPane);
    // make viz
    WindowListener exitListener = new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            prefs.putInt(DIALOG_WIDTH_PREFS_KEY, (int) dialog.getSize().getWidth());
            prefs.putInt(DIALOG_HEIGHT_PREFS_KEY, (int) dialog.getSize().getHeight());
            prefs.putDouble(DIALOG_X_PREFS_KEY, dialog.getLocationOnScreen().getX());
            prefs.putDouble(DIALOG_Y_PREFS_KEY, dialog.getLocationOnScreen().getY());
            prefs.putInt(DIALOG_DIVIDER_LOC_PREFS_KEY, splitPane.getDividerLocation());
            prefs.putDouble(DIALOG_VIEWER_SCALE_PREFS_KEY, viewer.getScale());
            dialog.setVisible(false);
            dialog.dispose();
        }
    };
    dialog.addWindowListener(exitListener);
    dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    int width = prefs.getInt(DIALOG_WIDTH_PREFS_KEY, 600);
    int height = prefs.getInt(DIALOG_HEIGHT_PREFS_KEY, 500);
    dialog.setPreferredSize(new Dimension(width, height));
    dialog.pack();
    // After pack(): set the divider at 1/3 (200/600) of the frame.
    int dividerLocation = prefs.getInt(DIALOG_DIVIDER_LOC_PREFS_KEY, 200);
    splitPane.setDividerLocation(dividerLocation);
    if (prefs.getDouble(DIALOG_X_PREFS_KEY, -1) != -1) {
        dialog.setLocation((int) prefs.getDouble(DIALOG_X_PREFS_KEY, 100), (int) prefs.getDouble(DIALOG_Y_PREFS_KEY, 100));
    } else {
        dialog.setLocationRelativeTo(null);
    }
    dialog.setVisible(true);
    return dialog;
}
Also used : ActionEvent(java.awt.event.ActionEvent) WindowAdapter(java.awt.event.WindowAdapter) TreeSelectionListener(javax.swing.event.TreeSelectionListener) Tree(org.antlr.v4.runtime.tree.Tree) ChangeListener(javax.swing.event.ChangeListener) Preferences(java.util.prefs.Preferences) WindowListener(java.awt.event.WindowListener) ActionListener(java.awt.event.ActionListener) ChangeEvent(javax.swing.event.ChangeEvent) TreePath(javax.swing.tree.TreePath) WindowEvent(java.awt.event.WindowEvent) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent)

Example 19 with Tree

use of org.antlr.v4.runtime.tree.Tree in project antlr4 by antlr.

the class GrammarASTAdaptor method create.

@Override
public /** Make sure even imaginary nodes know the input stream */
Object create(int tokenType, String text) {
    GrammarAST t;
    if (tokenType == ANTLRParser.RULE) {
        // needed by TreeWizard to make RULE tree
        t = new RuleAST(new CommonToken(tokenType, text));
    } else if (tokenType == ANTLRParser.STRING_LITERAL) {
        // implicit lexer construction done with wizard; needs this node type
        // whereas grammar ANTLRParser.g can use token option to spec node type
        t = new TerminalAST(new CommonToken(tokenType, text));
    } else {
        t = (GrammarAST) super.create(tokenType, text);
    }
    t.token.setInputStream(input);
    return t;
}
Also used : RuleAST(org.antlr.v4.tool.ast.RuleAST) GrammarAST(org.antlr.v4.tool.ast.GrammarAST) CommonToken(org.antlr.runtime.CommonToken) TerminalAST(org.antlr.v4.tool.ast.TerminalAST)

Example 20 with Tree

use of org.antlr.v4.runtime.tree.Tree in project antlr4 by antlr.

the class TreePostScriptGenerator method generateEdges.

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);
        }
    }
}
Also used : Rectangle2D(java.awt.geom.Rectangle2D) Tree(org.antlr.v4.runtime.tree.Tree)

Aggregations

ParseTree (org.antlr.v4.runtime.tree.ParseTree)20 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)17 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)15 GrammarAST (org.antlr.v4.tool.ast.GrammarAST)12 ParserRuleContext (org.antlr.v4.runtime.ParserRuleContext)9 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 ArrayList (java.util.ArrayList)6 BailErrorStrategy (org.antlr.v4.runtime.BailErrorStrategy)6 Tree (org.antlr.v4.runtime.tree.Tree)6 IOException (java.io.IOException)5 Method (java.lang.reflect.Method)4 Tree (org.antlr.runtime.tree.Tree)4 ParserInterpreter (org.antlr.v4.runtime.ParserInterpreter)4 Rectangle2D (java.awt.geom.Rectangle2D)3 FileInputStream (java.io.FileInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 Map (java.util.Map)3 GrammarASTAdaptor (org.antlr.v4.parse.GrammarASTAdaptor)3