1 //===- unittest/Format/FormatTestUtils.h - Formatting unit tests ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines utility functions for Clang-Format related tests.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_UNITTESTS_FORMAT_FORMATTESTUTILS_H
14 #define LLVM_CLANG_UNITTESTS_FORMAT_FORMATTESTUTILS_H
15 
16 #include "llvm/ADT/StringRef.h"
17 
18 namespace clang {
19 namespace format {
20 namespace test {
21 
messUp(llvm::StringRef Code)22 inline std::string messUp(llvm::StringRef Code) {
23   std::string MessedUp(Code.str());
24   bool InComment = false;
25   bool InPreprocessorDirective = false;
26   bool JustReplacedNewline = false;
27   for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
28     if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
29       if (JustReplacedNewline)
30         MessedUp[i - 1] = '\n';
31       InComment = true;
32     } else if (MessedUp[i] == '#' &&
33                (JustReplacedNewline || i == 0 || MessedUp[i - 1] == '\n')) {
34       if (i != 0)
35         MessedUp[i - 1] = '\n';
36       InPreprocessorDirective = true;
37     } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
38       MessedUp[i] = ' ';
39       MessedUp[i + 1] = ' ';
40     } else if (MessedUp[i] == '\n') {
41       if (InComment) {
42         InComment = false;
43       } else if (InPreprocessorDirective) {
44         InPreprocessorDirective = false;
45       } else {
46         JustReplacedNewline = true;
47         MessedUp[i] = ' ';
48       }
49     } else if (MessedUp[i] != ' ') {
50       JustReplacedNewline = false;
51     }
52   }
53   std::string WithoutWhitespace;
54   if (MessedUp[0] != ' ')
55     WithoutWhitespace.push_back(MessedUp[0]);
56   for (unsigned i = 1, e = MessedUp.size(); i != e; ++i) {
57     if (MessedUp[i] != ' ' || MessedUp[i - 1] != ' ')
58       WithoutWhitespace.push_back(MessedUp[i]);
59   }
60   return WithoutWhitespace;
61 }
62 
63 } // end namespace test
64 } // end namespace format
65 } // end namespace clang
66 
67 #endif
68