Optional<ReplacementItem> formatv_object_base::parseReplacementItem(StringRef Spec) { StringRef RepString = Spec.trim("{}"); // If the replacement sequence does not start with a non-negative integer, // this is an error. char Pad = ' '; std::size_t Align = 0; AlignStyle Where = AlignStyle::Right; StringRef Options; size_t Index = 0; RepString = RepString.trim(); if (RepString.consumeInteger(0, Index)) { assert(false && "Invalid replacement sequence index!"); return ReplacementItem{}; } RepString = RepString.trim(); if (!RepString.empty() && RepString.front() == ',') { RepString = RepString.drop_front(); if (!consumeFieldLayout(RepString, Where, Align, Pad)) assert(false && "Invalid replacement field layout specification!"); } RepString = RepString.trim(); if (!RepString.empty() && RepString.front() == ':') { Options = RepString.drop_front().trim(); RepString = StringRef(); } RepString = RepString.trim(); if (!RepString.empty()) { assert(false && "Unexpected characters found in replacement string!"); } return ReplacementItem{Spec, Index, Align, Where, Pad, Options}; }
static std::string auxName(StringRef ModuleName, StringRef InputName, StringRef TripleName, StringRef OutputType, StringRef OptType) { if (InputName.empty()) { InputName = "all"; } // Dispose of path prefix, which might make composite name too long. InputName = path::filename(InputName); if (OptType.empty()) { OptType = "Onone"; } if (!OutputType.empty() && OutputType.front() == '.') { OutputType = OutputType.substr(1); } if (!OptType.empty() && OptType.front() == '-') { OptType = OptType.substr(1); } return (cleanName(ModuleName) + "-" + cleanName(InputName) + "-" + cleanName(TripleName) + "-" + cleanName(OutputType) + "-" + cleanName(OptType)); }
/// Unescapes the given string value. /// /// Expects the string value to be quoted. static std::string unescapeQuotedString(StringRef Value) { assert(Value.front() == '"' && Value.back() == '"'); Cursor C = Cursor(Value.substr(1, Value.size() - 2)); std::string Str; Str.reserve(C.remaining().size()); while (!C.isEOF()) { char Char = C.peek(); if (Char == '\\') { if (C.peek(1) == '\\') { // Two '\' become one Str += '\\'; C.advance(2); continue; } if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) { Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2)); C.advance(3); continue; } } Str += Char; C.advance(); } return Str; }
bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result) { unsigned long long ULLVal; // Handle positive strings first. if (Str.empty() || Str.front() != '-') { if (getAsUnsignedInteger(Str, Radix, ULLVal) || // Check for value so large it overflows a signed value. (long long)ULLVal < 0) return true; Result = ULLVal; return false; } // Get the positive part of the value. if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) || // Reject values so large they'd overflow as negative signed, but allow // "-0". This negates the unsigned so that the negative isn't undefined // on signed overflow. (long long)-ULLVal > 0) return true; Result = -ULLVal; return false; }
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OIT_None; StringRef name = first->getName(); if (name.empty()) return OIT_None; switch (name.front()) { case 'a': if (startsWithWord(name, "alloc")) return OIT_MemManage; else if (startsWithWord(name, "array")) return OIT_Array; break; case 'd': if (startsWithWord(name, "dictionary")) return OIT_Dictionary; break; case 'i': if (startsWithWord(name, "init")) return OIT_MemManage; break; case 's': if (startsWithWord(name, "string")) return OIT_NSString; else if (startsWithWord(name, "set")) return OIT_NSSet; break; case 'U': if (startsWithWord(name, "URL")) return OIT_NSURL; break; default: break; } return OIT_None; }
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OIT_None; StringRef name = first->getName(); if (name.empty()) return OIT_None; switch (name.front()) { case 'a': if (startsWithWord(name, "array")) return OIT_Array; break; case 'd': if (startsWithWord(name, "default")) return OIT_ReturnsSelf; if (startsWithWord(name, "dictionary")) return OIT_Dictionary; break; case 's': if (startsWithWord(name, "shared")) return OIT_ReturnsSelf; if (startsWithWord(name, "standard")) return OIT_Singleton; case 'i': if (startsWithWord(name, "init")) return OIT_Init; default: break; } return OIT_None; }
void MIToken::unescapeQuotedStringValue(std::string &Str) const { assert(isStringValueQuoted() && "String value isn't quoted"); StringRef Value = Range.drop_front(StringOffset); assert(Value.front() == '"' && Value.back() == '"'); Cursor C = Cursor(Value.substr(1, Value.size() - 2)); Str.clear(); Str.reserve(C.remaining().size()); while (!C.isEOF()) { char Char = C.peek(); if (Char == '\\') { if (C.peek(1) == '\\') { // Two '\' become one Str += '\\'; C.advance(2); continue; } if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) { Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2)); C.advance(3); continue; } } Str += Char; C.advance(); } }
void Output::scalarString(StringRef &S) { const char ScalarSafeChars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/^., \t"; this->newLineCheck(); if (S.empty()) { // Print '' for the empty string because leaving the field empty is not // allowed. this->outputUpToEndOfLine("''"); return; } if (S.find_first_not_of(ScalarSafeChars) == StringRef::npos && !isspace(S.front()) && !isspace(S.back())) { // If the string consists only of safe characters, print it out without // quotes. this->outputUpToEndOfLine(S); return; } unsigned i = 0; unsigned j = 0; unsigned End = S.size(); output("'"); // Starting single quote. const char *Base = S.data(); while (j < End) { // Escape a single quote by doubling it. if (S[j] == '\'') { output(StringRef(&Base[i], j - i + 1)); output("'"); i = j + 1; } ++j; } output(StringRef(&Base[i], j - i)); this->outputUpToEndOfLine("'"); // Ending single quote. }
ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return SFF_None; StringRef name = first->getName(); switch (name.front()) { case 'a': if (name == "appendFormat") return SFF_NSString; break; case 'i': if (name == "initWithFormat") return SFF_NSString; break; case 'l': if (name == "localizedStringWithFormat") return SFF_NSString; break; case 's': if (name == "stringByAppendingFormat" || name == "stringWithFormat") return SFF_NSString; break; } return SFF_None; }
ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OMF_None; StringRef name = first->getName(); if (sel.isUnarySelector()) { if (name == "autorelease") return OMF_autorelease; if (name == "dealloc") return OMF_dealloc; if (name == "finalize") return OMF_finalize; if (name == "release") return OMF_release; if (name == "retain") return OMF_retain; if (name == "retainCount") return OMF_retainCount; if (name == "self") return OMF_self; if (name == "initialize") return OMF_initialize; } if (name == "performSelector" || name == "performSelectorInBackground" || name == "performSelectorOnMainThread") return OMF_performSelector; // The other method families may begin with a prefix of underscores. while (!name.empty() && name.front() == '_') name = name.substr(1); if (name.empty()) return OMF_None; switch (name.front()) { case 'a': if (startsWithWord(name, "alloc")) return OMF_alloc; break; case 'c': if (startsWithWord(name, "copy")) return OMF_copy; break; case 'i': if (startsWithWord(name, "init")) return OMF_init; break; case 'm': if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy; break; case 'n': if (startsWithWord(name, "new")) return OMF_new; break; default: break; } return OMF_None; }
/// getMDKindID - Return a unique non-zero ID for the specified metadata kind. unsigned LLVMContext::getMDKindID(StringRef Name) const { assert(!std::isdigit(Name.front()) && "Named metadata may not start with a digit"); // If this is new, assign it its ID. return pImpl->CustomMDKindNames.insert(std::make_pair( Name, pImpl->CustomMDKindNames.size())) .first->second; }
ID types::lookupTypeForExtension(StringRef Ext) { if (Ext.empty()) return TY_INVALID; assert(Ext.front() == '.' && "not a file extension"); return llvm::StringSwitch<types::ID>(Ext.drop_front()) #define TYPE(NAME, ID, SUFFIX, FLAGS) \ .Case(SUFFIX, TY_##ID) #include "swift/Driver/Types.def" .Default(TY_INVALID); }
bool HSAILELFMCAsmInfo::isValidUnquotedName(StringRef Name) const { char First = Name.front(); assert((First == '%' || First == '&' || First == '@') && "Missing valid prefix character"); Name = Name.drop_front(1); if (!Name.empty()) { if (!isValidFirstChar(Name.front())) return false; Name = Name.drop_front(); } for (char C : Name) { if (!isValidChar(C)) return false; } return true; }
uint32_t llvm::caseFoldingDjbHash(StringRef Buffer, uint32_t H) { while (!Buffer.empty()) { unsigned char C = Buffer.front(); if (LLVM_LIKELY(C <= 0x7f)) { // US-ASCII, encoded as one character in utf-8. // This is by far the most common case, so handle this specially. if (C >= 'A' && C <= 'Z') C = 'a' + (C - 'A'); // fold uppercase into lowercase H = (H << 5) + H + C; Buffer = Buffer.drop_front(); continue; } H = caseFoldingDjbHashCharSlow(Buffer, H); } return H; }
size_t QueryRequest::get_indices(StringRef name, IndexVec* indices) { set_has_names_for_values(true); if (value_names_.get_indices(name, indices) == 0) { if (value_names_.size() > elements_count()) { // No more space left for new named values return 0; } if (name.size() > 0 && name.front() == '"' && name.back() == '"') { name = name.substr(1, name.size() - 2); } indices->push_back(value_names_.add(ValueName(name.to_string()))); } return indices->size(); }
size_t CaseInsensitiveHashTable<T>::get_indices(StringRef name, IndexVec* result) const { result->clear(); bool is_case_sensitive = false; if (name.size() > 0 && name.front() == '"' && name.back() == '"') { is_case_sensitive = true; name = name.substr(1, name.size() - 2); } size_t h = fnv1a_hash_lower(name) & index_mask_; size_t start = h; while (index_[h] != NULL && !iequals(name, index_[h]->name)) { h = (h + 1) & index_mask_; if (h == start) { return 0; } } const T* entry = index_[h]; if (entry == NULL) { return 0; } if (!is_case_sensitive) { while (entry != NULL) { result->push_back(entry->index); entry = entry->next; } } else { while (entry != NULL) { if (name.equals(entry->name)) { result->push_back(entry->index); } entry = entry->next; } } return result->size(); }
bool TargetLibraryInfo::getLibFunc(StringRef funcName, LibFunc::Func &F) const { const char **Start = &StandardNames[0]; const char **End = &StandardNames[LibFunc::NumLibFuncs]; // Filter out empty names and names containing null bytes, those can't be in // our table. if (funcName.empty() || funcName.find('\0') != StringRef::npos) return false; // Check for \01 prefix that is used to mangle __asm declarations and // strip it if present. if (funcName.front() == '\01') funcName = funcName.substr(1); const char **I = std::lower_bound(Start, End, funcName, StringComparator()); if (I != End && *I == funcName) { F = (LibFunc::Func)(I - Start); return true; } return false; }
StringRef MCMachObjectSymbolizer::findExternalFunctionAt(uint64_t Addr) { // FIXME: also, this can all be done at the very beginning, by iterating over // all stubs and creating the calls to outside functions. Is it worth it // though? if (!StubSize) return StringRef(); uint64_t StubIdx = (Addr - StubsStart) / StubSize; if (StubIdx >= StubsCount) return StringRef(); uint32_t SymtabIdx = MOOF->getIndirectSymbolTableEntry(MOOF->getDysymtabLoadCommand(), StubIdx); StringRef SymName; symbol_iterator SI = MOOF->symbol_begin(); for (uint32_t i = 0; i != SymtabIdx; ++i) ++SI; SI->getName(SymName); assert(SI != MOOF->symbol_end() && "Stub wasn't found in the symbol table!"); assert(SymName.front() == '_' && "Mach-O symbol doesn't start with '_'!"); return SymName.substr(1); }
/// normalize Segment to "/foo/bar" or "". static void normalizePathSegment(std::string &Segment) { StringRef seg = Segment; // Prune trailing "/" or "./" while (1) { StringRef last = path::filename(seg); if (last != ".") break; seg = path::parent_path(seg); } if (seg.empty() || seg == "/") { Segment = ""; return; } // Add leading '/' if (seg.front() != '/') { Segment = "/" + seg.str(); } else { Segment = seg; } }
StringRef ScalarTraits<MCModuleYAML::Operand>::input(StringRef Scalar, void *Ctx, MCModuleYAML::Operand &Val) { InstrRegInfoHolder *IRI = (InstrRegInfoHolder *)Ctx; char Type = 0; if (Scalar.size() >= 1) Type = Scalar.front(); if (Type != 'R' && Type != 'I') return "Operand must start with 'R' (register) or 'I' (immediate)."; if (Type == 'R') { unsigned Reg; if (!IRI->matchRegister(Scalar.substr(1), Reg)) return "Invalid register name."; Val.MCOp = MCOperand::CreateReg(Reg); } else if (Type == 'I') { int64_t RIVal; if (Scalar.substr(1).getAsInteger(10, RIVal)) return "Invalid immediate value."; Val.MCOp = MCOperand::CreateImm(RIVal); } else { Val.MCOp = MCOperand(); } return StringRef(); }
static bool isFlagEnabled(StringRef Flag) { char Indicator = Flag.front(); assert(Indicator == '+' || Indicator == '-'); return Indicator == '+'; }
bool Punycode::decodePunycode(StringRef InputPunycode, std::vector<uint32_t> &OutCodePoints) { OutCodePoints.clear(); OutCodePoints.reserve(InputPunycode.size()); // -- Build the decoded string as UTF32 first because we need random access. uint32_t n = initial_n; int i = 0; int bias = initial_bias; /// let output = an empty string indexed from 0 // consume all code points before the last delimiter (if there is one) // and copy them to output, size_t lastDelimiter = InputPunycode.find_last_of(delimiter); if (lastDelimiter != StringRef::npos) { for (char c : InputPunycode.slice(0, lastDelimiter)) { // fail on any non-basic code point if (static_cast<unsigned char>(c) > 0x7f) return true; OutCodePoints.push_back(c); } // if more than zero code points were consumed then consume one more // (which will be the last delimiter) InputPunycode = InputPunycode.slice(lastDelimiter + 1, InputPunycode.size()); } while (!InputPunycode.empty()) { int oldi = i; int w = 1; for (int k = base; ; k += base) { // consume a code point, or fail if there was none to consume if (InputPunycode.empty()) return true; char codePoint = InputPunycode.front(); InputPunycode = InputPunycode.slice(1, InputPunycode.size()); // let digit = the code point's digit-value, fail if it has none int digit = digit_index(codePoint); if (digit < 0) return true; i = i + digit * w; int t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (digit < t) break; w = w * (base - t); } bias = adapt(i - oldi, OutCodePoints.size() + 1, oldi == 0); n = n + i / (OutCodePoints.size() + 1); i = i % (OutCodePoints.size() + 1); // if n is a basic code point then fail if (n < 0x80) return true; // insert n into output at position i OutCodePoints.insert(OutCodePoints.begin() + i, n); i++; } return true; }
bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const { StringRef Str = *this; // Autosense radix if not specified. if (Radix == 0) Radix = GetAutoSenseRadix(Str); assert(Radix > 1 && Radix <= 36); // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Skip leading zeroes. This can be a significant improvement if // it means we don't need > 64 bits. while (!Str.empty() && Str.front() == '0') Str = Str.substr(1); // If it was nothing but zeroes.... if (Str.empty()) { Result = APInt(64, 0); return false; } // (Over-)estimate the required number of bits. unsigned Log2Radix = 0; while ((1U << Log2Radix) < Radix) Log2Radix++; bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix); unsigned BitWidth = Log2Radix * Str.size(); if (BitWidth < Result.getBitWidth()) BitWidth = Result.getBitWidth(); // don't shrink the result else Result = Result.zext(BitWidth); APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix if (!IsPowerOf2Radix) { // These must have the same bit-width as Result. RadixAP = APInt(BitWidth, Radix); CharAP = APInt(BitWidth, 0); } // Parse all the bytes of the string given this radix. Result = 0; while (!Str.empty()) { unsigned CharVal; if (Str[0] >= '0' && Str[0] <= '9') CharVal = Str[0]-'0'; else if (Str[0] >= 'a' && Str[0] <= 'z') CharVal = Str[0]-'a'+10; else if (Str[0] >= 'A' && Str[0] <= 'Z') CharVal = Str[0]-'A'+10; else return true; // If the parsed value is larger than the integer radix, the string is // invalid. if (CharVal >= Radix) return true; // Add in this character. if (IsPowerOf2Radix) { Result <<= Log2Radix; Result |= CharVal; } else { Result *= RadixAP; CharAP = CharVal; Result += CharAP; } Str = Str.substr(1); } return false; }