FormatTestUtils.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. #ifndef LLVM_CLANG_UNITTESTS_FORMAT_FORMATTESTUTILS_H
  13. #define LLVM_CLANG_UNITTESTS_FORMAT_FORMATTESTUTILS_H
  14. #include "llvm/ADT/StringRef.h"
  15. namespace clang {
  16. namespace format {
  17. namespace test {
  18. inline std::string messUp(llvm::StringRef Code) {
  19. std::string MessedUp(Code.str());
  20. bool InComment = false;
  21. bool InPreprocessorDirective = false;
  22. bool JustReplacedNewline = false;
  23. for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
  24. if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
  25. if (JustReplacedNewline)
  26. MessedUp[i - 1] = '\n';
  27. InComment = true;
  28. } else if (MessedUp[i] == '#' &&
  29. (JustReplacedNewline || i == 0 || MessedUp[i - 1] == '\n')) {
  30. if (i != 0)
  31. MessedUp[i - 1] = '\n';
  32. InPreprocessorDirective = true;
  33. } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
  34. MessedUp[i] = ' ';
  35. MessedUp[i + 1] = ' ';
  36. } else if (MessedUp[i] == '\n') {
  37. if (InComment) {
  38. InComment = false;
  39. } else if (InPreprocessorDirective) {
  40. InPreprocessorDirective = false;
  41. } else {
  42. JustReplacedNewline = true;
  43. MessedUp[i] = ' ';
  44. }
  45. } else if (MessedUp[i] != ' ') {
  46. JustReplacedNewline = false;
  47. }
  48. }
  49. std::string WithoutWhitespace;
  50. if (MessedUp[0] != ' ')
  51. WithoutWhitespace.push_back(MessedUp[0]);
  52. for (unsigned i = 1, e = MessedUp.size(); i != e; ++i) {
  53. if (MessedUp[i] != ' ' || MessedUp[i - 1] != ' ')
  54. WithoutWhitespace.push_back(MessedUp[i]);
  55. }
  56. return WithoutWhitespace;
  57. }
  58. } // end namespace test
  59. } // end namespace format
  60. } // end namespace clang
  61. #endif