Streamlining OpenSCAD Code
I have written compilers and optimizers, as well as optimizers which work on raster operations.  I so want to offer you a beautiful solution, but I don't know of one.

If I really wanted to solve this, I would start with this approach:

First, identify each token and expression in the OpenSCAD code.  Assign each a unique identifier, and reserve one bit of storage, initially zeroed, that will be used later.

At the geometric database level, tag each geometric element with the identifier in the source code that generates it.  Intersections become labeled with both operands and the intersection operator.  Same with unions and other operations.

Then render the OpenSCAD form into some representation, perhaps voxels, perhaps STL.  Voxels have a resolution limit but are intrinsically the simplest form.  STLs might require an optimization pass to find redundant edges -- although that may already be part of STL generation process.

Now, go through the tagged representation voxel by voxel or triangle by triangle.  Set the bit reserved with every token and expression to "one" for every identifier associated with that voxel or trianble.

Finally, check the bits on each of the source tokens and expressions.  If the bit is zero, that particular element contributed nothing to the result.  If the bit is one, that is needed in the result.

This is oversimplified because one source element can be used several times.  Some may contribute to the output, and some may not.  A fully expanded version of the source should be used, and we have to invent notation for reporting that instance 1 and 3 is used but 2 is not.  I'm sure there are other over-simplifications which someone reading this will immediately realize.

I think, though, that this would be a path forward to the OpenSCAD optimizer you want.

In the meantime, OpenSCAD provides some prefix characters.  One of the, maybe "*", removes a sub-tree from the generated geometry without messing up the parsing.  I frequently use that mark to find out if code is used and to what it contributes.