コード例 #1
0
ファイル: StringRef.cpp プロジェクト: 32bitmicro/llvm
// Compute the edit distance between the two given strings.
unsigned StringRef::edit_distance(llvm::StringRef Other,
                                  bool AllowReplacements,
                                  unsigned MaxEditDistance) {
  return llvm::ComputeEditDistance(
      llvm::ArrayRef<char>(data(), size()),
      llvm::ArrayRef<char>(Other.data(), Other.size()),
      AllowReplacements, MaxEditDistance);
}
コード例 #2
0
ファイル: StringRef.cpp プロジェクト: hsorby/opencor
// Compute the edit distance between the two given strings.
unsigned StringRef::edit_distance(llvm::StringRef Other,
                                  bool AllowReplacements,
                                  unsigned MaxEditDistance) const {
  return llvm::ComputeEditDistance(
      makeArrayRef(data(), size()),
      makeArrayRef(Other.data(), Other.size()),
      AllowReplacements, MaxEditDistance);
}
コード例 #3
0
void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
                                      llvm::StringRef Arg2) {
    if (DelayedDiagID)
        return;

    DelayedDiagID = DiagID;
    DelayedDiagArg1 = Arg1.str();
    DelayedDiagArg2 = Arg2.str();
}
コード例 #4
0
lldb::ScriptLanguage
ScriptInterpreter::StringToLanguage(const llvm::StringRef &language) {
  if (language.equals_lower(LanguageToString(eScriptLanguageNone)))
    return eScriptLanguageNone;
  else if (language.equals_lower(LanguageToString(eScriptLanguagePython)))
    return eScriptLanguagePython;
  else
    return eScriptLanguageUnknown;
}
コード例 #5
0
void PythonString::SetString(llvm::StringRef string) {
#if PY_MAJOR_VERSION >= 3
  PyObject *unicode = PyUnicode_FromStringAndSize(string.data(), string.size());
  PythonObject::Reset(PyRefType::Owned, unicode);
#else
  PyObject *str = PyString_FromStringAndSize(string.data(), string.size());
  PythonObject::Reset(PyRefType::Owned, str);
#endif
}
コード例 #6
0
bool
impl::ElfMatch_x86_amd64(llvm::StringRef arch_keyword,
                         llvm::StringRef arch_machine,
                         ElfClass cls)
{
    return (arch_keyword.equals_lower("x86") &&
            arch_machine.equals_lower("amd64") &&
            (cls == ELFCLASSNONE || cls == ELFCLASS64));
}
コード例 #7
0
ファイル: abi-arm.cpp プロジェクト: John-Colvin/ldc
 Type *vaListType() override {
   // We need to pass the actual va_list type for correct mangling. Simply
   // using TypeIdentifier here is a bit wonky but works, as long as the name
   // is actually available in the scope (this is what DMD does, so if a better
   // solution is found there, this should be adapted).
   static const llvm::StringRef ident = "__va_list";
   return (createTypeIdentifier(
       Loc(), Identifier::idPool(ident.data(), ident.size())));
 }
