/// Runs <code>xcrun -f clang</code> in order to find the location of Clang for /// the currently active Xcode. /// /// We get the "currently active" part by passing through the DEVELOPER_DIR /// environment variable (along with the rest of the environment). static bool findXcodeClangPath(llvm::SmallVectorImpl<char> &path) { assert(path.empty()); auto xcrunPath = llvm::sys::findProgramByName("xcrun"); if (!xcrunPath.getError()) { const char *args[] = {"-f", "clang", nullptr}; sys::TaskQueue queue; queue.addTask(xcrunPath->c_str(), args, /*Env=*/llvm::None, /*Context=*/nullptr, /*SeparateErrors=*/true); queue.execute(nullptr, [&path](sys::ProcessId PID, int returnCode, StringRef output, StringRef errors, sys::TaskProcessInformation ProcInfo, void *unused) -> sys::TaskFinishedResponse { if (returnCode == 0) { output = output.rtrim(); path.append(output.begin(), output.end()); } return sys::TaskFinishedResponse::ContinueExecution; }); } return !path.empty(); }
static void appendCodePoint(unsigned Codepoint, llvm::SmallVectorImpl<char> &Str) { char ResultBuf[4]; char *ResultPtr = ResultBuf; bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr); (void)Res; assert(Res && "Unexpected conversion failure"); Str.append(ResultBuf, ResultPtr); }
llvm::StringRef ParserImpl::MergeTokensUntil(const unsigned int* toks, unsigned int num_toks, SourceLocation* start, SourceLocation* end, llvm::SmallVectorImpl<char>& buffer, bool stop_at_eos, bool stop_at_ws) { buffer.clear(); *start = *end = m_token.getLocation(); for (;;) { // If we found one of the tokens, stop. for (unsigned i = 0; i < num_toks; ++i) { if (m_token.is(toks[i])) goto done; } // If we hit end of statement, stop. if (stop_at_eos && m_token.isEndOfStatement()) break; // Turn the token back into characters. // The first if's are optimizations for common cases. llvm::StringRef data; if (m_token.isLiteral()) { data = m_token.getLiteral(); } else if (m_token.is(Token::identifier) || m_token.is(Token::label)) { IdentifierInfo* ii = m_token.getIdentifierInfo(); data = ii->getName(); } else { // Get the raw data from the source manager. SourceManager& smgr = m_preproc.getSourceManager(); data = llvm::StringRef(smgr.getCharacterData(m_token.getLocation()), m_token.getLength()); } buffer.append(data.begin(), data.end()); *end = m_token.getEndLocation(); ConsumeAnyToken(); // If we hit a token with leading space, stop. // We do this down here in case the first token had preceding ws. if (stop_at_ws && m_token.hasLeadingSpace()) break; } done: return llvm::StringRef(buffer.data(), buffer.size()); }
static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT, const char *Modifier, unsigned ML, const char *Argument, unsigned ArgLen, const Diagnostic::ArgumentValue *PrevArgs, unsigned NumPrevArgs, llvm::SmallVectorImpl<char> &Output, void *Cookie) { const char *Str = "<can't format argument>"; Output.append(Str, Str+strlen(Str)); }
void HostThreadLinux::GetName(lldb::thread_t thread, llvm::SmallVectorImpl<char> &name) { // Read /proc/$TID/comm file. lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(thread, "comm"); const char *comm_str = (const char *)buf_sp->GetBytes(); const char *cr_str = ::strchr(comm_str, '\n'); size_t length = cr_str ? (cr_str - comm_str) : strlen(comm_str); name.clear(); name.append(comm_str, comm_str + length); }
/// FormatDiagnostic - Format this diagnostic into a string, substituting the /// formal arguments into the %0 slots. The result is appended onto the Str /// array. void DiagnosticInfo:: FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const { if (!StoredDiagMessage.empty()) { OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); return; } llvm::StringRef Diag = getDiags()->getDiagnosticIDs()->getDescription(getID()); FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); }
/// HandleSelectModifier - Handle the integer 'select' modifier. This is used /// like this: %select{foo|bar|baz}2. This means that the integer argument /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. /// This is very useful for certain classes of variant diagnostics. static void HandleSelectModifier(unsigned ValNo, const char *Argument, unsigned ArgumentLen, llvm::SmallVectorImpl<char> &OutStr) { const char *ArgumentEnd = Argument+ArgumentLen; // Skip over 'ValNo' |'s. while (ValNo) { const char *NextVal = std::find(Argument, ArgumentEnd, '|'); assert(NextVal != ArgumentEnd && "Value for integer select modifier was" " larger than the number of options in the diagnostic string!"); Argument = NextVal+1; // Skip this string. --ValNo; } // Get the end of the value. This is either the } or the |. const char *EndPtr = std::find(Argument, ArgumentEnd, '|'); // Add the value to the output string. OutStr.append(Argument, EndPtr); }
void HostThreadFreeBSD::GetName(lldb::tid_t tid, llvm::SmallVectorImpl<char> &name) { name.clear(); int pid = Host::GetCurrentProcessID(); struct kinfo_proc *kp = nullptr, *nkp; size_t len = 0; int error; int ctl[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD, (int)pid}; while (1) { error = sysctl(ctl, 4, kp, &len, nullptr, 0); if (kp == nullptr || (error != 0 && errno == ENOMEM)) { // Add extra space in case threads are added before next call. len += sizeof(*kp) + len / 10; nkp = (struct kinfo_proc *)realloc(kp, len); if (nkp == nullptr) { free(kp); return; } kp = nkp; continue; } if (error != 0) len = 0; break; } for (size_t i = 0; i < len / sizeof(*kp); i++) { if (kp[i].ki_tid == (lwpid_t)tid) { name.append(kp[i].ki_tdname, kp[i].ki_tdname + strlen(kp[i].ki_tdname)); break; } } free(kp); }
void FunctionSignatureTransformDescriptor::addThunkArgument( ArgumentDescriptor &AD, SILBuilder &Builder, SILBasicBlock *BB, llvm::SmallVectorImpl<SILValue> &NewArgs) { // Dead argument. if (AD.IsEntirelyDead) { return; } // Explode the argument. if (AD.Explode) { llvm::SmallVector<SILValue, 4> LeafValues; AD.ProjTree.createTreeFromValue(Builder, BB->getParent()->getLocation(), BB->getArgument(AD.Index), LeafValues); NewArgs.append(LeafValues.begin(), LeafValues.end()); return; } // All other arguments get pushed as what they are. NewArgs.push_back(BB->getArgument(AD.Index)); }
/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used /// for complex plural forms, or in languages where all plurals are complex. /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are /// conditions that are tested in order, the form corresponding to the first /// that applies being emitted. The empty condition is always true, making the /// last form a default case. /// Conditions are simple boolean expressions, where n is the number argument. /// Here are the rules. /// condition := expression | empty /// empty := -> always true /// expression := numeric [',' expression] -> logical or /// numeric := range -> true if n in range /// | '%' number '=' range -> true if n % number in range /// range := number /// | '[' number ',' number ']' -> ranges are inclusive both ends /// /// Here are some examples from the GNU gettext manual written in this form: /// English: /// {1:form0|:form1} /// Latvian: /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} /// Gaeilge: /// {1:form0|2:form1|:form2} /// Romanian: /// {1:form0|0,%100=[1,19]:form1|:form2} /// Lithuanian: /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} /// Russian (requires repeated form): /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} /// Slovak /// {1:form0|[2,4]:form1|:form2} /// Polish (requires repeated form): /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} static void HandlePluralModifier(unsigned ValNo, const char *Argument, unsigned ArgumentLen, llvm::SmallVectorImpl<char> &OutStr) { const char *ArgumentEnd = Argument + ArgumentLen; while (1) { assert(Argument < ArgumentEnd && "Plural expression didn't match."); const char *ExprEnd = Argument; while (*ExprEnd != ':') { assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); ++ExprEnd; } if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { Argument = ExprEnd + 1; ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); OutStr.append(Argument, ExprEnd); return; } Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; } }
void clang::FormatASTNodeDiagnosticArgument(Diagnostic::ArgumentKind Kind, intptr_t Val, const char *Modifier, unsigned ModLen, const char *Argument, unsigned ArgLen, const Diagnostic::ArgumentValue *PrevArgs, unsigned NumPrevArgs, llvm::SmallVectorImpl<char> &Output, void *Cookie) { ASTContext &Context = *static_cast<ASTContext*>(Cookie); std::string S; bool NeedQuotes = true; switch (Kind) { default: assert(0 && "unknown ArgumentKind"); case Diagnostic::ak_qualtype: { assert(ModLen == 0 && ArgLen == 0 && "Invalid modifier for QualType argument"); QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs); NeedQuotes = false; break; } case Diagnostic::ak_declarationname: { DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); S = N.getAsString(); if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) S = '+' + S; else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) S = '-' + S; else assert(ModLen == 0 && ArgLen == 0 && "Invalid modifier for DeclarationName argument"); break; } case Diagnostic::ak_nameddecl: { bool Qualified; if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) Qualified = true; else { assert(ModLen == 0 && ArgLen == 0 && "Invalid modifier for NamedDecl* argument"); Qualified = false; } reinterpret_cast<NamedDecl*>(Val)-> getNameForDiagnostic(S, Context.PrintingPolicy, Qualified); break; } case Diagnostic::ak_nestednamespec: { llvm::raw_string_ostream OS(S); reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS, Context.PrintingPolicy); NeedQuotes = false; break; } case Diagnostic::ak_declcontext: { DeclContext *DC = reinterpret_cast<DeclContext *> (Val); assert(DC && "Should never have a null declaration context"); if (DC->isTranslationUnit()) { // FIXME: Get these strings from some localized place if (Context.getLangOptions().CPlusPlus) S = "the global namespace"; else S = "the global scope"; } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) { S = ConvertTypeToDiagnosticString(Context, Context.getTypeDeclType(Type), PrevArgs, NumPrevArgs); } else { // FIXME: Get these strings from some localized place NamedDecl *ND = cast<NamedDecl>(DC); if (isa<NamespaceDecl>(ND)) S += "namespace "; else if (isa<ObjCMethodDecl>(ND)) S += "method "; else if (isa<FunctionDecl>(ND)) S += "function "; S += "'"; ND->getNameForDiagnostic(S, Context.PrintingPolicy, true); S += "'"; } NeedQuotes = false; break; } } if (NeedQuotes) Output.push_back('\''); Output.append(S.begin(), S.end()); if (NeedQuotes) Output.push_back('\''); }
void DiagnosticInfo:: FormatDiagnostic(const char *DiagStr, const char *DiagEnd, llvm::SmallVectorImpl<char> &OutStr) const { /// FormattedArgs - Keep track of all of the arguments formatted by /// ConvertArgToString and pass them into subsequent calls to /// ConvertArgToString, allowing the implementation to avoid redundancies in /// obvious cases. llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs; while (DiagStr != DiagEnd) { if (DiagStr[0] != '%') { // Append non-%0 substrings to Str if we have one. const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); OutStr.append(DiagStr, StrEnd); DiagStr = StrEnd; continue; } else if (ispunct(DiagStr[1])) { OutStr.push_back(DiagStr[1]); // %% -> %. DiagStr += 2; continue; } // Skip the %. ++DiagStr; // This must be a placeholder for a diagnostic argument. The format for a // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". // The digit is a number from 0-9 indicating which argument this comes from. // The modifier is a string of digits from the set [-a-z]+, arguments is a // brace enclosed string. const char *Modifier = 0, *Argument = 0; unsigned ModifierLen = 0, ArgumentLen = 0; // Check to see if we have a modifier. If so eat it. if (!isdigit(DiagStr[0])) { Modifier = DiagStr; while (DiagStr[0] == '-' || (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) ++DiagStr; ModifierLen = DiagStr-Modifier; // If we have an argument, get it next. if (DiagStr[0] == '{') { ++DiagStr; // Skip {. Argument = DiagStr; DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); ArgumentLen = DiagStr-Argument; ++DiagStr; // Skip }. } } assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); unsigned ArgNo = *DiagStr++ - '0'; Diagnostic::ArgumentKind Kind = getArgKind(ArgNo); switch (Kind) { // ---- STRINGS ---- case Diagnostic::ak_std_string: { const std::string &S = getArgStdStr(ArgNo); assert(ModifierLen == 0 && "No modifiers for strings yet"); OutStr.append(S.begin(), S.end()); break; } case Diagnostic::ak_c_string: { const char *S = getArgCStr(ArgNo); assert(ModifierLen == 0 && "No modifiers for strings yet"); // Don't crash if get passed a null pointer by accident. if (!S) S = "(null)"; OutStr.append(S, S + strlen(S)); break; } // ---- INTEGERS ---- case Diagnostic::ak_sint: { int Val = getArgSInt(ArgNo); if (ModifierIs(Modifier, ModifierLen, "select")) { HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "s")) { HandleIntegerSModifier(Val, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "plural")) { HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { HandleOrdinalModifier((unsigned)Val, OutStr); } else { assert(ModifierLen == 0 && "Unknown integer modifier"); llvm::raw_svector_ostream(OutStr) << Val; } break; } case Diagnostic::ak_uint: { unsigned Val = getArgUInt(ArgNo); if (ModifierIs(Modifier, ModifierLen, "select")) { HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "s")) { HandleIntegerSModifier(Val, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "plural")) { HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { HandleOrdinalModifier(Val, OutStr); } else { assert(ModifierLen == 0 && "Unknown integer modifier"); llvm::raw_svector_ostream(OutStr) << Val; } break; } // ---- NAMES and TYPES ---- case Diagnostic::ak_identifierinfo: { const IdentifierInfo *II = getArgIdentifier(ArgNo); assert(ModifierLen == 0 && "No modifiers for strings yet"); // Don't crash if get passed a null pointer by accident. if (!II) { const char *S = "(null)"; OutStr.append(S, S + strlen(S)); continue; } llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; break; } case Diagnostic::ak_qualtype: case Diagnostic::ak_declarationname: case Diagnostic::ak_nameddecl: case Diagnostic::ak_nestednamespec: case Diagnostic::ak_declcontext: getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), Modifier, ModifierLen, Argument, ArgumentLen, FormattedArgs.data(), FormattedArgs.size(), OutStr); break; } // Remember this argument info for subsequent formatting operations. Turn // std::strings into a null terminated string to make it be the same case as // all the other ones. if (Kind != Diagnostic::ak_std_string) FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); else FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string, (intptr_t)getArgStdStr(ArgNo).c_str())); } }