-
Notifications
You must be signed in to change notification settings - Fork 10.7k
Expand file tree
/
Copy pathFrontend.cpp
More file actions
824 lines (712 loc) · 29.6 KB
/
Frontend.cpp
File metadata and controls
824 lines (712 loc) · 29.6 KB
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//===--- Frontend.cpp - frontend utility methods --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 contains utility methods for parsing and performing semantic
// on modules.
//
//===----------------------------------------------------------------------===//
#include "swift/Frontend/Frontend.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Module.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Parse/DelayedParsingCallbacks.h"
#include "swift/Parse/Lexer.h"
#include "swift/SIL/SILModule.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace swift;
std::string CompilerInvocation::getPCHHash() const {
using llvm::hash_code;
using llvm::hash_value;
using llvm::hash_combine;
auto Code = hash_value(LangOpts.getPCHHashComponents());
Code = hash_combine(Code, FrontendOpts.getPCHHashComponents());
Code = hash_combine(Code, ClangImporterOpts.getPCHHashComponents());
Code = hash_combine(Code, SearchPathOpts.getPCHHashComponents());
Code = hash_combine(Code, DiagnosticOpts.getPCHHashComponents());
Code = hash_combine(Code, SILOpts.getPCHHashComponents());
Code = hash_combine(Code, IRGenOpts.getPCHHashComponents());
return llvm::APInt(64, Code).toString(36, /*Signed=*/false);
}
void CompilerInstance::createSILModule() {
assert(MainModule && "main module not created yet");
// Assume WMO if a -primary-file option was not provided.
TheSILModule = SILModule::createEmptyModule(
getMainModule(), Invocation.getSILOptions(),
Invocation.getFrontendOptions().Inputs.isWholeModule());
}
void CompilerInstance::recordPrimaryInputBuffer(unsigned BufID) {
PrimaryBufferIDs.insert(BufID);
}
void CompilerInstance::recordPrimarySourceFile(SourceFile *SF) {
assert(MainModule && "main module not created yet");
PrimarySourceFiles.push_back(SF);
SF->setReferencedNameTracker(NameTracker);
if (SF->getBufferID().hasValue())
recordPrimaryInputBuffer(SF->getBufferID().getValue());
}
bool CompilerInstance::setup(const CompilerInvocation &Invok) {
Invocation = Invok;
setUpLLVMArguments();
setUpDiagnosticOptions();
// If we are asked to emit a module documentation file, configure lexing and
// parsing to remember comments.
if (!Invocation.getFrontendOptions().ModuleDocOutputPath.empty())
Invocation.getLangOptions().AttachCommentsToDecls = true;
// If we are doing index-while-building, configure lexing and parsing to
// remember comments.
if (!Invocation.getFrontendOptions().IndexStorePath.empty()) {
Invocation.getLangOptions().AttachCommentsToDecls = true;
}
Context.reset(new ASTContext(Invocation.getLangOptions(),
Invocation.getSearchPathOptions(), SourceMgr,
Diagnostics));
if (setUpModuleLoaders())
return true;
assert(Lexer::isIdentifier(Invocation.getModuleName()));
if (isInSILMode())
Invocation.getLangOptions().EnableAccessControl = false;
return setUpInputs();
}
void CompilerInstance::setUpLLVMArguments() {
// Honor -Xllvm.
if (!Invocation.getFrontendOptions().LLVMArgs.empty()) {
llvm::SmallVector<const char *, 4> Args;
Args.push_back("swift (LLVM option parsing)");
for (unsigned i = 0, e = Invocation.getFrontendOptions().LLVMArgs.size();
i != e; ++i)
Args.push_back(Invocation.getFrontendOptions().LLVMArgs[i].c_str());
Args.push_back(nullptr);
llvm::cl::ParseCommandLineOptions(Args.size()-1, Args.data());
}
}
void CompilerInstance::setUpDiagnosticOptions() {
if (Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {
Diagnostics.setShowDiagnosticsAfterFatalError();
}
if (Invocation.getDiagnosticOptions().SuppressWarnings) {
Diagnostics.setSuppressWarnings(true);
}
if (Invocation.getDiagnosticOptions().WarningsAsErrors) {
Diagnostics.setWarningsAsErrors(true);
}
}
bool CompilerInstance::setUpModuleLoaders() {
if (hasSourceImport()) {
bool immediate = FrontendOptions::isActionImmediate(
Invocation.getFrontendOptions().RequestedAction);
bool enableResilience = Invocation.getFrontendOptions().EnableResilience;
Context->addModuleLoader(SourceLoader::create(*Context,
!immediate,
enableResilience,
DepTracker));
}
{
auto SML = SerializedModuleLoader::create(*Context, DepTracker);
this->SML = SML.get();
Context->addModuleLoader(std::move(SML));
}
{
// Wire up the Clang importer. If the user has specified an SDK, use it.
// Otherwise, we just keep it around as our interface to Clang's ABI
// knowledge.
auto clangImporter =
ClangImporter::create(*Context, Invocation.getClangImporterOptions(),
Invocation.getPCHHash(), DepTracker);
if (!clangImporter) {
Diagnostics.diagnose(SourceLoc(), diag::error_clang_importer_create_fail);
return true;
}
Context->addModuleLoader(std::move(clangImporter), /*isClang*/ true);
}
return false;
}
Optional<unsigned> CompilerInstance::setUpCodeCompletionBuffer() {
Optional<unsigned> codeCompletionBufferID;
auto codeCompletePoint = Invocation.getCodeCompletionPoint();
if (codeCompletePoint.first) {
auto memBuf = codeCompletePoint.first;
// CompilerInvocation doesn't own the buffers, copy to a new buffer.
codeCompletionBufferID = SourceMgr.addMemBufferCopy(memBuf);
InputSourceCodeBufferIDs.push_back(*codeCompletionBufferID);
SourceMgr.setCodeCompletionPoint(*codeCompletionBufferID,
codeCompletePoint.second);
}
return codeCompletionBufferID;
}
bool CompilerInstance::setUpInputs() {
// Adds to InputSourceCodeBufferIDs, so may need to happen before the
// per-input setup.
const Optional<unsigned> codeCompletionBufferID = setUpCodeCompletionBuffer();
for (const InputFile &input :
Invocation.getFrontendOptions().Inputs.getAllInputs())
if (setUpForInput(input))
return true;
// Set the primary file to the code-completion point if one exists.
if (codeCompletionBufferID.hasValue() &&
!isPrimaryInput(*codeCompletionBufferID)) {
assert(PrimaryBufferIDs.empty() && "re-setting PrimaryBufferID");
recordPrimaryInputBuffer(*codeCompletionBufferID);
}
if (isInputSwift() && MainBufferID == NO_SUCH_BUFFER &&
InputSourceCodeBufferIDs.size() == 1)
MainBufferID = InputSourceCodeBufferIDs.front();
return false;
}
bool CompilerInstance::setUpForInput(const InputFile &input) {
bool failed = false;
Optional<unsigned> bufferID = getRecordedBufferID(input, failed);
if (failed)
return true;
if (!bufferID)
return false;
if (isInSILMode() ||
(input.buffer() == nullptr && isInputSwift() &&
llvm::sys::path::filename(input.file()) == "main.swift")) {
assert(MainBufferID == NO_SUCH_BUFFER && "re-setting MainBufferID");
MainBufferID = *bufferID;
}
if (input.isPrimary()) {
assert(PrimaryBufferIDs.empty() && "re-setting PrimaryBufferID");
recordPrimaryInputBuffer(*bufferID);
}
return false;
}
Optional<unsigned> CompilerInstance::getRecordedBufferID(const InputFile &input,
bool &failed) {
if (!input.buffer()) {
if (Optional<unsigned> existingBufferID =
SourceMgr.getIDForBufferIdentifier(input.file())) {
return existingBufferID;
}
}
std::pair<std::unique_ptr<llvm::MemoryBuffer>,
std::unique_ptr<llvm::MemoryBuffer>>
buffers = getInputBufferAndModuleDocBufferIfPresent(input);
if (!buffers.first) {
failed = true;
return None;
}
// FIXME: The fact that this test happens twice, for some cases,
// suggests that setupInputs could use another round of refactoring.
if (serialization::isSerializedAST(buffers.first->getBuffer())) {
PartialModules.push_back(
{std::move(buffers.first), std::move(buffers.second)});
return None;
}
assert(buffers.second.get() == nullptr);
// Transfer ownership of the MemoryBuffer to the SourceMgr.
unsigned bufferID = SourceMgr.addNewSourceBuffer(std::move(buffers.first));
InputSourceCodeBufferIDs.push_back(bufferID);
return bufferID;
}
std::pair<std::unique_ptr<llvm::MemoryBuffer>,
std::unique_ptr<llvm::MemoryBuffer>>
CompilerInstance::getInputBufferAndModuleDocBufferIfPresent(
const InputFile &input) {
if (auto b = input.buffer()) {
return std::make_pair(llvm::MemoryBuffer::getMemBufferCopy(
b->getBuffer(), b->getBufferIdentifier()),
nullptr);
}
// FIXME: Working with filenames is fragile, maybe use the real path
// or have some kind of FileManager.
using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
FileOrError inputFileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(input.file());
if (!inputFileOrErr) {
Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file, input.file(),
inputFileOrErr.getError().message());
return std::make_pair(nullptr, nullptr);
}
if (!serialization::isSerializedAST((*inputFileOrErr)->getBuffer()))
return std::make_pair(std::move(*inputFileOrErr), nullptr);
if (Optional<std::unique_ptr<llvm::MemoryBuffer>> moduleDocBuffer =
openModuleDoc(input)) {
return std::make_pair(std::move(*inputFileOrErr),
std::move(*moduleDocBuffer));
}
return std::make_pair(nullptr, nullptr);
}
Optional<std::unique_ptr<llvm::MemoryBuffer>>
CompilerInstance::openModuleDoc(const InputFile &input) {
llvm::SmallString<128> moduleDocFilePath(input.file());
llvm::sys::path::replace_extension(moduleDocFilePath,
SERIALIZED_MODULE_DOC_EXTENSION);
using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
FileOrError moduleDocFileOrErr =
llvm::MemoryBuffer::getFileOrSTDIN(moduleDocFilePath);
if (moduleDocFileOrErr)
return std::move(*moduleDocFileOrErr);
if (moduleDocFileOrErr.getError() == std::errc::no_such_file_or_directory)
return std::unique_ptr<llvm::MemoryBuffer>();
Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file,
moduleDocFilePath,
moduleDocFileOrErr.getError().message());
return None;
}
ModuleDecl *CompilerInstance::getMainModule() {
if (!MainModule) {
Identifier ID = Context->getIdentifier(Invocation.getModuleName());
MainModule = ModuleDecl::create(ID, *Context);
if (Invocation.getFrontendOptions().EnableTesting)
MainModule->setTestingEnabled();
if (Invocation.getFrontendOptions().EnableResilience)
MainModule->setResilienceStrategy(ResilienceStrategy::Resilient);
}
return MainModule;
}
static void addAdditionalInitialImportsTo(
SourceFile *SF, const CompilerInstance::ImplicitImports &implicitImports) {
using ImportPair =
std::pair<ModuleDecl::ImportedModule, SourceFile::ImportOptions>;
SmallVector<ImportPair, 4> additionalImports;
if (implicitImports.objCModuleUnderlyingMixedFramework)
additionalImports.push_back(
{{/*accessPath=*/{},
implicitImports.objCModuleUnderlyingMixedFramework},
SourceFile::ImportFlags::Exported});
if (implicitImports.headerModule)
additionalImports.push_back(
{{/*accessPath=*/{}, implicitImports.headerModule},
SourceFile::ImportFlags::Exported});
if (!implicitImports.modules.empty()) {
for (auto &importModule : implicitImports.modules) {
additionalImports.push_back({{/*accessPath=*/{}, importModule}, {}});
}
}
SF->addImports(additionalImports);
}
static bool shouldImportSwiftOnoneModuleIfNoneOrImplicitOptimization(
FrontendOptions::ActionType RequestedAction) {
return RequestedAction == FrontendOptions::ActionType::EmitObject ||
RequestedAction == FrontendOptions::ActionType::Immediate ||
RequestedAction == FrontendOptions::ActionType::EmitSIL;
}
/// Implicitly import the SwiftOnoneSupport module in non-optimized
/// builds. This allows for use of popular specialized functions
/// from the standard library, which makes the non-optimized builds
/// execute much faster.
static bool
shouldImplicityImportSwiftOnoneSupportModule(CompilerInvocation &Invocation) {
if (Invocation.getImplicitModuleImportKind() !=
SourceFile::ImplicitModuleImportKind::Stdlib)
return false;
if (Invocation.getSILOptions().shouldOptimize())
return false;
if (shouldImportSwiftOnoneModuleIfNoneOrImplicitOptimization(
Invocation.getFrontendOptions().RequestedAction)) {
return true;
}
return Invocation.getFrontendOptions().isCreatingSIL();
}
void CompilerInstance::performSema() {
SharedTimer timer("performSema");
Context->LoadedModules[MainModule->getName()] = getMainModule();
if (Invocation.getInputKind() == InputFileKind::IFK_SIL) {
assert(!InputSourceCodeBufferIDs.empty());
assert(InputSourceCodeBufferIDs.size() == 1);
assert(MainBufferID != NO_SUCH_BUFFER);
createSILModule();
}
if (Invocation.getImplicitModuleImportKind() ==
SourceFile::ImplicitModuleImportKind::Stdlib) {
if (!loadStdlib())
return;
}
if (shouldImplicityImportSwiftOnoneSupportModule(Invocation)) {
Invocation.getFrontendOptions().ImplicitImportModuleNames.push_back(
SWIFT_ONONE_SUPPORT);
}
const ImplicitImports implicitImports(*this);
if (Invocation.getInputKind() == InputFileKind::IFK_Swift_REPL) {
createREPLFile(implicitImports);
return;
}
// Make sure the main file is the first file in the module, so do this now.
if (MainBufferID != NO_SUCH_BUFFER)
addMainFileToModule(implicitImports);
parseAndCheckTypes(implicitImports);
}
CompilerInstance::ImplicitImports::ImplicitImports(CompilerInstance &compiler) {
kind = compiler.Invocation.getImplicitModuleImportKind();
objCModuleUnderlyingMixedFramework =
compiler.Invocation.getFrontendOptions().ImportUnderlyingModule
? compiler.importUnderlyingModule()
: nullptr;
compiler.getImplicitlyImportedModules(modules);
headerModule = compiler.importBridgingHeader();
}
bool CompilerInstance::loadStdlib() {
SharedTimer timer("performSema-loadStdlib");
ModuleDecl *M = Context->getStdlibModule(true);
if (!M) {
Diagnostics.diagnose(SourceLoc(), diag::error_stdlib_not_found,
Invocation.getTargetTriple());
return false;
}
// If we failed to load, we should have already diagnosed
if (M->failedToLoad()) {
assert(Diagnostics.hadAnyError() &&
"Module failed to load but nothing was diagnosed?");
return false;
}
return true;
}
ModuleDecl *CompilerInstance::importUnderlyingModule() {
SharedTimer timer("performSema-importUnderlyingModule");
ModuleDecl *objCModuleUnderlyingMixedFramework =
static_cast<ClangImporter *>(Context->getClangModuleLoader())
->loadModule(SourceLoc(),
std::make_pair(MainModule->getName(), SourceLoc()));
if (objCModuleUnderlyingMixedFramework)
return objCModuleUnderlyingMixedFramework;
Diagnostics.diagnose(SourceLoc(), diag::error_underlying_module_not_found,
MainModule->getName());
return nullptr;
}
ModuleDecl *CompilerInstance::importBridgingHeader() {
SharedTimer timer("performSema-importBridgingHeader");
const StringRef implicitHeaderPath =
Invocation.getFrontendOptions().ImplicitObjCHeaderPath;
auto clangImporter =
static_cast<ClangImporter *>(Context->getClangModuleLoader());
if (implicitHeaderPath.empty() ||
clangImporter->importBridgingHeader(implicitHeaderPath, MainModule))
return nullptr;
ModuleDecl *importedHeaderModule = clangImporter->getImportedHeaderModule();
assert(importedHeaderModule);
return importedHeaderModule;
}
void CompilerInstance::getImplicitlyImportedModules(
SmallVectorImpl<ModuleDecl *> &importModules) {
SharedTimer timer("performSema-getImplicitlyImportedModules");
for (auto &ImplicitImportModuleName :
Invocation.getFrontendOptions().ImplicitImportModuleNames) {
if (Lexer::isIdentifier(ImplicitImportModuleName)) {
auto moduleID = Context->getIdentifier(ImplicitImportModuleName);
ModuleDecl *importModule =
Context->getModule(std::make_pair(moduleID, SourceLoc()));
if (importModule) {
importModules.push_back(importModule);
} else {
Diagnostics.diagnose(SourceLoc(), diag::sema_no_import,
ImplicitImportModuleName);
if (Invocation.getSearchPathOptions().SDKPath.empty() &&
llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) {
Diagnostics.diagnose(SourceLoc(), diag::sema_no_import_no_sdk);
Diagnostics.diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun);
}
}
} else {
Diagnostics.diagnose(SourceLoc(), diag::error_bad_module_name,
ImplicitImportModuleName, false);
}
}
}
void CompilerInstance::createREPLFile(const ImplicitImports &implicitImports) {
auto *SingleInputFile = createSourceFileForMainModule(
Invocation.getSourceFileKind(), implicitImports.kind, None);
addAdditionalInitialImportsTo(SingleInputFile, implicitImports);
}
std::unique_ptr<DelayedParsingCallbacks>
CompilerInstance::computeDelayedParsingCallback(bool isPrimary) {
if (Invocation.isCodeCompletion())
return llvm::make_unique<CodeCompleteDelayedCallbacks>(
SourceMgr.getCodeCompletionLoc());
if (!isPrimary)
return llvm::make_unique<AlwaysDelayedCallbacks>();
return nullptr;
}
void CompilerInstance::addMainFileToModule(
const ImplicitImports &implicitImports) {
const InputFileKind Kind = Invocation.getInputKind();
assert(Kind == InputFileKind::IFK_Swift || Kind == InputFileKind::IFK_SIL);
if (Kind == InputFileKind::IFK_Swift)
SourceMgr.setHashbangBufferID(MainBufferID);
auto *MainFile = createSourceFileForMainModule(
Invocation.getSourceFileKind(), implicitImports.kind, MainBufferID);
addAdditionalInitialImportsTo(MainFile, implicitImports);
}
void CompilerInstance::parseAndCheckTypes(
const ImplicitImports &implicitImports) {
SharedTimer timer("performSema-parseAndCheckTypes");
// Delayed parsing callback for the primary file, or all files
// in non-WMO mode.
std::unique_ptr<DelayedParsingCallbacks> PrimaryDelayedCB{
computeDelayedParsingCallback(true)};
// Delayed parsing callback for non-primary files. Not used in
// WMO mode.
std::unique_ptr<DelayedParsingCallbacks> SecondaryDelayedCB{
computeDelayedParsingCallback(false)};
PersistentParserState PersistentState;
bool hadLoadError = parsePartialModulesAndLibraryFiles(
implicitImports, PersistentState,
PrimaryDelayedCB.get(),
SecondaryDelayedCB.get());
if (Invocation.isCodeCompletion()) {
// When we are doing code completion, make sure to emit at least one
// diagnostic, so that ASTContext is marked as erroneous. In this case
// various parts of the compiler (for example, AST verifier) have less
// strict assumptions about the AST.
Diagnostics.diagnose(SourceLoc(), diag::error_doing_code_completion);
}
if (hadLoadError)
return;
OptionSet<TypeCheckingFlags> TypeCheckOptions = computeTypeCheckingOptions();
// Type-check main file after parsing all other files so that
// it can use declarations from other files.
// In addition, the main file has parsing and type-checking
// interwined.
if (MainBufferID != NO_SUCH_BUFFER) {
parseAndTypeCheckMainFile(PersistentState, PrimaryDelayedCB.get(),
TypeCheckOptions);
}
const auto &options = Invocation.getFrontendOptions();
forEachFileToTypeCheck([&](SourceFile &SF) {
performTypeChecking(SF, PersistentState.getTopLevelContext(),
TypeCheckOptions, /*curElem*/ 0,
options.WarnLongFunctionBodies,
options.WarnLongExpressionTypeChecking,
options.SolverExpressionTimeThreshold);
});
// Even if there were no source files, we should still record known
// protocols.
if (auto *stdlib = Context->getStdlibModule())
Context->recordKnownProtocols(stdlib);
if (Invocation.isCodeCompletion()) {
performDelayedParsing(MainModule, PersistentState,
Invocation.getCodeCompletionFactory());
}
finishTypeChecking(TypeCheckOptions);
}
void CompilerInstance::parseLibraryFile(
unsigned BufferID, const ImplicitImports &implicitImports,
PersistentParserState &PersistentState,
DelayedParsingCallbacks *PrimaryDelayedCB,
DelayedParsingCallbacks *SecondaryDelayedCB) {
SharedTimer timer("performSema-parseLibraryFile");
auto *NextInput = createSourceFileForMainModule(
SourceFileKind::Library, implicitImports.kind, BufferID);
addAdditionalInitialImportsTo(NextInput, implicitImports);
auto *DelayedCB = SecondaryDelayedCB;
if (isPrimaryInput(BufferID)) {
DelayedCB = PrimaryDelayedCB;
}
if (isWholeModuleCompilation())
DelayedCB = PrimaryDelayedCB;
auto &Diags = NextInput->getASTContext().Diags;
auto DidSuppressWarnings = Diags.getSuppressWarnings();
auto IsPrimary = isWholeModuleCompilation() || isPrimaryInput(BufferID);
Diags.setSuppressWarnings(DidSuppressWarnings || !IsPrimary);
bool Done;
do {
// Parser may stop at some erroneous constructions like #else, #endif
// or '}' in some cases, continue parsing until we are done
parseIntoSourceFile(*NextInput, BufferID, &Done, nullptr, &PersistentState,
DelayedCB);
} while (!Done);
Diags.setSuppressWarnings(DidSuppressWarnings);
performNameBinding(*NextInput);
}
OptionSet<TypeCheckingFlags> CompilerInstance::computeTypeCheckingOptions() {
OptionSet<TypeCheckingFlags> TypeCheckOptions;
if (isWholeModuleCompilation()) {
TypeCheckOptions |= TypeCheckingFlags::DelayWholeModuleChecking;
}
const auto &options = Invocation.getFrontendOptions();
if (options.DebugTimeFunctionBodies) {
TypeCheckOptions |= TypeCheckingFlags::DebugTimeFunctionBodies;
}
if (FrontendOptions::isActionImmediate(options.RequestedAction)) {
TypeCheckOptions |= TypeCheckingFlags::ForImmediateMode;
}
if (options.DebugTimeExpressionTypeChecking) {
TypeCheckOptions |= TypeCheckingFlags::DebugTimeExpressions;
}
return TypeCheckOptions;
}
bool CompilerInstance::parsePartialModulesAndLibraryFiles(
const ImplicitImports &implicitImports,
PersistentParserState &PersistentState,
DelayedParsingCallbacks *PrimaryDelayedCB,
DelayedParsingCallbacks *SecondaryDelayedCB) {
SharedTimer timer("performSema-parsePartialModulesAndLibraryFiles");
bool hadLoadError = false;
// Parse all the partial modules first.
for (auto &PM : PartialModules) {
assert(PM.ModuleBuffer);
if (!SML->loadAST(*MainModule, SourceLoc(), std::move(PM.ModuleBuffer),
std::move(PM.ModuleDocBuffer)))
hadLoadError = true;
}
// Then parse all the library files.
for (auto BufferID : InputSourceCodeBufferIDs) {
if (BufferID != MainBufferID) {
parseLibraryFile(BufferID, implicitImports, PersistentState,
PrimaryDelayedCB, SecondaryDelayedCB);
}
}
return hadLoadError;
}
void CompilerInstance::parseAndTypeCheckMainFile(
PersistentParserState &PersistentState,
DelayedParsingCallbacks *DelayedParseCB,
OptionSet<TypeCheckingFlags> TypeCheckOptions) {
SharedTimer timer(
"performSema-checkTypesWhileParsingMain-parseAndTypeCheckMainFile");
bool mainIsPrimary =
(isWholeModuleCompilation() || isPrimaryInput(MainBufferID));
SourceFile &MainFile =
MainModule->getMainSourceFile(Invocation.getSourceFileKind());
auto &Diags = MainFile.getASTContext().Diags;
auto DidSuppressWarnings = Diags.getSuppressWarnings();
Diags.setSuppressWarnings(DidSuppressWarnings || !mainIsPrimary);
SILParserState SILContext(TheSILModule.get());
unsigned CurTUElem = 0;
bool Done;
do {
// Pump the parser multiple times if necessary. It will return early
// after parsing any top level code in a main module, or in SIL mode when
// there are chunks of swift decls (e.g. imports and types) interspersed
// with 'sil' definitions.
parseIntoSourceFile(MainFile, MainFile.getBufferID().getValue(), &Done,
TheSILModule ? &SILContext : nullptr, &PersistentState,
DelayedParseCB);
if (mainIsPrimary) {
const auto &options = Invocation.getFrontendOptions();
performTypeChecking(MainFile, PersistentState.getTopLevelContext(),
TypeCheckOptions, CurTUElem,
options.WarnLongFunctionBodies,
options.WarnLongExpressionTypeChecking,
options.SolverExpressionTimeThreshold);
}
CurTUElem = MainFile.Decls.size();
} while (!Done);
Diags.setSuppressWarnings(DidSuppressWarnings);
if (mainIsPrimary && !Context->hadError() &&
Invocation.getFrontendOptions().PCMacro) {
performPCMacro(MainFile, PersistentState.getTopLevelContext());
}
// Playground transform knows to look out for PCMacro's changes and not
// to playground log them.
if (mainIsPrimary && !Context->hadError() &&
Invocation.getFrontendOptions().PlaygroundTransform)
performPlaygroundTransform(
MainFile, Invocation.getFrontendOptions().PlaygroundHighPerformance);
if (!mainIsPrimary) {
performNameBinding(MainFile);
}
}
static void
forEachSourceFileIn(ModuleDecl *module,
llvm::function_ref<void(SourceFile &)> fn) {
for (auto fileName : module->getFiles()) {
if (auto SF = dyn_cast<SourceFile>(fileName))
fn(*SF);
}
}
void CompilerInstance::forEachFileToTypeCheck(
llvm::function_ref<void(SourceFile &)> fn) {
if (isWholeModuleCompilation()) {
forEachSourceFileIn(MainModule, [&](SourceFile &SF) { fn(SF); });
} else {
for (auto *SF : PrimarySourceFiles) {
fn(*SF);
}
}
}
void CompilerInstance::finishTypeChecking(
OptionSet<TypeCheckingFlags> TypeCheckOptions) {
if (TypeCheckOptions & TypeCheckingFlags::DelayWholeModuleChecking) {
forEachSourceFileIn(MainModule, [&](SourceFile &SF) {
performWholeModuleTypeChecking(SF);
});
}
}
SourceFile *CompilerInstance::createSourceFileForMainModule(
SourceFileKind fileKind, SourceFile::ImplicitModuleImportKind importKind,
Optional<unsigned> bufferID) {
ModuleDecl *mainModule = getMainModule();
bool keepSyntaxInfo = Invocation.getLangOptions().KeepSyntaxInfoInSourceFile;
SourceFile *inputFile = new (*Context)
SourceFile(*mainModule, fileKind, bufferID, importKind, keepSyntaxInfo);
MainModule->addFile(*inputFile);
if (bufferID && isPrimaryInput(*bufferID)) {
recordPrimarySourceFile(inputFile);
}
return inputFile;
}
void CompilerInstance::performParseOnly(bool EvaluateConditionals) {
const InputFileKind Kind = Invocation.getInputKind();
ModuleDecl *const MainModule = getMainModule();
Context->LoadedModules[MainModule->getName()] = MainModule;
assert((Kind == InputFileKind::IFK_Swift ||
Kind == InputFileKind::IFK_Swift_Library) &&
"only supports parsing .swift files");
(void)Kind;
// Make sure the main file is the first file in the module but parse it last,
// to match the parsing logic used when performing Sema.
if (MainBufferID != NO_SUCH_BUFFER) {
assert(Kind == InputFileKind::IFK_Swift);
SourceMgr.setHashbangBufferID(MainBufferID);
createSourceFileForMainModule(Invocation.getSourceFileKind(),
SourceFile::ImplicitModuleImportKind::None,
MainBufferID);
}
PersistentParserState PersistentState;
PersistentState.PerformConditionEvaluation = EvaluateConditionals;
// Parse all the library files.
for (auto BufferID : InputSourceCodeBufferIDs) {
if (BufferID == MainBufferID)
continue;
SourceFile *NextInput = createSourceFileForMainModule(
SourceFileKind::Library, SourceFile::ImplicitModuleImportKind::None,
BufferID);
bool Done;
do {
// Parser may stop at some erroneous constructions like #else, #endif
// or '}' in some cases, continue parsing until we are done
parseIntoSourceFile(*NextInput, BufferID, &Done, nullptr,
&PersistentState, nullptr);
} while (!Done);
}
// Now parse the main file.
if (MainBufferID != NO_SUCH_BUFFER) {
SourceFile &MainFile =
MainModule->getMainSourceFile(Invocation.getSourceFileKind());
bool Done;
do {
parseIntoSourceFile(MainFile, MainFile.getBufferID().getValue(), &Done,
nullptr, &PersistentState, nullptr);
} while (!Done);
}
assert(Context->LoadedModules.size() == 1 &&
"Loaded a module during parse-only");
}
void CompilerInstance::freeContextAndSIL() {
Context.reset();
TheSILModule.reset();
MainModule = nullptr;
SML = nullptr;
PrimaryBufferIDs.clear();
PrimarySourceFiles.clear();
}