コード例 #8
0
    void redirect(llvm::StringRef file, bool apnd,
                  MetaProcessor::RedirectionScope scope) {
      if (file.empty()) {
        // Unredirection, remove last redirection state(s) for given scope(s)
        if (m_Stack.empty()) {
          cling::errs() << "No redirections left to remove\n";
          return;
        }

        MetaProcessor::RedirectionScope lScope = scope;
        SmallVector<RedirectStack::iterator, 2> Remove;
        for (auto it = m_Stack.rbegin(), e = m_Stack.rend(); it != e; ++it) {
          Redirect *R = (*it).get();
          const unsigned Match = R->Scope & lScope;
          if (Match) {
#ifdef LLVM_ON_WIN32
            // stdout back from stderr, fix up our console output on destruction
            if (m_TTY && R->FD == m_Bak[1] && scope & kSTDOUT)
              m_TTY = 2;
#endif
            // Clear the flag so restore below will ignore R for scope
            R->Scope = MetaProcessor::RedirectionScope(R->Scope & ~Match);
            // If no scope left, then R should be removed
            if (!R->Scope) {
              // standard [24.4.1/1] says &*(reverse_iterator(i)) == &*(i - 1)
              Remove.push_back(std::next(it).base());
            }
            // Clear match to reduce lScope (kSTDBOTH -> kSTDOUT or kSTDERR)
            lScope = MetaProcessor::RedirectionScope(lScope & ~Match);
            // If nothing to match anymore, then we're done
            if (!lScope)
              break;
          }
        }
        // std::vector::erase invalidates iterators at or after the point of
        // the erase, so if we reverse iterate on Remove everything is fine
        for (auto it = Remove.rbegin(), e = Remove.rend(); it != e; ++it)
          m_Stack.erase(*it);
      } else {
        // Add new redirection state
        if (push(new Redirect(file.str(), apnd, scope, m_Bak)) != kInvalidFD) {
          // Save a backup for the scope(s), if not already done
          if (scope & MetaProcessor::kSTDOUT)
            dupOnce(STDOUT_FILENO, m_Bak[0]);
          if (scope & MetaProcessor::kSTDERR)
            dupOnce(STDERR_FILENO, m_Bak[1]);
        } else
          return; // Failure
      }

      if (scope & MetaProcessor::kSTDOUT)
        m_CurStdOut =
            restore(STDOUT_FILENO, stdout, MetaProcessor::kSTDOUT, m_Bak[0]);
      if (scope & MetaProcessor::kSTDERR)
        restore(STDERR_FILENO, stderr, MetaProcessor::kSTDERR, m_Bak[1]);
    }
