Skip to content

Commit 893c295

Browse files
committed
[Format] Fix detection of languages when reading from stdin
1 parent d7fb9eb commit 893c295

File tree

3 files changed

+26
-11
lines changed

3 files changed

+26
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// RUN: clang-format -dump-config - < %s | FileCheck %s
2+
3+
// CHECK: Language: ObjC
4+
@interface Foo
5+
@end

clang/tools/clang-format/ClangFormat.cpp

+13-11
Original file line numberDiff line numberDiff line change
@@ -547,18 +547,20 @@ static void PrintVersion(raw_ostream &OS) {
547547
// Dump the configuration.
548548
static int dumpConfig(bool IsSTDIN) {
549549
std::unique_ptr<llvm::MemoryBuffer> Code;
550-
// We can't read the code to detect the language if there's no file name.
551-
if (!IsSTDIN) {
552-
// Read in the code in case the filename alone isn't enough to detect the
553-
// language.
554-
ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
555-
MemoryBuffer::getFileOrSTDIN(FileNames[0]);
556-
if (std::error_code EC = CodeOrErr.getError()) {
557-
llvm::errs() << EC.message() << "\n";
558-
return 1;
559-
}
560-
Code = std::move(CodeOrErr.get());
550+
551+
// `FileNames` must have at least "-" in it even if no file was specified.
552+
assert(!FileNames.empty());
553+
554+
// Read in the code in case the filename alone isn't enough to detect the
555+
// language.
556+
ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
557+
MemoryBuffer::getFileOrSTDIN(FileNames[0]);
558+
if (std::error_code EC = CodeOrErr.getError()) {
559+
llvm::errs() << EC.message() << "\n";
560+
return 1;
561561
}
562+
Code = std::move(CodeOrErr.get());
563+
562564
llvm::Expected<clang::format::FormatStyle> FormatStyle =
563565
clang::format::getStyle(Style, IsSTDIN ? AssumeFileName : FileNames[0],
564566
FallbackStyle, Code ? Code->getBuffer() : "");

clang/unittests/Format/FormatTestObjC.cpp

+8
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,14 @@ class FormatTestObjC : public FormatTestBase {
3131
_verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
3232
#define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
3333

34+
TEST(FormatTestObjCStyle, DetectsObjCInStdin) {
35+
auto Style = getStyle("LLVM", "<stdin>", "none",
36+
"@interface\n"
37+
"- (id)init;");
38+
ASSERT_TRUE((bool)Style);
39+
EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
40+
}
41+
3442
TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
3543
auto Style = getStyle("LLVM", "a.h", "none",
3644
"@interface\n"

0 commit comments

Comments
 (0)