1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
|
//===------------ DependencyScanningTool.cpp - Swift Compiler -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/TargetInfo.h"
#include "swift/Basic/ColorUtils.h"
#include "swift/DependencyScan/DependencyScanningTool.h"
#include "swift/DependencyScan/DependencyScanImpl.h"
#include "swift/DependencyScan/SerializedModuleDependencyCacheFormat.h"
#include "swift/DependencyScan/StringUtils.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/VirtualOutputBackends.h"
#include <sstream>
namespace swift {
namespace dependencies {
// Global mutex for target info queries since they are executed separately .
llvm::sys::SmartMutex<true> TargetInfoMutex;
llvm::ErrorOr<swiftscan_string_ref_t> getTargetInfo(ArrayRef<const char *> Command,
const char *main_executable_path) {
llvm::sys::SmartScopedLock<true> Lock(TargetInfoMutex);
// Parse arguments.
std::string CommandString;
for (const auto *c : Command) {
CommandString.append(c);
CommandString.append(" ");
}
SmallVector<const char *, 4> Args;
llvm::BumpPtrAllocator Alloc;
llvm::StringSaver Saver(Alloc);
// Ensure that we use the Windows command line parsing on Windows as we need
// to ensure that we properly handle paths.
if (llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows())
llvm::cl::TokenizeWindowsCommandLine(CommandString, Saver, Args);
else
llvm::cl::TokenizeGNUCommandLine(CommandString, Saver, Args);
SourceManager dummySM;
DiagnosticEngine DE(dummySM);
CompilerInvocation Invocation;
if (Invocation.parseArgs(Args, DE, nullptr, {}, main_executable_path)) {
return std::make_error_code(std::errc::invalid_argument);
}
// Store the result to a string.
std::string ResultStr;
llvm::raw_string_ostream StrOS(ResultStr);
swift::targetinfo::printTargetInfo(Invocation, StrOS);
return c_string_utils::create_clone(ResultStr.c_str());
}
void DependencyScanDiagnosticCollector::handleDiagnostic(SourceManager &SM,
const DiagnosticInfo &Info) {
addDiagnostic(SM, Info);
for (auto ChildInfo : Info.ChildDiagnosticInfo) {
addDiagnostic(SM, *ChildInfo);
}
}
void DependencyScanDiagnosticCollector::addDiagnostic(
SourceManager &SM, const DiagnosticInfo &Info) {
// Determine what kind of diagnostic we're emitting.
llvm::SourceMgr::DiagKind SMKind;
switch (Info.Kind) {
case DiagnosticKind::Error:
SMKind = llvm::SourceMgr::DK_Error;
break;
case DiagnosticKind::Warning:
SMKind = llvm::SourceMgr::DK_Warning;
break;
case DiagnosticKind::Note:
SMKind = llvm::SourceMgr::DK_Note;
break;
case DiagnosticKind::Remark:
SMKind = llvm::SourceMgr::DK_Remark;
break;
}
// Translate ranges.
SmallVector<llvm::SMRange, 2> Ranges;
for (auto R : Info.Ranges)
Ranges.push_back(getRawRange(SM, R));
// Translate fix-its.
SmallVector<llvm::SMFixIt, 2> FixIts;
for (DiagnosticInfo::FixIt F : Info.FixIts)
FixIts.push_back(getRawFixIt(SM, F));
// Display the diagnostic.
std::string FormattedMessage;
llvm::raw_string_ostream Stream(FormattedMessage);
// Actually substitute the diagnostic arguments into the diagnostic text.
llvm::SmallString<256> Text;
{
llvm::raw_svector_ostream Out(Text);
DiagnosticEngine::formatDiagnosticText(Out, Info.FormatString,
Info.FormatArgs);
auto Msg = SM.GetMessage(Info.Loc, SMKind, Text, Ranges, FixIts, true);
Msg.print(nullptr, Stream, false, false, false);
Stream.flush();
}
if (Info.Loc && Info.Loc.isValid()) {
auto bufferIdentifier = SM.getDisplayNameForLoc(Info.Loc);
auto lineAndColumnNumbers = SM.getLineAndColumnInBuffer(Info.Loc);
auto importLocation = ScannerImportStatementInfo::ImportDiagnosticLocationInfo(
bufferIdentifier.str(), lineAndColumnNumbers.first,
lineAndColumnNumbers.second);
Diagnostics.push_back(
ScannerDiagnosticInfo{FormattedMessage, SMKind, importLocation});
} else {
Diagnostics.push_back(
ScannerDiagnosticInfo{FormattedMessage, SMKind, std::nullopt});
}
}
void LockingDependencyScanDiagnosticCollector::addDiagnostic(
SourceManager &SM, const DiagnosticInfo &Info) {
llvm::sys::SmartScopedLock<true> Lock(ScanningDiagnosticConsumerStateLock);
DependencyScanDiagnosticCollector::addDiagnostic(SM, Info);
}
swiftscan_diagnostic_set_t *mapCollectedDiagnosticsForOutput(
const DependencyScanDiagnosticCollector *diagnosticCollector) {
auto collectedDiagnostics = diagnosticCollector->getDiagnostics();
auto numDiagnostics = collectedDiagnostics.size();
swiftscan_diagnostic_set_t *diagnosticOutput = new swiftscan_diagnostic_set_t;
diagnosticOutput->count = numDiagnostics;
diagnosticOutput->diagnostics =
new swiftscan_diagnostic_info_t[numDiagnostics];
for (size_t i = 0; i < numDiagnostics; ++i) {
const auto &Diagnostic = collectedDiagnostics[i];
swiftscan_diagnostic_info_s *diagnosticInfo =
new swiftscan_diagnostic_info_s;
diagnosticInfo->message =
swift::c_string_utils::create_clone(Diagnostic.Message.c_str());
switch (Diagnostic.Severity) {
case llvm::SourceMgr::DK_Error:
diagnosticInfo->severity = SWIFTSCAN_DIAGNOSTIC_SEVERITY_ERROR;
break;
case llvm::SourceMgr::DK_Warning:
diagnosticInfo->severity = SWIFTSCAN_DIAGNOSTIC_SEVERITY_WARNING;
break;
case llvm::SourceMgr::DK_Note:
diagnosticInfo->severity = SWIFTSCAN_DIAGNOSTIC_SEVERITY_NOTE;
break;
case llvm::SourceMgr::DK_Remark:
diagnosticInfo->severity = SWIFTSCAN_DIAGNOSTIC_SEVERITY_REMARK;
break;
}
if (Diagnostic.ImportLocation.has_value()) {
auto importLocation = Diagnostic.ImportLocation.value();
swiftscan_source_location_s *sourceLoc = new swiftscan_source_location_s;
if (importLocation.bufferIdentifier.empty())
sourceLoc->buffer_identifier = swift::c_string_utils::create_null();
else
sourceLoc->buffer_identifier = swift::c_string_utils::create_clone(
importLocation.bufferIdentifier.c_str());
sourceLoc->line_number = importLocation.lineNumber;
sourceLoc->column_number = importLocation.columnNumber;
diagnosticInfo->source_location = sourceLoc;
} else {
diagnosticInfo->source_location = nullptr;
}
diagnosticOutput->diagnostics[i] = diagnosticInfo;
}
return diagnosticOutput;
}
// Generate an instance of the `swiftscan_dependency_graph_s` which contains no
// module dependnecies but captures the diagnostics emitted during the attempted
// scan query.
static swiftscan_dependency_graph_t generateHollowDiagnosticOutput(
const DependencyScanDiagnosticCollector &ScanDiagnosticConsumer) {
// Create a dependency graph instance
swiftscan_dependency_graph_t hollowResult = new swiftscan_dependency_graph_s;
// Populate the `modules` with a single info for the main module
// containing no dependencies
swiftscan_dependency_set_t *dependencySet = new swiftscan_dependency_set_t;
dependencySet->count = 1;
dependencySet->modules = new swiftscan_dependency_info_t[1];
swiftscan_dependency_info_s *hollowMainModuleInfo =
new swiftscan_dependency_info_s;
dependencySet->modules[0] = hollowMainModuleInfo;
hollowResult->dependencies = dependencySet;
// Other main module details empty
hollowMainModuleInfo->direct_dependencies =
c_string_utils::create_empty_set();
hollowMainModuleInfo->source_files = c_string_utils::create_empty_set();
hollowMainModuleInfo->module_path = c_string_utils::create_null();
hollowResult->main_module_name = c_string_utils::create_clone("unknown");
hollowMainModuleInfo->module_name =
c_string_utils::create_clone("swiftTextual:unknown");
// Hollow info details
swiftscan_module_details_s *hollowDetails = new swiftscan_module_details_s;
hollowDetails->kind = SWIFTSCAN_DEPENDENCY_INFO_SWIFT_TEXTUAL;
hollowDetails->swift_textual_details = {c_string_utils::create_null(),
c_string_utils::create_empty_set(),
c_string_utils::create_null(),
c_string_utils::create_empty_set(),
c_string_utils::create_empty_set(),
c_string_utils::create_empty_set(),
c_string_utils::create_empty_set(),
c_string_utils::create_empty_set(),
c_string_utils::create_empty_set(),
c_string_utils::create_null(),
false,
c_string_utils::create_null(),
c_string_utils::create_null(),
c_string_utils::create_null(),
nullptr};
hollowMainModuleInfo->details = hollowDetails;
// Populate the diagnostic info
hollowResult->diagnostics =
mapCollectedDiagnosticsForOutput(&ScanDiagnosticConsumer);
return hollowResult;
}
// Generate an instance of the `swiftscan_import_set_t` which contains no
// imports but captures the diagnostics emitted during the attempted
// scan query.
static swiftscan_import_set_t generateHollowDiagnosticOutputImportSet(
const DependencyScanDiagnosticCollector &ScanDiagnosticConsumer) {
// Create an dependency graph instance
swiftscan_import_set_t hollowResult = new swiftscan_import_set_s;
hollowResult->imports = c_string_utils::create_empty_set();
hollowResult->diagnostics =
mapCollectedDiagnosticsForOutput(&ScanDiagnosticConsumer);
return hollowResult;
}
DependencyScanningTool::DependencyScanningTool()
: ScanningService(std::make_unique<SwiftDependencyScanningService>()),
VersionedPCMInstanceCacheCache(
std::make_unique<CompilerArgInstanceCacheMap>()),
CDC(), Alloc(), Saver(Alloc) {}
llvm::ErrorOr<swiftscan_dependency_graph_t>
DependencyScanningTool::getDependencies(
ArrayRef<const char *> Command,
const llvm::StringSet<> &PlaceholderModules,
StringRef WorkingDirectory) {
// There may be errors as early as in instance initialization, so we must ensure
// we can catch those.
auto ScanDiagnosticConsumer = std::make_shared<DependencyScanDiagnosticCollector>();
// The primary instance used to scan the query Swift source-code
auto QueryContextOrErr = initCompilerInstanceForScan(Command,
WorkingDirectory,
ScanDiagnosticConsumer);
if (QueryContextOrErr.getError())
return generateHollowDiagnosticOutput(*ScanDiagnosticConsumer);
auto QueryContext = std::move(*QueryContextOrErr);
// Local scan cache instance, wrapping the shared global cache.
ModuleDependenciesCache cache(
*ScanningService, QueryContext.ScanInstance->getMainModule()->getNameStr().str(),
QueryContext.ScanInstance->getInvocation().getFrontendOptions().ExplicitModulesOutputPath,
QueryContext.ScanInstance->getInvocation().getModuleScanningHash());
// Execute the scanning action, retrieving the in-memory result
auto DependenciesOrErr = performModuleScan(*QueryContext.ScanInstance.get(),
QueryContext.ScanDiagnostics.get(),
cache);
if (DependenciesOrErr.getError())
return generateHollowDiagnosticOutput(*ScanDiagnosticConsumer);
return std::move(*DependenciesOrErr);
}
llvm::ErrorOr<swiftscan_import_set_t>
DependencyScanningTool::getImports(ArrayRef<const char *> Command,
StringRef WorkingDirectory) {
// There may be errors as early as in instance initialization, so we must ensure
// we can catch those
auto ScanDiagnosticConsumer = std::make_shared<DependencyScanDiagnosticCollector>();
// The primary instance used to scan the query Swift source-code
auto QueryContextOrErr = initCompilerInstanceForScan(Command,
WorkingDirectory,
ScanDiagnosticConsumer);
if (QueryContextOrErr.getError())
return generateHollowDiagnosticOutputImportSet(*ScanDiagnosticConsumer);
auto QueryContext = std::move(*QueryContextOrErr);
// Local scan cache instance, wrapping the shared global cache.
ModuleDependenciesCache cache(
*ScanningService, QueryContext.ScanInstance->getMainModule()->getNameStr().str(),
QueryContext.ScanInstance->getInvocation().getFrontendOptions().ExplicitModulesOutputPath,
QueryContext.ScanInstance->getInvocation().getModuleScanningHash());
auto DependenciesOrErr = performModulePrescan(*QueryContext.ScanInstance.get(),
QueryContext.ScanDiagnostics.get(),
cache);
if (DependenciesOrErr.getError())
return generateHollowDiagnosticOutputImportSet(*ScanDiagnosticConsumer);
return std::move(*DependenciesOrErr);
}
std::vector<llvm::ErrorOr<swiftscan_dependency_graph_t>>
DependencyScanningTool::getDependencies(
ArrayRef<const char *> Command,
const std::vector<BatchScanInput> &BatchInput,
const llvm::StringSet<> &PlaceholderModules, StringRef WorkingDirectory) {
// The primary instance used to scan Swift modules
auto ScanDiagnosticConsumer = std::make_shared<DependencyScanDiagnosticCollector>();
auto QueryContextOrErr = initCompilerInstanceForScan(Command,
WorkingDirectory,
ScanDiagnosticConsumer);
if (std::error_code EC = QueryContextOrErr.getError())
return std::vector<llvm::ErrorOr<swiftscan_dependency_graph_t>>(
BatchInput.size(), std::make_error_code(std::errc::invalid_argument));
auto QueryContext = std::move(*QueryContextOrErr);
// Local scan cache instance, wrapping the shared global cache.
ModuleDependenciesCache cache(
*ScanningService, QueryContext.ScanInstance->getMainModule()->getNameStr().str(),
QueryContext.ScanInstance->getInvocation().getFrontendOptions().ExplicitModulesOutputPath,
QueryContext.ScanInstance->getInvocation().getModuleScanningHash());
auto BatchScanResults = performBatchModuleScan(
*QueryContext.ScanInstance.get(), QueryContext.ScanDiagnostics.get(),
cache, VersionedPCMInstanceCacheCache.get(),
Saver, BatchInput);
return BatchScanResults;
}
void DependencyScanningTool::serializeCache(llvm::StringRef path) {
llvm::sys::SmartScopedLock<true> Lock(DependencyScanningToolStateLock);
SourceManager SM;
DiagnosticEngine Diags(SM);
Diags.addConsumer(CDC);
llvm::vfs::OnDiskOutputBackend Backend;
module_dependency_cache_serialization::writeInterModuleDependenciesCache(
Diags, Backend, path, *ScanningService);
}
bool DependencyScanningTool::loadCache(llvm::StringRef path) {
llvm::sys::SmartScopedLock<true> Lock(DependencyScanningToolStateLock);
SourceManager SM;
DiagnosticEngine Diags(SM);
Diags.addConsumer(CDC);
ScanningService = std::make_unique<SwiftDependencyScanningService>();
bool readFailed =
module_dependency_cache_serialization::readInterModuleDependenciesCache(
path, *ScanningService);
if (readFailed) {
Diags.diagnose(SourceLoc(), diag::warn_scanner_deserialize_failed, path);
}
return readFailed;
}
void DependencyScanningTool::resetCache() {
llvm::sys::SmartScopedLock<true> Lock(DependencyScanningToolStateLock);
ScanningService.reset(new SwiftDependencyScanningService());
}
std::vector<
DependencyScanDiagnosticCollector::ScannerDiagnosticInfo>
DependencyScanningTool::getDiagnostics() {
llvm::sys::SmartScopedLock<true> Lock(DependencyScanningToolStateLock);
return CDC.Diagnostics;
}
void DependencyScanningTool::resetDiagnostics() {
llvm::sys::SmartScopedLock<true> Lock(DependencyScanningToolStateLock);
CDC.reset();
}
llvm::ErrorOr<ScanQueryInstance>
DependencyScanningTool::initCompilerInstanceForScan(
ArrayRef<const char *> CommandArgs,
StringRef WorkingDir,
std::shared_ptr<DependencyScanDiagnosticCollector> scannerDiagnosticsCollector) {
// The remainder of this method operates on shared state in the
// scanning service
llvm::sys::SmartScopedLock<true> Lock(DependencyScanningToolStateLock);
// FIXME: Instead, target-info and supported-features queries must use
// `DependencyScanningToolStateLock`, but this currently requires further
// client-side API plumbing.
llvm::sys::SmartScopedLock<true> TargetInfoLock(TargetInfoMutex);
// State unique to an individual scan
auto Instance = std::make_unique<CompilerInstance>();
// FIXME: The shared CDC must be deprecated once all clients have switched
// to using per-scan diagnostic output embedded in the `swiftscan_dependency_graph_s`
Instance->addDiagnosticConsumer(&CDC);
Instance->addDiagnosticConsumer(scannerDiagnosticsCollector.get());
// Basic error checking on the arguments
if (CommandArgs.empty()) {
Instance->getDiags().diagnose(SourceLoc(), diag::error_no_frontend_args);
return std::make_error_code(std::errc::invalid_argument);
}
CompilerInvocation Invocation;
SmallString<128> WorkingDirectory(WorkingDir);
if (WorkingDirectory.empty())
llvm::sys::fs::current_path(WorkingDirectory);
// Parse/tokenize arguments.
std::string CommandString;
for (const auto *c : CommandArgs) {
CommandString.append(c);
CommandString.append(" ");
}
SmallVector<const char *, 4> Args;
llvm::BumpPtrAllocator Alloc;
llvm::StringSaver Saver(Alloc);
// Ensure that we use the Windows command line parsing on Windows as we need
// to ensure that we properly handle paths.
if (llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows())
llvm::cl::TokenizeWindowsCommandLine(CommandString, Saver, Args);
else
llvm::cl::TokenizeGNUCommandLine(CommandString, Saver, Args);
if (Invocation.parseArgs(Args, Instance->getDiags(),
nullptr, WorkingDirectory, "/tmp/foo")) {
return std::make_error_code(std::errc::invalid_argument);
}
// Setup the instance
std::string InstanceSetupError;
if (Instance->setup(Invocation, InstanceSetupError)) {
return std::make_error_code(std::errc::not_supported);
}
Invocation.getFrontendOptions().LLVMArgs.clear();
// Setup the caching service after the instance finishes setup.
if (ScanningService->setupCachingDependencyScanningService(*Instance))
return std::make_error_code(std::errc::invalid_argument);
(void)Instance->getMainModule();
return ScanQueryInstance{std::move(Instance),
scannerDiagnosticsCollector};
}
} // namespace dependencies
} // namespace swift
|