Index: lib/Format/Format.cpp =================================================================== --- lib/Format/Format.cpp +++ lib/Format/Format.cpp @@ -1303,6 +1303,27 @@ unsigned> PenaltyCache; }; +static bool isCommentWithText(const FormatToken &Tok, const StringRef &Text) { + if (!Tok.is(tok::comment)) + return false; + + StringRef CommentText(Tok.TokenText); + + if (CommentText.startswith("/*") && CommentText.endswith("*/")) { + // C-style comment + std::size_t LeftBound = 2; + std::size_t RightBound = CommentText.size() - 2; + LeftBound = CommentText.find_first_not_of('*', LeftBound); + CommentText = CommentText.slice(LeftBound, RightBound); + } + if (CommentText.startswith("//")) { + // C++-style inline comment + std::size_t TextPos = CommentText.find_first_not_of('/'); + CommentText = CommentText.substr(TextPos); + } + return CommentText.trim() == Text; +} + class FormatTokenLexer { public: FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style, @@ -1725,10 +1746,10 @@ Tok.Tok.setKind(tok::char_constant); } } - if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format on") + if (isCommentWithText(Tok, "clang-format on")) FormattingDisabled = false; Tok.Finalized = FormattingDisabled; - if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format off") + if (isCommentWithText(Tok, "clang-format off")) FormattingDisabled = true; } }; Index: unittests/Format/FormatTest.cpp =================================================================== --- unittests/Format/FormatTest.cpp +++ unittests/Format/FormatTest.cpp @@ -9355,6 +9355,37 @@ " int j;\n" " // clang-format on\n" " int k;")); + EXPECT_EQ("int i;\n" + "/// clang-format off\n" + " int j;\n" + "/// clang-format on\n" + "int k;", + format(" int i;\n" + " /// clang-format off\n" + " int j;\n" + " /// clang-format on\n" + " int k;")); + EXPECT_EQ("int i;\n" + "/* clang-format off */\n" + " int j;\n" + "/* clang-format on */\n" + "int k;", + format(" int i;\n" + " /* clang-format off */\n" + " int j;\n" + " /* clang-format on */\n" + " int k;")); + EXPECT_EQ("int i;\n" + "/** clang-format off */\n" + " int j;\n" + "/** clang-format on */\n" + "int k;", + format(" int i;\n" + " /** clang-format off */\n" + " int j;\n" + " /** clang-format on */\n" + " int k;")); + } TEST_F(FormatTest, DoNotCrashOnInvalidInput) {