error_code llvmutil_createtemporaryfile(const Twine &Prefix, StringRef Suffix, SmallVectorImpl<char> &ResultPath) { llvm::sys::Path P("/tmp"); P.appendComponent(Prefix.str()); P.appendSuffix(Suffix); P.makeUnique(false,NULL); StringRef str = P.str(); ResultPath.append(str.begin(),str.end()); return error_code(); }
void Value::setName(const Twine &NewName) { assert(SubclassID != MDStringVal && "Cannot set the name of MDString with this method!"); // Fast path for common IRBuilder case of setName("") when there is no name. if (NewName.isTriviallyEmpty() && !hasName()) return; SmallString<256> NameData; StringRef NameRef = NewName.toStringRef(NameData); // Name isn't changing? if (getName() == NameRef) return; assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); // Get the symbol table to update for this object. ValueSymbolTable *ST; if (getSymTab(this, ST)) return; // Cannot set a name on this value (e.g. constant). if (!ST) { // No symbol table to update? Just do the change. if (NameRef.empty()) { // Free the name for this value. Name->Destroy(); Name = 0; return; } if (Name) Name->Destroy(); // NOTE: Could optimize for the case the name is shrinking to not deallocate // then reallocated. // Create the new name. Name = ValueName::Create(NameRef.begin(), NameRef.end()); Name->setValue(this); return; } // NOTE: Could optimize for the case the name is shrinking to not deallocate // then reallocated. if (hasName()) { // Remove old name. ST->removeValueName(Name); Name->Destroy(); Name = 0; if (NameRef.empty()) return; } // Name is changing to something new. Name = ST->createValueName(NameRef, this); }
static void getPath(SmallVectorImpl<char> &Path, const MDNode *MD) { if(MD==NULL) return; StringRef Filename = DIScope(MD).getFilename(); if (sys::path::is_absolute(Filename)) Path.append(Filename.begin(), Filename.end()); else sys::path::append(Path, DIScope(MD).getDirectory(), Filename); }
// parser<double>/parser<float> implementation // static bool parseDouble(Option &O, StringRef Arg, double &Value) { SmallString<32> TmpStr(Arg.begin(), Arg.end()); const char *ArgStart = TmpStr.c_str(); char *End; Value = strtod(ArgStart, &End); if (*End != 0) return O.error("'" + Arg + "' value invalid for floating point argument!"); return false; }
error_code MemoryBuffer::getFile(StringRef Filename, OwningPtr<MemoryBuffer> &result, int64_t FileSize, bool RequiresNullTerminator) { // Ensure the path is null terminated. SmallString<256> PathBuf(Filename.begin(), Filename.end()); return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize, RequiresNullTerminator); }
static std::error_code getRelocationValueString(const COFFObjectFile *Obj, const RelocationRef &Rel, SmallVectorImpl<char> &Result) { symbol_iterator SymI = Rel.getSymbol(); StringRef SymName; if (std::error_code EC = SymI->getName(SymName)) return EC; Result.append(SymName.begin(), SymName.end()); return std::error_code(); }
static bool getNumber(const StringRef &S, uint64_t &N) { N = 0; for (StringRef::iterator I = S.begin(), E = S.end(); I != E; ++I) if (*I >= '0' && *I <= '9') N = N * 10 + (*I - '0'); else return false; return true; }
/// \brief Find the end of the end of the directive, either the beginning of a /// newline or the end of file. // // \return The offset into the file where the directive ends along with a // boolean value indicating whether the directive ends because the end of file // was reached or not. static std::pair<unsigned, bool> findDirectiveEnd(SourceLocation HashLoc, SourceManager &SM, const LangOptions &LangOpts) { FileID FID = SM.getFileID(HashLoc); unsigned Offset = SM.getFileOffset(HashLoc); StringRef Content = SM.getBufferData(FID); Lexer Lex(SM.getLocForStartOfFile(FID), LangOpts, Content.begin(), Content.begin() + Offset, Content.end()); Lex.SetCommentRetentionState(true); Token Tok; // This loop look for the newline after our directive but avoids the ones part // of a multi-line comments: // // #include <foo> /* long \n comment */\n // ~~ no ~~ yes for (;;) { // find the beginning of the end-of-line sequence StringRef::size_type EOLOffset = Content.find_first_of("\r\n", Offset); // ends because EOF was reached if (EOLOffset == StringRef::npos) return std::make_pair(Content.size(), true); // find the token that contains our end-of-line unsigned TokEnd = 0; do { Lex.LexFromRawLexer(Tok); TokEnd = SM.getFileOffset(Tok.getLocation()) + Tok.getLength(); // happens when the whitespaces are eaten after a multiline comment if (Tok.is(tok::eof)) return std::make_pair(EOLOffset, false); } while (TokEnd < EOLOffset); // the end-of-line is not part of a multi-line comment, return its location if (Tok.isNot(tok::comment)) return std::make_pair(EOLOffset, false); // for the next search to start after the end of this token Offset = TokEnd; } }
PooledStringPtr StringPool::intern(StringRef Key) { table_t::iterator I = InternTable.find(Key); if (I != InternTable.end()) return PooledStringPtr(&*I); entry_t *S = entry_t::Create(Key.begin(), Key.end()); S->getValue().Pool = this; InternTable.insert(S); return PooledStringPtr(S); }
/// Reencode well-formed UTF-8 as UTF-32. /// /// This entry point is only called from compiler-internal entry points, so does /// only minimal validation. In particular, it does *not* check for overlong /// encodings. /// If \p mapNonSymbolChars is true, non-symbol ASCII characters (characters /// except [$_a-zA-Z0-9]) are also encoded like non-ASCII unicode characters. /// Returns false if \p InputUTF8 contains surrogate code points. static bool convertUTF8toUTF32(StringRef InputUTF8, std::vector<uint32_t> &OutUTF32, bool mapNonSymbolChars) { auto ptr = InputUTF8.begin(); auto end = InputUTF8.end(); while (ptr < end) { uint8_t first = *ptr++; if (first < 0x80) { if (NewMangling::isValidSymbolChar(first) || !mapNonSymbolChars) { OutUTF32.push_back(first); } else { OutUTF32.push_back((uint32_t)first + 0xD800); } } else if (first < 0xC0) { // Invalid continuation byte. return false; } else if (first < 0xE0) { // Two-byte sequence. if (ptr == end) return false; uint8_t second = *ptr++; if (!isContinuationByte(second)) return false; OutUTF32.push_back(((first & 0x1F) << 6) | (second & 0x3F)); } else if (first < 0xF0) { // Three-byte sequence. if (end - ptr < 2) return false; uint8_t second = *ptr++; uint8_t third = *ptr++; if (!isContinuationByte(second) || !isContinuationByte(third)) return false; OutUTF32.push_back(((first & 0xF) << 12) | ((second & 0x3F) << 6) | ( third & 0x3F )); } else if (first < 0xF8) { // Four-byte sequence. if (end - ptr < 3) return false; uint8_t second = *ptr++; uint8_t third = *ptr++; uint8_t fourth = *ptr++; if (!isContinuationByte(second) || !isContinuationByte(third) || !isContinuationByte(fourth)) return false; OutUTF32.push_back(((first & 0x7) << 18) | ((second & 0x3F) << 12) | ((third & 0x3F) << 6) | ( fourth & 0x3F )); } else { // Unused sequence length. return false; } } return true; }
/* Based on the one from Support/Unix/PathV2 but with different default rights */ static llvm::error_code create_directory(const llvm::Twine& path) { using namespace llvm; SmallString<128> path_storage; StringRef p = path.toNullTerminatedStringRef(path_storage); if (::mkdir(p.begin(), 0755) == -1) { if (errno != errc::file_exists) return error_code(errno, system_category()); } return error_code::success(); }
const char *CodeCompletionAllocator::CopyString(const Twine &String) { SmallString<128> Data; StringRef Ref = String.toStringRef(Data); // FIXME: It would be more efficient to teach Twine to tell us its size and // then add a routine there to fill in an allocated char* with the contents // of the string. char *Mem = (char *)Allocate(Ref.size() + 1, 1); std::copy(Ref.begin(), Ref.end(), Mem); Mem[Ref.size()] = 0; return Mem; }
TimerGroup::TimerGroup(StringRef name) : Name(name.begin(), name.end()), FirstTimer(0) { // Add the group to TimerGroupList. sys::SmartScopedLock<true> L(*TimerLock); if (TimerGroupList) TimerGroupList->Prev = &Next; Next = TimerGroupList; Prev = &TimerGroupList; TimerGroupList = this; }
StringRef camel_case::appendSentenceCase(SmallVectorImpl<char> &buffer, StringRef string) { // Trivial case: empty string. if (string.empty()) return StringRef(buffer.data(), buffer.size()); // Uppercase the first letter, append the rest. buffer.push_back(clang::toUppercase(string[0])); buffer.append(string.begin() + 1, string.end()); return StringRef(buffer.data(), buffer.size()); }
unsigned getStringIndex(StringRef Str) { StringMap<unsigned>::iterator i = StringTableMap.find(Str); if (i == StringTableMap.end()) { unsigned Index = StringTable.size(); StringTable.append(Str.begin(), Str.end()); StringTable.push_back(0); StringTableMap[Str] = Index; return Index; } return i->second; }
// This function is an adaptation from StringLiteral::getLocationOfByte in llvm-3.7.1\src\tools\clang\lib\AST\Expr.cpp std::vector<std::string> splitStringLiteral(StringLiteral *S, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target) { // Loop over all of the tokens in this string until we find the one that // contains the byte we're looking for. unsigned TokNo = 0; std::vector<std::string> result; for (TokNo = 0; TokNo < S->getNumConcatenated(); ++TokNo) { SourceLocation StrTokLoc = S->getStrTokenLoc(TokNo); // Get the spelling of the string so that we can get the data that makes up // the string literal, not the identifier for the macro it is potentially // expanded through. SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc); // Re-lex the token to get its length and original spelling. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(StrTokSpellingLoc); bool Invalid = false; StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) continue; // We ignore this part const char *StrData = Buffer.data() + LocInfo.second; // Create a lexer starting at the beginning of this token. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features, Buffer.begin(), StrData, Buffer.end()); Token TheTok; TheLexer.LexFromRawLexer(TheTok); if (TheTok.isAnyIdentifier()) { // It should not be, since we are parsing inside a string literal, but it can happen with special macros such as __func__ // of __PRETTY_FUNCTION__ that are not resolved at this time. In that case, we just ignore them... continue; } // Get the spelling of the token. SmallString<32> SpellingBuffer; SpellingBuffer.resize(TheTok.getLength()); bool StringInvalid = false; const char *SpellingPtr = &SpellingBuffer[0]; unsigned TokLen = Lexer::getSpelling(TheTok, SpellingPtr, SM, Features, &StringInvalid); if (StringInvalid) continue; const char *SpellingStart = SpellingPtr; const char *SpellingEnd = SpellingPtr + TokLen; result.push_back(std::string(SpellingStart, SpellingEnd)); } return result; }
bool Identifier::isOperatorSlow() const { StringRef data = str(); auto *s = reinterpret_cast<llvm::UTF8 const *>(data.begin()), *end = reinterpret_cast<llvm::UTF8 const *>(data.end()); llvm::UTF32 codePoint; llvm::ConversionResult res = llvm::convertUTF8Sequence(&s, end, &codePoint, llvm::strictConversion); assert(res == llvm::conversionOK && "invalid UTF-8 in identifier?!"); (void)res; return !empty() && isOperatorStartCodePoint(codePoint); }
static std::string QuoteProgramPathIfNeeded(StringRef Command) { if (Command.find_first_of(' ') == StringRef::npos) return Command; else { std::string ret; ret.reserve(Command.size() + 3); ret.push_back('"'); ret.append(Command.begin(), Command.end()); ret.push_back('"'); return ret; } }
void MCObjectStreamer::EmitBytes(StringRef Data) { MCDwarfLineEntry::Make(this, getCurrentSectionOnly()); MCDataFragment *DF = getOrCreateDataFragment(); flushPendingLabels(DF, DF->getContents().size()); DF->getContents().append(Data.begin(), Data.end()); // EmitBytes might not cover all possible ways we emit data (or could be used // to emit executable code in some cases), but is the best method we have // right now for checking this. MCSection *Sec = getCurrentSectionOnly(); Sec->setHasData(true); }
/// FormatDiagnostic - Format this diagnostic into a string, substituting the /// formal arguments into the %0 slots. The result is appended onto the Str /// array. void Diagnostic:: FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { if (!StoredDiagMessage.empty()) { OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); return; } StringRef Diag = getDiags()->getDiagnosticIDs()->getDescription(getID()); FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); }
static size_t findNull(StringRef S, size_t EntSize) { // Optimize the common case. if (EntSize == 1) return S.find(0); for (unsigned I = 0, N = S.size(); I != N; I += EntSize) { const char *B = S.begin() + I; if (std::all_of(B, B + EntSize, [](char C) { return C == 0; })) return I; } return StringRef::npos; }
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID. /// RewriteBuffer &Rewriter::getEditBuffer(FileID FID) { std::map<FileID, RewriteBuffer>::iterator I = RewriteBuffers.lower_bound(FID); if (I != RewriteBuffers.end() && I->first == FID) return I->second; I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer())); StringRef MB = SourceMgr->getBufferData(FID); I->second.Initialize(MB.begin(), MB.end()); return I->second; }
void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str, bool InsertAfter) { // Nothing to insert, exit early. if (Str.empty()) return; unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter); Buffer.insert(RealOffset, Str.begin(), Str.end()); // Add a delta so that future changes are offset correctly. AddInsertDelta(OrigOffset, Str.size()); }
bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { // For now, *just* base this on the function name, not on anything else. const IdentifierInfo *ident = fn->getIdentifier(); if (!ident) return false; StringRef functionName = ident->getName(); StringRef::iterator it = functionName.begin(); StringRef::iterator start = it; StringRef::iterator endI = functionName.end(); while (true) { // Scan for the start of 'create' or 'copy'. for ( ; it != endI ; ++it) { // Search for the first character. It can either be 'C' or 'c'. char ch = *it; if (ch == 'C' || ch == 'c') { // Make sure this isn't something like 'recreate' or 'Scopy'. if (ch == 'c' && it != start && isalpha(*(it - 1))) continue; ++it; break; } } // Did we hit the end of the string? If so, we didn't find a match. if (it == endI) return false; // Scan for *lowercase* 'reate' or 'opy', followed by no lowercase // character. StringRef suffix = functionName.substr(it - start); if (suffix.startswith("reate")) { it += 5; } else if (suffix.startswith("opy")) { it += 3; } else { // Keep scanning. continue; } if (it == endI || !islower(*it)) return true; // If we matched a lowercase character, it isn't the end of the // word. Keep scanning. } return false; }
std::string Disassembler::rawBytesToString(StringRef Bytes) { static const char hex_rep[] = "0123456789abcdef"; std::string Str; for (StringRef::iterator i = Bytes.begin(), e = Bytes.end(); i != e; ++i) { Str += hex_rep[(*i & 0xF0) >> 4]; Str += hex_rep[*i & 0xF]; Str += ' '; } return Str; }
// Escape XML characters inside the raw string. static void emitString(llvm::raw_svector_ostream &OS, const StringRef Raw) { for (StringRef::iterator I = Raw.begin(), E = Raw.end(); I != E; ++I) { char c = *I; switch (c) { default: OS << c; break; case '&': OS << "&"; break; case '<': OS << "<"; break; case '>': OS << ">"; break; case '\'': OS << "'"; break; case '\"': OS << """; break; } } }
StringRef EnumInfoCache::getEnumInfoKey(const clang::EnumDecl *decl, SmallVectorImpl<char> &scratch) { StringRef moduleName; if (auto moduleOpt = getClangSubmoduleForDecl(decl)) { if (*moduleOpt) moduleName = (*moduleOpt)->getTopLevelModuleName(); } if (moduleName.empty()) moduleName = decl->getASTContext().getLangOpts().CurrentModule; StringRef enumName = decl->getDeclName() ? decl->getName() : decl->getTypedefNameForAnonDecl()->getName(); if (moduleName.empty()) return enumName; scratch.append(moduleName.begin(), moduleName.end()); scratch.push_back('.'); scratch.append(enumName.begin(), enumName.end()); return StringRef(scratch.data(), scratch.size()); }
Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body, StringRef HintPath) const override { if (!HintPath.startswith(testRoot())) return make_error<StringError>( "Hint path doesn't start with test root: " + HintPath, inconvertibleErrorCode()); if (!Body.consume_front("/")) return make_error<StringError>( "Body of an unittest: URI must start with '/'", inconvertibleErrorCode()); SmallString<16> Path(Body.begin(), Body.end()); sys::path::native(Path); return testPath(Path); }
/// isValidName - Return true if Name is a valid custom metadata handler name. static bool isValidName(StringRef MDName) { if (MDName.empty()) return false; if (!isalpha(MDName[0])) return false; for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E; ++I) { if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.') return false; } return true; }
bool asctime(const StringRef &value, posix_time::ptime &datetime) { using namespace gregorian; using namespace posix_time; typedef date::year_type::value_type year_type; typedef date::month_type::value_type month_type; typedef date::day_type::value_type day_type; typedef time_duration::hour_type hour_type; typedef time_duration::min_type min_type; typedef time_duration::sec_type sec_type; static const std::basic_regex<typename StringRef::value_type> regex("(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) " // day "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) " // month-1 "((?:\\d| )\\d) " // day-2 "(\\d{2}):" // hour-3 "(\\d{2}):" // minutes-4 "(\\d{2}) " // seconds-5 "(\\d{4})" // year-6 ); std::match_results<typename StringRef::const_iterator> matches; if (!std::regex_match(value.begin(), value.end(), matches, regex)) return false; hour_type hour = from_decimal_submatch<hour_type>(matches[3]); min_type min = from_decimal_submatch<min_type>(matches[4]); sec_type sec = from_decimal_submatch<sec_type>(matches[5]); if (hour > 23 || min > 59 || sec > 60) return false; try { datetime = ptime(date(from_decimal_submatch<year_type>(matches[6]), from_submatch_to_month<month_type>(matches[1]), [&matches]() { auto m = matches[2]; if (*m.first == ' ') ++m.first; return from_decimal_submatch<day_type>(m); }()), time_duration(hour, min, sec)); } catch(std::out_of_range&) { return false; } return true; }