diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp --- a/clang/lib/Lex/PPDirectives.cpp +++ b/clang/lib/Lex/PPDirectives.cpp @@ -595,6 +595,9 @@ CurPPLexer->LexingRawMode = false; IdentifierInfo *IfNDefMacro = nullptr; DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro); + // Stop if Lexer became invalid after hitting code completion token. + if (!CurPPLexer) + return; const bool CondValue = DER.Conditional; CurPPLexer->LexingRawMode = true; if (Callbacks) { @@ -3023,6 +3026,10 @@ IdentifierInfo *IfNDefMacro = nullptr; const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro); const bool ConditionalTrue = DER.Conditional; + // Lexer might become invalid if we hit code completion point while evaluating + // expression. + if (!CurPPLexer) + return; // If this condition is equivalent to #ifndef X, and if this is the first // directive seen, handle it for the multiple-include optimization. diff --git a/clang/test/CodeCompletion/crash-if-directive.cpp b/clang/test/CodeCompletion/crash-if-directive.cpp new file mode 100644 --- /dev/null +++ b/clang/test/CodeCompletion/crash-if-directive.cpp @@ -0,0 +1,6 @@ +#define FOO(X) X +#if FOO( +#elif FOO( +#endif +// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:2:9 %s +// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:3:11 %s