コード例 #9
0
static bool doesNoDiscardMacroExist(ASTContext &Context,
                                    const llvm::StringRef &MacroId) {
  // Don't check for the Macro existence if we are using an attribute
  // either a C++17 standard attribute or pre C++17 syntax
  if (MacroId.startswith("[[") || MacroId.startswith("__attribute__"))
    return true;

  // Otherwise look up the macro name in the context to see if its defined.
  return Context.Idents.get(MacroId).hasMacroDefinition();
}
コード例 #10
0
void ClangDocBitcodeWriter::emitRecord(llvm::StringRef Str, RecordId ID) {
  assert(RecordIdNameMap[ID] && "Unknown RecordId.");
  assert(RecordIdNameMap[ID].Abbrev == &StringAbbrev &&
         "Abbrev type mismatch.");
  if (!prepRecordData(ID, !Str.empty()))
    return;
  assert(Str.size() < (1U << BitCodeConstants::StringLengthSize));
  Record.push_back(Str.size());
  Stream.EmitRecordWithBlob(Abbrevs.get(ID), Record, Str);
}
コード例 #11
0
ファイル: Context.cpp プロジェクト: DevAndArtist/swift
std::string Context::demangleTypeAsString(llvm::StringRef MangledName,
                                          const DemangleOptions &Options) {
  NodePointer root = demangleTypeAsNode(MangledName);
  if (!root) return MangledName.str();
  
  std::string demangling = nodeToString(root, Options);
  if (demangling.empty())
    return MangledName.str();
  return demangling;
}
コード例 #12
0
ファイル: ObjectFile.cpp プロジェクト: CodaFi/swift-lldb
lldb::SymbolType
ObjectFile::GetSymbolTypeFromName(llvm::StringRef name,
                                  lldb::SymbolType symbol_type_hint) {
  if (!name.empty()) {
    if (name.startswith("_T")) {
      // Swift
      if (name.startswith("_TM"))
        return lldb::eSymbolTypeMetadata;
      if (name.startswith("_TWvd"))
        return lldb::eSymbolTypeIVarOffset;
    } else if (name.startswith("_OBJC_")) {
      // ObjC
      if (name.startswith("_OBJC_CLASS_$_"))
        return lldb::eSymbolTypeObjCClass;
      if (name.startswith("_OBJC_METACLASS_$_"))
        return lldb::eSymbolTypeObjCMetaClass;
      if (name.startswith("_OBJC_IVAR_$_"))
        return lldb::eSymbolTypeObjCIVar;
    } else if (name.startswith(".objc_class_name_")) {
      // ObjC v1
      return lldb::eSymbolTypeObjCClass;
    }
  }
  return symbol_type_hint;
}
コード例 #13
0
static void EscapeBackticks(llvm::StringRef str, std::string &dst) {
  dst.clear();
  dst.reserve(str.size());

  for (size_t i = 0, e = str.size(); i != e; ++i) {
    char c = str[i];
    if (c == '`') {
      if (i == 0 || str[i - 1] != '\\')
        dst += '\\';
    }
    dst += c;
  }
}
コード例 #14
0
ファイル: TestIndex.cpp プロジェクト: ingowald/llvm-project
Symbol symbol(llvm::StringRef QName) {
  Symbol Sym;
  Sym.ID = SymbolID(QName.str());
  size_t Pos = QName.rfind("::");
  if (Pos == llvm::StringRef::npos) {
    Sym.Name = QName;
    Sym.Scope = "";
  } else {
    Sym.Name = QName.substr(Pos + 2);
    Sym.Scope = QName.substr(0, Pos + 2);
  }
  return Sym;
}
コード例 #15
0
ファイル: ErrorBase.cpp プロジェクト: frc1678/third-party
void ErrorBase::SetGlobalWPIError(llvm::StringRef errorMessage,
                                  llvm::StringRef contextMessage,
                                  llvm::StringRef filename,
                                  llvm::StringRef function,
                                  uint32_t lineNumber) {
  std::string err = errorMessage.str() + ": " + contextMessage.str();

  std::lock_guard<priority_mutex> mutex(_globalErrorMutex);
  if (_globalError.GetCode() != 0) {
    _globalError.Clear();
  }
  _globalError.Set(-1, err, filename, function, lineNumber, nullptr);
}
コード例 #16
0
MCLDDirectory::MCLDDirectory(llvm::StringRef pName)
  : Directory(), m_Name(pName.data(), pName.size()) {
  Directory::m_Path.assign(pName.str());

  if (!Directory::m_Path.empty())
    m_bInSysroot = ('=' == Directory::m_Path.native()[0]);

  Directory::m_Path.m_append_separator_if_needed();
  if (m_bInSysroot)
    Directory::m_Path.native().erase(Directory::m_Path.native().begin());
  else
    detail::open_dir(*this);
}
コード例 #17
0
  int MetaProcessor::process(llvm::StringRef input_line,
                             Interpreter::CompilationResult& compRes,
                             Value* result,
                             bool disableValuePrinting /* = false */) {
    if (result)
      *result = Value();
    compRes = Interpreter::kSuccess;
    int expectedIndent = m_InputValidator->getExpectedIndent();

    if (expectedIndent)
      compRes = Interpreter::kMoreInputExpected;

    if (input_line.empty() ||
        (input_line.size() == 1 && input_line.front() == '\n')) {
      // just a blank line, nothing to do.
      return expectedIndent;
    }

    //  Check for and handle meta commands.
    m_MetaParser->enterNewInputLine(input_line);
    MetaSema::ActionResult actionResult = MetaSema::AR_Success;
    if (!m_InputValidator->inBlockComment() &&
         m_MetaParser->isMetaCommand(actionResult, result)) {

      if (m_MetaParser->isQuitRequested())
        return -1;

      if (actionResult != MetaSema::AR_Success)
        compRes = Interpreter::kFailure;
       // ExpectedIndent might have changed after meta command.
       return m_InputValidator->getExpectedIndent();
    }

    // Check if the current statement is now complete. If not, return to
    // prompt for more.
    if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) {
      compRes = Interpreter::kMoreInputExpected;
      return m_InputValidator->getExpectedIndent();
    }

    //  We have a complete statement, compile and execute it.
    std::string input;
    m_InputValidator->reset(&input);
    // if (m_Options.RawInput)
    //   compResLocal = m_Interp.declare(input);
    // else
    compRes = m_Interp.process(input, result, /*Transaction*/ nullptr,
                               disableValuePrinting);

    return 0;
  }
