Bug 203020 - formatter may change code semantics on unary operators
Summary: formatter may change code semantics on unary operators
Status: VERIFIED FIXED
Alias: None
Product: JDT
Classification: Eclipse Project
Component: Core (show other bugs)
Version: 3.3   Edit
Hardware: PC Windows XP
: P3 normal (vote)
Target Milestone: 3.4 M2   Edit
Assignee: Olivier Thomann CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2007-09-11 22:15 EDT by Ralf Ullrich CLA
Modified: 2007-09-18 04:25 EDT (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
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