allwpilib icon indicating copy to clipboard operation
allwpilib copied to clipboard

Use Java StackWalker API instead of custom logic

Open Starlight220 opened this issue 1 year ago • 1 comments

Apparently Java has a stackwalking API: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/StackWalker.html

We currently do the logic inline (for example, in the scheduler code) via an Exception.getStackTrace().

This API is more ergonomic and is supposedly more efficient.

Starlight220 avatar May 17 '24 15:05 Starlight220

Based on https://stackoverflow.com/questions/66122388/is-it-possible-to-walk-stack-frames-from-an-exception and looking through the StackWalker docs, I'm not sure the complete issue would be feasible. (We can do some parts of it but not all of it)

  1. Most of our usages of getStackTrace() are from reporting the stack trace of an already thrown exception. However, the StackOverflow post linked above indicates that StackWalker can't be used to process the stack trace of an already thrown exception, so DriverStation.reportError() and MathSharedStore.reportError() have to keep the StackTraceElement[] parameter for that use case. We could make DriverStation.reportError(String error, boolean printTrace) overload use StackWalker, but that would lead to code duplication since we still need the logic for the StackTraceElement[] case.
  2. This isn't the main point of this issue, but the efficiency seems to be from not having to create all of the stack trace elements, but because our usages of the stack traces are reporting errors, we have to process all of the stack trace elements anyways. (The only elements we skip are from the top of the stack, which means that the walker still has to create all of the elements for us to either determine we should skip or to report in the (processed) stack trace)

Summary: We could use StackWalker for DriverStation.reportError(String error, boolean printTrace), but that would lead to code duplication. If we want to use the stream API for more ergonomic processing, we could stream the array of stack trace elements (though that would add the stream API's overhead).

KangarooKoala avatar May 17 '24 21:05 KangarooKoala