コード例 #18
0
ファイル: Interpreter.cpp プロジェクト: aurelie-flandi/root
  void Interpreter::GenerateAutoloadingMap(llvm::StringRef inFile,
                                           llvm::StringRef outFile,
                                           bool enableMacros,
                                           bool enableLogs) {

    const char *const dummy="cling";
    // Create an interpreter without any runtime, producing the fwd decls.
    cling::Interpreter fwdGen(1, &dummy, nullptr, true);

    // Copy the same header search options to the new instance.
    Preprocessor& fwdGenPP = fwdGen.getCI()->getPreprocessor();
    HeaderSearchOptions headerOpts = getCI()->getHeaderSearchOpts();
    clang::ApplyHeaderSearchOptions(fwdGenPP.getHeaderSearchInfo(), headerOpts,
                                    fwdGenPP.getLangOpts(),
                                    fwdGenPP.getTargetInfo().getTriple());


    CompilationOptions CO;
    CO.DeclarationExtraction = 0;
    CO.ValuePrinting = 0;
    CO.ResultEvaluation = 0;
    CO.DynamicScoping = 0;
    CO.Debug = isPrintingDebug();


    std::string includeFile = std::string("#include \"") + inFile.str() + "\"";
    cling::Transaction* T = fwdGen.m_IncrParser->Parse(includeFile , CO);

    // If this was already #included we will get a T == 0.
    if (!T)
      return;

    std::string err;
    llvm::raw_fd_ostream out(outFile.data(), err,
                             llvm::sys::fs::OpenFlags::F_None);
    if (enableLogs){
      llvm::raw_fd_ostream log(llvm::Twine(outFile).concat(llvm::Twine(".skipped")).str().c_str(),
                             err, llvm::sys::fs::OpenFlags::F_None);
      log << "Generated for :" << inFile << "\n";
      ForwardDeclPrinter visitor(out, log, fwdGen.getSema().getSourceManager(), *T);
      visitor.printStats();
    }
    else {
      llvm::raw_null_ostream sink;
      ForwardDeclPrinter visitor(out, sink, fwdGen.getSema().getSourceManager(), *T);
    }
    // Avoid assertion in the ~IncrementalParser.
    T->setState(Transaction::kCommitted);
    // unload(1);
    return;
  }
