eppleton commented on code in PR #9691:
URL: https://github.com/apache/netbeans/pull/9691#discussion_r4259678590


##########
java/debugger.jpda.ui/src/org/netbeans/modules/debugger/jpda/ui/BreakpointOutput.java:
##########
@@ -373,67 +377,99 @@ private String substitute (String printText, 
JPDABreakpointEvent event) {
         }
              
         // 5) resolve all expressions {=expression}
+        printExpressions(event, printText, (msg, action) -> {
+            io.printWithAction(msg, action, false);
+        }, (msg) -> {
+            io.println(msg, null);
+        });
+    }
+
+    /* Processing all expressions. Expressions take form of {=expression}.
+    * Invoked from {@code BreakpointOutputTest}.
+    */
+    final void printExpressions(
+        JPDABreakpointEvent event,
+        String message,
+        BiConsumer<String, Runnable> print,
+        Consumer<String> println
+    ) {
+        String printText = message;
+        Session session = event.getDebugger().getSession();
+        var dumpErrors = new ArrayList<Runnable>();
         for (;;) {
             Matcher m = expressionPattern.matcher (printText);
             if (!m.find ()) {
                 break;
             }
             String expression = m.group (1);
-            String value = "";
             try {
                 JPDADebugger theDebugger;
                 synchronized (lock) {
                     if (debugger == null) {
-                        return value; // The debugger is gone
+                        // The debugger is gone
+                        return;
                     }
                     theDebugger = debugger;
                 }
+
+                String beforeExpression = printText.substring(0, m.start());
+                print.accept(beforeExpression, null);
+
                 CallStackFrame csf = null;
-                if (t != null && !isThreadDeath) {
+                JPDAThread t = event.getThread();
+                if (t != null && !event.isThreadDeath()) {
                     try {
                         CallStackFrame[] topFramePtr = t.getCallStack(0, 1);
                         if (topFramePtr.length > 0) {
                             csf = topFramePtr[0];
                         }
                     } catch (AbsentInformationException aiex) {}
                 }
-                try {
-                value = ((Variable) 
theDebugger.getClass().getMethod("evaluate", String.class, 
CallStackFrame.class).
-                        invoke(theDebugger, expression, csf)).getValue();
-                } catch (InvocationTargetException itex) {
-                    if (itex.getTargetException() instanceof 
InvalidExpressionException) {
-                        throw (InvalidExpressionException) 
itex.getTargetException();
-                    }
-                } catch (Exception ex) {
-                    Exceptions.printStackTrace(ex);
+                Variable refValue = theDebugger.evaluate(expression, csf);

Review Comment:
   Before this PR, `evaluate` was called through reflection, and anything that 
wasn't an `InvalidExpressionException` was caught (`catch (Exception ex)`). Now 
only `InvalidExpressionException` is caught, so runtime exceptions thrown by 
the evaluator escape.
   
   I tried `{=i/0}` in a local copy of `BreakpointOutputTest`: an 
`ArithmeticException` ("/ by zero", from `EvaluatorVisitor.visitBinary`) 
propagates out of `printExpressions`. The rest of the log line is never 
printed, and the exception ends up in the breakpoint listener chain. Errors 
raised in the target VM (e.g. `{=when.substring(99)}`) still arrive as 
`InvalidExpressionException` and are printed nicely.
   
   Maybe also catch `RuntimeException` here and treat it like an invalid 
expression?



##########
java/debugger.jpda.ui/test/unit/src/org/netbeans/modules/debugger/jpda/ui/BreakpointOutputTest.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.netbeans.modules.debugger.jpda.ui;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import junit.framework.Test;
+import org.netbeans.api.debugger.DebuggerManager;
+import org.netbeans.api.debugger.Session;
+import org.netbeans.api.debugger.jpda.ExceptionBreakpoint;
+import org.netbeans.api.debugger.jpda.JPDADebugger;
+import org.netbeans.api.debugger.jpda.JPDASupport;
+import org.netbeans.api.debugger.jpda.LineBreakpoint;
+import org.netbeans.api.debugger.jpda.MethodBreakpoint;
+import org.netbeans.api.debugger.jpda.event.JPDABreakpointEvent;
+import org.netbeans.api.debugger.jpda.event.JPDABreakpointListener;
+import org.netbeans.junit.NbTestCase;
+import org.openide.util.Pair;
+import org.openide.util.Utilities;
+
+/** Testing {@link BreakpointOutput#printExpressions}
+ */
+public class BreakpointOutputTest extends NbTestCase {
+
+    public BreakpointOutputTest(String name) {
+        super(name);
+    }
+
+    public static Test suite() {
+        return JPDASupport.createTestSuite(BreakpointOutputTest.class);
+    }
+
+    public void testBreakpointOutputLinks() throws Throwable {
+        ExceptionBreakpoint breakPoint = ExceptionBreakpoint.create(
+            "java.lang.IllegalStateException",
+            ExceptionBreakpoint.TYPE_EXCEPTION_CAUGHT_UNCAUGHT
+        );
+        JPDABreakpointListener[] onBreakpoint = { null };
+        breakPoint.addJPDABreakpointListener((event) -> {
+            onBreakpoint[0].breakpointReached(event);
+        });
+        DebuggerManager.getDebuggerManager().addBreakpoint(breakPoint);
+
+        final URI cpUrl = 
test.SampleMain.class.getProtectionDomain().getCodeSource().getLocation().toURI();
+        System.setProperty ("test.dir.src", findSourcePath());
+        JPDASupport support = JPDASupport.attach(new String[0], 
"test.SampleMain", new String[0], new File[] {
+            Utilities.toFile(cpUrl)
+        });
+        final Session session = support.getDebugger().getSession();
+
+        //
+        // now the real test and collect the printed messages
+        //
+
+        var collected = new StringWriter();
+        var writer = new PrintWriter(collected);
+        var format = "breakpoint hit {=i}, {=when}, {=arr}, {=obj}";
+        BreakpointOutput out = new BreakpointOutput(session);
+        onBreakpoint[0] = (event) -> {
+            writer.append("on 
").append(event.getThread().getName()).append("\n");
+            try {
+                printExpressions(out, event, format, (msg, action) -> {
+                    if (action != null) {
+                        writer.append("<a ");
+                    }
+                    writer.append(msg);
+                    if (action != null) {
+                        writer.append(">");
+                    }
+                }, (msg) -> {
+                    writer.append(msg).append("\n");
+                });
+            } catch (ReflectiveOperationException ex) {
+                ex.printStackTrace(writer);
+            }
+        };
+
+        //
+        // launch the debugger and run the test
+        //
+
+        for (;;) {
+            support.waitState(JPDADebugger.STATE_STOPPED);
+            if (support.getDebugger().getState() == 
JPDADebugger.STATE_DISCONNECTED) {
+                break;
+            }
+            support.doContinue();
+        }
+
+        //
+        // verify result
+        //
+        assertEquals("""
+        on main
+        breakpoint hit 42, <a "Now">, <a #94(length=1)>, <a class 
test.SampleMain>

Review Comment:
   This fails for me: the array's unique ID is `#396` here, not `#94` (JDK 21, 
macOS). The ID depends on how many objects the debugger has seen before, so it 
changes with the JDK and environment. Maybe match the ID with a regex, or take 
it from the evaluated `ObjectVariable`?



##########
java/debugger.jpda.ui/test/unit/src/org/netbeans/modules/debugger/jpda/ui/BreakpointOutputTest.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.netbeans.modules.debugger.jpda.ui;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import junit.framework.Test;
+import org.netbeans.api.debugger.DebuggerManager;
+import org.netbeans.api.debugger.Session;
+import org.netbeans.api.debugger.jpda.ExceptionBreakpoint;
+import org.netbeans.api.debugger.jpda.JPDADebugger;
+import org.netbeans.api.debugger.jpda.JPDASupport;
+import org.netbeans.api.debugger.jpda.LineBreakpoint;
+import org.netbeans.api.debugger.jpda.MethodBreakpoint;
+import org.netbeans.api.debugger.jpda.event.JPDABreakpointEvent;
+import org.netbeans.api.debugger.jpda.event.JPDABreakpointListener;
+import org.netbeans.junit.NbTestCase;
+import org.openide.util.Pair;
+import org.openide.util.Utilities;
+
+/** Testing {@link BreakpointOutput#printExpressions}
+ */
+public class BreakpointOutputTest extends NbTestCase {
+
+    public BreakpointOutputTest(String name) {
+        super(name);
+    }
+
+    public static Test suite() {
+        return JPDASupport.createTestSuite(BreakpointOutputTest.class);
+    }
+
+    public void testBreakpointOutputLinks() throws Throwable {
+        ExceptionBreakpoint breakPoint = ExceptionBreakpoint.create(
+            "java.lang.IllegalStateException",
+            ExceptionBreakpoint.TYPE_EXCEPTION_CAUGHT_UNCAUGHT
+        );
+        JPDABreakpointListener[] onBreakpoint = { null };
+        breakPoint.addJPDABreakpointListener((event) -> {
+            onBreakpoint[0].breakpointReached(event);
+        });
+        DebuggerManager.getDebuggerManager().addBreakpoint(breakPoint);
+
+        final URI cpUrl = 
test.SampleMain.class.getProtectionDomain().getCodeSource().getLocation().toURI();
+        System.setProperty ("test.dir.src", findSourcePath());
+        JPDASupport support = JPDASupport.attach(new String[0], 
"test.SampleMain", new String[0], new File[] {
+            Utilities.toFile(cpUrl)
+        });
+        final Session session = support.getDebugger().getSession();
+
+        //
+        // now the real test and collect the printed messages
+        //
+
+        var collected = new StringWriter();
+        var writer = new PrintWriter(collected);
+        var format = "breakpoint hit {=i}, {=when}, {=arr}, {=obj}";
+        BreakpointOutput out = new BreakpointOutput(session);
+        onBreakpoint[0] = (event) -> {
+            writer.append("on 
").append(event.getThread().getName()).append("\n");
+            try {
+                printExpressions(out, event, format, (msg, action) -> {
+                    if (action != null) {
+                        writer.append("<a ");
+                    }
+                    writer.append(msg);
+                    if (action != null) {
+                        writer.append(">");
+                    }
+                }, (msg) -> {
+                    writer.append(msg).append("\n");
+                });
+            } catch (ReflectiveOperationException ex) {
+                ex.printStackTrace(writer);
+            }
+        };
+
+        //
+        // launch the debugger and run the test
+        //
+
+        for (;;) {
+            support.waitState(JPDADebugger.STATE_STOPPED);
+            if (support.getDebugger().getState() == 
JPDADebugger.STATE_DISCONNECTED) {
+                break;
+            }
+            support.doContinue();
+        }
+
+        //
+        // verify result
+        //
+        assertEquals("""
+        on main
+        breakpoint hit 42, <a "Now">, <a #94(length=1)>, <a class 
test.SampleMain>
+        """, collected.toString());
+    }
+
+    private String findSourcePath() throws IOException {
+        File curDir = getWorkDir();
+        for (;;) {
+            var testSrc = new File(new File(new File(curDir, "test"), "unit"), 
"src");
+            if (testSrc.isDirectory()) {
+                return testSrc.getPath();
+            }
+            curDir = curDir.getParentFile();

Review Comment:
   Nit: if `test/unit/src` is never found, `getParentFile()` eventually returns 
`null` and this ends in an NPE. A clearer failure message would help.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to