eclipse-cdt / cdt

Eclipse CDT™ C/C++ Development Tools
http://eclipse.org/cdt
Eclipse Public License 2.0
299 stars 198 forks source link

Formatter breaks code containing macros #121

Open iloveeclipse opened 1 year ago

iloveeclipse commented 1 year ago

Using C/C++ Development Tools SDK 10.7.1.202208222120.

/*
 * CodeFormatTest.cpp
 */
#define s
#define ms *1.0
class CodeFormatTest{
public:
        void methodWithParam(double d){

        }

        void test(){
                methodWithParam(1 s);
                methodWithParam(1 ms);
        }

};

This will produce this (broken, not compilable) code (note missing space between 1 and ms inside methodWithParam(1ms);)

/*
 * CodeFormatTest.cpp
 */
#define s
#define ms *1.0
class CodeFormatTest {
public:
  void methodWithParam(double d)
  {

  }

  void test()
  {
    methodWithParam(1 s);
    methodWithParam(1ms);
  }

};

image

jonahgraham commented 1 year ago

Here is a test to add to CodeFormatterTest for anyone planning on working on this:

Test code ```java //#define s //#define ms *1.0 //class CodeFormatTest{ //public: // void methodWithParam(double d){ // // } // // void test(){ // methodWithParam(1 s); // methodWithParam(1 ms); // } // //}; //#define s //#define ms *1.0 //class CodeFormatTest { //public: // void methodWithParam(double d) { // // } // // void test() { // methodWithParam(1 s); // methodWithParam(1 ms); // } // //}; public void testIssue121() throws Exception { assertFormatterResult(); } ```
The above test fails with this stack trace ```java junit.framework.ComparisonFailure: expected:<... methodWithParam(1[ ]ms); } }; > but was:<... methodWithParam(1[]ms); } }; > at junit.framework.Assert.assertEquals(Assert.java:100) at junit.framework.Assert.assertEquals(Assert.java:107) at junit.framework.TestCase.assertEquals(TestCase.java:260) at org.eclipse.cdt.ui.tests.text.CodeFormatterTest.assertFormatterResult(CodeFormatterTest.java:75) at org.eclipse.cdt.ui.tests.text.CodeFormatterTest.assertFormatterResult(CodeFormatterTest.java:66) at org.eclipse.cdt.ui.tests.text.CodeFormatterTest.testIssue121(CodeFormatterTest.java:4851) ```

This may be a good fix to work on for someone new to the CDT code base as this code is reasonably well tested and well contained. See these packages for the main part of the code formatter code:

jonahgraham commented 1 year ago

Some more useful reference - Bug 268962 is a similar class of bug and at the time Anton who was very familiar with the code base, said:

Macros can easily pose a problem for the formatter, esp. when they span only parts of a syntactic element. There are some heuristics in place, but a general solution is difficult.