コード例 #19
0
ファイル: WireEncoder.cpp プロジェクト: gmckaskle/ntcore
void WireEncoder::WriteString(llvm::StringRef str) {
  // length
  std::size_t len = str.size();
  if (m_proto_rev < 0x0300u) {
    if (len > 0xffff) len = 0xffff; // Limited to 64K length; truncate
    Write16(len);
  } else
    WriteUleb128(len);

  // contents
  Reserve(len);
  std::memcpy(m_cur, str.data(), len);
  m_cur += len;
}
コード例 #20
0
InclusionDirective::InclusionDirective(PreprocessingRecord &PPRec,
                                       InclusionKind Kind, 
                                       llvm::StringRef FileName, 
                                       bool InQuotes, const FileEntry *File, 
                                       SourceRange Range)
  : PreprocessingDirective(InclusionDirectiveKind, Range), 
    InQuotes(InQuotes), Kind(Kind), File(File) 
{ 
  char *Memory 
    = (char*)PPRec.Allocate(FileName.size() + 1, llvm::alignOf<char>());
  memcpy(Memory, FileName.data(), FileName.size());
  Memory[FileName.size()] = 0;
  this->FileName = llvm::StringRef(Memory, FileName.size());
}
コード例 #21
0
lldb::OptionValueSP
OptionValueDictionary::GetSubValue(const ExecutionContext *exe_ctx,
                                   llvm::StringRef name, bool will_modify,
                                   Status &error) const {
  lldb::OptionValueSP value_sp;
  if (name.empty())
    return nullptr;

  llvm::StringRef left, temp;
  std::tie(left, temp) = name.split('[');
  if (left.size() == name.size()) {
    error.SetErrorStringWithFormat("invalid value path '%s', %s values only "
      "support '[<key>]' subvalues where <key> "
      "a string value optionally delimited by "
      "single or double quotes",
      name.str().c_str(), GetTypeAsCString());
    return nullptr;
  }
  assert(!temp.empty());

  llvm::StringRef key, quote_char;

  if (temp[0] == '\"' || temp[0] == '\'') {
    quote_char = temp.take_front();
    temp = temp.drop_front();
  }

  llvm::StringRef sub_name;
  std::tie(key, sub_name) = temp.split(']');

  if (!key.consume_back(quote_char) || key.empty()) {
    error.SetErrorStringWithFormat("invalid value path '%s', "
      "key names must be formatted as ['<key>'] where <key> "
      "is a string that doesn't contain quotes and the quote"
      " char is optional", name.str().c_str());
    return nullptr;
  }

  value_sp = GetValueForKey(ConstString(key));
  if (!value_sp) {
    error.SetErrorStringWithFormat(
      "dictionary does not contain a value for the key name '%s'",
      key.str().c_str());
    return nullptr;
  }

  if (sub_name.empty())
    return value_sp;
  return value_sp->GetSubValue(exe_ctx, sub_name, will_modify, error);
}
コード例 #22
0
ファイル: Context.cpp プロジェクト: DevAndArtist/swift
std::string Context::getThunkTarget(llvm::StringRef MangledName) {
  if (!isThunkSymbol(MangledName))
    return std::string();

  if (isMangledName(MangledName)) {
    // The targets of those thunks not derivable from the mangling.
    if (MangledName.endswith("TR") ||
        MangledName.endswith("Tr") ||
        MangledName.endswith("TW") )
      return std::string();

    if (MangledName.endswith("fC")) {
      std::string target = MangledName.str();
      target[target.size() - 1] = 'c';
      return target;
    }

    return MangledName.substr(0, MangledName.size() - 2).str();
  }
  // Old mangling.
  assert(MangledName.startswith("_T"));
  StringRef Remaining = MangledName.substr(2);
  if (Remaining.startswith("PA_"))
    return Remaining.substr(3).str();
  if (Remaining.startswith("PAo_"))
    return Remaining.substr(4).str();
  assert(Remaining.startswith("To") || Remaining.startswith("TO"));
  return std::string("_T") + Remaining.substr(2).str();
}
コード例 #23
0
bool RSContext::insertExportType(const llvm::StringRef &TypeName,
                                 RSExportType *ET) {
  ExportTypeMap::value_type *NewItem =
      ExportTypeMap::value_type::Create(TypeName.begin(),
                                        TypeName.end(),
                                        mExportTypes.getAllocator(),
                                        ET);

  if (mExportTypes.insert(NewItem)) {
    return true;
  } else {
    free(NewItem);
    return false;
  }
}
コード例 #24
0
uint32_t
PythonFile::GetOptionsFromMode(llvm::StringRef mode)
{
    if (mode.empty())
        return 0;

    return llvm::StringSwitch<uint32_t>(mode.str().c_str())
           .Case("r",   File::eOpenOptionRead)
           .Case("w",   File::eOpenOptionWrite)
           .Case("a",   File::eOpenOptionWrite|File::eOpenOptionAppend|File::eOpenOptionCanCreate)
           .Case("r+",  File::eOpenOptionRead|File::eOpenOptionWrite)
           .Case("w+",  File::eOpenOptionRead|File::eOpenOptionWrite|File::eOpenOptionCanCreate|File::eOpenOptionTruncate)
           .Case("a+",  File::eOpenOptionRead|File::eOpenOptionWrite|File::eOpenOptionAppend|File::eOpenOptionCanCreate)
           .Default(0);
}
コード例 #25
0
PythonObject
PythonObject::ResolveNameWithDictionary(llvm::StringRef name,
                                        const PythonDictionary &dict) {
  size_t dot_pos = name.find('.');
  llvm::StringRef piece = name.substr(0, dot_pos);
  PythonObject result = dict.GetItemForKey(PythonString(piece));
  if (dot_pos == llvm::StringRef::npos) {
    // There was no dot, we're done.
    return result;
  }

  // There was a dot.  The remaining portion of the name should be looked up in
  // the context of the object that was found in the dictionary.
  return result.ResolveName(name.substr(dot_pos + 1));
}
コード例 #26
0
ファイル: ErrorBase.cpp プロジェクト: frc1678/third-party
/**
 * @brief Set the current error information associated with this sensor.
 *
 * @param errorMessage   The error message from WPIErrors.h
 * @param contextMessage A custom message from the code that set the error.
 * @param filename       Filename of the error source
 * @param function       Function of the error source
 * @param lineNumber     Line number of the error source
 */
