From b7cb3b67bf7827235854256dc489a5ac13bc327c Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Sun, 8 Dec 2019 22:51:48 +0300 Subject: [PATCH 01/10] SR-11889: Using Located instead of std::pair --- include/swift/AST/ASTContext.h | 7 +-- include/swift/AST/Decl.h | 9 ++-- include/swift/AST/Module.h | 4 +- include/swift/AST/ModuleLoader.h | 5 ++- include/swift/Basic/Located.h | 39 ++++++++++++++++ include/swift/ClangImporter/ClangImporter.h | 6 +-- include/swift/Parse/CodeCompletionCallbacks.h | 2 +- include/swift/Sema/SourceLoader.h | 4 +- .../Serialization/SerializedModuleLoader.h | 10 ++--- lib/AST/ASTContext.cpp | 18 ++++---- lib/AST/ASTDumper.cpp | 2 +- lib/AST/ASTPrinter.cpp | 4 +- lib/AST/ImportCache.cpp | 2 +- lib/AST/Module.cpp | 14 +++--- lib/ClangImporter/ClangImporter.cpp | 28 ++++++------ lib/ClangImporter/DWARFImporter.cpp | 4 +- lib/ClangImporter/ImporterImpl.h | 4 +- lib/Frontend/Frontend.cpp | 4 +- lib/Frontend/ModuleInterfaceLoader.cpp | 6 +-- lib/Frontend/ModuleInterfaceSupport.cpp | 4 +- lib/FrontendTool/ImportedModules.cpp | 5 +-- lib/IDE/CodeCompletion.cpp | 15 +++---- lib/IDE/ModuleInterfacePrinting.cpp | 2 +- lib/IDE/SourceEntityWalker.cpp | 14 +++--- lib/IDE/SwiftSourceDocInfo.cpp | 2 +- lib/IRGen/GenDecl.cpp | 2 +- lib/Parse/ParseDecl.cpp | 12 ++--- lib/ParseSIL/ParseSIL.cpp | 18 ++++---- lib/SILGen/SILGenFunction.cpp | 2 +- lib/Sema/NameBinding.cpp | 44 +++++++++---------- lib/Sema/SourceLoader.cpp | 25 +++++------ lib/Serialization/ModuleFile.cpp | 16 +++---- lib/Serialization/Serialization.cpp | 2 +- lib/Serialization/SerializedModuleLoader.cpp | 26 +++++------ .../lib/SwiftLang/SwiftDocSupport.cpp | 4 +- .../lib/SwiftLang/SwiftEditorInterfaceGen.cpp | 4 +- .../lldb-moduleimport-test.cpp | 4 +- tools/swift-ide-test/swift-ide-test.cpp | 7 ++- 38 files changed, 209 insertions(+), 171 deletions(-) create mode 100644 include/swift/Basic/Located.h diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h index 51e85ae49a550..fd717bb31df10 100644 --- a/include/swift/AST/ASTContext.h +++ b/include/swift/AST/ASTContext.h @@ -26,6 +26,7 @@ #include "swift/AST/TypeAlignments.h" #include "swift/Basic/LangOptions.h" #include "swift/Basic/Malloc.h" +#include "swift/Basic/Located.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" @@ -718,12 +719,12 @@ class ASTContext final { /// /// Note that even if this check succeeds, errors may still occur if the /// module is loaded in full. - bool canImportModule(std::pair ModulePath); + bool canImportModule(Located ModulePath); /// \returns a module with a given name that was already loaded. If the /// module was not loaded, returns nullptr. ModuleDecl *getLoadedModule( - ArrayRef> ModulePath) const; + ArrayRef> ModulePath) const; ModuleDecl *getLoadedModule(Identifier ModuleName) const; @@ -733,7 +734,7 @@ class ASTContext final { /// be returned. /// /// \returns The requested module, or NULL if the module cannot be found. - ModuleDecl *getModule(ArrayRef> ModulePath); + ModuleDecl *getModule(ArrayRef> ModulePath); ModuleDecl *getModuleByName(StringRef ModuleName); diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index f129b5086a36d..4d714102a351f 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -40,6 +40,7 @@ #include "swift/Basic/NullablePtr.h" #include "swift/Basic/OptionalEnum.h" #include "swift/Basic/Range.h" +#include "swift/Basic/Located.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/TrailingObjects.h" @@ -1503,11 +1504,11 @@ enum class ImportKind : uint8_t { /// import Swift /// import typealias Swift.Int class ImportDecl final : public Decl, - private llvm::TrailingObjects> { + private llvm::TrailingObjects> { friend TrailingObjects; friend class Decl; public: - typedef std::pair AccessPathElement; + typedef Located AccessPathElement; private: SourceLoc ImportLoc; @@ -1577,9 +1578,9 @@ class ImportDecl final : public Decl, } SourceLoc getStartLoc() const { return ImportLoc; } - SourceLoc getLocFromSource() const { return getFullAccessPath().front().second; } + SourceLoc getLocFromSource() const { return getFullAccessPath().front().loc; } SourceRange getSourceRange() const { - return SourceRange(ImportLoc, getFullAccessPath().back().second); + return SourceRange(ImportLoc, getFullAccessPath().back().loc); } SourceLoc getKindLoc() const { return KindLoc; } diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h index 8f4a28ab2da87..d364053d313eb 100644 --- a/include/swift/AST/Module.h +++ b/include/swift/AST/Module.h @@ -132,14 +132,14 @@ enum class ResilienceStrategy : unsigned { /// \sa FileUnit class ModuleDecl : public DeclContext, public TypeDecl { public: - typedef ArrayRef> AccessPathTy; + typedef ArrayRef> AccessPathTy; typedef std::pair ImportedModule; static bool matchesAccessPath(AccessPathTy AccessPath, DeclName Name) { assert(AccessPath.size() <= 1 && "can only refer to top-level decls"); return AccessPath.empty() - || DeclName(AccessPath.front().first).matchesRef(Name); + || DeclName(AccessPath.front().item).matchesRef(Name); } /// Arbitrarily orders ImportedModule records, for inclusion in sets and such. diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h index af1d372659b69..92c05dc1f0630 100644 --- a/include/swift/AST/ModuleLoader.h +++ b/include/swift/AST/ModuleLoader.h @@ -23,6 +23,7 @@ #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/TinyPtrVector.h" +#include "swift/Basic/Located.h" namespace llvm { class FileCollector; @@ -100,7 +101,7 @@ class ModuleLoader { /// /// Note that even if this check succeeds, errors may still occur if the /// module is loaded in full. - virtual bool canImportModule(std::pair named) = 0; + virtual bool canImportModule(Located named) = 0; /// Import a module with the given module path. /// @@ -113,7 +114,7 @@ class ModuleLoader { /// emits a diagnostic and returns NULL. virtual ModuleDecl *loadModule(SourceLoc importLoc, - ArrayRef> path) = 0; + ArrayRef> path) = 0; /// Load extensions to the given nominal type. /// diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h new file mode 100644 index 0000000000000..34427aaf99ed2 --- /dev/null +++ b/include/swift/Basic/Located.h @@ -0,0 +1,39 @@ +//===--- Located.h - Source Location and Associated Value ----------*- C++ -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file forward declares and imports various common LLVM datatypes that +// swift wants to use unqualified. +// +//===----------------------------------------------------------------------===// + + +#ifndef SWIFT_BASIC_LOCATED_H +#define SWIFT_BASIC_LOCATED_H +#include "swift/Basic/SourceLoc.h" + +namespace swift { + +template +struct Located { + + T item; + + SourceLoc loc; + + template + friend bool operator ==(const Located lhs, const Located rhs) { + return lhs.item == rhs.item && lhs.loc == rhs.loc; + } +}; +} + +#endif // SWIFT_BASIC_LOCATED_H diff --git a/include/swift/ClangImporter/ClangImporter.h b/include/swift/ClangImporter/ClangImporter.h index 9150852c0088a..9cace98692d33 100644 --- a/include/swift/ClangImporter/ClangImporter.h +++ b/include/swift/ClangImporter/ClangImporter.h @@ -173,7 +173,7 @@ class ClangImporter final : public ClangModuleLoader { /// /// Note that even if this check succeeds, errors may still occur if the /// module is loaded in full. - virtual bool canImportModule(std::pair named) override; + virtual bool canImportModule(Located named) override; /// Import a module with the given module path. /// @@ -189,7 +189,7 @@ class ClangImporter final : public ClangModuleLoader { /// emits a diagnostic and returns NULL. virtual ModuleDecl *loadModule( SourceLoc importLoc, - ArrayRef> path) + ArrayRef> path) override; /// Determine whether \c overlayDC is within an overlay module for the @@ -399,7 +399,7 @@ class ClangImporter final : public ClangModuleLoader { /// Given the path of a Clang module, collect the names of all its submodules. /// Calling this function does not load the module. void collectSubModuleNames( - ArrayRef> path, + ArrayRef> path, std::vector &names) const; /// Given a Clang module, decide whether this module is imported already. diff --git a/include/swift/Parse/CodeCompletionCallbacks.h b/include/swift/Parse/CodeCompletionCallbacks.h index cf18c459c642e..e0b0de34a65c6 100644 --- a/include/swift/Parse/CodeCompletionCallbacks.h +++ b/include/swift/Parse/CodeCompletionCallbacks.h @@ -194,7 +194,7 @@ class CodeCompletionCallbacks { /// Complete the import decl with importable modules. virtual void - completeImportDecl(std::vector> &Path) {}; + completeImportDecl(std::vector> &Path) {}; /// Complete unresolved members after dot. virtual void completeUnresolvedMember(CodeCompletionExpr *E, diff --git a/include/swift/Sema/SourceLoader.h b/include/swift/Sema/SourceLoader.h index 004e7eb724ebd..cb8f4d19e9bf9 100644 --- a/include/swift/Sema/SourceLoader.h +++ b/include/swift/Sema/SourceLoader.h @@ -56,7 +56,7 @@ class SourceLoader : public ModuleLoader { /// /// Note that even if this check succeeds, errors may still occur if the /// module is loaded in full. - virtual bool canImportModule(std::pair named) override; + virtual bool canImportModule(Located named) override; /// Import a module with the given module path. /// @@ -69,7 +69,7 @@ class SourceLoader : public ModuleLoader { /// returns NULL. virtual ModuleDecl * loadModule(SourceLoc importLoc, - ArrayRef> path) override; + ArrayRef> path) override; /// Load extensions to the given nominal type. /// diff --git a/include/swift/Serialization/SerializedModuleLoader.h b/include/swift/Serialization/SerializedModuleLoader.h index 094941bcb50ac..7247ee8b34bc9 100644 --- a/include/swift/Serialization/SerializedModuleLoader.h +++ b/include/swift/Serialization/SerializedModuleLoader.h @@ -50,7 +50,7 @@ class SerializedModuleLoaderBase : public ModuleLoader { void collectVisibleTopLevelModuleNamesImpl(SmallVectorImpl &names, StringRef extension) const; - using AccessPathElem = std::pair; + using AccessPathElem = Located; bool findModule(AccessPathElem moduleID, SmallVectorImpl *moduleInterfacePath, std::unique_ptr *moduleBuffer, @@ -140,7 +140,7 @@ class SerializedModuleLoaderBase : public ModuleLoader { /// /// Note that even if this check succeeds, errors may still occur if the /// module is loaded in full. - virtual bool canImportModule(std::pair named) override; + virtual bool canImportModule(Located named) override; /// Import a module with the given module path. /// @@ -153,7 +153,7 @@ class SerializedModuleLoaderBase : public ModuleLoader { /// emits a diagnostic and returns a FailedImportModule object. virtual ModuleDecl * loadModule(SourceLoc importLoc, - ArrayRef> path) override; + ArrayRef> path) override; virtual void loadExtensions(NominalTypeDecl *nominal, @@ -240,10 +240,10 @@ class MemoryBufferSerializedModuleLoader : public SerializedModuleLoaderBase { public: virtual ~MemoryBufferSerializedModuleLoader(); - bool canImportModule(std::pair named) override; + bool canImportModule(Located named) override; ModuleDecl * loadModule(SourceLoc importLoc, - ArrayRef> path) override; + ArrayRef> path) override; /// Register a memory buffer that contains the serialized module for the given /// access path. This API is intended to be used by LLDB to add swiftmodules diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index 6c3d74ffb322d..96c5257100982 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -1468,12 +1468,12 @@ ClangModuleLoader *ASTContext::getDWARFModuleLoader() const { } ModuleDecl *ASTContext::getLoadedModule( - ArrayRef> ModulePath) const { + ArrayRef> ModulePath) const { assert(!ModulePath.empty()); // TODO: Swift submodules. if (ModulePath.size() == 1) { - return getLoadedModule(ModulePath[0].first); + return getLoadedModule(ModulePath[0].item); } return nullptr; } @@ -1723,13 +1723,13 @@ bool ASTContext::shouldPerformTypoCorrection() { return NumTypoCorrections <= LangOpts.TypoCorrectionLimit; } -bool ASTContext::canImportModule(std::pair ModulePath) { +bool ASTContext::canImportModule(Located ModulePath) { // If this module has already been successfully imported, it is importable. if (getLoadedModule(ModulePath) != nullptr) return true; // If we've failed loading this module before, don't look for it again. - if (FailedModuleImportNames.count(ModulePath.first)) + if (FailedModuleImportNames.count(ModulePath.item)) return false; // Otherwise, ask the module loaders. @@ -1739,12 +1739,12 @@ bool ASTContext::canImportModule(std::pair ModulePath) { } } - FailedModuleImportNames.insert(ModulePath.first); + FailedModuleImportNames.insert(ModulePath.item); return false; } ModuleDecl * -ASTContext::getModule(ArrayRef> ModulePath) { +ASTContext::getModule(ArrayRef> ModulePath) { assert(!ModulePath.empty()); if (auto *M = getLoadedModule(ModulePath)) @@ -1752,7 +1752,7 @@ ASTContext::getModule(ArrayRef> ModulePath) { auto moduleID = ModulePath[0]; for (auto &importer : getImpl().ModuleLoaders) { - if (ModuleDecl *M = importer->loadModule(moduleID.second, ModulePath)) { + if (ModuleDecl *M = importer->loadModule(moduleID.loc, ModulePath)) { return M; } } @@ -1761,7 +1761,7 @@ ASTContext::getModule(ArrayRef> ModulePath) { } ModuleDecl *ASTContext::getModuleByName(StringRef ModuleName) { - SmallVector, 4> + SmallVector, 4> AccessPath; while (!ModuleName.empty()) { StringRef SubModuleName; @@ -1778,7 +1778,7 @@ ModuleDecl *ASTContext::getStdlibModule(bool loadIfAbsent) { if (loadIfAbsent) { auto mutableThis = const_cast(this); TheStdlibModule = - mutableThis->getModule({ std::make_pair(StdlibModuleName, SourceLoc()) }); + mutableThis->getModule({{ StdlibModuleName, SourceLoc() }}); } else { TheStdlibModule = getLoadedModule(StdlibModuleName); } diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index 08e03ecfed560..2c8658354c632 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -589,7 +589,7 @@ namespace { OS << " '"; interleave(ID->getFullAccessPath(), [&](const ImportDecl::AccessPathElement &Elem) { - OS << Elem.first; + OS << Elem.item; }, [&] { OS << '.'; }); OS << "')"; diff --git a/lib/AST/ASTPrinter.cpp b/lib/AST/ASTPrinter.cpp index e4e038947fc01..e58dc963f79e3 100644 --- a/lib/AST/ASTPrinter.cpp +++ b/lib/AST/ASTPrinter.cpp @@ -2097,10 +2097,10 @@ void PrintAST::visitImportDecl(ImportDecl *decl) { interleave(decl->getFullAccessPath(), [&](const ImportDecl::AccessPathElement &Elem) { if (!Mods.empty()) { - Printer.printModuleRef(Mods.front(), Elem.first); + Printer.printModuleRef(Mods.front(), Elem.item); Mods = Mods.slice(1); } else { - Printer << Elem.first.str(); + Printer << Elem.item.str(); } }, [&] { Printer << "."; }); diff --git a/lib/AST/ImportCache.cpp b/lib/AST/ImportCache.cpp index 2d8ff08890c96..e99e8c8f419ea 100644 --- a/lib/AST/ImportCache.cpp +++ b/lib/AST/ImportCache.cpp @@ -57,7 +57,7 @@ void ImportSet::Profile( for (auto import : topLevelImports) { ID.AddInteger(import.first.size()); for (auto accessPathElt : import.first) { - ID.AddPointer(accessPathElt.first.getAsOpaquePointer()); + ID.AddPointer(accessPathElt.item.getAsOpaquePointer()); } ID.AddPointer(import.second); } diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp index 486a1e26ba6dd..90fe1cc7aa913 100644 --- a/lib/AST/Module.cpp +++ b/lib/AST/Module.cpp @@ -303,7 +303,7 @@ void SourceLookupCache::lookupVisibleDecls(AccessPathTy AccessPath, assert(AccessPath.size() <= 1 && "can only refer to top-level decls"); if (!AccessPath.empty()) { - auto I = TopLevelValues.find(AccessPath.front().first); + auto I = TopLevelValues.find(AccessPath.front().item); if (I == TopLevelValues.end()) return; for (auto vd : I->second) @@ -335,7 +335,7 @@ void SourceLookupCache::lookupClassMembers(AccessPathTy accessPath, for (ValueDecl *vd : member.second) { auto *nominal = vd->getDeclContext()->getSelfNominalTypeDecl(); - if (nominal && nominal->getName() == accessPath.front().first) + if (nominal && nominal->getName() == accessPath.front().item) consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup, DynamicLookupInfo::AnyObject); } @@ -367,7 +367,7 @@ void SourceLookupCache::lookupClassMember(AccessPathTy accessPath, if (!accessPath.empty()) { for (ValueDecl *vd : iter->second) { auto *nominal = vd->getDeclContext()->getSelfNominalTypeDecl(); - if (nominal && nominal->getName() == accessPath.front().first) + if (nominal && nominal->getName() == accessPath.front().item) results.push_back(vd); } return; @@ -1181,13 +1181,13 @@ void ModuleDecl::getImportedModulesForLookup( } bool ModuleDecl::isSameAccessPath(AccessPathTy lhs, AccessPathTy rhs) { - using AccessPathElem = std::pair; + using AccessPathElem = Located; if (lhs.size() != rhs.size()) return false; return std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](const AccessPathElem &lElem, const AccessPathElem &rElem) { - return lElem.first == rElem.first; + return lElem.item == rElem.item; }); } @@ -1251,12 +1251,12 @@ ModuleDecl::removeDuplicateImports(SmallVectorImpl &imports) { lhs.second->getReverseFullModuleName(), {}, rhs.second->getReverseFullModuleName(), {}); } - using AccessPathElem = std::pair; + using AccessPathElem = Located; return std::lexicographical_compare(lhs.first.begin(), lhs.first.end(), rhs.first.begin(), rhs.first.end(), [](const AccessPathElem &lElem, const AccessPathElem &rElem) { - return lElem.first.str() < rElem.first.str(); + return lElem.item.str() < rElem.item.str(); }); }); auto last = std::unique(imports.begin(), imports.end(), diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index e74b691817ed7..d4a4dbd05e400 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -1619,19 +1619,19 @@ void ClangImporter::collectVisibleTopLevelModuleNames( } void ClangImporter::collectSubModuleNames( - ArrayRef> path, + ArrayRef> path, std::vector &names) const { auto &clangHeaderSearch = Impl.getClangPreprocessor().getHeaderSearchInfo(); // Look up the top-level module first. clang::Module *clangModule = clangHeaderSearch.lookupModule( - path.front().first.str(), /*AllowSearch=*/true, + path.front().item.str(), /*AllowSearch=*/true, /*AllowExtraModuleMapSearch=*/true); if (!clangModule) return; clang::Module *submodule = clangModule; for (auto component : path.slice(1)) { - submodule = submodule->findSubmodule(component.first.str()); + submodule = submodule->findSubmodule(component.item.str()); if (!submodule) return; } @@ -1643,12 +1643,12 @@ bool ClangImporter::isModuleImported(const clang::Module *M) { return M->NameVisibility == clang::Module::NameVisibilityKind::AllVisible; } -bool ClangImporter::canImportModule(std::pair moduleID) { +bool ClangImporter::canImportModule(Located moduleID) { // Look up the top-level module to see if it exists. // FIXME: This only works with top-level modules. auto &clangHeaderSearch = Impl.getClangPreprocessor().getHeaderSearchInfo(); clang::Module *clangModule = - clangHeaderSearch.lookupModule(moduleID.first.str(), /*AllowSearch=*/true, + clangHeaderSearch.lookupModule(moduleID.item.str(), /*AllowSearch=*/true, /*AllowExtraModuleMapSearch=*/true); if (!clangModule) { return false; @@ -1662,13 +1662,13 @@ bool ClangImporter::canImportModule(std::pair moduleID) { } ModuleDecl *ClangImporter::Implementation::loadModuleClang( - SourceLoc importLoc, ArrayRef> path) { + SourceLoc importLoc, ArrayRef> path) { auto &clangContext = getClangASTContext(); auto &clangHeaderSearch = getClangPreprocessor().getHeaderSearchInfo(); // Look up the top-level module first, to see if it exists at all. clang::Module *clangModule = clangHeaderSearch.lookupModule( - path.front().first.str(), /*AllowSearch=*/true, + path.front().item.str(), /*AllowSearch=*/true, /*AllowExtraModuleMapSearch=*/true); if (!clangModule) return nullptr; @@ -1677,8 +1677,8 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( SmallVector, 4> clangPath; for (auto component : path) { - clangPath.push_back({&clangContext.Idents.get(component.first.str()), - exportSourceLoc(component.second)}); + clangPath.push_back({&clangContext.Idents.get(component.item.str()), + exportSourceLoc(component.loc)}); } auto &rawDiagClient = Instance->getDiagnosticClient(); @@ -1728,13 +1728,13 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( // Verify that the submodule exists. clang::Module *submodule = clangModule; for (auto &component : path.slice(1)) { - submodule = submodule->findSubmodule(component.first.str()); + submodule = submodule->findSubmodule(component.item.str()); // Special case: a submodule named "Foo.Private" can be moved to a top-level // module named "Foo_Private". Clang has special support for this. // We're limiting this to just submodules named "Private" because this will // put the Clang AST in a fatal error state if it /doesn't/ exist. - if (!submodule && component.first.str() == "Private" && + if (!submodule && component.item.str() == "Private" && (&component) == (&path[1])) { submodule = loadModule(llvm::makeArrayRef(clangPath).slice(0, 2), false); } @@ -1755,12 +1755,12 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( ModuleDecl * ClangImporter::loadModule(SourceLoc importLoc, - ArrayRef> path) { + ArrayRef> path) { return Impl.loadModule(importLoc, path); } ModuleDecl *ClangImporter::Implementation::loadModule( - SourceLoc importLoc, ArrayRef> path) { + SourceLoc importLoc, ArrayRef> path) { ModuleDecl *MD = nullptr; if (!DisableSourceImport) MD = loadModuleClang(importLoc, path); @@ -2786,7 +2786,7 @@ ImportDecl *swift::createImportDecl(ASTContext &Ctx, ArrayRef Exported) { auto *ImportedMod = ClangN.getClangModule(); assert(ImportedMod); - SmallVector, 4> AccessPath; + SmallVector, 4> AccessPath; auto *TmpMod = ImportedMod; while (TmpMod) { AccessPath.push_back({ Ctx.getIdentifier(TmpMod->Name), SourceLoc() }); diff --git a/lib/ClangImporter/DWARFImporter.cpp b/lib/ClangImporter/DWARFImporter.cpp index c1168b8d2569d..fab4bcbcf3c8b 100644 --- a/lib/ClangImporter/DWARFImporter.cpp +++ b/lib/ClangImporter/DWARFImporter.cpp @@ -99,13 +99,13 @@ static_assert(IsTriviallyDestructible::value, "DWARFModuleUnits are BumpPtrAllocated; the d'tor is not called"); ModuleDecl *ClangImporter::Implementation::loadModuleDWARF( - SourceLoc importLoc, ArrayRef> path) { + SourceLoc importLoc, ArrayRef> path) { // There's no importing from debug info if no importer is installed. if (!DWARFImporter) return nullptr; // FIXME: Implement submodule support! - Identifier name = path[0].first; + Identifier name = path[0].item; auto it = DWARFModuleUnits.find(name); if (it != DWARFModuleUnits.end()) return it->second->getParentModule(); diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h index f1e24877cd594..f21345fc10b15 100644 --- a/lib/ClangImporter/ImporterImpl.h +++ b/lib/ClangImporter/ImporterImpl.h @@ -621,12 +621,12 @@ class LLVM_LIBRARY_VISIBILITY ClangImporter::Implementation /// Load a module using the clang::CompilerInstance. ModuleDecl *loadModuleClang(SourceLoc importLoc, - ArrayRef> path); + ArrayRef> path); /// "Load" a module from debug info. Because debug info types are read on /// demand, this doesn't really do any work. ModuleDecl *loadModuleDWARF(SourceLoc importLoc, - ArrayRef> path); + ArrayRef> path); public: /// Load a module using either method. diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp index f43739bf2bde8..fe18c24bc92ff 100644 --- a/lib/Frontend/Frontend.cpp +++ b/lib/Frontend/Frontend.cpp @@ -778,7 +778,7 @@ ModuleDecl *CompilerInstance::importUnderlyingModule() { ModuleDecl *objCModuleUnderlyingMixedFramework = static_cast(Context->getClangModuleLoader()) ->loadModule(SourceLoc(), - std::make_pair(MainModule->getName(), SourceLoc())); + {{MainModule->getName(), SourceLoc()}}); if (objCModuleUnderlyingMixedFramework) return objCModuleUnderlyingMixedFramework; Diagnostics.diagnose(SourceLoc(), diag::error_underlying_module_not_found, @@ -808,7 +808,7 @@ void CompilerInstance::getImplicitlyImportedModules( if (Lexer::isIdentifier(ImplicitImportModuleName)) { auto moduleID = Context->getIdentifier(ImplicitImportModuleName); ModuleDecl *importModule = - Context->getModule(std::make_pair(moduleID, SourceLoc())); + Context->getModule({{moduleID, SourceLoc()}}); if (importModule) { importModules.push_back(importModule); } else { diff --git a/lib/Frontend/ModuleInterfaceLoader.cpp b/lib/Frontend/ModuleInterfaceLoader.cpp index 4b238525dd14e..42ed6c18fae43 100644 --- a/lib/Frontend/ModuleInterfaceLoader.cpp +++ b/lib/Frontend/ModuleInterfaceLoader.cpp @@ -340,7 +340,7 @@ struct ModuleRebuildInfo { /// normal cache, the prebuilt cache, a module adjacent to the interface, or /// a module that we'll build from a module interface. class ModuleInterfaceLoaderImpl { - using AccessPathElem = std::pair; + using AccessPathElem = Located; friend class swift::ModuleInterfaceLoader; ASTContext &ctx; llvm::vfs::FileSystem &fs; @@ -1020,10 +1020,10 @@ std::error_code ModuleInterfaceLoader::findModuleFilesInDirectory( } // Create an instance of the Impl to do the heavy lifting. - auto ModuleName = ModuleID.first.str(); + auto ModuleName = ModuleID.item.str(); ModuleInterfaceLoaderImpl Impl( Ctx, ModPath, InPath, ModuleName, - CacheDir, PrebuiltCacheDir, ModuleID.second, + CacheDir, PrebuiltCacheDir, ModuleID.loc, RemarkOnRebuildFromInterface, dependencyTracker, llvm::is_contained(PreferInterfaceForModules, ModuleName) ? diff --git a/lib/Frontend/ModuleInterfaceSupport.cpp b/lib/Frontend/ModuleInterfaceSupport.cpp index 7fa40c3a94b5f..2e30bc98dc0b0 100644 --- a/lib/Frontend/ModuleInterfaceSupport.cpp +++ b/lib/Frontend/ModuleInterfaceSupport.cpp @@ -49,7 +49,7 @@ static void diagnoseScopedImports(DiagnosticEngine &diags, for (const ModuleDecl::ImportedModule &importPair : imports) { if (importPair.first.empty()) continue; - diags.diagnose(importPair.first.front().second, + diags.diagnose(importPair.first.front().loc, diag::module_interface_scoped_import_unsupported); } } @@ -119,7 +119,7 @@ static void printImports(raw_ostream &out, ModuleDecl *M) { if (!import.first.empty()) { out << "/*"; for (const auto &accessPathElem : import.first) - out << "." << accessPathElem.first; + out << "." << accessPathElem.item; out << "*/"; } diff --git a/lib/FrontendTool/ImportedModules.cpp b/lib/FrontendTool/ImportedModules.cpp index 5b9837f424f99..59b6088da4d54 100644 --- a/lib/FrontendTool/ImportedModules.cpp +++ b/lib/FrontendTool/ImportedModules.cpp @@ -68,7 +68,7 @@ bool swift::emitImportedModules(ASTContext &Context, ModuleDecl *mainModule, auto accessPath = ID->getModulePath(); // only the top-level name is needed (i.e. A in A.B.C) - Modules.insert(accessPath[0].first.str()); + Modules.insert(accessPath[0].item.str()); } // And now look in the C code we're possibly using. @@ -98,8 +98,7 @@ bool swift::emitImportedModules(ASTContext &Context, ModuleDecl *mainModule, } if (opts.ImportUnderlyingModule) { - auto underlyingModule = clangImporter->loadModule( - SourceLoc(), std::make_pair(mainModule->getName(), SourceLoc())); + auto underlyingModule = clangImporter->loadModule(SourceLoc(), {{ mainModule->getName(), SourceLoc() }}); if (!underlyingModule) { Context.Diags.diagnose(SourceLoc(), diag::error_underlying_module_not_found, diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index 0c0ec66fb7fb8..fe74c698d2c53 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -1377,7 +1377,7 @@ class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks { void completeAccessorBeginning(CodeCompletionExpr *E) override; void completePoundAvailablePlatform() override; - void completeImportDecl(std::vector> &Path) override; + void completeImportDecl(std::vector> &Path) override; void completeUnresolvedMember(CodeCompletionExpr *E, SourceLoc DotLoc) override; void completeCallArg(CodeCompletionExpr *E, bool isFirst) override; @@ -4080,10 +4080,9 @@ class CompletionLookup final : public swift::VisibleDeclConsumer { Kind = LookupKind::ImportFromModule; NeedLeadingDot = ResultsHaveLeadingDot; - llvm::SmallVector, 1> LookupAccessPath; + llvm::SmallVector, 1> LookupAccessPath; for (auto Piece : AccessPath) { - LookupAccessPath.push_back( - std::make_pair(Ctx.getIdentifier(Piece), SourceLoc())); + LookupAccessPath.push_back({Ctx.getIdentifier(Piece), SourceLoc()}); } AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this); TheModule->lookupVisibleDecls(LookupAccessPath, FilteringConsumer, @@ -4725,10 +4724,10 @@ void CodeCompletionCallbacksImpl::completeCaseStmtBeginning(CodeCompletionExpr * } void CodeCompletionCallbacksImpl::completeImportDecl( - std::vector> &Path) { + std::vector> &Path) { Kind = CompletionKind::Import; CurDeclContext = P.CurDeclContext; - DotLoc = Path.empty() ? SourceLoc() : Path.back().second; + DotLoc = Path.empty() ? SourceLoc() : Path.back().loc; if (DotLoc.isInvalid()) return; auto Importer = static_cast(CurDeclContext->getASTContext(). @@ -4737,7 +4736,7 @@ void CodeCompletionCallbacksImpl::completeImportDecl( Importer->collectSubModuleNames(Path, SubNames); ASTContext &Ctx = CurDeclContext->getASTContext(); for (StringRef Sub : SubNames) { - Path.push_back(std::make_pair(Ctx.getIdentifier(Sub), SourceLoc())); + Path.push_back({ Ctx.getIdentifier(Sub), SourceLoc() }); SubModuleNameVisibilityPairs.push_back( std::make_pair(Sub.str(), Ctx.getLoadedModule(Path))); Path.pop_back(); @@ -5574,7 +5573,7 @@ void CodeCompletionCallbacksImpl::doneParsing() { std::vector AccessPath; for (auto Piece : Path) { - AccessPath.push_back(Piece.first.str()); + AccessPath.push_back(Piece.item.str()); } StringRef ModuleFilename = TheModule->getModuleFilename(); diff --git a/lib/IDE/ModuleInterfacePrinting.cpp b/lib/IDE/ModuleInterfacePrinting.cpp index e87deadb53b05..e2cdc3f37eabf 100644 --- a/lib/IDE/ModuleInterfacePrinting.cpp +++ b/lib/IDE/ModuleInterfacePrinting.cpp @@ -448,7 +448,7 @@ void swift::ide::printSubmoduleInterface( auto RHSPath = RHS->getFullAccessPath(); for (unsigned i = 0, e = std::min(LHSPath.size(), RHSPath.size()); i != e; i++) { - if (int Ret = LHSPath[i].first.str().compare(RHSPath[i].first.str())) + if (int Ret = LHSPath[i].item.str().compare(RHSPath[i].item.str())) return Ret < 0; } return false; diff --git a/lib/IDE/SourceEntityWalker.cpp b/lib/IDE/SourceEntityWalker.cpp index 156a64129b648..f7d679ae4fd72 100644 --- a/lib/IDE/SourceEntityWalker.cpp +++ b/lib/IDE/SourceEntityWalker.cpp @@ -74,7 +74,7 @@ class SemaAnnotator : public ASTWalker { bool passReference(ValueDecl *D, Type Ty, SourceLoc Loc, SourceRange Range, ReferenceMetaData Data); bool passReference(ValueDecl *D, Type Ty, DeclNameLoc Loc, ReferenceMetaData Data); - bool passReference(ModuleEntity Mod, std::pair IdLoc); + bool passReference(ModuleEntity Mod, Located IdLoc); bool passSubscriptReference(ValueDecl *D, SourceLoc Loc, ReferenceMetaData Data, bool IsOpenBracket); @@ -270,7 +270,7 @@ std::pair SemaAnnotator::walkToExprPre(Expr *E) { if (auto *DRE = dyn_cast(E)) { if (auto *module = dyn_cast(DRE->getDecl())) { if (!passReference(ModuleEntity(module), - std::make_pair(module->getName(), E->getLoc()))) + {module->getName(), E->getLoc()})) return { false, nullptr }; } else if (!passReference(DRE->getDecl(), DRE->getType(), DRE->getNameLoc(), @@ -491,7 +491,7 @@ bool SemaAnnotator::walkToTypeReprPre(TypeRepr *T) { if (ValueDecl *VD = IdT->getBoundDecl()) { if (auto *ModD = dyn_cast(VD)) { auto ident = IdT->getNameRef().getBaseIdentifier(); - return passReference(ModD, std::make_pair(ident, IdT->getLoc())); + return passReference(ModD, { ident, IdT->getLoc() }); } return passReference(VD, Type(), IdT->getNameLoc(), @@ -669,11 +669,11 @@ passReference(ValueDecl *D, Type Ty, SourceLoc BaseNameLoc, SourceRange Range, } bool SemaAnnotator::passReference(ModuleEntity Mod, - std::pair IdLoc) { - if (IdLoc.second.isInvalid()) + Located IdLoc) { + if (IdLoc.loc.isInvalid()) return true; - unsigned NameLen = IdLoc.first.getLength(); - CharSourceRange Range{ IdLoc.second, NameLen }; + unsigned NameLen = IdLoc.item.getLength(); + CharSourceRange Range{ IdLoc.loc, NameLen }; bool Continue = SEWalker.visitModuleReference(Mod, Range); if (!Continue) Cancelled = true; diff --git a/lib/IDE/SwiftSourceDocInfo.cpp b/lib/IDE/SwiftSourceDocInfo.cpp index bb645722236da..4861fbe40d92e 100644 --- a/lib/IDE/SwiftSourceDocInfo.cpp +++ b/lib/IDE/SwiftSourceDocInfo.cpp @@ -246,7 +246,7 @@ bool NameMatcher::walkToDeclPre(Decl *D) { } } else if (ImportDecl *ID = dyn_cast(D)) { for(const ImportDecl::AccessPathElement &Element: ID->getFullAccessPath()) { - tryResolve(ASTWalker::ParentTy(D), Element.second); + tryResolve(ASTWalker::ParentTy(D), Element.loc); if (isDone()) break; } diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index cc5e490b601ca..08e6d79e04976 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -1091,7 +1091,7 @@ void IRGenModule::finishEmitAfterTopLevel() { if (DebugInfo) { if (ModuleDecl *TheStdlib = Context.getStdlibModule()) { if (TheStdlib != getSwiftModule()) { - std::pair AccessPath[] = { + Located AccessPath[] = { { Context.StdlibModuleName, swift::SourceLoc() } }; diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 849ccd8a4fa94..74b87ee2cd791 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -4066,7 +4066,7 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, KindLoc = consumeToken(); } - std::vector> ImportPath; + std::vector> ImportPath; bool HasNext; do { SyntaxParsingContext AccessCompCtx(SyntaxContext, @@ -4078,8 +4078,8 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, } return makeParserCodeCompletionStatus(); } - ImportPath.push_back(std::make_pair(Identifier(), Tok.getLoc())); - if (parseAnyIdentifier(ImportPath.back().first, + ImportPath.push_back({Identifier(), Tok.getLoc()}); + if (parseAnyIdentifier(ImportPath.back().item, diag::expected_identifier_in_decl, "import")) return nullptr; HasNext = consumeIf(tok::period); @@ -4092,8 +4092,8 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, // We omit the code completion token if it immediately follows the module // identifiers. auto BufferId = SourceMgr.getCodeCompletionBufferID(); - auto IdEndOffset = SourceMgr.getLocOffsetInBuffer(ImportPath.back().second, - BufferId) + ImportPath.back().first.str().size(); + auto IdEndOffset = SourceMgr.getLocOffsetInBuffer(ImportPath.back().loc, + BufferId) + ImportPath.back().item.str().size(); auto CCTokenOffset = SourceMgr.getLocOffsetInBuffer(SourceMgr. getCodeCompletionLoc(), BufferId); if (IdEndOffset == CCTokenOffset) { @@ -4102,7 +4102,7 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, } if (Kind != ImportKind::Module && ImportPath.size() == 1) { - diagnose(ImportPath.front().second, diag::decl_expected_module_name); + diagnose(ImportPath.front().loc, diag::decl_expected_module_name); return nullptr; } diff --git a/lib/ParseSIL/ParseSIL.cpp b/lib/ParseSIL/ParseSIL.cpp index f20d804df0060..1bbd13839c659 100644 --- a/lib/ParseSIL/ParseSIL.cpp +++ b/lib/ParseSIL/ParseSIL.cpp @@ -60,7 +60,7 @@ class SILParserTUState : public SILParserTUStateBase { /// This is all of the forward referenced functions with /// the location for where the reference is. llvm::DenseMap> ForwardRefFns; + Located> ForwardRefFns; /// A list of all functions forward-declared by a sil_scope. llvm::DenseSet PotentialZombieFns; @@ -85,8 +85,8 @@ class SILParserTUState : public SILParserTUStateBase { SILParserTUState::~SILParserTUState() { if (!ForwardRefFns.empty()) { for (auto Entry : ForwardRefFns) { - if (Entry.second.second.isValid()) { - M.getASTContext().Diags.diagnose(Entry.second.second, + if (Entry.second.loc.isValid()) { + M.getASTContext().Diags.diagnose(Entry.second.loc, diag::sil_use_of_undefined_value, Entry.first.str()); } @@ -613,13 +613,13 @@ SILFunction *SILParser::getGlobalNameForDefinition(Identifier name, // complete the forward reference. auto iter = TUState.ForwardRefFns.find(name); if (iter != TUState.ForwardRefFns.end()) { - SILFunction *fn = iter->second.first; + SILFunction *fn = iter->second.item; // Verify that the types match up. if (fn->getLoweredFunctionType() != ty) { P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(), fn->getLoweredFunctionType(), ty); - P.diagnose(iter->second.second, diag::sil_prior_reference); + P.diagnose(iter->second.loc, diag::sil_prior_reference); fn = builder.createFunctionForForwardReference("" /*name*/, ty, silLoc); } @@ -2375,13 +2375,13 @@ bool SILParser::parseSILInstruction(SILBuilder &B) { return true; } - SmallVector, 4> resultNames; + SmallVector, 4> resultNames; SourceLoc resultClauseBegin; // If the instruction has a name '%foo =', parse it. if (P.Tok.is(tok::sil_local_name)) { resultClauseBegin = P.Tok.getLoc(); - resultNames.push_back(std::make_pair(P.Tok.getText(), P.Tok.getLoc())); + resultNames.push_back({P.Tok.getText(), P.Tok.getLoc()}); P.consumeToken(tok::sil_local_name); // If the instruction has a '(%foo, %bar) = ', parse it. @@ -2395,7 +2395,7 @@ bool SILParser::parseSILInstruction(SILBuilder &B) { return true; } - resultNames.push_back(std::make_pair(P.Tok.getText(), P.Tok.getLoc())); + resultNames.push_back({P.Tok.getText(), P.Tok.getLoc()}); P.consumeToken(tok::sil_local_name); if (P.consumeIf(tok::comma)) @@ -5084,7 +5084,7 @@ bool SILParser::parseSILInstruction(SILBuilder &B) { results.size()); } else { for (size_t i : indices(results)) { - setLocalValue(results[i], resultNames[i].first, resultNames[i].second); + setLocalValue(results[i], resultNames[i].item, resultNames[i].loc); } } } diff --git a/lib/SILGen/SILGenFunction.cpp b/lib/SILGen/SILGenFunction.cpp index 2548a1901de44..af4e167d37460 100644 --- a/lib/SILGen/SILGenFunction.cpp +++ b/lib/SILGen/SILGenFunction.cpp @@ -538,7 +538,7 @@ void SILGenFunction::emitArtificialTopLevel(ClassDecl *mainClass) { // be imported. ASTContext &ctx = getASTContext(); - std::pair UIKitName = + Located UIKitName = {ctx.getIdentifier("UIKit"), SourceLoc()}; ModuleDecl *UIKit = ctx diff --git a/lib/Sema/NameBinding.cpp b/lib/Sema/NameBinding.cpp index 4b86626e941da..28e6ab7b71127 100644 --- a/lib/Sema/NameBinding.cpp +++ b/lib/Sema/NameBinding.cpp @@ -61,19 +61,19 @@ namespace { /// Load a module referenced by an import statement. /// /// Returns null if no module can be loaded. - ModuleDecl *getModule(ArrayRef> ModuleID); + ModuleDecl *getModule(ArrayRef> ModuleID); }; } // end anonymous namespace ModuleDecl * -NameBinder::getModule(ArrayRef> modulePath) { +NameBinder::getModule(ArrayRef> modulePath) { assert(!modulePath.empty()); auto moduleID = modulePath[0]; // The Builtin module cannot be explicitly imported unless we're a .sil file // or in the REPL. if ((SF.Kind == SourceFileKind::SIL || SF.Kind == SourceFileKind::REPL) && - moduleID.first == Context.TheBuiltinModule->getName()) + moduleID.item == Context.TheBuiltinModule->getName()) return Context.TheBuiltinModule; // If the imported module name is the same as the current module, @@ -82,10 +82,10 @@ NameBinder::getModule(ArrayRef> modulePath) { // // FIXME: We'd like to only use this in SIL mode, but unfortunately we use it // for our fake overlays as well. - if (moduleID.first == SF.getParentModule()->getName() && + if (moduleID.item == SF.getParentModule()->getName() && modulePath.size() == 1) { if (auto importer = Context.getClangModuleLoader()) - return importer->loadModule(moduleID.second, modulePath); + return importer->loadModule(moduleID.loc, modulePath); return nullptr; } @@ -170,17 +170,17 @@ static bool shouldImportSelfImportClang(const ImportDecl *ID, void NameBinder::addImport( SmallVectorImpl &imports, ImportDecl *ID) { - if (ID->getModulePath().front().first == SF.getParentModule()->getName() && + if (ID->getModulePath().front().item == SF.getParentModule()->getName() && ID->getModulePath().size() == 1 && !shouldImportSelfImportClang(ID, SF)) { // If the imported module name is the same as the current module, // produce a diagnostic. StringRef filename = llvm::sys::path::filename(SF.getFilename()); if (filename.empty()) Context.Diags.diagnose(ID, diag::sema_import_current_module, - ID->getModulePath().front().first); + ID->getModulePath().front().item); else Context.Diags.diagnose(ID, diag::sema_import_current_module_with_file, - filename, ID->getModulePath().front().first); + filename, ID->getModulePath().front().item); ID->setModule(SF.getParentModule()); return; } @@ -190,7 +190,7 @@ void NameBinder::addImport( SmallString<64> modulePathStr; interleave(ID->getModulePath(), [&](ImportDecl::AccessPathElement elem) { - modulePathStr += elem.first.str(); + modulePathStr += elem.item.str(); }, [&] { modulePathStr += "."; }); @@ -214,7 +214,7 @@ void NameBinder::addImport( topLevelModule = M; } else { // If we imported a submodule, import the top-level module as well. - Identifier topLevelName = ID->getModulePath().front().first; + Identifier topLevelName = ID->getModulePath().front().item; topLevelModule = Context.getLoadedModule(topLevelName); if (!topLevelModule) { // Clang can sometimes import top-level modules as if they were @@ -234,8 +234,8 @@ void NameBinder::addImport( !topLevelModule->isTestingEnabled() && !topLevelModule->isNonSwiftModule() && Context.LangOpts.EnableTestableAttrRequiresTestableModule) { - diagnose(ID->getModulePath().front().second, diag::module_not_testable, - ID->getModulePath().front().first); + diagnose(ID->getModulePath().front().loc, diag::module_not_testable, + ID->getModulePath().front().item); testableAttr->setInvalid(); } @@ -243,9 +243,9 @@ void NameBinder::addImport( StringRef privateImportFileName; if (privateImportAttr) { if (!topLevelModule || !topLevelModule->arePrivateImportsEnabled()) { - diagnose(ID->getModulePath().front().second, + diagnose(ID->getModulePath().front().loc, diag::module_not_compiled_for_private_import, - ID->getModulePath().front().first); + ID->getModulePath().front().item); privateImportAttr->setInvalid(); } else { privateImportFileName = privateImportAttr->getSourceFile(); @@ -256,7 +256,7 @@ void NameBinder::addImport( !topLevelModule->isResilient() && !topLevelModule->isNonSwiftModule() && !ID->getAttrs().hasAttribute()) { - diagnose(ID->getModulePath().front().second, + diagnose(ID->getModulePath().front().loc, diag::module_not_compiled_with_library_evolution, topLevelModule->getName(), SF.getParentModule()->getName()); } @@ -296,17 +296,17 @@ void NameBinder::addImport( // FIXME: Doesn't handle scoped testable imports correctly. assert(declPath.size() == 1 && "can't handle sub-decl imports"); SmallVector decls; - lookupInModule(topLevelModule, declPath.front().first, decls, + lookupInModule(topLevelModule, declPath.front().item, decls, NLKind::QualifiedLookup, ResolutionKind::Overloadable, &SF); if (decls.empty()) { diagnose(ID, diag::decl_does_not_exist_in_module, static_cast(ID->getImportKind()), - declPath.front().first, - ID->getModulePath().front().first) - .highlight(SourceRange(declPath.front().second, - declPath.back().second)); + declPath.front().item, + ID->getModulePath().front().item) + .highlight(SourceRange(declPath.front().loc, + declPath.back().loc)); return; } @@ -316,7 +316,7 @@ void NameBinder::addImport( if (!actualKind.hasValue()) { // FIXME: print entire module name? diagnose(ID, diag::ambiguous_decl_in_module, - declPath.front().first, M->getName()); + declPath.front().item, M->getName()); for (auto next : decls) diagnose(next, diag::found_candidate); @@ -338,7 +338,7 @@ void NameBinder::addImport( getImportKindString(ID->getImportKind()))); } else { emittedDiag.emplace(diagnose(ID, diag::imported_decl_is_wrong_kind, - declPath.front().first, + declPath.front().item, getImportKindString(ID->getImportKind()), static_cast(*actualKind))); } diff --git a/lib/Sema/SourceLoader.cpp b/lib/Sema/SourceLoader.cpp index 690631dc9f5cb..1c7553f062a7e 100644 --- a/lib/Sema/SourceLoader.cpp +++ b/lib/Sema/SourceLoader.cpp @@ -62,15 +62,15 @@ void SourceLoader::collectVisibleTopLevelModuleNames( // TODO: Implement? } -bool SourceLoader::canImportModule(std::pair ID) { +bool SourceLoader::canImportModule(Located ID) { // Search the memory buffers to see if we can find this file on disk. - FileOrError inputFileOrError = findModule(Ctx, ID.first.str(), - ID.second); + FileOrError inputFileOrError = findModule(Ctx, ID.item.str(), + ID.loc); if (!inputFileOrError) { auto err = inputFileOrError.getError(); if (err != std::errc::no_such_file_or_directory) { - Ctx.Diags.diagnose(ID.second, diag::sema_opening_import, - ID.first, err.message()); + Ctx.Diags.diagnose(ID.loc, diag::sema_opening_import, + ID.item, err.message()); } return false; @@ -79,21 +79,20 @@ bool SourceLoader::canImportModule(std::pair ID) { } ModuleDecl *SourceLoader::loadModule(SourceLoc importLoc, - ArrayRef> path) { + ArrayRef> path) { // FIXME: Swift submodules? if (path.size() > 1) return nullptr; auto moduleID = path[0]; - FileOrError inputFileOrError = findModule(Ctx, moduleID.first.str(), - moduleID.second); + FileOrError inputFileOrError = findModule(Ctx, moduleID.item.str(), + moduleID.loc); if (!inputFileOrError) { auto err = inputFileOrError.getError(); if (err != std::errc::no_such_file_or_directory) { - Ctx.Diags.diagnose(moduleID.second, diag::sema_opening_import, - moduleID.first, err.message()); + Ctx.Diags.diagnose(moduleID.loc, diag::sema_opening_import, + moduleID.item, err.message()); } return nullptr; @@ -116,10 +115,10 @@ ModuleDecl *SourceLoader::loadModule(SourceLoc importLoc, else bufferID = Ctx.SourceMgr.addNewSourceBuffer(std::move(inputFile)); - auto *importMod = ModuleDecl::create(moduleID.first, Ctx); + auto *importMod = ModuleDecl::create(moduleID.item, Ctx); if (EnableLibraryEvolution) importMod->setResilienceStrategy(ResilienceStrategy::Resilient); - Ctx.LoadedModules[moduleID.first] = importMod; + Ctx.LoadedModules[moduleID.item] = importMod; auto implicitImportKind = SourceFile::ImplicitModuleImportKind::Stdlib; if (!Ctx.getStdlibModule()) diff --git a/lib/Serialization/ModuleFile.cpp b/lib/Serialization/ModuleFile.cpp index aad0ccc278fbc..cd099e829f17a 100644 --- a/lib/Serialization/ModuleFile.cpp +++ b/lib/Serialization/ModuleFile.cpp @@ -1983,7 +1983,7 @@ Status ModuleFile::associateWithFileContext(FileUnit *file, auto scopeID = ctx.getIdentifier(scopePath); assert(!scopeID.empty() && "invalid decl name (non-top-level decls not supported)"); - std::pair accessPathElem(scopeID, SourceLoc()); + Located accessPathElem = { scopeID, SourceLoc() }; dependency.Import = {ctx.AllocateCopy(llvm::makeArrayRef(accessPathElem)), module}; } @@ -2202,14 +2202,14 @@ void ModuleFile::getImportDecls(SmallVectorImpl &Results) { if (Dep.isScoped()) std::tie(ModulePathStr, ScopePath) = ModulePathStr.rsplit('\0'); - SmallVector, 1> AccessPath; + SmallVector, 1> AccessPath; while (!ModulePathStr.empty()) { StringRef NextComponent; std::tie(NextComponent, ModulePathStr) = ModulePathStr.split('\0'); AccessPath.push_back({Ctx.getIdentifier(NextComponent), SourceLoc()}); } - if (AccessPath.size() == 1 && AccessPath[0].first == Ctx.StdlibModuleName) + if (AccessPath.size() == 1 && AccessPath[0].item == Ctx.StdlibModuleName) continue; ModuleDecl *M = Ctx.getLoadedModule(AccessPath); @@ -2228,7 +2228,7 @@ void ModuleFile::getImportDecls(SmallVectorImpl &Results) { // Lookup the decl in the top-level module. ModuleDecl *TopLevelModule = M; if (AccessPath.size() > 1) - TopLevelModule = Ctx.getLoadedModule(AccessPath.front().first); + TopLevelModule = Ctx.getLoadedModule(AccessPath.front().item); SmallVector Decls; TopLevelModule->lookupQualified( @@ -2278,7 +2278,7 @@ void ModuleFile::lookupVisibleDecls(ModuleDecl::AccessPathTy accessPath, }; if (!accessPath.empty()) { - auto iter = TopLevelDecls->find(accessPath.front().first); + auto iter = TopLevelDecls->find(accessPath.front().item); if (iter == TopLevelDecls->end()) return; @@ -2454,7 +2454,7 @@ void ModuleFile::lookupClassMember(ModuleDecl::AccessPathTy accessPath, while (!dc->getParent()->isModuleScopeContext()) dc = dc->getParent(); if (auto nominal = dc->getSelfNominalTypeDecl()) - if (nominal->getName() == accessPath.front().first) + if (nominal->getName() == accessPath.front().item) results.push_back(vd); } } else { @@ -2467,7 +2467,7 @@ void ModuleFile::lookupClassMember(ModuleDecl::AccessPathTy accessPath, while (!dc->getParent()->isModuleScopeContext()) dc = dc->getParent(); if (auto nominal = dc->getSelfNominalTypeDecl()) - if (nominal->getName() == accessPath.front().first) + if (nominal->getName() == accessPath.front().item) results.push_back(vd); } } @@ -2496,7 +2496,7 @@ void ModuleFile::lookupClassMembers(ModuleDecl::AccessPathTy accessPath, while (!dc->getParent()->isModuleScopeContext()) dc = dc->getParent(); if (auto nominal = dc->getSelfNominalTypeDecl()) - if (nominal->getName() == accessPath.front().first) + if (nominal->getName() == accessPath.front().item) consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup, DynamicLookupInfo::AnyObject); } diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index 3f9471b7eb565..eb1cc5bafb8ff 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -915,7 +915,7 @@ static void flattenImportPath(const ModuleDecl::ImportedModule &import, outStream << '\0'; assert(import.first.size() == 1 && "can only handle top-level decl imports"); auto accessPathElem = import.first.front(); - outStream << accessPathElem.first.str(); + outStream << accessPathElem.item.str(); } uint64_t getRawModTimeOrHash(const SerializationOptions::FileDependency &dep) { diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp index 373f17f2b83f1..deab420ba56a7 100644 --- a/lib/Serialization/SerializedModuleLoader.cpp +++ b/lib/Serialization/SerializedModuleLoader.cpp @@ -428,7 +428,7 @@ SerializedModuleLoaderBase::findModule(AccessPathElem moduleID, std::unique_ptr *moduleDocBuffer, std::unique_ptr *moduleSourceInfoBuffer, bool &isFramework, bool &isSystemModule) { - llvm::SmallString<64> moduleName(moduleID.first.str()); + llvm::SmallString<64> moduleName(moduleID.item.str()); ModuleFilenamePair fileNames(moduleName); SmallVector targetFileNamePairs; @@ -465,7 +465,7 @@ SerializedModuleLoaderBase::findModule(AccessPathElem moduleID, // We can only get here if all targetFileNamePairs failed with // 'std::errc::no_such_file_or_directory'. - if (maybeDiagnoseTargetMismatch(moduleID.second, moduleName, + if (maybeDiagnoseTargetMismatch(moduleID.loc, moduleName, primaryTargetSpecificName, currPath)) { return false; } else { @@ -517,7 +517,7 @@ SerializedModuleLoaderBase::findModule(AccessPathElem moduleID, case SearchPathKind::Framework: { isFramework = true; llvm::sys::path::append(currPath, - moduleID.first.str() + ".framework"); + moduleID.item.str() + ".framework"); // Check if the framework directory exists. if (!fs.exists(currPath)) @@ -825,7 +825,7 @@ void swift::serialization::diagnoseSerializedASTLoadFailure( } bool SerializedModuleLoaderBase::canImportModule( - std::pair mID) { + Located mID) { // Look on disk. SmallVector *unusedModuleInterfacePath = nullptr; std::unique_ptr *unusedModuleBuffer = nullptr; @@ -839,9 +839,9 @@ bool SerializedModuleLoaderBase::canImportModule( } bool MemoryBufferSerializedModuleLoader::canImportModule( - std::pair mID) { + Located mID) { // See if we find it in the registered memory buffers. - return MemoryBuffers.count(mID.first.str()); + return MemoryBuffers.count(mID.item.str()); } ModuleDecl * @@ -876,15 +876,15 @@ SerializedModuleLoaderBase::loadModule(SourceLoc importLoc, assert(moduleInputBuffer); - auto M = ModuleDecl::create(moduleID.first, Ctx); + auto M = ModuleDecl::create(moduleID.item, Ctx); M->setIsSystemModule(isSystemModule); - Ctx.LoadedModules[moduleID.first] = M; + Ctx.LoadedModules[moduleID.item] = M; SWIFT_DEFER { M->setHasResolvedImports(); }; StringRef moduleInterfacePathStr = Ctx.AllocateCopy(moduleInterfacePath.str()); - if (!loadAST(*M, moduleID.second, moduleInterfacePathStr, + if (!loadAST(*M, moduleID.loc, moduleInterfacePathStr, std::move(moduleInputBuffer), std::move(moduleDocInputBuffer), std::move(moduleSourceInfoInputBuffer), isFramework, /*treatAsPartialModule*/false)) { @@ -908,7 +908,7 @@ MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc, // FIXME: Right now this works only with access paths of length 1. // Once submodules are designed, this needs to support suffix // matching and a search path. - auto bufIter = MemoryBuffers.find(moduleID.first.str()); + auto bufIter = MemoryBuffers.find(moduleID.item.str()); if (bufIter == MemoryBuffers.end()) return nullptr; @@ -919,16 +919,16 @@ MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc, MemoryBuffers.erase(bufIter); assert(moduleInputBuffer); - auto *M = ModuleDecl::create(moduleID.first, Ctx); + auto *M = ModuleDecl::create(moduleID.item, Ctx); SWIFT_DEFER { M->setHasResolvedImports(); }; - if (!loadAST(*M, moduleID.second, /*moduleInterfacePath*/ "", + if (!loadAST(*M, moduleID.loc, /*moduleInterfacePath*/ "", std::move(moduleInputBuffer), {}, {}, isFramework, treatAsPartialModule)) { return nullptr; } - Ctx.LoadedModules[moduleID.first] = M; + Ctx.LoadedModules[moduleID.item] = M; return M; } diff --git a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp index a439a4ae14b92..922639b27fca5 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp @@ -41,7 +41,7 @@ using namespace swift; using namespace ide; static ModuleDecl *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) { - SmallVector, 4> + SmallVector, 4> AccessPath; while (!ModuleName.empty()) { StringRef SubModuleName; @@ -52,7 +52,7 @@ static ModuleDecl *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) { } static ModuleDecl *getModuleByFullName(ASTContext &Ctx, Identifier ModuleName) { - return Ctx.getModule(std::make_pair(ModuleName, SourceLoc())); + return Ctx.getModule({{ModuleName, SourceLoc()}}); } namespace { diff --git a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp index a331e2051d61c..87e1a87d0ff09 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp @@ -92,7 +92,7 @@ typedef SwiftInterfaceGenContext::Implementation::TextDecl TextDecl; typedef SwiftInterfaceGenContext::Implementation::SourceTextInfo SourceTextInfo; static ModuleDecl *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) { - SmallVector, 4> + SmallVector, 4> AccessPath; while (!ModuleName.empty()) { StringRef SubModuleName; @@ -103,7 +103,7 @@ static ModuleDecl *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) { } static ModuleDecl *getModuleByFullName(ASTContext &Ctx, Identifier ModuleName) { - return Ctx.getModule(std::make_pair(ModuleName, SourceLoc())); + return Ctx.getModule({{ModuleName, SourceLoc()}}); } namespace { diff --git a/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp b/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp index def4356f2713d..ce0b3261257d0 100644 --- a/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp +++ b/tools/lldb-moduleimport-test/lldb-moduleimport-test.cpp @@ -325,14 +325,14 @@ int main(int argc, char **argv) { llvm::outs() << "Importing " << path << "... "; #ifdef SWIFT_SUPPORTS_SUBMODULES - std::vector > AccessPath; + std::vector> AccessPath; for (auto i = llvm::sys::path::begin(path); i != llvm::sys::path::end(path); ++i) if (!llvm::sys::path::is_separator((*i)[0])) AccessPath.push_back({ CI.getASTContext().getIdentifier(*i), swift::SourceLoc() }); #else - std::vector > AccessPath; + std::vector> AccessPath; AccessPath.push_back({ CI.getASTContext().getIdentifier(path), swift::SourceLoc() }); #endif diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/tools/swift-ide-test/swift-ide-test.cpp index 7d452e729a55f..f015a44409930 100644 --- a/tools/swift-ide-test/swift-ide-test.cpp +++ b/tools/swift-ide-test/swift-ide-test.cpp @@ -1585,7 +1585,7 @@ static int doInputCompletenessTest(StringRef SourceFilename) { //===----------------------------------------------------------------------===// static ModuleDecl *getModuleByFullName(ASTContext &Context, StringRef ModuleName) { - SmallVector, 4> + SmallVector, 4> AccessPath; while (!ModuleName.empty()) { StringRef SubModuleName; @@ -1600,8 +1600,7 @@ static ModuleDecl *getModuleByFullName(ASTContext &Context, StringRef ModuleName } static ModuleDecl *getModuleByFullName(ASTContext &Context, Identifier ModuleName) { - ModuleDecl *Result = Context.getModule(std::make_pair(ModuleName, - SourceLoc())); + ModuleDecl *Result = Context.getModule({{ModuleName,SourceLoc()}}); if (!Result || Result->failedToLoad()) return nullptr; return Result; @@ -2624,7 +2623,7 @@ static int doPrintModuleImports(const CompilerInvocation &InitInvok, for (auto &import : scratch) { llvm::outs() << "\t" << import.second->getName(); for (auto accessPathPiece : import.first) { - llvm::outs() << "." << accessPathPiece.first; + llvm::outs() << "." << accessPathPiece.item; } if (import.second->isClangModule()) From c1444dea18964f97f674cf1ddc15b44427cbf8ba Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Tue, 10 Dec 2019 23:46:25 +0300 Subject: [PATCH 02/10] SR-11889: Fixed code review issues --- include/swift/AST/ASTContext.h | 2 +- include/swift/AST/ModuleLoader.h | 2 +- include/swift/AST/NameLookup.h | 4 ++-- include/swift/AST/TypeRepr.h | 13 +++++++------ include/swift/Basic/Located.h | 19 +++++++++++++++---- include/swift/IDE/Utils.h | 2 +- include/swift/Parse/Parser.h | 2 +- lib/AST/ConformanceLookupTable.cpp | 14 +++++++------- lib/AST/Decl.cpp | 2 +- lib/AST/GenericSignatureBuilder.cpp | 14 +++++++------- lib/AST/NameLookup.cpp | 10 +++++----- lib/AST/TypeRepr.cpp | 2 +- lib/ClangImporter/ImportDecl.cpp | 2 +- lib/IDE/SwiftSourceDocInfo.cpp | 6 +++--- lib/IDE/SyntaxModel.cpp | 18 ++++++++---------- lib/Parse/ParseExpr.cpp | 8 ++++---- lib/ParseSIL/ParseSIL.cpp | 8 ++++---- lib/Sema/TypeCheckDecl.cpp | 6 +++--- unittests/AST/DiagnosticConsumerTests.cpp | 2 +- 19 files changed, 73 insertions(+), 63 deletions(-) diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h index fd717bb31df10..d81c4e2121179 100644 --- a/include/swift/AST/ASTContext.h +++ b/include/swift/AST/ASTContext.h @@ -25,8 +25,8 @@ #include "swift/AST/Types.h" #include "swift/AST/TypeAlignments.h" #include "swift/Basic/LangOptions.h" -#include "swift/Basic/Malloc.h" #include "swift/Basic/Located.h" +#include "swift/Basic/Malloc.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h index 92c05dc1f0630..d149611308e74 100644 --- a/include/swift/AST/ModuleLoader.h +++ b/include/swift/AST/ModuleLoader.h @@ -19,11 +19,11 @@ #include "swift/AST/Identifier.h" #include "swift/Basic/LLVM.h" +#include "swift/Basic/Located.h" #include "swift/Basic/SourceLoc.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/TinyPtrVector.h" -#include "swift/Basic/Located.h" namespace llvm { class FileCollector; diff --git a/include/swift/AST/NameLookup.h b/include/swift/AST/NameLookup.h index 374d8b4fcd310..fb0c7fc716056 100644 --- a/include/swift/AST/NameLookup.h +++ b/include/swift/AST/NameLookup.h @@ -495,7 +495,7 @@ void recordLookupOfTopLevelName(DeclContext *topLevelContext, DeclName name, void getDirectlyInheritedNominalTypeDecls( llvm::PointerUnion decl, unsigned i, - llvm::SmallVectorImpl> &result, + llvm::SmallVectorImpl> &result, bool &anyObject); /// Retrieve the set of nominal type declarations that are directly @@ -503,7 +503,7 @@ void getDirectlyInheritedNominalTypeDecls( /// and splitting out the components of compositions. /// /// If we come across the AnyObject type, set \c anyObject true. -SmallVector, 4> +SmallVector, 4> getDirectlyInheritedNominalTypeDecls( llvm::PointerUnion decl, bool &anyObject); diff --git a/include/swift/AST/TypeRepr.h b/include/swift/AST/TypeRepr.h index e4cce80d12353..f92cf8e68d18e 100644 --- a/include/swift/AST/TypeRepr.h +++ b/include/swift/AST/TypeRepr.h @@ -26,6 +26,7 @@ #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/STLExtras.h" #include "swift/Basic/Debug.h" +#include "swift/Basic/Located.h" #include "swift/Basic/InlineBitfield.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TrailingObjects.h" @@ -672,9 +673,9 @@ struct TupleTypeReprElement { /// \endcode class TupleTypeRepr final : public TypeRepr, private llvm::TrailingObjects> { + Located> { friend TrailingObjects; - typedef std::pair SourceLocAndIdx; + typedef Located SourceLocAndIdx; SourceRange Parens; @@ -745,12 +746,12 @@ class TupleTypeRepr final : public TypeRepr, SourceLoc getEllipsisLoc() const { return hasEllipsis() ? - getTrailingObjects()[0].first : SourceLoc(); + getTrailingObjects()[0].loc : SourceLoc(); } unsigned getEllipsisIndex() const { return hasEllipsis() ? - getTrailingObjects()[0].second : + getTrailingObjects()[0].item : Bits.TupleTypeRepr.NumElements; } @@ -758,8 +759,8 @@ class TupleTypeRepr final : public TypeRepr, if (hasEllipsis()) { Bits.TupleTypeRepr.HasEllipsis = false; getTrailingObjects()[0] = { - SourceLoc(), - getNumElements() + getNumElements(), + SourceLoc() }; } } diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index 34427aaf99ed2..2d21117d04578 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors +// Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -10,8 +10,7 @@ // //===----------------------------------------------------------------------===// // -// This file forward declares and imports various common LLVM datatypes that -// swift wants to use unqualified. +// Provides a currency data type Located that should be used instead of std::pair. // //===----------------------------------------------------------------------===// @@ -22,15 +21,27 @@ namespace swift { +/// A currency type for keeping track of items which were found in the source code. +/// +/// Several parts of the compiler need to keep track of a `SourceLoc` corresponding to an item, in case +/// they need to report some diagnostics later. For example, the ClangImporter needs to keep track +/// of where imports were originally written. Located makes it easy to do so while making the code +/// more readable, compared to using `std::pair`. template struct Located { + /// The main item whose source location is being tracked. T item; + /// The original source location from which the item was parsed. SourceLoc loc; + Located() {} + + Located(T item, SourceLoc loc): item(item), loc(loc) {} + template - friend bool operator ==(const Located lhs, const Located rhs) { + friend bool operator ==(const Located& lhs, const Located& rhs) { return lhs.item == rhs.item && lhs.loc == rhs.loc; } }; diff --git a/include/swift/IDE/Utils.h b/include/swift/IDE/Utils.h index d0a216a872405..928305e0bffa4 100644 --- a/include/swift/IDE/Utils.h +++ b/include/swift/IDE/Utils.h @@ -240,7 +240,7 @@ class NameMatcher: public ASTWalker { /// The \c Expr argument of a parent \c CustomAttr (if one exists) and /// the \c SourceLoc of the type name it applies to. - llvm::Optional> CustomAttrArg; + llvm::Optional> CustomAttrArg; unsigned InactiveConfigRegionNestings = 0; unsigned SelectorNestings = 0; diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h index ff70de7a7674e..8dcd373093321 100644 --- a/include/swift/Parse/Parser.h +++ b/include/swift/Parse/Parser.h @@ -120,7 +120,7 @@ class Parser { DeclContext *CurDeclContext; ASTContext &Context; CodeCompletionCallbacks *CodeCompletion = nullptr; - std::vector>> AnonClosureVars; + std::vector>> AnonClosureVars; bool IsParsingInterfaceTokens = false; diff --git a/lib/AST/ConformanceLookupTable.cpp b/lib/AST/ConformanceLookupTable.cpp index 642322ce76b07..4b7a25b7dab72 100644 --- a/lib/AST/ConformanceLookupTable.cpp +++ b/lib/AST/ConformanceLookupTable.cpp @@ -140,7 +140,7 @@ void ConformanceLookupTable::destroy() { } namespace { - using ConformanceConstructionInfo = std::pair; + using ConformanceConstructionInfo = Located; } template @@ -194,14 +194,14 @@ void ConformanceLookupTable::forEachInStage(ConformanceStage stage, loader.first->loadAllConformances(next, loader.second, conformances); loadAllConformances(next, conformances); for (auto conf : conformances) { - protocols.push_back({SourceLoc(), conf->getProtocol()}); + protocols.push_back({conf->getProtocol(), SourceLoc()}); } } else if (next->getParentSourceFile()) { bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls(next, anyObject)) { - if (auto proto = dyn_cast(found.second)) - protocols.push_back({found.first, proto}); + if (auto proto = dyn_cast(found.item)) + protocols.push_back({proto, found.loc}); } } @@ -281,7 +281,7 @@ void ConformanceLookupTable::updateLookupTable(NominalTypeDecl *nominal, // its inherited protocols directly. auto source = ConformanceSource::forExplicit(ext); for (auto locAndProto : protos) - addProtocol(locAndProto.second, locAndProto.first, source); + addProtocol(locAndProto.item, locAndProto.loc, source); }); break; @@ -470,8 +470,8 @@ void ConformanceLookupTable::addInheritedProtocols( bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls(decl, anyObject)) { - if (auto proto = dyn_cast(found.second)) - addProtocol(proto, found.first, source); + if (auto proto = dyn_cast(found.item)) + addProtocol(proto, found.loc, source); } } diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index a7ed7ccb7fd01..362c7f95246ca 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -4538,7 +4538,7 @@ ProtocolDecl::getInheritedProtocolsSlow() { for (const auto found : getDirectlyInheritedNominalTypeDecls( const_cast(this), anyObject)) { - if (auto proto = dyn_cast(found.second)) { + if (auto proto = dyn_cast(found.item)) { if (known.insert(proto).second) result.push_back(proto); } diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp index ad8b0fca4480e..038c81c434806 100644 --- a/lib/AST/GenericSignatureBuilder.cpp +++ b/lib/AST/GenericSignatureBuilder.cpp @@ -3939,13 +3939,13 @@ ConstraintResult GenericSignatureBuilder::expandConformanceRequirement( // Local function to find the insertion point for the protocol's "where" // clause, as well as the string to start the insertion ("where" or ","); - auto getProtocolWhereLoc = [&]() -> std::pair { + auto getProtocolWhereLoc = [&]() -> Located { // Already has a trailing where clause. if (auto trailing = proto->getTrailingWhereClause()) - return { trailing->getRequirements().back().getSourceRange().End, ", " }; + return { ", ", trailing->getRequirements().back().getSourceRange().End }; // Inheritance clause. - return { proto->getInherited().back().getSourceRange().End, " where " }; + return { " where ", proto->getInherited().back().getSourceRange().End }; }; // Retrieve the set of requirements that a given associated type declaration @@ -4060,8 +4060,8 @@ ConstraintResult GenericSignatureBuilder::expandConformanceRequirement( assocTypeDecl->getFullName(), inheritedFromProto->getDeclaredInterfaceType()) .fixItInsertAfter( - fixItWhere.first, - getAssociatedTypeReqs(assocTypeDecl, fixItWhere.second)) + fixItWhere.loc, + getAssociatedTypeReqs(assocTypeDecl, fixItWhere.item)) .fixItRemove(assocTypeDecl->getSourceRange()); Diags.diagnose(inheritedAssocTypeDecl, diag::decl_declared_here, @@ -4136,8 +4136,8 @@ ConstraintResult GenericSignatureBuilder::expandConformanceRequirement( diag::typealias_override_associated_type, name, inheritedFromProto->getDeclaredInterfaceType()) - .fixItInsertAfter(fixItWhere.first, - getConcreteTypeReq(type, fixItWhere.second)) + .fixItInsertAfter(fixItWhere.loc, + getConcreteTypeReq(type, fixItWhere.item)) .fixItRemove(type->getSourceRange()); Diags.diagnose(inheritedAssocTypeDecl, diag::decl_declared_here, inheritedAssocTypeDecl->getFullName()); diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp index 193f6c5323f5d..95c1004be5cf8 100644 --- a/lib/AST/NameLookup.cpp +++ b/lib/AST/NameLookup.cpp @@ -2333,7 +2333,7 @@ CustomAttrNominalRequest::evaluate(Evaluator &evaluator, void swift::getDirectlyInheritedNominalTypeDecls( llvm::PointerUnion decl, unsigned i, - llvm::SmallVectorImpl> &result, + llvm::SmallVectorImpl> &result, bool &anyObject) { auto typeDecl = decl.dyn_cast(); auto extDecl = decl.dyn_cast(); @@ -2362,11 +2362,11 @@ void swift::getDirectlyInheritedNominalTypeDecls( // Form the result. for (auto nominal : nominalTypes) { - result.push_back({loc, nominal}); + result.push_back({nominal, loc}); } } -SmallVector, 4> +SmallVector, 4> swift::getDirectlyInheritedNominalTypeDecls( llvm::PointerUnion decl, bool &anyObject) { @@ -2376,7 +2376,7 @@ swift::getDirectlyInheritedNominalTypeDecls( // Gather results from all of the inherited types. unsigned numInherited = typeDecl ? typeDecl->getInherited().size() : extDecl->getInherited().size(); - SmallVector, 4> result; + SmallVector, 4> result; for (unsigned i : range(numInherited)) { getDirectlyInheritedNominalTypeDecls(decl, i, result, anyObject); } @@ -2413,7 +2413,7 @@ swift::getDirectlyInheritedNominalTypeDecls( anyObject |= selfBounds.anyObject; for (auto inheritedNominal : selfBounds.decls) - result.emplace_back(loc, inheritedNominal); + result.emplace_back(inheritedNominal, loc); return result; } diff --git a/lib/AST/TypeRepr.cpp b/lib/AST/TypeRepr.cpp index 7340027e31c8d..a1fd18d5af19b 100644 --- a/lib/AST/TypeRepr.cpp +++ b/lib/AST/TypeRepr.cpp @@ -425,7 +425,7 @@ TupleTypeRepr::TupleTypeRepr(ArrayRef Elements, // Set ellipsis location and index. if (Ellipsis.isValid()) { - getTrailingObjects()[0] = {Ellipsis, EllipsisIdx}; + getTrailingObjects()[0] = {EllipsisIdx, Ellipsis}; } } diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp index 6459d0e9cbf04..1ceff206802d6 100644 --- a/lib/ClangImporter/ImportDecl.cpp +++ b/lib/ClangImporter/ImportDecl.cpp @@ -5457,7 +5457,7 @@ namespace { bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls(decl, anyObject)) { - if (auto protoDecl = dyn_cast(found.second)) + if (auto protoDecl = dyn_cast(found.item)) if (protoDecl == proto || protoDecl->inheritsFrom(proto)) return true; } diff --git a/lib/IDE/SwiftSourceDocInfo.cpp b/lib/IDE/SwiftSourceDocInfo.cpp index 4861fbe40d92e..8fe2ac59783c4 100644 --- a/lib/IDE/SwiftSourceDocInfo.cpp +++ b/lib/IDE/SwiftSourceDocInfo.cpp @@ -177,7 +177,7 @@ bool NameMatcher::handleCustomAttrs(Decl *D) { // CustomAttr's type, e.g. on `Wrapper` in `@Wrapper(wrappedValue: 10)`. SWIFT_DEFER { CustomAttrArg = None; }; if (Arg && !Arg->isImplicit()) - CustomAttrArg = {Repr->getLoc(), Arg}; + CustomAttrArg = Located(Arg, Repr->getLoc()); if (!Repr->walk(*this)) return false; } @@ -416,9 +416,9 @@ bool NameMatcher::walkToTypeReprPre(TypeRepr *T) { if (isa(T)) { // If we're walking a CustomAttr's type we may have an associated call // argument to resolve with from its semantic initializer. - if (CustomAttrArg.hasValue() && CustomAttrArg->first == T->getLoc()) { + if (CustomAttrArg.hasValue() && CustomAttrArg->loc == T->getLoc()) { tryResolve(ASTWalker::ParentTy(T), T->getLoc(), LabelRangeType::CallArg, - getCallArgLabelRanges(getSourceMgr(), CustomAttrArg->second, LabelRangeEndAt::BeforeElemStart)); + getCallArgLabelRanges(getSourceMgr(), CustomAttrArg->item, LabelRangeEndAt::BeforeElemStart)); } else { tryResolve(ASTWalker::ParentTy(T), T->getLoc()); } diff --git a/lib/IDE/SyntaxModel.cpp b/lib/IDE/SyntaxModel.cpp index af2e4e13d01af..66adaf5e20aa0 100644 --- a/lib/IDE/SyntaxModel.cpp +++ b/lib/IDE/SyntaxModel.cpp @@ -57,7 +57,7 @@ struct SyntaxModelContext::Implementation { /// If the given tokens start with the expected tokens and they all appear on /// the same line, the source location beyond the final matched token and /// number of matched tokens are returned. Otherwise None is returned. -static Optional> +static Optional> matchImageOrFileLiteralArg(ArrayRef Tokens) { const unsigned NUM_TOKENS = 5; if (Tokens.size() < NUM_TOKENS) @@ -76,8 +76,7 @@ matchImageOrFileLiteralArg(ArrayRef Tokens) { if (Tokens[1].getText() != "resourceName") return None; auto EndToken = Tokens[NUM_TOKENS-1]; - return std::make_pair(EndToken.getLoc().getAdvancedLoc(EndToken.getLength()), - NUM_TOKENS); + return Located(NUM_TOKENS, EndToken.getLoc().getAdvancedLoc(EndToken.getLength())); } /// Matches the tokens in the argument of an image literal expression if its @@ -86,7 +85,7 @@ matchImageOrFileLiteralArg(ArrayRef Tokens) { /// If the given tokens start with the expected tokens and they all appear on /// the same line, the source location beyond the final matched token and number /// of matched tokens are returned. Otherwise None is returned. -static Optional> +static Optional> matchColorLiteralArg(ArrayRef Tokens) { const unsigned NUM_TOKENS = 17; if (Tokens.size() < NUM_TOKENS) @@ -112,8 +111,7 @@ matchColorLiteralArg(ArrayRef Tokens) { Tokens[9].getText() != "blue" || Tokens[13].getText() != "alpha") return None; auto EndToken = Tokens[NUM_TOKENS-1]; - return std::make_pair(EndToken.getLoc().getAdvancedLoc(EndToken.getLength()), - NUM_TOKENS); + return Located(NUM_TOKENS, EndToken.getLoc().getAdvancedLoc(EndToken.getLength())); } SyntaxModelContext::SyntaxModelContext(SourceFile &SrcFile) @@ -172,9 +170,9 @@ SyntaxModelContext::SyntaxModelContext(SourceFile &SrcFile) case tok::pound_imageLiteral: if (auto Match = matchImageOrFileLiteralArg(Tokens.slice(I+1))) { Kind = SyntaxNodeKind::ObjectLiteral; - Length = SM.getByteDistance(Loc, Match->first); + Length = SM.getByteDistance(Loc, Match->loc); // skip over the extra matched tokens - I += Match->second - 1; + I += Match->item - 1; } else { Kind = SyntaxNodeKind::Keyword; } @@ -182,9 +180,9 @@ SyntaxModelContext::SyntaxModelContext(SourceFile &SrcFile) case tok::pound_colorLiteral: if (auto Match = matchColorLiteralArg(Tokens.slice(I+1))) { Kind = SyntaxNodeKind::ObjectLiteral; - Length = SM.getByteDistance(Loc, Match->first); + Length = SM.getByteDistance(Loc, Match->loc); // skip over the matches tokens - I += Match->second - 1; + I += Match->item - 1; } else { Kind = SyntaxNodeKind::Keyword; } diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 5963e405678a8..3e0cd03ce8b7c 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -2811,7 +2811,7 @@ ParserResult Parser::parseExprClosure() { // FIXME: We could do this all the time, and then provide Fix-Its // to map $i -> the appropriately-named argument. This might help // users who are refactoring code by adding names. - AnonClosureVars.push_back({ leftBrace, {}}); + AnonClosureVars.push_back({{}, leftBrace}); } // Add capture list variables to scope. @@ -2835,7 +2835,7 @@ ParserResult Parser::parseExprClosure() { // anonymous closure arguments. if (!params) { // Create a parameter pattern containing the anonymous variables. - auto &anonVars = AnonClosureVars.back().second; + auto &anonVars = AnonClosureVars.back().item; SmallVector elements; for (auto anonVar : anonVars) elements.push_back(anonVar); @@ -2948,8 +2948,8 @@ Expr *Parser::parseExprAnonClosureArg() { } } - auto leftBraceLoc = AnonClosureVars.back().first; - auto &decls = AnonClosureVars.back().second; + auto leftBraceLoc = AnonClosureVars.back().loc; + auto &decls = AnonClosureVars.back().item; while (ArgNo >= decls.size()) { unsigned nextIdx = decls.size(); SmallVector StrBuf; diff --git a/lib/ParseSIL/ParseSIL.cpp b/lib/ParseSIL/ParseSIL.cpp index 1bbd13839c659..989ce83f0eda2 100644 --- a/lib/ParseSIL/ParseSIL.cpp +++ b/lib/ParseSIL/ParseSIL.cpp @@ -228,7 +228,7 @@ namespace { /// Data structures used to perform name lookup of basic blocks. llvm::DenseMap BlocksByName; llvm::DenseMap> UndefinedBlocks; + Located> UndefinedBlocks; /// Data structures used to perform name lookup for local values. llvm::StringMap LocalValues; @@ -584,8 +584,8 @@ bool SILParser::diagnoseProblems() { if (!UndefinedBlocks.empty()) { // FIXME: These are going to come out in nondeterministic order. for (auto Entry : UndefinedBlocks) - P.diagnose(Entry.second.first, diag::sil_undefined_basicblock_use, - Entry.second.second); + P.diagnose(Entry.second.loc, diag::sil_undefined_basicblock_use, + Entry.second.item); HadError = true; } @@ -717,7 +717,7 @@ SILBasicBlock *SILParser::getBBForReference(Identifier Name, SourceLoc Loc) { // Otherwise, create it and remember that this is a forward reference so // that we can diagnose use without definition problems. BB = F->createBasicBlock(); - UndefinedBlocks[BB] = {Loc, Name}; + UndefinedBlocks[BB] = {Name, Loc}; return BB; } diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp index ab00f3b15603c..1c55842c9af01 100644 --- a/lib/Sema/TypeCheckDecl.cpp +++ b/lib/Sema/TypeCheckDecl.cpp @@ -258,7 +258,7 @@ HasCircularInheritedProtocolsRequest::evaluate(Evaluator &evaluator, bool anyObject = false; auto inherited = getDirectlyInheritedNominalTypeDecls(decl, anyObject); for (auto &found : inherited) { - auto *protoDecl = dyn_cast(found.second); + auto *protoDecl = dyn_cast(found.item); if (!protoDecl) continue; @@ -490,11 +490,11 @@ ProtocolRequiresClassRequest::evaluate(Evaluator &evaluator, // class-bound protocol. for (const auto found : allInheritedNominals) { // Superclass bound. - if (isa(found.second)) + if (isa(found.item)) return true; // A protocol that might be class-constrained. - if (auto proto = dyn_cast(found.second)) { + if (auto proto = dyn_cast(found.item)) { if (proto->requiresClass()) return true; } diff --git a/unittests/AST/DiagnosticConsumerTests.cpp b/unittests/AST/DiagnosticConsumerTests.cpp index d347f8f32845f..d3d24a3a8098a 100644 --- a/unittests/AST/DiagnosticConsumerTests.cpp +++ b/unittests/AST/DiagnosticConsumerTests.cpp @@ -17,7 +17,7 @@ using namespace swift; namespace { - using ExpectedDiagnostic = std::pair; + using ExpectedDiagnostic = Located; class ExpectationDiagnosticConsumer: public DiagnosticConsumer { ExpectationDiagnosticConsumer *previous; From c88ac85b3f8acc41a5fde406b34f72a8de28d411 Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Wed, 11 Dec 2019 00:19:15 +0300 Subject: [PATCH 03/10] SR-11889: Fixed code review issues 1. Removed two braces {{ usage of Located initialization 2. Wrapped documentation into 80 characters --- include/swift/Basic/Located.h | 14 ++++++++------ lib/AST/ASTContext.cpp | 2 +- lib/Frontend/Frontend.cpp | 4 ++-- lib/FrontendTool/ImportedModules.cpp | 2 +- tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp | 2 +- .../lib/SwiftLang/SwiftEditorInterfaceGen.cpp | 2 +- tools/swift-ide-test/swift-ide-test.cpp | 2 +- 7 files changed, 15 insertions(+), 13 deletions(-) diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index 2d21117d04578..c014d08063c86 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -10,7 +10,8 @@ // //===----------------------------------------------------------------------===// // -// Provides a currency data type Located that should be used instead of std::pair. +// Provides a currency data type Located that should be used instead +// of std::pair. // //===----------------------------------------------------------------------===// @@ -22,11 +23,12 @@ namespace swift { /// A currency type for keeping track of items which were found in the source code. -/// -/// Several parts of the compiler need to keep track of a `SourceLoc` corresponding to an item, in case -/// they need to report some diagnostics later. For example, the ClangImporter needs to keep track -/// of where imports were originally written. Located makes it easy to do so while making the code -/// more readable, compared to using `std::pair`. +/// Several parts of the compiler need to keep track of a `SourceLoc` corresponding +/// to an item, in case they need to report some diagnostics later. For example, +/// the ClangImporter needs to keep track of where imports were originally written. +/// Located makes it easy to do so while making the code more readable, compared to +/// using `std::pair`. + template struct Located { diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index 96c5257100982..cd1524ee6aabc 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -1778,7 +1778,7 @@ ModuleDecl *ASTContext::getStdlibModule(bool loadIfAbsent) { if (loadIfAbsent) { auto mutableThis = const_cast(this); TheStdlibModule = - mutableThis->getModule({{ StdlibModuleName, SourceLoc() }}); + mutableThis->getModule({ Located(StdlibModuleName, SourceLoc()) }); } else { TheStdlibModule = getLoadedModule(StdlibModuleName); } diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp index fe18c24bc92ff..c0b4f9e3b54dd 100644 --- a/lib/Frontend/Frontend.cpp +++ b/lib/Frontend/Frontend.cpp @@ -778,7 +778,7 @@ ModuleDecl *CompilerInstance::importUnderlyingModule() { ModuleDecl *objCModuleUnderlyingMixedFramework = static_cast(Context->getClangModuleLoader()) ->loadModule(SourceLoc(), - {{MainModule->getName(), SourceLoc()}}); + { Located(MainModule->getName(), SourceLoc()) }); if (objCModuleUnderlyingMixedFramework) return objCModuleUnderlyingMixedFramework; Diagnostics.diagnose(SourceLoc(), diag::error_underlying_module_not_found, @@ -808,7 +808,7 @@ void CompilerInstance::getImplicitlyImportedModules( if (Lexer::isIdentifier(ImplicitImportModuleName)) { auto moduleID = Context->getIdentifier(ImplicitImportModuleName); ModuleDecl *importModule = - Context->getModule({{moduleID, SourceLoc()}}); + Context->getModule({ Located(moduleID, SourceLoc()) }); if (importModule) { importModules.push_back(importModule); } else { diff --git a/lib/FrontendTool/ImportedModules.cpp b/lib/FrontendTool/ImportedModules.cpp index 59b6088da4d54..069c989534520 100644 --- a/lib/FrontendTool/ImportedModules.cpp +++ b/lib/FrontendTool/ImportedModules.cpp @@ -98,7 +98,7 @@ bool swift::emitImportedModules(ASTContext &Context, ModuleDecl *mainModule, } if (opts.ImportUnderlyingModule) { - auto underlyingModule = clangImporter->loadModule(SourceLoc(), {{ mainModule->getName(), SourceLoc() }}); + auto underlyingModule = clangImporter->loadModule(SourceLoc(), { Located(mainModule->getName(), SourceLoc()) }); if (!underlyingModule) { Context.Diags.diagnose(SourceLoc(), diag::error_underlying_module_not_found, diff --git a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp index 922639b27fca5..9ed275a1d1a87 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp @@ -52,7 +52,7 @@ static ModuleDecl *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) { } static ModuleDecl *getModuleByFullName(ASTContext &Ctx, Identifier ModuleName) { - return Ctx.getModule({{ModuleName, SourceLoc()}}); + return Ctx.getModule({ Located(ModuleName, SourceLoc()) }); } namespace { diff --git a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp index 87e1a87d0ff09..475629e4a22db 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp @@ -103,7 +103,7 @@ static ModuleDecl *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) { } static ModuleDecl *getModuleByFullName(ASTContext &Ctx, Identifier ModuleName) { - return Ctx.getModule({{ModuleName, SourceLoc()}}); + return Ctx.getModule({ Located(ModuleName, SourceLoc()) }); } namespace { diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/tools/swift-ide-test/swift-ide-test.cpp index f015a44409930..1704f85756259 100644 --- a/tools/swift-ide-test/swift-ide-test.cpp +++ b/tools/swift-ide-test/swift-ide-test.cpp @@ -1600,7 +1600,7 @@ static ModuleDecl *getModuleByFullName(ASTContext &Context, StringRef ModuleName } static ModuleDecl *getModuleByFullName(ASTContext &Context, Identifier ModuleName) { - ModuleDecl *Result = Context.getModule({{ModuleName,SourceLoc()}}); + ModuleDecl *Result = Context.getModule({ Located(ModuleName,SourceLoc()) }); if (!Result || Result->failedToLoad()) return nullptr; return Result; From 5fdea64d7ec7763387d00082db250c2ef46334ab Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Wed, 11 Dec 2019 00:21:34 +0300 Subject: [PATCH 04/10] SR-11889: Fixed code review issues. --- include/swift/Basic/Located.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index c014d08063c86..d87548f0833b2 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -28,7 +28,6 @@ namespace swift { /// the ClangImporter needs to keep track of where imports were originally written. /// Located makes it easy to do so while making the code more readable, compared to /// using `std::pair`. - template struct Located { From ea6a2dc094c6490b0819c281e19bd6a54b16990a Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Sat, 14 Dec 2019 13:39:53 +0300 Subject: [PATCH 05/10] SR-11889: Fixed code review issues 1. Updated Located field names with Pascal Case 2. Updated Located constuctor 3. Formatted lines with more than 80 symbols --- include/swift/AST/Decl.h | 4 +- include/swift/AST/Module.h | 2 +- include/swift/AST/TypeRepr.h | 4 +- include/swift/Basic/Located.h | 10 ++--- lib/AST/ASTContext.cpp | 8 ++-- lib/AST/ASTDumper.cpp | 2 +- lib/AST/ASTPrinter.cpp | 4 +- lib/AST/ConformanceLookupTable.cpp | 10 ++--- lib/AST/Decl.cpp | 2 +- lib/AST/GenericSignatureBuilder.cpp | 8 ++-- lib/AST/ImportCache.cpp | 2 +- lib/AST/Module.cpp | 10 ++--- lib/ClangImporter/ClangImporter.cpp | 16 ++++---- lib/ClangImporter/DWARFImporter.cpp | 2 +- lib/ClangImporter/ImportDecl.cpp | 2 +- lib/Frontend/ModuleInterfaceLoader.cpp | 4 +- lib/Frontend/ModuleInterfaceSupport.cpp | 4 +- lib/FrontendTool/ImportedModules.cpp | 5 ++- lib/IDE/CodeCompletion.cpp | 4 +- lib/IDE/ModuleInterfacePrinting.cpp | 2 +- lib/IDE/SourceEntityWalker.cpp | 6 +-- lib/IDE/SwiftSourceDocInfo.cpp | 6 +-- lib/IDE/SyntaxModel.cpp | 8 ++-- lib/Parse/ParseDecl.cpp | 8 ++-- lib/Parse/ParseExpr.cpp | 6 +-- lib/ParseSIL/ParseSIL.cpp | 14 +++---- lib/Sema/NameBinding.cpp | 40 ++++++++++---------- lib/Sema/SourceLoader.cpp | 20 +++++----- lib/Sema/TypeCheckDecl.cpp | 6 +-- lib/Serialization/ModuleFile.cpp | 12 +++--- lib/Serialization/Serialization.cpp | 2 +- lib/Serialization/SerializedModuleLoader.cpp | 22 +++++------ tools/swift-ide-test/swift-ide-test.cpp | 2 +- 33 files changed, 129 insertions(+), 128 deletions(-) diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 4d714102a351f..c3b8bf961daf4 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -1578,9 +1578,9 @@ class ImportDecl final : public Decl, } SourceLoc getStartLoc() const { return ImportLoc; } - SourceLoc getLocFromSource() const { return getFullAccessPath().front().loc; } + SourceLoc getLocFromSource() const { return getFullAccessPath().front().Loc; } SourceRange getSourceRange() const { - return SourceRange(ImportLoc, getFullAccessPath().back().loc); + return SourceRange(ImportLoc, getFullAccessPath().back().Loc); } SourceLoc getKindLoc() const { return KindLoc; } diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h index d364053d313eb..833c4cc1e72d7 100644 --- a/include/swift/AST/Module.h +++ b/include/swift/AST/Module.h @@ -139,7 +139,7 @@ class ModuleDecl : public DeclContext, public TypeDecl { assert(AccessPath.size() <= 1 && "can only refer to top-level decls"); return AccessPath.empty() - || DeclName(AccessPath.front().item).matchesRef(Name); + || DeclName(AccessPath.front().Item).matchesRef(Name); } /// Arbitrarily orders ImportedModule records, for inclusion in sets and such. diff --git a/include/swift/AST/TypeRepr.h b/include/swift/AST/TypeRepr.h index f92cf8e68d18e..56e4995aad08c 100644 --- a/include/swift/AST/TypeRepr.h +++ b/include/swift/AST/TypeRepr.h @@ -746,12 +746,12 @@ class TupleTypeRepr final : public TypeRepr, SourceLoc getEllipsisLoc() const { return hasEllipsis() ? - getTrailingObjects()[0].loc : SourceLoc(); + getTrailingObjects()[0].Loc : SourceLoc(); } unsigned getEllipsisIndex() const { return hasEllipsis() ? - getTrailingObjects()[0].item : + getTrailingObjects()[0].Item : Bits.TupleTypeRepr.NumElements; } diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index d87548f0833b2..ceda184fd3845 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -32,18 +32,18 @@ template struct Located { /// The main item whose source location is being tracked. - T item; + T Item; /// The original source location from which the item was parsed. - SourceLoc loc; + SourceLoc Loc; - Located() {} + Located(): Item(), Loc() {} - Located(T item, SourceLoc loc): item(item), loc(loc) {} + Located(T Item, SourceLoc loc): Item(Item), Loc(loc) {} template friend bool operator ==(const Located& lhs, const Located& rhs) { - return lhs.item == rhs.item && lhs.loc == rhs.loc; + return lhs.Item == rhs.Item && lhs.Loc == rhs.Loc; } }; } diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index cd1524ee6aabc..379deec5e599a 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -1473,7 +1473,7 @@ ModuleDecl *ASTContext::getLoadedModule( // TODO: Swift submodules. if (ModulePath.size() == 1) { - return getLoadedModule(ModulePath[0].item); + return getLoadedModule(ModulePath[0].Item); } return nullptr; } @@ -1729,7 +1729,7 @@ bool ASTContext::canImportModule(Located ModulePath) { return true; // If we've failed loading this module before, don't look for it again. - if (FailedModuleImportNames.count(ModulePath.item)) + if (FailedModuleImportNames.count(ModulePath.Item)) return false; // Otherwise, ask the module loaders. @@ -1739,7 +1739,7 @@ bool ASTContext::canImportModule(Located ModulePath) { } } - FailedModuleImportNames.insert(ModulePath.item); + FailedModuleImportNames.insert(ModulePath.Item); return false; } @@ -1752,7 +1752,7 @@ ASTContext::getModule(ArrayRef> ModulePath) { auto moduleID = ModulePath[0]; for (auto &importer : getImpl().ModuleLoaders) { - if (ModuleDecl *M = importer->loadModule(moduleID.loc, ModulePath)) { + if (ModuleDecl *M = importer->loadModule(moduleID.Loc, ModulePath)) { return M; } } diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index 2c8658354c632..4fd89ceded63a 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -589,7 +589,7 @@ namespace { OS << " '"; interleave(ID->getFullAccessPath(), [&](const ImportDecl::AccessPathElement &Elem) { - OS << Elem.item; + OS << Elem.Item; }, [&] { OS << '.'; }); OS << "')"; diff --git a/lib/AST/ASTPrinter.cpp b/lib/AST/ASTPrinter.cpp index e58dc963f79e3..72b18789df6a0 100644 --- a/lib/AST/ASTPrinter.cpp +++ b/lib/AST/ASTPrinter.cpp @@ -2097,10 +2097,10 @@ void PrintAST::visitImportDecl(ImportDecl *decl) { interleave(decl->getFullAccessPath(), [&](const ImportDecl::AccessPathElement &Elem) { if (!Mods.empty()) { - Printer.printModuleRef(Mods.front(), Elem.item); + Printer.printModuleRef(Mods.front(), Elem.Item); Mods = Mods.slice(1); } else { - Printer << Elem.item.str(); + Printer << Elem.Item.str(); } }, [&] { Printer << "."; }); diff --git a/lib/AST/ConformanceLookupTable.cpp b/lib/AST/ConformanceLookupTable.cpp index 4b7a25b7dab72..414d3d8803984 100644 --- a/lib/AST/ConformanceLookupTable.cpp +++ b/lib/AST/ConformanceLookupTable.cpp @@ -200,8 +200,8 @@ void ConformanceLookupTable::forEachInStage(ConformanceStage stage, bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls(next, anyObject)) { - if (auto proto = dyn_cast(found.item)) - protocols.push_back({proto, found.loc}); + if (auto proto = dyn_cast(found.Item)) + protocols.push_back({proto, found.Loc}); } } @@ -281,7 +281,7 @@ void ConformanceLookupTable::updateLookupTable(NominalTypeDecl *nominal, // its inherited protocols directly. auto source = ConformanceSource::forExplicit(ext); for (auto locAndProto : protos) - addProtocol(locAndProto.item, locAndProto.loc, source); + addProtocol(locAndProto.Item, locAndProto.Loc, source); }); break; @@ -470,8 +470,8 @@ void ConformanceLookupTable::addInheritedProtocols( bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls(decl, anyObject)) { - if (auto proto = dyn_cast(found.item)) - addProtocol(proto, found.loc, source); + if (auto proto = dyn_cast(found.Item)) + addProtocol(proto, found.Loc, source); } } diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 362c7f95246ca..87030221c2779 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -4538,7 +4538,7 @@ ProtocolDecl::getInheritedProtocolsSlow() { for (const auto found : getDirectlyInheritedNominalTypeDecls( const_cast(this), anyObject)) { - if (auto proto = dyn_cast(found.item)) { + if (auto proto = dyn_cast(found.Item)) { if (known.insert(proto).second) result.push_back(proto); } diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp index 038c81c434806..1f5bdfdd93f2e 100644 --- a/lib/AST/GenericSignatureBuilder.cpp +++ b/lib/AST/GenericSignatureBuilder.cpp @@ -4060,8 +4060,8 @@ ConstraintResult GenericSignatureBuilder::expandConformanceRequirement( assocTypeDecl->getFullName(), inheritedFromProto->getDeclaredInterfaceType()) .fixItInsertAfter( - fixItWhere.loc, - getAssociatedTypeReqs(assocTypeDecl, fixItWhere.item)) + fixItWhere.Loc, + getAssociatedTypeReqs(assocTypeDecl, fixItWhere.Item)) .fixItRemove(assocTypeDecl->getSourceRange()); Diags.diagnose(inheritedAssocTypeDecl, diag::decl_declared_here, @@ -4136,8 +4136,8 @@ ConstraintResult GenericSignatureBuilder::expandConformanceRequirement( diag::typealias_override_associated_type, name, inheritedFromProto->getDeclaredInterfaceType()) - .fixItInsertAfter(fixItWhere.loc, - getConcreteTypeReq(type, fixItWhere.item)) + .fixItInsertAfter(fixItWhere.Loc, + getConcreteTypeReq(type, fixItWhere.Item)) .fixItRemove(type->getSourceRange()); Diags.diagnose(inheritedAssocTypeDecl, diag::decl_declared_here, inheritedAssocTypeDecl->getFullName()); diff --git a/lib/AST/ImportCache.cpp b/lib/AST/ImportCache.cpp index e99e8c8f419ea..1b667a75d7373 100644 --- a/lib/AST/ImportCache.cpp +++ b/lib/AST/ImportCache.cpp @@ -57,7 +57,7 @@ void ImportSet::Profile( for (auto import : topLevelImports) { ID.AddInteger(import.first.size()); for (auto accessPathElt : import.first) { - ID.AddPointer(accessPathElt.item.getAsOpaquePointer()); + ID.AddPointer(accessPathElt.Item.getAsOpaquePointer()); } ID.AddPointer(import.second); } diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp index 90fe1cc7aa913..df3874d544686 100644 --- a/lib/AST/Module.cpp +++ b/lib/AST/Module.cpp @@ -303,7 +303,7 @@ void SourceLookupCache::lookupVisibleDecls(AccessPathTy AccessPath, assert(AccessPath.size() <= 1 && "can only refer to top-level decls"); if (!AccessPath.empty()) { - auto I = TopLevelValues.find(AccessPath.front().item); + auto I = TopLevelValues.find(AccessPath.front().Item); if (I == TopLevelValues.end()) return; for (auto vd : I->second) @@ -335,7 +335,7 @@ void SourceLookupCache::lookupClassMembers(AccessPathTy accessPath, for (ValueDecl *vd : member.second) { auto *nominal = vd->getDeclContext()->getSelfNominalTypeDecl(); - if (nominal && nominal->getName() == accessPath.front().item) + if (nominal && nominal->getName() == accessPath.front().Item) consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup, DynamicLookupInfo::AnyObject); } @@ -367,7 +367,7 @@ void SourceLookupCache::lookupClassMember(AccessPathTy accessPath, if (!accessPath.empty()) { for (ValueDecl *vd : iter->second) { auto *nominal = vd->getDeclContext()->getSelfNominalTypeDecl(); - if (nominal && nominal->getName() == accessPath.front().item) + if (nominal && nominal->getName() == accessPath.front().Item) results.push_back(vd); } return; @@ -1187,7 +1187,7 @@ bool ModuleDecl::isSameAccessPath(AccessPathTy lhs, AccessPathTy rhs) { return std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](const AccessPathElem &lElem, const AccessPathElem &rElem) { - return lElem.item == rElem.item; + return lElem.Item == rElem.Item; }); } @@ -1256,7 +1256,7 @@ ModuleDecl::removeDuplicateImports(SmallVectorImpl &imports) { rhs.first.begin(), rhs.first.end(), [](const AccessPathElem &lElem, const AccessPathElem &rElem) { - return lElem.item.str() < rElem.item.str(); + return lElem.Item.str() < rElem.Item.str(); }); }); auto last = std::unique(imports.begin(), imports.end(), diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index d4a4dbd05e400..8a8b5d1781619 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -1625,13 +1625,13 @@ void ClangImporter::collectSubModuleNames( // Look up the top-level module first. clang::Module *clangModule = clangHeaderSearch.lookupModule( - path.front().item.str(), /*AllowSearch=*/true, + path.front().Item.str(), /*AllowSearch=*/true, /*AllowExtraModuleMapSearch=*/true); if (!clangModule) return; clang::Module *submodule = clangModule; for (auto component : path.slice(1)) { - submodule = submodule->findSubmodule(component.item.str()); + submodule = submodule->findSubmodule(component.Item.str()); if (!submodule) return; } @@ -1648,7 +1648,7 @@ bool ClangImporter::canImportModule(Located moduleID) { // FIXME: This only works with top-level modules. auto &clangHeaderSearch = Impl.getClangPreprocessor().getHeaderSearchInfo(); clang::Module *clangModule = - clangHeaderSearch.lookupModule(moduleID.item.str(), /*AllowSearch=*/true, + clangHeaderSearch.lookupModule(moduleID.Item.str(), /*AllowSearch=*/true, /*AllowExtraModuleMapSearch=*/true); if (!clangModule) { return false; @@ -1668,7 +1668,7 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( // Look up the top-level module first, to see if it exists at all. clang::Module *clangModule = clangHeaderSearch.lookupModule( - path.front().item.str(), /*AllowSearch=*/true, + path.front().Item.str(), /*AllowSearch=*/true, /*AllowExtraModuleMapSearch=*/true); if (!clangModule) return nullptr; @@ -1677,8 +1677,8 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( SmallVector, 4> clangPath; for (auto component : path) { - clangPath.push_back({&clangContext.Idents.get(component.item.str()), - exportSourceLoc(component.loc)}); + clangPath.push_back({&clangContext.Idents.get(component.Item.str()), + exportSourceLoc(component.Loc)}); } auto &rawDiagClient = Instance->getDiagnosticClient(); @@ -1728,13 +1728,13 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( // Verify that the submodule exists. clang::Module *submodule = clangModule; for (auto &component : path.slice(1)) { - submodule = submodule->findSubmodule(component.item.str()); + submodule = submodule->findSubmodule(component.Item.str()); // Special case: a submodule named "Foo.Private" can be moved to a top-level // module named "Foo_Private". Clang has special support for this. // We're limiting this to just submodules named "Private" because this will // put the Clang AST in a fatal error state if it /doesn't/ exist. - if (!submodule && component.item.str() == "Private" && + if (!submodule && component.Item.str() == "Private" && (&component) == (&path[1])) { submodule = loadModule(llvm::makeArrayRef(clangPath).slice(0, 2), false); } diff --git a/lib/ClangImporter/DWARFImporter.cpp b/lib/ClangImporter/DWARFImporter.cpp index fab4bcbcf3c8b..d044355cb0d10 100644 --- a/lib/ClangImporter/DWARFImporter.cpp +++ b/lib/ClangImporter/DWARFImporter.cpp @@ -105,7 +105,7 @@ ModuleDecl *ClangImporter::Implementation::loadModuleDWARF( return nullptr; // FIXME: Implement submodule support! - Identifier name = path[0].item; + Identifier name = path[0].Item; auto it = DWARFModuleUnits.find(name); if (it != DWARFModuleUnits.end()) return it->second->getParentModule(); diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp index 1ceff206802d6..1466521c15f99 100644 --- a/lib/ClangImporter/ImportDecl.cpp +++ b/lib/ClangImporter/ImportDecl.cpp @@ -5457,7 +5457,7 @@ namespace { bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls(decl, anyObject)) { - if (auto protoDecl = dyn_cast(found.item)) + if (auto protoDecl = dyn_cast(found.Item)) if (protoDecl == proto || protoDecl->inheritsFrom(proto)) return true; } diff --git a/lib/Frontend/ModuleInterfaceLoader.cpp b/lib/Frontend/ModuleInterfaceLoader.cpp index 42ed6c18fae43..ceb0cb7ae7ad8 100644 --- a/lib/Frontend/ModuleInterfaceLoader.cpp +++ b/lib/Frontend/ModuleInterfaceLoader.cpp @@ -1020,10 +1020,10 @@ std::error_code ModuleInterfaceLoader::findModuleFilesInDirectory( } // Create an instance of the Impl to do the heavy lifting. - auto ModuleName = ModuleID.item.str(); + auto ModuleName = ModuleID.Item.str(); ModuleInterfaceLoaderImpl Impl( Ctx, ModPath, InPath, ModuleName, - CacheDir, PrebuiltCacheDir, ModuleID.loc, + CacheDir, PrebuiltCacheDir, ModuleID.Loc, RemarkOnRebuildFromInterface, dependencyTracker, llvm::is_contained(PreferInterfaceForModules, ModuleName) ? diff --git a/lib/Frontend/ModuleInterfaceSupport.cpp b/lib/Frontend/ModuleInterfaceSupport.cpp index 2e30bc98dc0b0..b1b6b73673822 100644 --- a/lib/Frontend/ModuleInterfaceSupport.cpp +++ b/lib/Frontend/ModuleInterfaceSupport.cpp @@ -49,7 +49,7 @@ static void diagnoseScopedImports(DiagnosticEngine &diags, for (const ModuleDecl::ImportedModule &importPair : imports) { if (importPair.first.empty()) continue; - diags.diagnose(importPair.first.front().loc, + diags.diagnose(importPair.first.front().Loc, diag::module_interface_scoped_import_unsupported); } } @@ -119,7 +119,7 @@ static void printImports(raw_ostream &out, ModuleDecl *M) { if (!import.first.empty()) { out << "/*"; for (const auto &accessPathElem : import.first) - out << "." << accessPathElem.item; + out << "." << accessPathElem.Item; out << "*/"; } diff --git a/lib/FrontendTool/ImportedModules.cpp b/lib/FrontendTool/ImportedModules.cpp index 069c989534520..82a683236668c 100644 --- a/lib/FrontendTool/ImportedModules.cpp +++ b/lib/FrontendTool/ImportedModules.cpp @@ -68,7 +68,7 @@ bool swift::emitImportedModules(ASTContext &Context, ModuleDecl *mainModule, auto accessPath = ID->getModulePath(); // only the top-level name is needed (i.e. A in A.B.C) - Modules.insert(accessPath[0].item.str()); + Modules.insert(accessPath[0].Item.str()); } // And now look in the C code we're possibly using. @@ -98,7 +98,8 @@ bool swift::emitImportedModules(ASTContext &Context, ModuleDecl *mainModule, } if (opts.ImportUnderlyingModule) { - auto underlyingModule = clangImporter->loadModule(SourceLoc(), { Located(mainModule->getName(), SourceLoc()) }); + auto underlyingModule = clangImporter->loadModule(SourceLoc(), + { Located(mainModule->getName(), SourceLoc()) }); if (!underlyingModule) { Context.Diags.diagnose(SourceLoc(), diag::error_underlying_module_not_found, diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index fe74c698d2c53..88ae650a9c495 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -4727,7 +4727,7 @@ void CodeCompletionCallbacksImpl::completeImportDecl( std::vector> &Path) { Kind = CompletionKind::Import; CurDeclContext = P.CurDeclContext; - DotLoc = Path.empty() ? SourceLoc() : Path.back().loc; + DotLoc = Path.empty() ? SourceLoc() : Path.back().Loc; if (DotLoc.isInvalid()) return; auto Importer = static_cast(CurDeclContext->getASTContext(). @@ -5573,7 +5573,7 @@ void CodeCompletionCallbacksImpl::doneParsing() { std::vector AccessPath; for (auto Piece : Path) { - AccessPath.push_back(Piece.item.str()); + AccessPath.push_back(Piece.Item.str()); } StringRef ModuleFilename = TheModule->getModuleFilename(); diff --git a/lib/IDE/ModuleInterfacePrinting.cpp b/lib/IDE/ModuleInterfacePrinting.cpp index e2cdc3f37eabf..2eaa67f1bb1a9 100644 --- a/lib/IDE/ModuleInterfacePrinting.cpp +++ b/lib/IDE/ModuleInterfacePrinting.cpp @@ -448,7 +448,7 @@ void swift::ide::printSubmoduleInterface( auto RHSPath = RHS->getFullAccessPath(); for (unsigned i = 0, e = std::min(LHSPath.size(), RHSPath.size()); i != e; i++) { - if (int Ret = LHSPath[i].item.str().compare(RHSPath[i].item.str())) + if (int Ret = LHSPath[i].Item.str().compare(RHSPath[i].Item.str())) return Ret < 0; } return false; diff --git a/lib/IDE/SourceEntityWalker.cpp b/lib/IDE/SourceEntityWalker.cpp index f7d679ae4fd72..e551ced63b7aa 100644 --- a/lib/IDE/SourceEntityWalker.cpp +++ b/lib/IDE/SourceEntityWalker.cpp @@ -670,10 +670,10 @@ passReference(ValueDecl *D, Type Ty, SourceLoc BaseNameLoc, SourceRange Range, bool SemaAnnotator::passReference(ModuleEntity Mod, Located IdLoc) { - if (IdLoc.loc.isInvalid()) + if (IdLoc.Loc.isInvalid()) return true; - unsigned NameLen = IdLoc.item.getLength(); - CharSourceRange Range{ IdLoc.loc, NameLen }; + unsigned NameLen = IdLoc.Item.getLength(); + CharSourceRange Range{ IdLoc.Loc, NameLen }; bool Continue = SEWalker.visitModuleReference(Mod, Range); if (!Continue) Cancelled = true; diff --git a/lib/IDE/SwiftSourceDocInfo.cpp b/lib/IDE/SwiftSourceDocInfo.cpp index 8fe2ac59783c4..a60e6ab70e276 100644 --- a/lib/IDE/SwiftSourceDocInfo.cpp +++ b/lib/IDE/SwiftSourceDocInfo.cpp @@ -246,7 +246,7 @@ bool NameMatcher::walkToDeclPre(Decl *D) { } } else if (ImportDecl *ID = dyn_cast(D)) { for(const ImportDecl::AccessPathElement &Element: ID->getFullAccessPath()) { - tryResolve(ASTWalker::ParentTy(D), Element.loc); + tryResolve(ASTWalker::ParentTy(D), Element.Loc); if (isDone()) break; } @@ -416,9 +416,9 @@ bool NameMatcher::walkToTypeReprPre(TypeRepr *T) { if (isa(T)) { // If we're walking a CustomAttr's type we may have an associated call // argument to resolve with from its semantic initializer. - if (CustomAttrArg.hasValue() && CustomAttrArg->loc == T->getLoc()) { + if (CustomAttrArg.hasValue() && CustomAttrArg->Loc == T->getLoc()) { tryResolve(ASTWalker::ParentTy(T), T->getLoc(), LabelRangeType::CallArg, - getCallArgLabelRanges(getSourceMgr(), CustomAttrArg->item, LabelRangeEndAt::BeforeElemStart)); + getCallArgLabelRanges(getSourceMgr(), CustomAttrArg->Item, LabelRangeEndAt::BeforeElemStart)); } else { tryResolve(ASTWalker::ParentTy(T), T->getLoc()); } diff --git a/lib/IDE/SyntaxModel.cpp b/lib/IDE/SyntaxModel.cpp index 66adaf5e20aa0..faa7da133ab17 100644 --- a/lib/IDE/SyntaxModel.cpp +++ b/lib/IDE/SyntaxModel.cpp @@ -170,9 +170,9 @@ SyntaxModelContext::SyntaxModelContext(SourceFile &SrcFile) case tok::pound_imageLiteral: if (auto Match = matchImageOrFileLiteralArg(Tokens.slice(I+1))) { Kind = SyntaxNodeKind::ObjectLiteral; - Length = SM.getByteDistance(Loc, Match->loc); + Length = SM.getByteDistance(Loc, Match->Loc); // skip over the extra matched tokens - I += Match->item - 1; + I += Match->Item - 1; } else { Kind = SyntaxNodeKind::Keyword; } @@ -180,9 +180,9 @@ SyntaxModelContext::SyntaxModelContext(SourceFile &SrcFile) case tok::pound_colorLiteral: if (auto Match = matchColorLiteralArg(Tokens.slice(I+1))) { Kind = SyntaxNodeKind::ObjectLiteral; - Length = SM.getByteDistance(Loc, Match->loc); + Length = SM.getByteDistance(Loc, Match->Loc); // skip over the matches tokens - I += Match->item - 1; + I += Match->Item - 1; } else { Kind = SyntaxNodeKind::Keyword; } diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 74b87ee2cd791..b28a8b50164c6 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -4079,7 +4079,7 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, return makeParserCodeCompletionStatus(); } ImportPath.push_back({Identifier(), Tok.getLoc()}); - if (parseAnyIdentifier(ImportPath.back().item, + if (parseAnyIdentifier(ImportPath.back().Item, diag::expected_identifier_in_decl, "import")) return nullptr; HasNext = consumeIf(tok::period); @@ -4092,8 +4092,8 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, // We omit the code completion token if it immediately follows the module // identifiers. auto BufferId = SourceMgr.getCodeCompletionBufferID(); - auto IdEndOffset = SourceMgr.getLocOffsetInBuffer(ImportPath.back().loc, - BufferId) + ImportPath.back().item.str().size(); + auto IdEndOffset = SourceMgr.getLocOffsetInBuffer(ImportPath.back().Loc, + BufferId) + ImportPath.back().Item.str().size(); auto CCTokenOffset = SourceMgr.getLocOffsetInBuffer(SourceMgr. getCodeCompletionLoc(), BufferId); if (IdEndOffset == CCTokenOffset) { @@ -4102,7 +4102,7 @@ ParserResult Parser::parseDeclImport(ParseDeclOptions Flags, } if (Kind != ImportKind::Module && ImportPath.size() == 1) { - diagnose(ImportPath.front().loc, diag::decl_expected_module_name); + diagnose(ImportPath.front().Loc, diag::decl_expected_module_name); return nullptr; } diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 3e0cd03ce8b7c..b8aaa0bb2f9fc 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -2835,7 +2835,7 @@ ParserResult Parser::parseExprClosure() { // anonymous closure arguments. if (!params) { // Create a parameter pattern containing the anonymous variables. - auto &anonVars = AnonClosureVars.back().item; + auto &anonVars = AnonClosureVars.back().Item; SmallVector elements; for (auto anonVar : anonVars) elements.push_back(anonVar); @@ -2948,8 +2948,8 @@ Expr *Parser::parseExprAnonClosureArg() { } } - auto leftBraceLoc = AnonClosureVars.back().loc; - auto &decls = AnonClosureVars.back().item; + auto leftBraceLoc = AnonClosureVars.back().Loc; + auto &decls = AnonClosureVars.back().Item; while (ArgNo >= decls.size()) { unsigned nextIdx = decls.size(); SmallVector StrBuf; diff --git a/lib/ParseSIL/ParseSIL.cpp b/lib/ParseSIL/ParseSIL.cpp index 989ce83f0eda2..f1bb364e62844 100644 --- a/lib/ParseSIL/ParseSIL.cpp +++ b/lib/ParseSIL/ParseSIL.cpp @@ -85,8 +85,8 @@ class SILParserTUState : public SILParserTUStateBase { SILParserTUState::~SILParserTUState() { if (!ForwardRefFns.empty()) { for (auto Entry : ForwardRefFns) { - if (Entry.second.loc.isValid()) { - M.getASTContext().Diags.diagnose(Entry.second.loc, + if (Entry.second.Loc.isValid()) { + M.getASTContext().Diags.diagnose(Entry.second.Loc, diag::sil_use_of_undefined_value, Entry.first.str()); } @@ -584,8 +584,8 @@ bool SILParser::diagnoseProblems() { if (!UndefinedBlocks.empty()) { // FIXME: These are going to come out in nondeterministic order. for (auto Entry : UndefinedBlocks) - P.diagnose(Entry.second.loc, diag::sil_undefined_basicblock_use, - Entry.second.item); + P.diagnose(Entry.second.Loc, diag::sil_undefined_basicblock_use, + Entry.second.Item); HadError = true; } @@ -613,13 +613,13 @@ SILFunction *SILParser::getGlobalNameForDefinition(Identifier name, // complete the forward reference. auto iter = TUState.ForwardRefFns.find(name); if (iter != TUState.ForwardRefFns.end()) { - SILFunction *fn = iter->second.item; + SILFunction *fn = iter->second.Item; // Verify that the types match up. if (fn->getLoweredFunctionType() != ty) { P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(), fn->getLoweredFunctionType(), ty); - P.diagnose(iter->second.loc, diag::sil_prior_reference); + P.diagnose(iter->second.Loc, diag::sil_prior_reference); fn = builder.createFunctionForForwardReference("" /*name*/, ty, silLoc); } @@ -5084,7 +5084,7 @@ bool SILParser::parseSILInstruction(SILBuilder &B) { results.size()); } else { for (size_t i : indices(results)) { - setLocalValue(results[i], resultNames[i].item, resultNames[i].loc); + setLocalValue(results[i], resultNames[i].Item, resultNames[i].Loc); } } } diff --git a/lib/Sema/NameBinding.cpp b/lib/Sema/NameBinding.cpp index 28e6ab7b71127..54c9f4e01e621 100644 --- a/lib/Sema/NameBinding.cpp +++ b/lib/Sema/NameBinding.cpp @@ -73,7 +73,7 @@ NameBinder::getModule(ArrayRef> modulePath) { // The Builtin module cannot be explicitly imported unless we're a .sil file // or in the REPL. if ((SF.Kind == SourceFileKind::SIL || SF.Kind == SourceFileKind::REPL) && - moduleID.item == Context.TheBuiltinModule->getName()) + moduleID.Item == Context.TheBuiltinModule->getName()) return Context.TheBuiltinModule; // If the imported module name is the same as the current module, @@ -82,10 +82,10 @@ NameBinder::getModule(ArrayRef> modulePath) { // // FIXME: We'd like to only use this in SIL mode, but unfortunately we use it // for our fake overlays as well. - if (moduleID.item == SF.getParentModule()->getName() && + if (moduleID.Item == SF.getParentModule()->getName() && modulePath.size() == 1) { if (auto importer = Context.getClangModuleLoader()) - return importer->loadModule(moduleID.loc, modulePath); + return importer->loadModule(moduleID.Loc, modulePath); return nullptr; } @@ -170,17 +170,17 @@ static bool shouldImportSelfImportClang(const ImportDecl *ID, void NameBinder::addImport( SmallVectorImpl &imports, ImportDecl *ID) { - if (ID->getModulePath().front().item == SF.getParentModule()->getName() && + if (ID->getModulePath().front().Item == SF.getParentModule()->getName() && ID->getModulePath().size() == 1 && !shouldImportSelfImportClang(ID, SF)) { // If the imported module name is the same as the current module, // produce a diagnostic. StringRef filename = llvm::sys::path::filename(SF.getFilename()); if (filename.empty()) Context.Diags.diagnose(ID, diag::sema_import_current_module, - ID->getModulePath().front().item); + ID->getModulePath().front().Item); else Context.Diags.diagnose(ID, diag::sema_import_current_module_with_file, - filename, ID->getModulePath().front().item); + filename, ID->getModulePath().front().Item); ID->setModule(SF.getParentModule()); return; } @@ -190,7 +190,7 @@ void NameBinder::addImport( SmallString<64> modulePathStr; interleave(ID->getModulePath(), [&](ImportDecl::AccessPathElement elem) { - modulePathStr += elem.item.str(); + modulePathStr += elem.Item.str(); }, [&] { modulePathStr += "."; }); @@ -214,7 +214,7 @@ void NameBinder::addImport( topLevelModule = M; } else { // If we imported a submodule, import the top-level module as well. - Identifier topLevelName = ID->getModulePath().front().item; + Identifier topLevelName = ID->getModulePath().front().Item; topLevelModule = Context.getLoadedModule(topLevelName); if (!topLevelModule) { // Clang can sometimes import top-level modules as if they were @@ -234,8 +234,8 @@ void NameBinder::addImport( !topLevelModule->isTestingEnabled() && !topLevelModule->isNonSwiftModule() && Context.LangOpts.EnableTestableAttrRequiresTestableModule) { - diagnose(ID->getModulePath().front().loc, diag::module_not_testable, - ID->getModulePath().front().item); + diagnose(ID->getModulePath().front().Loc, diag::module_not_testable, + ID->getModulePath().front().Item); testableAttr->setInvalid(); } @@ -243,9 +243,9 @@ void NameBinder::addImport( StringRef privateImportFileName; if (privateImportAttr) { if (!topLevelModule || !topLevelModule->arePrivateImportsEnabled()) { - diagnose(ID->getModulePath().front().loc, + diagnose(ID->getModulePath().front().Loc, diag::module_not_compiled_for_private_import, - ID->getModulePath().front().item); + ID->getModulePath().front().Item); privateImportAttr->setInvalid(); } else { privateImportFileName = privateImportAttr->getSourceFile(); @@ -256,7 +256,7 @@ void NameBinder::addImport( !topLevelModule->isResilient() && !topLevelModule->isNonSwiftModule() && !ID->getAttrs().hasAttribute()) { - diagnose(ID->getModulePath().front().loc, + diagnose(ID->getModulePath().front().Loc, diag::module_not_compiled_with_library_evolution, topLevelModule->getName(), SF.getParentModule()->getName()); } @@ -296,17 +296,17 @@ void NameBinder::addImport( // FIXME: Doesn't handle scoped testable imports correctly. assert(declPath.size() == 1 && "can't handle sub-decl imports"); SmallVector decls; - lookupInModule(topLevelModule, declPath.front().item, decls, + lookupInModule(topLevelModule, declPath.front().Item, decls, NLKind::QualifiedLookup, ResolutionKind::Overloadable, &SF); if (decls.empty()) { diagnose(ID, diag::decl_does_not_exist_in_module, static_cast(ID->getImportKind()), - declPath.front().item, - ID->getModulePath().front().item) - .highlight(SourceRange(declPath.front().loc, - declPath.back().loc)); + declPath.front().Item, + ID->getModulePath().front().Item) + .highlight(SourceRange(declPath.front().Loc, + declPath.back().Loc)); return; } @@ -316,7 +316,7 @@ void NameBinder::addImport( if (!actualKind.hasValue()) { // FIXME: print entire module name? diagnose(ID, diag::ambiguous_decl_in_module, - declPath.front().item, M->getName()); + declPath.front().Item, M->getName()); for (auto next : decls) diagnose(next, diag::found_candidate); @@ -338,7 +338,7 @@ void NameBinder::addImport( getImportKindString(ID->getImportKind()))); } else { emittedDiag.emplace(diagnose(ID, diag::imported_decl_is_wrong_kind, - declPath.front().item, + declPath.front().Item, getImportKindString(ID->getImportKind()), static_cast(*actualKind))); } diff --git a/lib/Sema/SourceLoader.cpp b/lib/Sema/SourceLoader.cpp index 1c7553f062a7e..c1300e38e9054 100644 --- a/lib/Sema/SourceLoader.cpp +++ b/lib/Sema/SourceLoader.cpp @@ -64,13 +64,13 @@ void SourceLoader::collectVisibleTopLevelModuleNames( bool SourceLoader::canImportModule(Located ID) { // Search the memory buffers to see if we can find this file on disk. - FileOrError inputFileOrError = findModule(Ctx, ID.item.str(), - ID.loc); + FileOrError inputFileOrError = findModule(Ctx, ID.Item.str(), + ID.Loc); if (!inputFileOrError) { auto err = inputFileOrError.getError(); if (err != std::errc::no_such_file_or_directory) { - Ctx.Diags.diagnose(ID.loc, diag::sema_opening_import, - ID.item, err.message()); + Ctx.Diags.diagnose(ID.Loc, diag::sema_opening_import, + ID.Item, err.message()); } return false; @@ -86,13 +86,13 @@ ModuleDecl *SourceLoader::loadModule(SourceLoc importLoc, auto moduleID = path[0]; - FileOrError inputFileOrError = findModule(Ctx, moduleID.item.str(), - moduleID.loc); + FileOrError inputFileOrError = findModule(Ctx, moduleID.Item.str(), + moduleID.Loc); if (!inputFileOrError) { auto err = inputFileOrError.getError(); if (err != std::errc::no_such_file_or_directory) { - Ctx.Diags.diagnose(moduleID.loc, diag::sema_opening_import, - moduleID.item, err.message()); + Ctx.Diags.diagnose(moduleID.Loc, diag::sema_opening_import, + moduleID.Item, err.message()); } return nullptr; @@ -115,10 +115,10 @@ ModuleDecl *SourceLoader::loadModule(SourceLoc importLoc, else bufferID = Ctx.SourceMgr.addNewSourceBuffer(std::move(inputFile)); - auto *importMod = ModuleDecl::create(moduleID.item, Ctx); + auto *importMod = ModuleDecl::create(moduleID.Item, Ctx); if (EnableLibraryEvolution) importMod->setResilienceStrategy(ResilienceStrategy::Resilient); - Ctx.LoadedModules[moduleID.item] = importMod; + Ctx.LoadedModules[moduleID.Item] = importMod; auto implicitImportKind = SourceFile::ImplicitModuleImportKind::Stdlib; if (!Ctx.getStdlibModule()) diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp index 1c55842c9af01..a394d8671136a 100644 --- a/lib/Sema/TypeCheckDecl.cpp +++ b/lib/Sema/TypeCheckDecl.cpp @@ -258,7 +258,7 @@ HasCircularInheritedProtocolsRequest::evaluate(Evaluator &evaluator, bool anyObject = false; auto inherited = getDirectlyInheritedNominalTypeDecls(decl, anyObject); for (auto &found : inherited) { - auto *protoDecl = dyn_cast(found.item); + auto *protoDecl = dyn_cast(found.Item); if (!protoDecl) continue; @@ -490,11 +490,11 @@ ProtocolRequiresClassRequest::evaluate(Evaluator &evaluator, // class-bound protocol. for (const auto found : allInheritedNominals) { // Superclass bound. - if (isa(found.item)) + if (isa(found.Item)) return true; // A protocol that might be class-constrained. - if (auto proto = dyn_cast(found.item)) { + if (auto proto = dyn_cast(found.Item)) { if (proto->requiresClass()) return true; } diff --git a/lib/Serialization/ModuleFile.cpp b/lib/Serialization/ModuleFile.cpp index cd099e829f17a..510a62db0c63b 100644 --- a/lib/Serialization/ModuleFile.cpp +++ b/lib/Serialization/ModuleFile.cpp @@ -2209,7 +2209,7 @@ void ModuleFile::getImportDecls(SmallVectorImpl &Results) { AccessPath.push_back({Ctx.getIdentifier(NextComponent), SourceLoc()}); } - if (AccessPath.size() == 1 && AccessPath[0].item == Ctx.StdlibModuleName) + if (AccessPath.size() == 1 && AccessPath[0].Item == Ctx.StdlibModuleName) continue; ModuleDecl *M = Ctx.getLoadedModule(AccessPath); @@ -2228,7 +2228,7 @@ void ModuleFile::getImportDecls(SmallVectorImpl &Results) { // Lookup the decl in the top-level module. ModuleDecl *TopLevelModule = M; if (AccessPath.size() > 1) - TopLevelModule = Ctx.getLoadedModule(AccessPath.front().item); + TopLevelModule = Ctx.getLoadedModule(AccessPath.front().Item); SmallVector Decls; TopLevelModule->lookupQualified( @@ -2278,7 +2278,7 @@ void ModuleFile::lookupVisibleDecls(ModuleDecl::AccessPathTy accessPath, }; if (!accessPath.empty()) { - auto iter = TopLevelDecls->find(accessPath.front().item); + auto iter = TopLevelDecls->find(accessPath.front().Item); if (iter == TopLevelDecls->end()) return; @@ -2454,7 +2454,7 @@ void ModuleFile::lookupClassMember(ModuleDecl::AccessPathTy accessPath, while (!dc->getParent()->isModuleScopeContext()) dc = dc->getParent(); if (auto nominal = dc->getSelfNominalTypeDecl()) - if (nominal->getName() == accessPath.front().item) + if (nominal->getName() == accessPath.front().Item) results.push_back(vd); } } else { @@ -2467,7 +2467,7 @@ void ModuleFile::lookupClassMember(ModuleDecl::AccessPathTy accessPath, while (!dc->getParent()->isModuleScopeContext()) dc = dc->getParent(); if (auto nominal = dc->getSelfNominalTypeDecl()) - if (nominal->getName() == accessPath.front().item) + if (nominal->getName() == accessPath.front().Item) results.push_back(vd); } } @@ -2496,7 +2496,7 @@ void ModuleFile::lookupClassMembers(ModuleDecl::AccessPathTy accessPath, while (!dc->getParent()->isModuleScopeContext()) dc = dc->getParent(); if (auto nominal = dc->getSelfNominalTypeDecl()) - if (nominal->getName() == accessPath.front().item) + if (nominal->getName() == accessPath.front().Item) consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup, DynamicLookupInfo::AnyObject); } diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index eb1cc5bafb8ff..fcdbdf15452de 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -915,7 +915,7 @@ static void flattenImportPath(const ModuleDecl::ImportedModule &import, outStream << '\0'; assert(import.first.size() == 1 && "can only handle top-level decl imports"); auto accessPathElem = import.first.front(); - outStream << accessPathElem.item.str(); + outStream << accessPathElem.Item.str(); } uint64_t getRawModTimeOrHash(const SerializationOptions::FileDependency &dep) { diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp index deab420ba56a7..bee83dc0e7a7a 100644 --- a/lib/Serialization/SerializedModuleLoader.cpp +++ b/lib/Serialization/SerializedModuleLoader.cpp @@ -428,7 +428,7 @@ SerializedModuleLoaderBase::findModule(AccessPathElem moduleID, std::unique_ptr *moduleDocBuffer, std::unique_ptr *moduleSourceInfoBuffer, bool &isFramework, bool &isSystemModule) { - llvm::SmallString<64> moduleName(moduleID.item.str()); + llvm::SmallString<64> moduleName(moduleID.Item.str()); ModuleFilenamePair fileNames(moduleName); SmallVector targetFileNamePairs; @@ -465,7 +465,7 @@ SerializedModuleLoaderBase::findModule(AccessPathElem moduleID, // We can only get here if all targetFileNamePairs failed with // 'std::errc::no_such_file_or_directory'. - if (maybeDiagnoseTargetMismatch(moduleID.loc, moduleName, + if (maybeDiagnoseTargetMismatch(moduleID.Loc, moduleName, primaryTargetSpecificName, currPath)) { return false; } else { @@ -517,7 +517,7 @@ SerializedModuleLoaderBase::findModule(AccessPathElem moduleID, case SearchPathKind::Framework: { isFramework = true; llvm::sys::path::append(currPath, - moduleID.item.str() + ".framework"); + moduleID.Item.str() + ".framework"); // Check if the framework directory exists. if (!fs.exists(currPath)) @@ -841,7 +841,7 @@ bool SerializedModuleLoaderBase::canImportModule( bool MemoryBufferSerializedModuleLoader::canImportModule( Located mID) { // See if we find it in the registered memory buffers. - return MemoryBuffers.count(mID.item.str()); + return MemoryBuffers.count(mID.Item.str()); } ModuleDecl * @@ -876,15 +876,15 @@ SerializedModuleLoaderBase::loadModule(SourceLoc importLoc, assert(moduleInputBuffer); - auto M = ModuleDecl::create(moduleID.item, Ctx); + auto M = ModuleDecl::create(moduleID.Item, Ctx); M->setIsSystemModule(isSystemModule); - Ctx.LoadedModules[moduleID.item] = M; + Ctx.LoadedModules[moduleID.Item] = M; SWIFT_DEFER { M->setHasResolvedImports(); }; StringRef moduleInterfacePathStr = Ctx.AllocateCopy(moduleInterfacePath.str()); - if (!loadAST(*M, moduleID.loc, moduleInterfacePathStr, + if (!loadAST(*M, moduleID.Loc, moduleInterfacePathStr, std::move(moduleInputBuffer), std::move(moduleDocInputBuffer), std::move(moduleSourceInfoInputBuffer), isFramework, /*treatAsPartialModule*/false)) { @@ -908,7 +908,7 @@ MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc, // FIXME: Right now this works only with access paths of length 1. // Once submodules are designed, this needs to support suffix // matching and a search path. - auto bufIter = MemoryBuffers.find(moduleID.item.str()); + auto bufIter = MemoryBuffers.find(moduleID.Item.str()); if (bufIter == MemoryBuffers.end()) return nullptr; @@ -919,16 +919,16 @@ MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc, MemoryBuffers.erase(bufIter); assert(moduleInputBuffer); - auto *M = ModuleDecl::create(moduleID.item, Ctx); + auto *M = ModuleDecl::create(moduleID.Item, Ctx); SWIFT_DEFER { M->setHasResolvedImports(); }; - if (!loadAST(*M, moduleID.loc, /*moduleInterfacePath*/ "", + if (!loadAST(*M, moduleID.Loc, /*moduleInterfacePath*/ "", std::move(moduleInputBuffer), {}, {}, isFramework, treatAsPartialModule)) { return nullptr; } - Ctx.LoadedModules[moduleID.item] = M; + Ctx.LoadedModules[moduleID.Item] = M; return M; } diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/tools/swift-ide-test/swift-ide-test.cpp index 1704f85756259..adfd9d0ee73a2 100644 --- a/tools/swift-ide-test/swift-ide-test.cpp +++ b/tools/swift-ide-test/swift-ide-test.cpp @@ -2623,7 +2623,7 @@ static int doPrintModuleImports(const CompilerInvocation &InitInvok, for (auto &import : scratch) { llvm::outs() << "\t" << import.second->getName(); for (auto accessPathPiece : import.first) { - llvm::outs() << "." << accessPathPiece.item; + llvm::outs() << "." << accessPathPiece.Item; } if (import.second->isClangModule()) From b4b3f98d869ef6384d79024704167d9c116a5356 Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Sun, 15 Dec 2019 20:42:55 +0300 Subject: [PATCH 06/10] SR-11889: Fixed code review issues 1. Use Located in Convention structure --- include/swift/AST/Attr.h | 8 +++----- lib/AST/Attr.cpp | 4 ++-- lib/AST/NameLookup.cpp | 4 ++-- lib/Parse/ParseDecl.cpp | 3 +-- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h index f3a7083b49aea..91b3d5410dd12 100644 --- a/include/swift/AST/Attr.h +++ b/include/swift/AST/Attr.h @@ -25,6 +25,7 @@ #include "swift/Basic/Range.h" #include "swift/Basic/OptimizationMode.h" #include "swift/Basic/Version.h" +#include "swift/Basic/Located.h" #include "swift/AST/Identifier.h" #include "swift/AST/AttrKind.h" #include "swift/AST/AutoDiff.h" @@ -69,16 +70,13 @@ class TypeAttributes { struct Convention { StringRef Name = {}; DeclNameRef WitnessMethodProtocol = {}; - StringRef ClangType = {}; - // Carry the source location for diagnostics. - SourceLoc ClangTypeLoc = {}; - + Located ClangType = {}; /// Convenience factory function to create a Swift convention. /// /// Don't use this function if you are creating a C convention as you /// probably need a ClangType field as well. static Convention makeSwiftConvention(StringRef name) { - return {name, DeclNameRef(), "", {}}; + return {name, DeclNameRef(), Located("", {})}; } }; diff --git a/lib/AST/Attr.cpp b/lib/AST/Attr.cpp index 65333c36d96de..bb6d7c47d8079 100644 --- a/lib/AST/Attr.cpp +++ b/lib/AST/Attr.cpp @@ -92,8 +92,8 @@ void TypeAttributes::getConventionArguments(SmallVectorImpl &buf) const { stream << ": " << convention.WitnessMethodProtocol; return; } - if (!convention.ClangType.empty()) - stream << ", cType: " << QuotedString(convention.ClangType); + if (!convention.ClangType.Item.empty()) + stream << ", cType: " << QuotedString(convention.ClangType.Item); } /// Given a name like "autoclosure", return the type attribute ID that diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp index 95c1004be5cf8..d4b7b28115633 100644 --- a/lib/AST/NameLookup.cpp +++ b/lib/AST/NameLookup.cpp @@ -2402,8 +2402,8 @@ swift::getDirectlyInheritedNominalTypeDecls( if (!req.getFirstType()->isEqual(protoSelfTy)) continue; - result.emplace_back( - loc, req.getSecondType()->castTo()->getDecl()); + result.emplace_back(req.getSecondType()->castTo()->getDecl(), + loc); } return result; } diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index b28a8b50164c6..a5000705d9b56 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -2699,8 +2699,7 @@ bool Parser::parseConventionAttributeInternal( return true; } if (auto ty = getStringLiteralIfNotInterpolated(Tok.getLoc(), "(C type)")) { - convention.ClangType = ty.getValue(); - convention.ClangTypeLoc = Tok.getLoc(); + convention.ClangType = { ty.getValue(), Tok.getLoc() }; } consumeToken(tok::string_literal); } From c70bd2b2c98b5b586d26ec42362a2e87af091c82 Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Mon, 16 Dec 2019 00:40:04 +0300 Subject: [PATCH 07/10] SR-11889: Located added dump methods --- include/swift/Basic/Located.h | 8 +++++++- lib/Basic/CMakeLists.txt | 1 + lib/Basic/Located.cpp | 24 ++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 lib/Basic/Located.cpp diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index ceda184fd3845..9b2eeb8d6710c 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -18,6 +18,8 @@ #ifndef SWIFT_BASIC_LOCATED_H #define SWIFT_BASIC_LOCATED_H +#include "swift/Basic/Debug.h" +#include "swift/Basic/LLVM.h" #include "swift/Basic/SourceLoc.h" namespace swift { @@ -41,11 +43,15 @@ struct Located { Located(T Item, SourceLoc loc): Item(Item), Loc(loc) {} + SWIFT_DEBUG_DUMP; + void dump(raw_ostream &os) const; + template friend bool operator ==(const Located& lhs, const Located& rhs) { return lhs.Item == rhs.Item && lhs.Loc == rhs.Loc; } }; -} + +} // end namespace swift #endif // SWIFT_BASIC_LOCATED_H diff --git a/lib/Basic/CMakeLists.txt b/lib/Basic/CMakeLists.txt index 8504b672afc70..6cd7577ce3f93 100644 --- a/lib/Basic/CMakeLists.txt +++ b/lib/Basic/CMakeLists.txt @@ -77,6 +77,7 @@ add_swift_host_library(swiftBasic STATIC JSONSerialization.cpp LangOptions.cpp LLVMContext.cpp + Located.cpp Mangler.cpp OutputFileMap.cpp Platform.cpp diff --git a/lib/Basic/Located.cpp b/lib/Basic/Located.cpp new file mode 100644 index 0000000000000..2167d5abde334 --- /dev/null +++ b/lib/Basic/Located.cpp @@ -0,0 +1,24 @@ +//===--- Located.cpp - Source Location and Associated Value ----------*- C++ -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2019 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +#include "llvm/Support/raw_ostream.h" +#include "swift/Basic/Located.h" + +using namespace swift; + +template +void Located::dump() const { + dump(llvm::errs()); +} + +template +void Located::dump(raw_ostream &os) const { + os << Loc << " " << Item; +} From a2cce2b2933884520d3331828590b79c9e156fc8 Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Fri, 20 Dec 2019 17:12:57 +0300 Subject: [PATCH 08/10] SR-11889: Fixed code review issues --- include/swift/AST/Attr.h | 2 +- include/swift/Basic/Located.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h index 91b3d5410dd12..e4d624c0bd42e 100644 --- a/include/swift/AST/Attr.h +++ b/include/swift/AST/Attr.h @@ -70,7 +70,7 @@ class TypeAttributes { struct Convention { StringRef Name = {}; DeclNameRef WitnessMethodProtocol = {}; - Located ClangType = {}; + Located ClangType = Located(StringRef(), {}); /// Convenience factory function to create a Swift convention. /// /// Don't use this function if you are creating a C convention as you diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index 9b2eeb8d6710c..3b7b6d537a66f 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -39,15 +39,15 @@ struct Located { /// The original source location from which the item was parsed. SourceLoc Loc; - Located(): Item(), Loc() {} + Located() : Item(), Loc() {} - Located(T Item, SourceLoc loc): Item(Item), Loc(loc) {} + Located(T Item, SourceLoc loc) : Item(Item), Loc(loc) {} SWIFT_DEBUG_DUMP; void dump(raw_ostream &os) const; template - friend bool operator ==(const Located& lhs, const Located& rhs) { + friend bool operator ==(const Located &lhs, const Located &rhs) { return lhs.Item == rhs.Item && lhs.Loc == rhs.Loc; } }; From 646e9ac77f779cbf4e77e34372a35e9beb357702 Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Sun, 22 Dec 2019 14:42:47 +0300 Subject: [PATCH 09/10] SR-11889: Fixed code review issues --- include/swift/Basic/Located.h | 29 +++++++++++++++++++++++++++++ lib/ClangImporter/ImporterImpl.h | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/include/swift/Basic/Located.h b/include/swift/Basic/Located.h index 3b7b6d537a66f..79721d257b041 100644 --- a/include/swift/Basic/Located.h +++ b/include/swift/Basic/Located.h @@ -54,4 +54,33 @@ struct Located { } // end namespace swift +namespace llvm { + +template struct DenseMapInfo; + +template +struct DenseMapInfo> { + + static inline swift::Located getEmptyKey() { + return swift::Located(DenseMapInfo::getEmptyKey(), + DenseMapInfo::getEmptyKey()); + } + + static inline swift::Located getTombstoneKey() { + return swift::Located(DenseMapInfo::getTombstoneKey(), + DenseMapInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const swift::Located &LocatedVal) { + return combineHashValue(DenseMapInfo::getHashValue(LocatedVal.Item), + DenseMapInfo::getHashValue(LocatedVal.Loc)); + } + + static bool isEqual(const swift::Located &LHS, const swift::Located &RHS) { + return DenseMapInfo::isEqual(LHS.Item, RHS.Item) && + DenseMapInfo::isEqual(LHS.Loc, RHS.Loc); + } +}; +} // namespace llvm + #endif // SWIFT_BASIC_LOCATED_H diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h index f21345fc10b15..bc4e7028c0158 100644 --- a/lib/ClangImporter/ImporterImpl.h +++ b/lib/ClangImporter/ImporterImpl.h @@ -631,7 +631,7 @@ class LLVM_LIBRARY_VISIBILITY ClangImporter::Implementation public: /// Load a module using either method. ModuleDecl *loadModule(SourceLoc importLoc, - ArrayRef> path); + ArrayRef> path); void recordImplicitUnwrapForDecl(ValueDecl *decl, bool isIUO) { if (!isIUO) From 76373b6c7469106ac68aca61a7f60e1e036f4ec5 Mon Sep 17 00:00:00 2001 From: "Kita, Maksim" Date: Sat, 4 Jan 2020 20:20:41 +0300 Subject: [PATCH 10/10] SR-11889: Fixed code review issues --- unittests/AST/DiagnosticConsumerTests.cpp | 153 +++++++++++----------- 1 file changed, 77 insertions(+), 76 deletions(-) diff --git a/unittests/AST/DiagnosticConsumerTests.cpp b/unittests/AST/DiagnosticConsumerTests.cpp index d3d24a3a8098a..77032b705a935 100644 --- a/unittests/AST/DiagnosticConsumerTests.cpp +++ b/unittests/AST/DiagnosticConsumerTests.cpp @@ -11,6 +11,7 @@ //===----------------------------------------------------------------------===// #include "swift/AST/DiagnosticConsumer.h" +#include "swift/Basic/Located.h" #include "swift/Basic/SourceManager.h" #include "gtest/gtest.h" @@ -37,7 +38,7 @@ namespace { void handleDiagnostic(SourceManager &SM, const DiagnosticInfo &Info) override { ASSERT_FALSE(expected.empty()); - EXPECT_EQ(std::make_pair(Info.Loc, Info.FormatString), expected.front()); + EXPECT_EQ(Located(Info.FormatString, Info.Loc), expected.front()); expected.erase(expected.begin()); } @@ -83,7 +84,7 @@ TEST(FileSpecificDiagnosticConsumer, InvalidLocDiagsGoToEveryConsumer) { (void)sourceMgr.addMemBufferCopy("abcde", "A"); (void)sourceMgr.addMemBufferCopy("vwxyz", "B"); - ExpectedDiagnostic expected[] = { {SourceLoc(), "dummy"} }; + ExpectedDiagnostic expected[] = { Located("dummy", SourceLoc()) }; auto consumerA = llvm::make_unique( nullptr, expected); auto consumerUnaffiliated = llvm::make_unique( @@ -116,14 +117,14 @@ TEST(FileSpecificDiagnosticConsumer, ErrorsWithLocationsGoToExpectedConsumers) { SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4); ExpectedDiagnostic expectedA[] = { - {frontOfA, "front"}, - {middleOfA, "middle"}, - {backOfA, "back"}, + {"front", frontOfA}, + {"middle", middleOfA}, + {"back", backOfA}, }; ExpectedDiagnostic expectedB[] = { - {frontOfB, "front"}, - {middleOfB, "middle"}, - {backOfB, "back"} + {"front", frontOfB}, + {"middle", middleOfB}, + {"back", backOfB} }; auto consumerA = llvm::make_unique( @@ -170,17 +171,17 @@ TEST(FileSpecificDiagnosticConsumer, SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4); ExpectedDiagnostic expectedA[] = { - {frontOfA, "front"}, - {frontOfB, "front"}, - {middleOfA, "middle"}, - {middleOfB, "middle"}, - {backOfA, "back"}, - {backOfB, "back"} + {"front", frontOfA}, + {"front", frontOfB}, + {"middle", middleOfA}, + {"middle", middleOfB}, + {"back", backOfA}, + {"back", backOfB} }; ExpectedDiagnostic expectedUnaffiliated[] = { - {frontOfB, "front"}, - {middleOfB, "middle"}, - {backOfB, "back"} + {"front", frontOfB}, + {"middle", middleOfB}, + {"back", backOfB} }; auto consumerA = llvm::make_unique( @@ -221,14 +222,14 @@ TEST(FileSpecificDiagnosticConsumer, WarningsAndRemarksAreTreatedLikeErrors) { SourceLoc frontOfB = sourceMgr.getLocForBufferStart(bufferB); ExpectedDiagnostic expectedA[] = { - {frontOfA, "warning"}, - {frontOfB, "warning"}, - {frontOfA, "remark"}, - {frontOfB, "remark"}, + {"warning", frontOfA}, + {"warning", frontOfB}, + {"remark", frontOfA}, + {"remark", frontOfB}, }; ExpectedDiagnostic expectedUnaffiliated[] = { - {frontOfB, "warning"}, - {frontOfB, "remark"}, + {"warning", frontOfB}, + {"remark", frontOfB}, }; auto consumerA = llvm::make_unique( @@ -272,20 +273,20 @@ TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToErrors) { SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4); ExpectedDiagnostic expectedA[] = { - {frontOfA, "error"}, - {middleOfA, "note"}, - {backOfA, "note"}, - {frontOfB, "error"}, - {middleOfB, "note"}, - {backOfB, "note"}, - {frontOfA, "error"}, - {middleOfA, "note"}, - {backOfA, "note"}, + {"error", frontOfA}, + {"note", middleOfA}, + {"note", backOfA}, + {"error", frontOfB}, + {"note", middleOfB}, + {"note", backOfB}, + {"error", frontOfA}, + {"note", middleOfA}, + {"note", backOfA}, }; ExpectedDiagnostic expectedUnaffiliated[] = { - {frontOfB, "error"}, - {middleOfB, "note"}, - {backOfB, "note"}, + {"error", frontOfB}, + {"note", middleOfB}, + {"note", backOfB}, }; auto consumerA = llvm::make_unique( @@ -335,20 +336,20 @@ TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToWarningsAndRemarks) { SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4); ExpectedDiagnostic expectedA[] = { - {frontOfA, "warning"}, - {middleOfA, "note"}, - {backOfA, "note"}, - {frontOfB, "warning"}, - {middleOfB, "note"}, - {backOfB, "note"}, - {frontOfA, "remark"}, - {middleOfA, "note"}, - {backOfA, "note"}, + {"warning", frontOfA}, + {"note", middleOfA}, + {"note", backOfA}, + {"warning", frontOfB}, + {"note", middleOfB}, + {"note", backOfB}, + {"remark", frontOfA}, + {"note", middleOfA}, + {"note", backOfA}, }; ExpectedDiagnostic expectedUnaffiliated[] = { - {frontOfB, "warning"}, - {middleOfB, "note"}, - {backOfB, "note"}, + {"warning", frontOfB}, + {"note", middleOfB}, + {"note", backOfB}, }; auto consumerA = llvm::make_unique( @@ -401,17 +402,17 @@ TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToErrorsEvenAcrossFiles) { SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4); ExpectedDiagnostic expectedA[] = { - {frontOfA, "error"}, - {middleOfB, "note"}, - {backOfA, "note"}, - {frontOfA, "error"}, - {middleOfB, "note"}, - {backOfA, "note"}, + {"error", frontOfA}, + {"note", middleOfB}, + {"note", backOfA}, + {"error", frontOfA}, + {"note", middleOfB}, + {"note", backOfA}, }; ExpectedDiagnostic expectedB[] = { - {frontOfB, "error"}, - {middleOfA, "note"}, - {backOfB, "note"}, + {"error", frontOfB}, + {"note", middleOfA}, + {"note", backOfB}, }; auto consumerA = llvm::make_unique( @@ -462,20 +463,20 @@ TEST(FileSpecificDiagnosticConsumer, SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4); ExpectedDiagnostic expectedA[] = { - {frontOfA, "error"}, - {middleOfB, "note"}, - {backOfA, "note"}, - {frontOfB, "error"}, - {middleOfA, "note"}, - {backOfB, "note"}, - {frontOfA, "error"}, - {middleOfB, "note"}, - {backOfA, "note"}, + {"error", frontOfA}, + {"note", middleOfB}, + {"note", backOfA}, + {"error", frontOfB}, + {"note", middleOfA}, + {"note", backOfB}, + {"error", frontOfA}, + {"note", middleOfB}, + {"note", backOfA}, }; ExpectedDiagnostic expectedUnaffiliated[] = { - {frontOfB, "error"}, - {middleOfA, "note"}, - {backOfB, "note"}, + {"error", frontOfB}, + {"note", middleOfA}, + {"note", backOfB}, }; auto consumerA = llvm::make_unique( @@ -522,16 +523,16 @@ TEST(FileSpecificDiagnosticConsumer, SourceLoc frontOfB = sourceMgr.getLocForBufferStart(bufferB); ExpectedDiagnostic expectedA[] = { - {frontOfA, "error"}, - {SourceLoc(), "note"}, - {frontOfB, "error"}, - {SourceLoc(), "note"}, - {frontOfA, "error"}, - {SourceLoc(), "note"}, + {"error", frontOfA}, + {"note", SourceLoc()}, + {"error", frontOfB}, + {"note", SourceLoc()}, + {"error", frontOfA}, + {"note", SourceLoc()}, }; ExpectedDiagnostic expectedUnaffiliated[] = { - {frontOfB, "error"}, - {SourceLoc(), "note"}, + {"error", frontOfB}, + {"note", SourceLoc()}, }; auto consumerA = llvm::make_unique(