Bug 203020

Summary: formatter may change code semantics on unary operators
Product: [Eclipse Project] JDT Reporter: Ralf Ullrich <ru>
Component: CoreAssignee: Olivier Thomann <Olivier_Thomann>
Status: VERIFIED FIXED QA Contact:
Severity: normal    
Priority: P3 CC: david_audel, Olivier_Thomann, ru
Version: 3.3   
Target Milestone: 3.4 M2   
Hardware: PC   
OS: Windows XP   
Whiteboard:

Description Ralf Ullrich CLA 2007-09-11 22:15:47 EDT
Build ID: I20070621-1340

Steps To Reproduce:
1. Use this sample code:

public class AmbiguousSyntaxDemo {

    @SuppressWarnings("boxing")
    public static void main(String[] args) {
        int i = 2;
        int a = 3;
        int b = a + -(-i);
        int c = a + - -i;
        int d = a + --i;
        System.out.printf("a=%d b=%d c=%d d=%d i=%d%n", a, b, c, d, i);
    }
}

2. Ensure formatter preferences for spaces in expressions on unary operators are set to _not_ insert spaces.

3. Format the code (Ctrl-Shift-F) and watch what happens to the assignment to "c".

More information:
On code like this:

        int c = a + - -i;

the formatter will change the assignment to "c" from "a + - - i" to "a + --i" if the formatter preferences for unary operators are set to not insert a space before or after the unary operator, as they are set with the eclipse defaults.

The formatter should not have to rely on the formatter preferences to produce semantically identical code after formatting is applied. Hence the formatter should always insert a space between two consecutive unary minus operators, regardless of the preferences.

The unary plus operator has the same problem:
        int b = a + +( +i);
        int c = a + + +i;
        int d = a + ++i;

Workarounds: of course one could (and probably should) use parentheses in such an ambiguous case of unary operator use. Also the bug does not manifest when formatter preferences are set to insert a space either before or after unary operators.
Comment 1 Olivier Thomann CLA 2007-09-12 10:09:49 EDT
Released for 3.4M2.
Regression tests added in org.eclipse.jdt.core.tests.formatter.FormatterRegressionTests#test669
org.eclipse.jdt.core.tests.formatter.FormatterRegressionTests#test670
Comment 2 David Audel CLA 2007-09-18 04:25:14 EDT
Verified for 3.4M2 using build I20070917-0010