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 
22 // When HandleHash is false, preprocessor directives starting with hash will not
23 // be on separate lines.  This is needed because Verilog uses hash for other
24 // purposes.
25 inline std::string messUp(llvm::StringRef Code, bool HandleHash = true) {
26   std::string MessedUp(Code.str());
27   bool InComment = false;
28   bool InPreprocessorDirective = false;
29   bool JustReplacedNewline = false;
30   for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
31     if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
32       if (JustReplacedNewline)
33         MessedUp[i - 1] = '\n';
34       InComment = true;
35     } else if (HandleHash && MessedUp[i] == '#' &&
36                (JustReplacedNewline || i == 0 || MessedUp[i - 1] == '\n')) {
37       if (i != 0)
38         MessedUp[i - 1] = '\n';
39       InPreprocessorDirective = true;
40     } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
41       MessedUp[i] = ' ';
42       MessedUp[i + 1] = ' ';
43     } else if (MessedUp[i] == '\n') {
44       if (InComment) {
45         InComment = false;
46       } else if (InPreprocessorDirective) {
47         InPreprocessorDirective = false;
48       } else {
49         JustReplacedNewline = true;
50         MessedUp[i] = ' ';
51       }
52     } else if (MessedUp[i] != ' ') {
53       JustReplacedNewline = false;
54     }
55   }
56   std::string WithoutWhitespace;
57   if (MessedUp[0] != ' ')
58     WithoutWhitespace.push_back(MessedUp[0]);
59   for (unsigned i = 1, e = MessedUp.size(); i != e; ++i)
60     if (MessedUp[i] != ' ' || MessedUp[i - 1] != ' ')
61       WithoutWhitespace.push_back(MessedUp[i]);
62   return WithoutWhitespace;
63 }
64 
65 } // end namespace test
66 } // end namespace format
67 } // end namespace clang
68 
69 #endif
70