void ErrorBase::SetWPIError(llvm::StringRef errorMessage, Error::Code code,
                            llvm::StringRef contextMessage,
                            llvm::StringRef filename, llvm::StringRef function,
                            uint32_t lineNumber) const {
  std::string err = errorMessage.str() + ": " + contextMessage.str();

  //  Set the current error information for this object.
  m_error.Set(code, err, filename, function, lineNumber, this);

  // Update the global error if there is not one already set.
  std::lock_guard<priority_mutex> mutex(_globalErrorMutex);
  if (_globalError.GetCode() == 0) {
    _globalError.Clone(m_error);
  }
}
コード例 #27
0
ファイル: AutoloadCallback.cpp プロジェクト: bellenot/root
  void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name,
                                llvm::StringRef header) {
    Sema& sema= m_Interpreter->getSema();

    unsigned id
      = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
                                                 "Note: '%0' can be found in %1");
/*    unsigned idn //TODO: To be enabled after we have a way to get the full path
      = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
                                                "Type : %0 , Full Path: %1")*/;

    if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag)))
      sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag);

  }
コード例 #28
0
Status OptionValueChar::SetValueFromString(llvm::StringRef value,
                                           VarSetOperationType op) {
  Status error;
  switch (op) {
  case eVarSetOperationClear:
    Clear();
    break;

  case eVarSetOperationReplace:
  case eVarSetOperationAssign: {
    bool success = false;
    char char_value = OptionArgParser::ToChar(value, '\0', &success);
    if (success) {
      m_current_value = char_value;
      m_value_was_set = true;
    } else
      error.SetErrorStringWithFormat("'%s' cannot be longer than 1 character",
                                     value.str().c_str());
  } break;

  default:
    error = OptionValue::SetValueFromString(value, op);
    break;
  }
  return error;
}
コード例 #29
0
Error
OptionValueArch::SetValueFromString (llvm::StringRef value, VarSetOperationType op)
{
    Error error;
    switch (op)
    {
    case eVarSetOperationClear:
        Clear();
        NotifyValueChanged();
        break;
        
    case eVarSetOperationReplace:
    case eVarSetOperationAssign:
        {
            std::string value_str = value.trim().str();
            if (m_current_value.SetTriple (value_str.c_str()))
            {
                m_value_was_set = true;
                NotifyValueChanged();
            }
            else
                error.SetErrorStringWithFormat("unsupported architecture '%s'", value_str.c_str());
            break;
        }
    case eVarSetOperationInsertBefore:
    case eVarSetOperationInsertAfter:
    case eVarSetOperationRemove:
    case eVarSetOperationAppend:
    case eVarSetOperationInvalid:
        error = OptionValue::SetValueFromString (value, op);
        break;
    }
    return error;
}
コード例 #30
0
  static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {
    using namespace llvm::sys::fs;
    file_magic Magic;
    std::error_code Error = identify_magic(LibName, Magic);
    bool onDisk = (Error != std::errc::no_such_file_or_directory);
    if (exists)
      *exists = onDisk;

    return onDisk &&
#ifdef __APPLE__
      (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib_stub
       || Magic == file_magic::macho_universal_binary)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
      (Magic == file_magic::pecoff_executable)
#else
      (Magic == file_magic::elf_shared_object)
#endif
#elif defined(LLVM_ON_WIN32)
      (Magic == file_magic::pecoff_executable || is_dll(LibName.str().c_str()))
#else
# error "Unsupported platform."
#endif
      ;
  }