allwpilib
allwpilib copied to clipboard
Use Java StackWalker API instead of custom logic
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.
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)
- Most of our usages of
getStackTrace()are from reporting the stack trace of an already thrown exception. However, the StackOverflow post linked above indicates thatStackWalkercan't be used to process the stack trace of an already thrown exception, soDriverStation.reportError()andMathSharedStore.reportError()have to keep theStackTraceElement[]parameter for that use case. We could makeDriverStation.reportError(String error, boolean printTrace)overload useStackWalker, but that would lead to code duplication since we still need the logic for theStackTraceElement[]case. - 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).