Consider allowing formatting in the presence of non-syntactic errors from the parser #59923
Description
Currently the formatter refuses to format if the file being formatted has any errors that came from the parser. The reason for this is because in general, the parser's error recovery process may lead to malformed ASTs, ASTs that don't reflect the token stream, or ASTs that don't reflect the user's intent, and trying to format based on such an AST would probably lead to a poor user experience.
However, there are some errors that are reported by the parser not because they are syntax errors per se, but simply because they are errors that are easy for the parser to detect and report. Prohibiting formatting in the presence of these non-syntactic errors causes its own user experience problems, by preventing the user from getting the benefit of auto-formatting until they have fixed them. We should consider allowing formatting even in the presence of these non-syntactic errors.
Note that deciding precisely which errors are safe to allow might require careful consideration. To name a particular subtle example that came up in discussion this morning, we believe that the parser recovers from a syntax error like final static int? foo;
by assuming it's equivalent to static final int? foo;
. In a sense, we can think of this as the parser accepting a broader grammar than what the language specification strictly allows, and so we can think of this as a non-syntactic error. But the AST that it produces in response would cause the formatter to output static final int? foo;
(essentially "correcting" the error without user consent). We think that having the formatter make corrections like this is a risky proposition. For example, what if the reason the user's code says final static int? foo;
is because they have a field static int? foo;
, and they are in the process of adding another field above it, that starts with final
? In this case if the formatter "fixed" the code by rewriting it to static final int? foo;
, that would be frustrating.