Path: blob/main/contrib/llvm-project/clang/lib/Basic/Diagnostic.cpp
35234 views
//===- Diagnostic.cpp - C Language Family Diagnostic Handling -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Diagnostic-related interfaces.9//10//===----------------------------------------------------------------------===//1112#include "clang/Basic/Diagnostic.h"13#include "clang/Basic/CharInfo.h"14#include "clang/Basic/DiagnosticError.h"15#include "clang/Basic/DiagnosticIDs.h"16#include "clang/Basic/DiagnosticOptions.h"17#include "clang/Basic/IdentifierTable.h"18#include "clang/Basic/PartialDiagnostic.h"19#include "clang/Basic/SourceLocation.h"20#include "clang/Basic/SourceManager.h"21#include "clang/Basic/Specifiers.h"22#include "clang/Basic/TokenKinds.h"23#include "llvm/ADT/SmallString.h"24#include "llvm/ADT/SmallVector.h"25#include "llvm/ADT/StringExtras.h"26#include "llvm/ADT/StringRef.h"27#include "llvm/Support/ConvertUTF.h"28#include "llvm/Support/CrashRecoveryContext.h"29#include "llvm/Support/Unicode.h"30#include "llvm/Support/raw_ostream.h"31#include <algorithm>32#include <cassert>33#include <cstddef>34#include <cstdint>35#include <cstring>36#include <limits>37#include <string>38#include <utility>39#include <vector>4041using namespace clang;4243const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,44DiagNullabilityKind nullability) {45DB.AddString(46("'" +47getNullabilitySpelling(nullability.first,48/*isContextSensitive=*/nullability.second) +49"'")50.str());51return DB;52}5354const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,55llvm::Error &&E) {56DB.AddString(toString(std::move(E)));57return DB;58}5960static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,61StringRef Modifier, StringRef Argument,62ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,63SmallVectorImpl<char> &Output,64void *Cookie,65ArrayRef<intptr_t> QualTypeVals) {66StringRef Str = "<can't format argument>";67Output.append(Str.begin(), Str.end());68}6970DiagnosticsEngine::DiagnosticsEngine(71IntrusiveRefCntPtr<DiagnosticIDs> diags,72IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, DiagnosticConsumer *client,73bool ShouldOwnClient)74: Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {75setClient(client, ShouldOwnClient);76ArgToStringFn = DummyArgToStringFn;7778Reset();79}8081DiagnosticsEngine::~DiagnosticsEngine() {82// If we own the diagnostic client, destroy it first so that it can access the83// engine from its destructor.84setClient(nullptr);85}8687void DiagnosticsEngine::dump() const {88DiagStatesByLoc.dump(*SourceMgr);89}9091void DiagnosticsEngine::dump(StringRef DiagName) const {92DiagStatesByLoc.dump(*SourceMgr, DiagName);93}9495void DiagnosticsEngine::setClient(DiagnosticConsumer *client,96bool ShouldOwnClient) {97Owner.reset(ShouldOwnClient ? client : nullptr);98Client = client;99}100101void DiagnosticsEngine::pushMappings(SourceLocation Loc) {102DiagStateOnPushStack.push_back(GetCurDiagState());103}104105bool DiagnosticsEngine::popMappings(SourceLocation Loc) {106if (DiagStateOnPushStack.empty())107return false;108109if (DiagStateOnPushStack.back() != GetCurDiagState()) {110// State changed at some point between push/pop.111PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);112}113DiagStateOnPushStack.pop_back();114return true;115}116117void DiagnosticsEngine::Reset(bool soft /*=false*/) {118ErrorOccurred = false;119UncompilableErrorOccurred = false;120FatalErrorOccurred = false;121UnrecoverableErrorOccurred = false;122123NumWarnings = 0;124NumErrors = 0;125TrapNumErrorsOccurred = 0;126TrapNumUnrecoverableErrorsOccurred = 0;127128CurDiagID = std::numeric_limits<unsigned>::max();129LastDiagLevel = DiagnosticIDs::Ignored;130DelayedDiagID = 0;131132if (!soft) {133// Clear state related to #pragma diagnostic.134DiagStates.clear();135DiagStatesByLoc.clear();136DiagStateOnPushStack.clear();137138// Create a DiagState and DiagStatePoint representing diagnostic changes139// through command-line.140DiagStates.emplace_back();141DiagStatesByLoc.appendFirst(&DiagStates.back());142}143}144145void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,146StringRef Arg2, StringRef Arg3) {147if (DelayedDiagID)148return;149150DelayedDiagID = DiagID;151DelayedDiagArg1 = Arg1.str();152DelayedDiagArg2 = Arg2.str();153DelayedDiagArg3 = Arg3.str();154}155156void DiagnosticsEngine::ReportDelayed() {157unsigned ID = DelayedDiagID;158DelayedDiagID = 0;159Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;160}161162DiagnosticMapping &163DiagnosticsEngine::DiagState::getOrAddMapping(diag::kind Diag) {164std::pair<iterator, bool> Result =165DiagMap.insert(std::make_pair(Diag, DiagnosticMapping()));166167// Initialize the entry if we added it.168if (Result.second)169Result.first->second = DiagnosticIDs::getDefaultMapping(Diag);170171return Result.first->second;172}173174void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {175assert(Files.empty() && "not first");176FirstDiagState = CurDiagState = State;177CurDiagStateLoc = SourceLocation();178}179180void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,181SourceLocation Loc,182DiagState *State) {183CurDiagState = State;184CurDiagStateLoc = Loc;185186std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);187unsigned Offset = Decomp.second;188for (File *F = getFile(SrcMgr, Decomp.first); F;189Offset = F->ParentOffset, F = F->Parent) {190F->HasLocalTransitions = true;191auto &Last = F->StateTransitions.back();192assert(Last.Offset <= Offset && "state transitions added out of order");193194if (Last.Offset == Offset) {195if (Last.State == State)196break;197Last.State = State;198continue;199}200201F->StateTransitions.push_back({State, Offset});202}203}204205DiagnosticsEngine::DiagState *206DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,207SourceLocation Loc) const {208// Common case: we have not seen any diagnostic pragmas.209if (Files.empty())210return FirstDiagState;211212std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);213const File *F = getFile(SrcMgr, Decomp.first);214return F->lookup(Decomp.second);215}216217DiagnosticsEngine::DiagState *218DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {219auto OnePastIt =220llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {221return P.Offset <= Offset;222});223assert(OnePastIt != StateTransitions.begin() && "missing initial state");224return OnePastIt[-1].State;225}226227DiagnosticsEngine::DiagStateMap::File *228DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,229FileID ID) const {230// Get or insert the File for this ID.231auto Range = Files.equal_range(ID);232if (Range.first != Range.second)233return &Range.first->second;234auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;235236// We created a new File; look up the diagnostic state at the start of it and237// initialize it.238if (ID.isValid()) {239std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);240F.Parent = getFile(SrcMgr, Decomp.first);241F.ParentOffset = Decomp.second;242F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});243} else {244// This is the (imaginary) root file into which we pretend all top-level245// files are included; it descends from the initial state.246//247// FIXME: This doesn't guarantee that we use the same ordering as248// isBeforeInTranslationUnit in the cases where someone invented another249// top-level file and added diagnostic pragmas to it. See the code at the250// end of isBeforeInTranslationUnit for the quirks it deals with.251F.StateTransitions.push_back({FirstDiagState, 0});252}253return &F;254}255256void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,257StringRef DiagName) const {258llvm::errs() << "diagnostic state at ";259CurDiagStateLoc.print(llvm::errs(), SrcMgr);260llvm::errs() << ": " << CurDiagState << "\n";261262for (auto &F : Files) {263FileID ID = F.first;264File &File = F.second;265266bool PrintedOuterHeading = false;267auto PrintOuterHeading = [&] {268if (PrintedOuterHeading) return;269PrintedOuterHeading = true;270271llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()272<< ">: " << SrcMgr.getBufferOrFake(ID).getBufferIdentifier();273274if (F.second.Parent) {275std::pair<FileID, unsigned> Decomp =276SrcMgr.getDecomposedIncludedLoc(ID);277assert(File.ParentOffset == Decomp.second);278llvm::errs() << " parent " << File.Parent << " <FileID "279<< Decomp.first.getHashValue() << "> ";280SrcMgr.getLocForStartOfFile(Decomp.first)281.getLocWithOffset(Decomp.second)282.print(llvm::errs(), SrcMgr);283}284if (File.HasLocalTransitions)285llvm::errs() << " has_local_transitions";286llvm::errs() << "\n";287};288289if (DiagName.empty())290PrintOuterHeading();291292for (DiagStatePoint &Transition : File.StateTransitions) {293bool PrintedInnerHeading = false;294auto PrintInnerHeading = [&] {295if (PrintedInnerHeading) return;296PrintedInnerHeading = true;297298PrintOuterHeading();299llvm::errs() << " ";300SrcMgr.getLocForStartOfFile(ID)301.getLocWithOffset(Transition.Offset)302.print(llvm::errs(), SrcMgr);303llvm::errs() << ": state " << Transition.State << ":\n";304};305306if (DiagName.empty())307PrintInnerHeading();308309for (auto &Mapping : *Transition.State) {310StringRef Option =311DiagnosticIDs::getWarningOptionForDiag(Mapping.first);312if (!DiagName.empty() && DiagName != Option)313continue;314315PrintInnerHeading();316llvm::errs() << " ";317if (Option.empty())318llvm::errs() << "<unknown " << Mapping.first << ">";319else320llvm::errs() << Option;321llvm::errs() << ": ";322323switch (Mapping.second.getSeverity()) {324case diag::Severity::Ignored: llvm::errs() << "ignored"; break;325case diag::Severity::Remark: llvm::errs() << "remark"; break;326case diag::Severity::Warning: llvm::errs() << "warning"; break;327case diag::Severity::Error: llvm::errs() << "error"; break;328case diag::Severity::Fatal: llvm::errs() << "fatal"; break;329}330331if (!Mapping.second.isUser())332llvm::errs() << " default";333if (Mapping.second.isPragma())334llvm::errs() << " pragma";335if (Mapping.second.hasNoWarningAsError())336llvm::errs() << " no-error";337if (Mapping.second.hasNoErrorAsFatal())338llvm::errs() << " no-fatal";339if (Mapping.second.wasUpgradedFromWarning())340llvm::errs() << " overruled";341llvm::errs() << "\n";342}343}344}345}346347void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,348SourceLocation Loc) {349assert(Loc.isValid() && "Adding invalid loc point");350DiagStatesByLoc.append(*SourceMgr, Loc, State);351}352353void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,354SourceLocation L) {355assert(Diag < diag::DIAG_UPPER_LIMIT &&356"Can only map builtin diagnostics");357assert((Diags->isBuiltinWarningOrExtension(Diag) ||358(Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&359"Cannot map errors into warnings!");360assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");361362// A command line -Wfoo has an invalid L and cannot override error/fatal363// mapping, while a warning pragma can.364bool WasUpgradedFromWarning = false;365if (Map == diag::Severity::Warning && L.isInvalid()) {366DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);367if (Info.getSeverity() == diag::Severity::Error ||368Info.getSeverity() == diag::Severity::Fatal) {369Map = Info.getSeverity();370WasUpgradedFromWarning = true;371}372}373DiagnosticMapping Mapping = makeUserMapping(Map, L);374Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);375376// Make sure we propagate the NoWarningAsError flag from an existing377// mapping (which may be the default mapping).378DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);379Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||380Mapping.hasNoWarningAsError());381382// Common case; setting all the diagnostics of a group in one place.383if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&384DiagStatesByLoc.getCurDiagState()) {385// FIXME: This is theoretically wrong: if the current state is shared with386// some other location (via push/pop) we will change the state for that387// other location as well. This cannot currently happen, as we can't update388// the diagnostic state at the same location at which we pop.389DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);390return;391}392393// A diagnostic pragma occurred, create a new DiagState initialized with394// the current one and a new DiagStatePoint to record at which location395// the new state became active.396DiagStates.push_back(*GetCurDiagState());397DiagStates.back().setMapping(Diag, Mapping);398PushDiagStatePoint(&DiagStates.back(), L);399}400401bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,402StringRef Group, diag::Severity Map,403SourceLocation Loc) {404// Get the diagnostics in this group.405SmallVector<diag::kind, 256> GroupDiags;406if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))407return true;408409// Set the mapping.410for (diag::kind Diag : GroupDiags)411setSeverity(Diag, Map, Loc);412413return false;414}415416bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,417diag::Group Group,418diag::Severity Map,419SourceLocation Loc) {420return setSeverityForGroup(Flavor, Diags->getWarningOptionForGroup(Group),421Map, Loc);422}423424bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,425bool Enabled) {426// If we are enabling this feature, just set the diagnostic mappings to map to427// errors.428if (Enabled)429return setSeverityForGroup(diag::Flavor::WarningOrError, Group,430diag::Severity::Error);431432// Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and433// potentially downgrade anything already mapped to be a warning.434435// Get the diagnostics in this group.436SmallVector<diag::kind, 8> GroupDiags;437if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,438GroupDiags))439return true;440441// Perform the mapping change.442for (diag::kind Diag : GroupDiags) {443DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);444445if (Info.getSeverity() == diag::Severity::Error ||446Info.getSeverity() == diag::Severity::Fatal)447Info.setSeverity(diag::Severity::Warning);448449Info.setNoWarningAsError(true);450}451452return false;453}454455bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,456bool Enabled) {457// If we are enabling this feature, just set the diagnostic mappings to map to458// fatal errors.459if (Enabled)460return setSeverityForGroup(diag::Flavor::WarningOrError, Group,461diag::Severity::Fatal);462463// Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,464// and potentially downgrade anything already mapped to be a fatal error.465466// Get the diagnostics in this group.467SmallVector<diag::kind, 8> GroupDiags;468if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,469GroupDiags))470return true;471472// Perform the mapping change.473for (diag::kind Diag : GroupDiags) {474DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);475476if (Info.getSeverity() == diag::Severity::Fatal)477Info.setSeverity(diag::Severity::Error);478479Info.setNoErrorAsFatal(true);480}481482return false;483}484485void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,486diag::Severity Map,487SourceLocation Loc) {488// Get all the diagnostics.489std::vector<diag::kind> AllDiags;490DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);491492// Set the mapping.493for (diag::kind Diag : AllDiags)494if (Diags->isBuiltinWarningOrExtension(Diag))495setSeverity(Diag, Map, Loc);496}497498void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {499assert(CurDiagID == std::numeric_limits<unsigned>::max() &&500"Multiple diagnostics in flight at once!");501502CurDiagLoc = storedDiag.getLocation();503CurDiagID = storedDiag.getID();504DiagStorage.NumDiagArgs = 0;505506DiagStorage.DiagRanges.clear();507DiagStorage.DiagRanges.append(storedDiag.range_begin(),508storedDiag.range_end());509510DiagStorage.FixItHints.clear();511DiagStorage.FixItHints.append(storedDiag.fixit_begin(),512storedDiag.fixit_end());513514assert(Client && "DiagnosticConsumer not set!");515Level DiagLevel = storedDiag.getLevel();516Diagnostic Info(this, storedDiag.getMessage());517Client->HandleDiagnostic(DiagLevel, Info);518if (Client->IncludeInDiagnosticCounts()) {519if (DiagLevel == DiagnosticsEngine::Warning)520++NumWarnings;521}522523CurDiagID = std::numeric_limits<unsigned>::max();524}525526bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {527assert(getClient() && "DiagnosticClient not set!");528529bool Emitted;530if (Force) {531Diagnostic Info(this);532533// Figure out the diagnostic level of this message.534DiagnosticIDs::Level DiagLevel535= Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);536537Emitted = (DiagLevel != DiagnosticIDs::Ignored);538if (Emitted) {539// Emit the diagnostic regardless of suppression level.540Diags->EmitDiag(*this, DiagLevel);541}542} else {543// Process the diagnostic, sending the accumulated information to the544// DiagnosticConsumer.545Emitted = ProcessDiag();546}547548// Clear out the current diagnostic object.549Clear();550551// If there was a delayed diagnostic, emit it now.552if (!Force && DelayedDiagID)553ReportDelayed();554555return Emitted;556}557558DiagnosticConsumer::~DiagnosticConsumer() = default;559560void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,561const Diagnostic &Info) {562if (!IncludeInDiagnosticCounts())563return;564565if (DiagLevel == DiagnosticsEngine::Warning)566++NumWarnings;567else if (DiagLevel >= DiagnosticsEngine::Error)568++NumErrors;569}570571/// ModifierIs - Return true if the specified modifier matches specified string.572template <std::size_t StrLen>573static bool ModifierIs(const char *Modifier, unsigned ModifierLen,574const char (&Str)[StrLen]) {575return StrLen-1 == ModifierLen && memcmp(Modifier, Str, StrLen-1) == 0;576}577578/// ScanForward - Scans forward, looking for the given character, skipping579/// nested clauses and escaped characters.580static const char *ScanFormat(const char *I, const char *E, char Target) {581unsigned Depth = 0;582583for ( ; I != E; ++I) {584if (Depth == 0 && *I == Target) return I;585if (Depth != 0 && *I == '}') Depth--;586587if (*I == '%') {588I++;589if (I == E) break;590591// Escaped characters get implicitly skipped here.592593// Format specifier.594if (!isDigit(*I) && !isPunctuation(*I)) {595for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;596if (I == E) break;597if (*I == '{')598Depth++;599}600}601}602return E;603}604605/// HandleSelectModifier - Handle the integer 'select' modifier. This is used606/// like this: %select{foo|bar|baz}2. This means that the integer argument607/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.608/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.609/// This is very useful for certain classes of variant diagnostics.610static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,611const char *Argument, unsigned ArgumentLen,612SmallVectorImpl<char> &OutStr) {613const char *ArgumentEnd = Argument+ArgumentLen;614615// Skip over 'ValNo' |'s.616while (ValNo) {617const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');618assert(NextVal != ArgumentEnd && "Value for integer select modifier was"619" larger than the number of options in the diagnostic string!");620Argument = NextVal+1; // Skip this string.621--ValNo;622}623624// Get the end of the value. This is either the } or the |.625const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');626627// Recursively format the result of the select clause into the output string.628DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);629}630631/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the632/// letter 's' to the string if the value is not 1. This is used in cases like633/// this: "you idiot, you have %4 parameter%s4!".634static void HandleIntegerSModifier(unsigned ValNo,635SmallVectorImpl<char> &OutStr) {636if (ValNo != 1)637OutStr.push_back('s');638}639640/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This641/// prints the ordinal form of the given integer, with 1 corresponding642/// to the first ordinal. Currently this is hard-coded to use the643/// English form.644static void HandleOrdinalModifier(unsigned ValNo,645SmallVectorImpl<char> &OutStr) {646assert(ValNo != 0 && "ValNo must be strictly positive!");647648llvm::raw_svector_ostream Out(OutStr);649650// We could use text forms for the first N ordinals, but the numeric651// forms are actually nicer in diagnostics because they stand out.652Out << ValNo << llvm::getOrdinalSuffix(ValNo);653}654655/// PluralNumber - Parse an unsigned integer and advance Start.656static unsigned PluralNumber(const char *&Start, const char *End) {657// Programming 101: Parse a decimal number :-)658unsigned Val = 0;659while (Start != End && *Start >= '0' && *Start <= '9') {660Val *= 10;661Val += *Start - '0';662++Start;663}664return Val;665}666667/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.668static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {669if (*Start != '[') {670unsigned Ref = PluralNumber(Start, End);671return Ref == Val;672}673674++Start;675unsigned Low = PluralNumber(Start, End);676assert(*Start == ',' && "Bad plural expression syntax: expected ,");677++Start;678unsigned High = PluralNumber(Start, End);679assert(*Start == ']' && "Bad plural expression syntax: expected )");680++Start;681return Low <= Val && Val <= High;682}683684/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.685static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {686// Empty condition?687if (*Start == ':')688return true;689690while (true) {691char C = *Start;692if (C == '%') {693// Modulo expression694++Start;695unsigned Arg = PluralNumber(Start, End);696assert(*Start == '=' && "Bad plural expression syntax: expected =");697++Start;698unsigned ValMod = ValNo % Arg;699if (TestPluralRange(ValMod, Start, End))700return true;701} else {702assert((C == '[' || (C >= '0' && C <= '9')) &&703"Bad plural expression syntax: unexpected character");704// Range expression705if (TestPluralRange(ValNo, Start, End))706return true;707}708709// Scan for next or-expr part.710Start = std::find(Start, End, ',');711if (Start == End)712break;713++Start;714}715return false;716}717718/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used719/// for complex plural forms, or in languages where all plurals are complex.720/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are721/// conditions that are tested in order, the form corresponding to the first722/// that applies being emitted. The empty condition is always true, making the723/// last form a default case.724/// Conditions are simple boolean expressions, where n is the number argument.725/// Here are the rules.726/// condition := expression | empty727/// empty := -> always true728/// expression := numeric [',' expression] -> logical or729/// numeric := range -> true if n in range730/// | '%' number '=' range -> true if n % number in range731/// range := number732/// | '[' number ',' number ']' -> ranges are inclusive both ends733///734/// Here are some examples from the GNU gettext manual written in this form:735/// English:736/// {1:form0|:form1}737/// Latvian:738/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}739/// Gaeilge:740/// {1:form0|2:form1|:form2}741/// Romanian:742/// {1:form0|0,%100=[1,19]:form1|:form2}743/// Lithuanian:744/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}745/// Russian (requires repeated form):746/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}747/// Slovak748/// {1:form0|[2,4]:form1|:form2}749/// Polish (requires repeated form):750/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}751static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,752const char *Argument, unsigned ArgumentLen,753SmallVectorImpl<char> &OutStr) {754const char *ArgumentEnd = Argument + ArgumentLen;755while (true) {756assert(Argument < ArgumentEnd && "Plural expression didn't match.");757const char *ExprEnd = Argument;758while (*ExprEnd != ':') {759assert(ExprEnd != ArgumentEnd && "Plural missing expression end");760++ExprEnd;761}762if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {763Argument = ExprEnd + 1;764ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');765766// Recursively format the result of the plural clause into the767// output string.768DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);769return;770}771Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;772}773}774775/// Returns the friendly description for a token kind that will appear776/// without quotes in diagnostic messages. These strings may be translatable in777/// future.778static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {779switch (Kind) {780case tok::identifier:781return "identifier";782default:783return nullptr;784}785}786787/// FormatDiagnostic - Format this diagnostic into a string, substituting the788/// formal arguments into the %0 slots. The result is appended onto the Str789/// array.790void Diagnostic::791FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {792if (StoredDiagMessage.has_value()) {793OutStr.append(StoredDiagMessage->begin(), StoredDiagMessage->end());794return;795}796797StringRef Diag =798getDiags()->getDiagnosticIDs()->getDescription(getID());799800FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);801}802803/// EscapeStringForDiagnostic - Append Str to the diagnostic buffer,804/// escaping non-printable characters and ill-formed code unit sequences.805void clang::EscapeStringForDiagnostic(StringRef Str,806SmallVectorImpl<char> &OutStr) {807OutStr.reserve(OutStr.size() + Str.size());808auto *Begin = reinterpret_cast<const unsigned char *>(Str.data());809llvm::raw_svector_ostream OutStream(OutStr);810const unsigned char *End = Begin + Str.size();811while (Begin != End) {812// ASCII case813if (isPrintable(*Begin) || isWhitespace(*Begin)) {814OutStream << *Begin;815++Begin;816continue;817}818if (llvm::isLegalUTF8Sequence(Begin, End)) {819llvm::UTF32 CodepointValue;820llvm::UTF32 *CpPtr = &CodepointValue;821const unsigned char *CodepointBegin = Begin;822const unsigned char *CodepointEnd =823Begin + llvm::getNumBytesForUTF8(*Begin);824llvm::ConversionResult Res = llvm::ConvertUTF8toUTF32(825&Begin, CodepointEnd, &CpPtr, CpPtr + 1, llvm::strictConversion);826(void)Res;827assert(828llvm::conversionOK == Res &&829"the sequence is legal UTF-8 but we couldn't convert it to UTF-32");830assert(Begin == CodepointEnd &&831"we must be further along in the string now");832if (llvm::sys::unicode::isPrintable(CodepointValue) ||833llvm::sys::unicode::isFormatting(CodepointValue)) {834OutStr.append(CodepointBegin, CodepointEnd);835continue;836}837// Unprintable code point.838OutStream << "<U+" << llvm::format_hex_no_prefix(CodepointValue, 4, true)839<< ">";840continue;841}842// Invalid code unit.843OutStream << "<" << llvm::format_hex_no_prefix(*Begin, 2, true) << ">";844++Begin;845}846}847848void Diagnostic::849FormatDiagnostic(const char *DiagStr, const char *DiagEnd,850SmallVectorImpl<char> &OutStr) const {851// When the diagnostic string is only "%0", the entire string is being given852// by an outside source. Remove unprintable characters from this string853// and skip all the other string processing.854if (DiagEnd - DiagStr == 2 && StringRef(DiagStr, DiagEnd - DiagStr) == "%0" &&855getArgKind(0) == DiagnosticsEngine::ak_std_string) {856const std::string &S = getArgStdStr(0);857EscapeStringForDiagnostic(S, OutStr);858return;859}860861/// FormattedArgs - Keep track of all of the arguments formatted by862/// ConvertArgToString and pass them into subsequent calls to863/// ConvertArgToString, allowing the implementation to avoid redundancies in864/// obvious cases.865SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;866867/// QualTypeVals - Pass a vector of arrays so that QualType names can be868/// compared to see if more information is needed to be printed.869SmallVector<intptr_t, 2> QualTypeVals;870SmallString<64> Tree;871872for (unsigned i = 0, e = getNumArgs(); i < e; ++i)873if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)874QualTypeVals.push_back(getRawArg(i));875876while (DiagStr != DiagEnd) {877if (DiagStr[0] != '%') {878// Append non-%0 substrings to Str if we have one.879const char *StrEnd = std::find(DiagStr, DiagEnd, '%');880OutStr.append(DiagStr, StrEnd);881DiagStr = StrEnd;882continue;883} else if (isPunctuation(DiagStr[1])) {884OutStr.push_back(DiagStr[1]); // %% -> %.885DiagStr += 2;886continue;887}888889// Skip the %.890++DiagStr;891892// This must be a placeholder for a diagnostic argument. The format for a893// placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".894// The digit is a number from 0-9 indicating which argument this comes from.895// The modifier is a string of digits from the set [-a-z]+, arguments is a896// brace enclosed string.897const char *Modifier = nullptr, *Argument = nullptr;898unsigned ModifierLen = 0, ArgumentLen = 0;899900// Check to see if we have a modifier. If so eat it.901if (!isDigit(DiagStr[0])) {902Modifier = DiagStr;903while (DiagStr[0] == '-' ||904(DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))905++DiagStr;906ModifierLen = DiagStr-Modifier;907908// If we have an argument, get it next.909if (DiagStr[0] == '{') {910++DiagStr; // Skip {.911Argument = DiagStr;912913DiagStr = ScanFormat(DiagStr, DiagEnd, '}');914assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");915ArgumentLen = DiagStr-Argument;916++DiagStr; // Skip }.917}918}919920assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");921unsigned ArgNo = *DiagStr++ - '0';922923// Only used for type diffing.924unsigned ArgNo2 = ArgNo;925926DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);927if (ModifierIs(Modifier, ModifierLen, "diff")) {928assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&929"Invalid format for diff modifier");930++DiagStr; // Comma.931ArgNo2 = *DiagStr++ - '0';932DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);933if (Kind == DiagnosticsEngine::ak_qualtype &&934Kind2 == DiagnosticsEngine::ak_qualtype)935Kind = DiagnosticsEngine::ak_qualtype_pair;936else {937// %diff only supports QualTypes. For other kinds of arguments,938// use the default printing. For example, if the modifier is:939// "%diff{compare $ to $|other text}1,2"940// treat it as:941// "compare %1 to %2"942const char *ArgumentEnd = Argument + ArgumentLen;943const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');944assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&945"Found too many '|'s in a %diff modifier!");946const char *FirstDollar = ScanFormat(Argument, Pipe, '$');947const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');948const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };949const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };950FormatDiagnostic(Argument, FirstDollar, OutStr);951FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);952FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);953FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);954FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);955continue;956}957}958959switch (Kind) {960// ---- STRINGS ----961case DiagnosticsEngine::ak_std_string: {962const std::string &S = getArgStdStr(ArgNo);963assert(ModifierLen == 0 && "No modifiers for strings yet");964EscapeStringForDiagnostic(S, OutStr);965break;966}967case DiagnosticsEngine::ak_c_string: {968const char *S = getArgCStr(ArgNo);969assert(ModifierLen == 0 && "No modifiers for strings yet");970971// Don't crash if get passed a null pointer by accident.972if (!S)973S = "(null)";974EscapeStringForDiagnostic(S, OutStr);975break;976}977// ---- INTEGERS ----978case DiagnosticsEngine::ak_sint: {979int64_t Val = getArgSInt(ArgNo);980981if (ModifierIs(Modifier, ModifierLen, "select")) {982HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,983OutStr);984} else if (ModifierIs(Modifier, ModifierLen, "s")) {985HandleIntegerSModifier(Val, OutStr);986} else if (ModifierIs(Modifier, ModifierLen, "plural")) {987HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,988OutStr);989} else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {990HandleOrdinalModifier((unsigned)Val, OutStr);991} else {992assert(ModifierLen == 0 && "Unknown integer modifier");993llvm::raw_svector_ostream(OutStr) << Val;994}995break;996}997case DiagnosticsEngine::ak_uint: {998uint64_t Val = getArgUInt(ArgNo);9991000if (ModifierIs(Modifier, ModifierLen, "select")) {1001HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);1002} else if (ModifierIs(Modifier, ModifierLen, "s")) {1003HandleIntegerSModifier(Val, OutStr);1004} else if (ModifierIs(Modifier, ModifierLen, "plural")) {1005HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,1006OutStr);1007} else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {1008HandleOrdinalModifier(Val, OutStr);1009} else {1010assert(ModifierLen == 0 && "Unknown integer modifier");1011llvm::raw_svector_ostream(OutStr) << Val;1012}1013break;1014}1015// ---- TOKEN SPELLINGS ----1016case DiagnosticsEngine::ak_tokenkind: {1017tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));1018assert(ModifierLen == 0 && "No modifiers for token kinds yet");10191020llvm::raw_svector_ostream Out(OutStr);1021if (const char *S = tok::getPunctuatorSpelling(Kind))1022// Quoted token spelling for punctuators.1023Out << '\'' << S << '\'';1024else if ((S = tok::getKeywordSpelling(Kind)))1025// Unquoted token spelling for keywords.1026Out << S;1027else if ((S = getTokenDescForDiagnostic(Kind)))1028// Unquoted translatable token name.1029Out << S;1030else if ((S = tok::getTokenName(Kind)))1031// Debug name, shouldn't appear in user-facing diagnostics.1032Out << '<' << S << '>';1033else1034Out << "(null)";1035break;1036}1037// ---- NAMES and TYPES ----1038case DiagnosticsEngine::ak_identifierinfo: {1039const IdentifierInfo *II = getArgIdentifier(ArgNo);1040assert(ModifierLen == 0 && "No modifiers for strings yet");10411042// Don't crash if get passed a null pointer by accident.1043if (!II) {1044const char *S = "(null)";1045OutStr.append(S, S + strlen(S));1046continue;1047}10481049llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';1050break;1051}1052case DiagnosticsEngine::ak_addrspace:1053case DiagnosticsEngine::ak_qual:1054case DiagnosticsEngine::ak_qualtype:1055case DiagnosticsEngine::ak_declarationname:1056case DiagnosticsEngine::ak_nameddecl:1057case DiagnosticsEngine::ak_nestednamespec:1058case DiagnosticsEngine::ak_declcontext:1059case DiagnosticsEngine::ak_attr:1060getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),1061StringRef(Modifier, ModifierLen),1062StringRef(Argument, ArgumentLen),1063FormattedArgs,1064OutStr, QualTypeVals);1065break;1066case DiagnosticsEngine::ak_qualtype_pair: {1067// Create a struct with all the info needed for printing.1068TemplateDiffTypes TDT;1069TDT.FromType = getRawArg(ArgNo);1070TDT.ToType = getRawArg(ArgNo2);1071TDT.ElideType = getDiags()->ElideType;1072TDT.ShowColors = getDiags()->ShowColors;1073TDT.TemplateDiffUsed = false;1074intptr_t val = reinterpret_cast<intptr_t>(&TDT);10751076const char *ArgumentEnd = Argument + ArgumentLen;1077const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');10781079// Print the tree. If this diagnostic already has a tree, skip the1080// second tree.1081if (getDiags()->PrintTemplateTree && Tree.empty()) {1082TDT.PrintFromType = true;1083TDT.PrintTree = true;1084getDiags()->ConvertArgToString(Kind, val,1085StringRef(Modifier, ModifierLen),1086StringRef(Argument, ArgumentLen),1087FormattedArgs,1088Tree, QualTypeVals);1089// If there is no tree information, fall back to regular printing.1090if (!Tree.empty()) {1091FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);1092break;1093}1094}10951096// Non-tree printing, also the fall-back when tree printing fails.1097// The fall-back is triggered when the types compared are not templates.1098const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');1099const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');11001101// Append before text1102FormatDiagnostic(Argument, FirstDollar, OutStr);11031104// Append first type1105TDT.PrintTree = false;1106TDT.PrintFromType = true;1107getDiags()->ConvertArgToString(Kind, val,1108StringRef(Modifier, ModifierLen),1109StringRef(Argument, ArgumentLen),1110FormattedArgs,1111OutStr, QualTypeVals);1112if (!TDT.TemplateDiffUsed)1113FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,1114TDT.FromType));11151116// Append middle text1117FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);11181119// Append second type1120TDT.PrintFromType = false;1121getDiags()->ConvertArgToString(Kind, val,1122StringRef(Modifier, ModifierLen),1123StringRef(Argument, ArgumentLen),1124FormattedArgs,1125OutStr, QualTypeVals);1126if (!TDT.TemplateDiffUsed)1127FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,1128TDT.ToType));11291130// Append end text1131FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);1132break;1133}1134}11351136// Remember this argument info for subsequent formatting operations. Turn1137// std::strings into a null terminated string to make it be the same case as1138// all the other ones.1139if (Kind == DiagnosticsEngine::ak_qualtype_pair)1140continue;1141else if (Kind != DiagnosticsEngine::ak_std_string)1142FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));1143else1144FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,1145(intptr_t)getArgStdStr(ArgNo).c_str()));1146}11471148// Append the type tree to the end of the diagnostics.1149OutStr.append(Tree.begin(), Tree.end());1150}11511152StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,1153StringRef Message)1154: ID(ID), Level(Level), Message(Message) {}11551156StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,1157const Diagnostic &Info)1158: ID(Info.getID()), Level(Level) {1159assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&1160"Valid source location without setting a source manager for diagnostic");1161if (Info.getLocation().isValid())1162Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());1163SmallString<64> Message;1164Info.FormatDiagnostic(Message);1165this->Message.assign(Message.begin(), Message.end());1166this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());1167this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());1168}11691170StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,1171StringRef Message, FullSourceLoc Loc,1172ArrayRef<CharSourceRange> Ranges,1173ArrayRef<FixItHint> FixIts)1174: ID(ID), Level(Level), Loc(Loc), Message(Message),1175Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())1176{1177}11781179llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,1180const StoredDiagnostic &SD) {1181if (SD.getLocation().hasManager())1182OS << SD.getLocation().printToString(SD.getLocation().getManager()) << ": ";1183OS << SD.getMessage();1184return OS;1185}11861187/// IncludeInDiagnosticCounts - This method (whose default implementation1188/// returns true) indicates whether the diagnostics handled by this1189/// DiagnosticConsumer should be included in the number of diagnostics1190/// reported by DiagnosticsEngine.1191bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }11921193void IgnoringDiagConsumer::anchor() {}11941195ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() = default;11961197void ForwardingDiagnosticConsumer::HandleDiagnostic(1198DiagnosticsEngine::Level DiagLevel,1199const Diagnostic &Info) {1200Target.HandleDiagnostic(DiagLevel, Info);1201}12021203void ForwardingDiagnosticConsumer::clear() {1204DiagnosticConsumer::clear();1205Target.clear();1206}12071208bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {1209return Target.IncludeInDiagnosticCounts();1210}12111212PartialDiagnostic::DiagStorageAllocator::DiagStorageAllocator() {1213for (unsigned I = 0; I != NumCached; ++I)1214FreeList[I] = Cached + I;1215NumFreeListEntries = NumCached;1216}12171218PartialDiagnostic::DiagStorageAllocator::~DiagStorageAllocator() {1219// Don't assert if we are in a CrashRecovery context, as this invariant may1220// be invalidated during a crash.1221assert((NumFreeListEntries == NumCached ||1222llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&1223"A partial is on the lam");1224}12251226char DiagnosticError::ID;122712281229