forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwiftEditorInterfaceGen.cpp
767 lines (655 loc) · 25.2 KB
/
SwiftEditorInterfaceGen.cpp
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
//===--- SwiftEditorIntefaceGen.cpp ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwiftLangSupport.h"
#include "SwiftInterfaceGenContext.h"
#include "SwiftASTManager.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTWalker.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/ModuleInterfacePrinting.h"
#include "swift/IDE/SyntaxModel.h"
#include "swift/IDE/Utils.h"
#include "swift/Strings.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/ConvertUTF.h"
using namespace SourceKit;
using namespace swift;
using namespace ide;
class SwiftInterfaceGenContext::Implementation {
public:
struct TextRange {
unsigned Offset;
unsigned Length;
};
struct TextReference {
/// The declaration from the module.
const ValueDecl *Dcl = nullptr;
const ModuleEntity Mod;
TextRange Range;
TextReference(const ValueDecl *D, unsigned Offset, unsigned Length)
: Dcl(D), Mod(), Range{Offset, Length} {}
TextReference(const ModuleEntity Mod, unsigned Offset, unsigned Length)
: Mod(Mod), Range{Offset, Length} {}
};
struct TextDecl {
/// The declaration from the module.
const Decl *Dcl = nullptr;
/// The range in the interface source.
TextRange Range;
TextDecl(const Decl *D, TextRange Range)
: Dcl(D), Range(Range) {}
TextDecl() = default;
};
struct SourceTextInfo {
std::string Text;
std::vector<TextReference> References;
std::vector<TextDecl> Decls;
llvm::StringMap<TextDecl> USRMap;
};
// Hold an AstUnit so that the Decl* we have are always valid.
ASTUnitRef AstUnit;
std::string DocumentName;
bool IsModule = false;
std::string ModuleOrHeaderName;
CompilerInvocation Invocation;
PrintingDiagnosticConsumer DiagConsumer;
CompilerInstance Instance;
Module *Mod = nullptr;
SourceTextInfo Info;
// This is the non-typechecked AST for the generated interface source.
CompilerInstance TextCI;
};
typedef SwiftInterfaceGenContext::Implementation::TextRange TextRange;
typedef SwiftInterfaceGenContext::Implementation::TextReference TextReference;
typedef SwiftInterfaceGenContext::Implementation::TextDecl TextDecl;
typedef SwiftInterfaceGenContext::Implementation::SourceTextInfo SourceTextInfo;
static Module *getModuleByFullName(ASTContext &Ctx, StringRef ModuleName) {
SmallVector<std::pair<Identifier, SourceLoc>, 4>
AccessPath;
while (!ModuleName.empty()) {
StringRef SubModuleName;
std::tie(SubModuleName, ModuleName) = ModuleName.split('.');
AccessPath.push_back({ Ctx.getIdentifier(SubModuleName), SourceLoc() });
}
return Ctx.getModule(AccessPath);
}
static Module *getModuleByFullName(ASTContext &Ctx, Identifier ModuleName) {
return Ctx.getModule(std::make_pair(ModuleName, SourceLoc()));
}
namespace {
class AnnotatingPrinter : public StreamPrinter {
SourceTextInfo &Info;
struct DeclUSR {
const Decl *Dcl = nullptr;
std::string USR;
DeclUSR(const Decl *D, StringRef USR) : Dcl(D), USR(USR) {}
};
std::vector<DeclUSR> DeclUSRs;
public:
AnnotatingPrinter(SourceTextInfo &Info, llvm::raw_ostream &OS)
: StreamPrinter(OS), Info(Info) { }
~AnnotatingPrinter() {
assert(DeclUSRs.empty() && "unmatched printDeclLoc call ?");
}
void printDeclLoc(const Decl *D) override {
unsigned LocOffset = OS.tell();
TextDecl Entry(D, TextRange{LocOffset, 0});
Info.Decls.emplace_back(Entry);
if (auto VD = dyn_cast<ValueDecl>(D)) {
// Only record non-local USRs.
if (D->getDeclContext()->getLocalContext())
return;
llvm::SmallString<64> Buf;
llvm::raw_svector_ostream OS(Buf);
if (!SwiftLangSupport::printUSR(VD, OS)) {
StringRef USR = OS.str();
Info.USRMap[USR] = Entry;
DeclUSRs.emplace_back(VD, USR);
}
}
}
void printDeclNameEndLoc(const Decl *D) override {
unsigned Offset = OS.tell();
if (!Info.Decls.empty() && Info.Decls.back().Dcl == D) {
TextDecl &Entry = Info.Decls.back();
Entry.Range.Length = Offset - Entry.Range.Offset;
}
if (!DeclUSRs.empty() && DeclUSRs.back().Dcl == D) {
TextDecl &Entry = Info.USRMap[DeclUSRs.back().USR];
assert(Entry.Dcl == D);
Entry.Range.Length = Offset - Entry.Range.Offset;
DeclUSRs.pop_back();
}
}
void printTypeRef(const TypeDecl *TD, Identifier Name) override {
unsigned StartOffset = OS.tell();
Info.References.emplace_back(TD, StartOffset, Name.str().size());
StreamPrinter::printTypeRef(TD, Name);
}
void printModuleRef(ModuleEntity Mod, Identifier Name) override {
unsigned StartOffset = OS.tell();
Info.References.emplace_back(Mod, StartOffset, Name.str().size());
StreamPrinter::printModuleRef(Mod, Name);
}
};
class DocSyntaxWalker : public SyntaxModelWalker {
SourceManager &SM;
unsigned BufferID;
EditorConsumer &Consumer;
public:
DocSyntaxWalker(SourceManager &SM, unsigned BufferID,
EditorConsumer &Consumer)
: SM(SM), BufferID(BufferID), Consumer(Consumer) {}
bool walkToNodePre(SyntaxNode Node) override {
unsigned Offset = SM.getLocOffsetInBuffer(Node.Range.getStart(), BufferID);
unsigned Length = Node.Range.getByteLength();
UIdent UID = SwiftLangSupport::getUIDForSyntaxNodeKind(Node.Kind);
if (UID.isValid())
Consumer.handleSyntaxMap(Offset, Length, UID);
return true;
}
};
}
static bool makeParserAST(CompilerInstance &CI, StringRef Text) {
CompilerInvocation Invocation;
Invocation.setModuleName("main");
Invocation.setInputKind(InputFileKind::IFK_Swift);
std::unique_ptr<llvm::MemoryBuffer> Buf;
Buf = llvm::MemoryBuffer::getMemBuffer(Text, "<module-interface>");
Invocation.addInputBuffer(Buf.get());
if (CI.setup(Invocation))
return true;
CI.performParseOnly();
return false;
}
static void reportSyntacticAnnotations(CompilerInstance &CI,
EditorConsumer &Consumer) {
auto SF = dyn_cast<SourceFile>(CI.getMainModule()->getFiles()[0]);
SyntaxModelContext SyntaxContext(*SF);
DocSyntaxWalker SyntaxWalker(CI.getSourceMgr(), *SF->getBufferID(),
Consumer);
SyntaxContext.walk(SyntaxWalker);
}
static void reportDocumentStructure(CompilerInstance &CI,
EditorConsumer &Consumer) {
auto SF = dyn_cast<SourceFile>(CI.getMainModule()->getFiles()[0]);
SwiftEditorDocument::reportDocumentStructure(*SF, Consumer);
}
static void reportSemanticAnnotations(const SourceTextInfo &IFaceInfo,
EditorConsumer &Consumer) {
for (auto &Ref : IFaceInfo.References) {
UIdent Kind;
bool IsSystem;
if (Ref.Mod) {
Kind = SwiftLangSupport::getUIDForModuleRef();
IsSystem = Ref.Mod.isSystemModule();
} else if (Ref.Dcl) {
Kind = SwiftLangSupport::getUIDForDecl(Ref.Dcl, /*IsRef=*/true);
IsSystem = Ref.Dcl->getModuleContext()->isSystemModule();
}
if (Kind.isInvalid())
continue;
unsigned Offset = Ref.Range.Offset;
unsigned Length = Ref.Range.Length;
Consumer.handleSemanticAnnotation(Offset, Length, Kind, IsSystem);
}
}
static bool getModuleInterfaceInfo(ASTContext &Ctx,
StringRef ModuleName,
SwiftInterfaceGenContext::Implementation &Impl,
std::string &ErrMsg) {
Module *&Mod = Impl.Mod;
SourceTextInfo &Info = Impl.Info;
if (ModuleName.empty()) {
ErrMsg = "Module name is empty";
return true;
}
// Get the (sub)module to generate.
Mod = getModuleByFullName(Ctx, ModuleName);
if (!Mod) {
ErrMsg = "Could not load module: ";
ErrMsg += ModuleName;
return true;
}
std::vector<StringRef> SplitModuleName;
while (!ModuleName.empty()) {
StringRef SubModuleName;
std::tie(SubModuleName, ModuleName) = ModuleName.split('.');
SplitModuleName.push_back(SubModuleName);
}
assert(!SplitModuleName.empty());
// FIXME: If this is a submodule, get its top-level module, which will be the
// DeclContext for all of its Decls since we don't have first-class submodules.
if (SplitModuleName.size() > 1) {
Mod = getModuleByFullName(Ctx, SplitModuleName[0]);
if (!Mod) {
ErrMsg = "Could not load module: ";
ErrMsg += ModuleName;
return true;
}
}
PrintOptions Options = PrintOptions::printInterface();
ModuleTraversalOptions TraversalOptions = None; // Don't print submodules.
SmallString<128> Text;
llvm::raw_svector_ostream OS(Text);
AnnotatingPrinter Printer(Info, OS);
printSubmoduleInterface(Mod, SplitModuleName,
TraversalOptions,
Printer, Options);
Info.Text = OS.str();
return false;
}
static bool getHeaderInterfaceInfo(ASTContext &Ctx,
StringRef HeaderName,
SourceTextInfo &Info,
std::string &ErrMsg) {
if (HeaderName.empty()) {
ErrMsg = "Header name is empty";
return true;
}
PrintOptions Options = PrintOptions::printInterface();
SmallString<128> Text;
llvm::raw_svector_ostream OS(Text);
AnnotatingPrinter Printer(Info, OS);
printHeaderInterface(HeaderName, Ctx, Printer, Options);
Info.Text = OS.str();
return false;
}
SwiftInterfaceGenContextRef
SwiftInterfaceGenContext::createForSwiftSource(StringRef DocumentName,
StringRef SourceFileName,
ASTUnitRef AstUnit,
std::string &ErrMsg) {
SwiftInterfaceGenContextRef IFaceGenCtx{ new SwiftInterfaceGenContext() };
IFaceGenCtx->Impl.DocumentName = DocumentName;
IFaceGenCtx->Impl.IsModule = true;
IFaceGenCtx->Impl.ModuleOrHeaderName = SourceFileName;
IFaceGenCtx->Impl.AstUnit = AstUnit;
PrintOptions Options = PrintOptions::printSwiftFileInterface();
SmallString<128> Text;
llvm::raw_svector_ostream OS(Text);
AnnotatingPrinter Printer(IFaceGenCtx->Impl.Info, OS);
printSwiftSourceInterface(AstUnit->getPrimarySourceFile(), Printer, Options);
IFaceGenCtx->Impl.Info.Text = OS.str();
if (makeParserAST(IFaceGenCtx->Impl.TextCI, IFaceGenCtx->Impl.Info.Text)) {
ErrMsg = "Error during syntactic parsing";
return nullptr;
}
return IFaceGenCtx;
}
SwiftInterfaceGenContextRef
SwiftInterfaceGenContext::create(StringRef DocumentName,
bool IsModule,
StringRef ModuleOrHeaderName,
CompilerInvocation Invocation,
std::string &ErrMsg) {
SwiftInterfaceGenContextRef IFaceGenCtx{ new SwiftInterfaceGenContext() };
IFaceGenCtx->Impl.DocumentName = DocumentName;
IFaceGenCtx->Impl.IsModule = IsModule;
IFaceGenCtx->Impl.ModuleOrHeaderName = ModuleOrHeaderName;
IFaceGenCtx->Impl.Invocation = Invocation;
CompilerInstance &CI = IFaceGenCtx->Impl.Instance;
// Display diagnostics to stderr.
CI.addDiagnosticConsumer(&IFaceGenCtx->Impl.DiagConsumer);
Invocation.clearInputs();
if (CI.setup(Invocation)) {
ErrMsg = "Error during invocation setup";
return nullptr;
}
ASTContext &Ctx = CI.getASTContext();
CloseClangModuleFiles scopedCloseFiles(*Ctx.getClangModuleLoader());
// Load standard library so that Clang importer can use it.
auto *Stdlib = getModuleByFullName(Ctx, Ctx.StdlibModuleName);
if (!Stdlib) {
ErrMsg = "Could not load the stdlib module";
return nullptr;
}
if (IsModule) {
if (getModuleInterfaceInfo(Ctx, ModuleOrHeaderName, IFaceGenCtx->Impl,
ErrMsg))
return nullptr;
} else {
auto &FEOpts = Invocation.getFrontendOptions();
if (FEOpts.ImplicitObjCHeaderPath.empty()) {
ErrMsg = "Implicit ObjC header path is empty";
return nullptr;
}
auto &Importer = static_cast<ClangImporter &>(*Ctx.getClangModuleLoader());
Importer.importBridgingHeader(FEOpts.ImplicitObjCHeaderPath,
CI.getMainModule(),
/*diagLoc=*/{},
/*trackParsedSymbols=*/true);
if (getHeaderInterfaceInfo(Ctx, ModuleOrHeaderName,
IFaceGenCtx->Impl.Info, ErrMsg))
return nullptr;
}
if (makeParserAST(IFaceGenCtx->Impl.TextCI, IFaceGenCtx->Impl.Info.Text)) {
ErrMsg = "Error during syntactic parsing";
return nullptr;
}
return IFaceGenCtx;
}
SwiftInterfaceGenContext::SwiftInterfaceGenContext()
: Impl(*new Implementation) {
}
SwiftInterfaceGenContext::~SwiftInterfaceGenContext() {
delete &Impl;
}
StringRef SwiftInterfaceGenContext::getDocumentName() const {
return Impl.DocumentName;
}
StringRef SwiftInterfaceGenContext::getModuleOrHeaderName() const {
return Impl.ModuleOrHeaderName;
}
bool SwiftInterfaceGenContext::isModule() const {
return Impl.IsModule;
}
bool SwiftInterfaceGenContext::matches(StringRef ModuleName,
const swift::CompilerInvocation &Invok) {
if (!Impl.IsModule)
return false;
if (ModuleName != Impl.ModuleOrHeaderName)
return false;
if (Invok.getTargetTriple() != Impl.Invocation.getTargetTriple())
return false;
if (ModuleName == STDLIB_NAME)
return true;
if (Invok.getSDKPath() != Impl.Invocation.getSDKPath())
return false;
if (Impl.Mod->isSystemModule())
return true;
const SearchPathOptions &SPOpts = Invok.getSearchPathOptions();
const SearchPathOptions &ImplSPOpts = Impl.Invocation.getSearchPathOptions();
if (SPOpts.ImportSearchPaths != ImplSPOpts.ImportSearchPaths)
return false;
if (SPOpts.FrameworkSearchPaths != ImplSPOpts.FrameworkSearchPaths)
return false;
if (Invok.getClangImporterOptions().ExtraArgs !=
Impl.Invocation.getClangImporterOptions().ExtraArgs)
return false;
return true;
}
void SwiftInterfaceGenContext::reportEditorInfo(EditorConsumer &Consumer) const {
Consumer.handleSourceText(Impl.Info.Text);
reportSyntacticAnnotations(Impl.TextCI, Consumer);
reportDocumentStructure(Impl.TextCI, Consumer);
reportSemanticAnnotations(Impl.Info, Consumer);
Consumer.finished();
}
SwiftInterfaceGenContext::ResolvedEntity
SwiftInterfaceGenContext::resolveEntityForOffset(unsigned Offset) const {
// Search among the references.
{
auto Pos = std::upper_bound(Impl.Info.References.begin(),
Impl.Info.References.end(),
Offset,
[&](unsigned Offset, const TextReference &RHS) -> bool {
return Offset < RHS.Range.Offset+RHS.Range.Length;
});
if (Pos != Impl.Info.References.end() && Pos->Range.Offset <= Offset) {
if (Pos->Mod)
return ResolvedEntity(Pos->Mod, true);
else
return ResolvedEntity(Pos->Dcl, true);
}
}
SourceManager &SM = Impl.TextCI.getSourceMgr();
auto SF = dyn_cast<SourceFile>(Impl.TextCI.getMainModule()->getFiles()[0]);
unsigned BufferID = *SF->getBufferID();
SourceLoc Loc = Lexer::getLocForStartOfToken(SM, BufferID, Offset);
Offset = SM.getLocOffsetInBuffer(Loc, BufferID);
// Search among the declarations.
{
auto Pos = std::lower_bound(Impl.Info.Decls.begin(),
Impl.Info.Decls.end(),
Offset,
[&](const TextDecl &LHS, unsigned Offset) -> bool {
return LHS.Range.Offset < Offset;
});
if (Pos != Impl.Info.Decls.end() && Pos->Range.Offset == Offset)
return ResolvedEntity(dyn_cast<ValueDecl>(Pos->Dcl), false);
}
return ResolvedEntity();
}
llvm::Optional<std::pair<unsigned, unsigned>>
SwiftInterfaceGenContext::findUSRRange(StringRef USR) const {
auto Pos = Impl.Info.USRMap.find(USR);
if (Pos == Impl.Info.USRMap.end())
return None;
return std::make_pair(Pos->getValue().Range.Offset,
Pos->getValue().Range.Length);
}
void SwiftInterfaceGenContext::applyTo(
swift::CompilerInvocation &CompInvok) const {
CompInvok = Impl.Invocation;
}
SwiftInterfaceGenContextRef SwiftInterfaceGenMap::get(StringRef Name) const {
llvm::sys::ScopedLock L(Mtx);
auto It = IFaceGens.find(Name);
if (It == IFaceGens.end())
return nullptr;
return It->second;
}
void SwiftInterfaceGenMap::set(StringRef Name,
SwiftInterfaceGenContextRef IFaceGen) {
llvm::sys::ScopedLock L(Mtx);
IFaceGens[Name] = IFaceGen;
}
bool SwiftInterfaceGenMap::remove(StringRef Name) {
llvm::sys::ScopedLock L(Mtx);
return IFaceGens.erase(Name);
}
SwiftInterfaceGenContextRef
SwiftInterfaceGenMap::find(StringRef ModuleName,
const CompilerInvocation &Invok) {
llvm::sys::ScopedLock L(Mtx);
for (auto &Entry : IFaceGens) {
if (Entry.getValue()->matches(ModuleName, Invok))
return Entry.getValue();
}
return nullptr;
}
//============================================================================//
// EditorOpenInterface
//============================================================================//
void SwiftLangSupport::editorOpenInterface(EditorConsumer &Consumer,
StringRef Name,
StringRef ModuleName,
ArrayRef<const char *> Args) {
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
CompilerInvocation Invocation;
std::string Error;
if (getASTManager().initCompilerInvocation(Invocation, Args, CI.getDiags(),
StringRef(), Error)) {
Consumer.handleRequestError(Error.c_str());
return;
}
trace::TracedOperation TracedOp;
if (trace::enabled()) {
trace::SwiftInvocation SwiftArgs;
SwiftArgs.Args.Args.assign(Args.begin(), Args.end());
// NOTE: do not use primary file
// NOTE: do not use files
TracedOp.start(trace::OperationKind::OpenInterface, SwiftArgs,
{std::make_pair("Name", Name),
std::make_pair("ModuleName", ModuleName)});
}
Invocation.getClangImporterOptions().ImportForwardDeclarations = true;
std::string ErrMsg;
auto IFaceGenRef = SwiftInterfaceGenContext::create(Name,
/*IsModule=*/true,
ModuleName,
Invocation,
ErrMsg);
if (!IFaceGenRef) {
Consumer.handleRequestError(ErrMsg.c_str());
return;
}
IFaceGenContexts.set(Name, IFaceGenRef);
IFaceGenRef->reportEditorInfo(Consumer);
}
class PrimaryFileInterfaceConsumer : public SwiftASTConsumer {
std::string Name;
std::string SourceFileName;
SwiftInterfaceGenMap &Contexts;
std::shared_ptr<EditorConsumer> Consumer;
public:
PrimaryFileInterfaceConsumer(StringRef Name, StringRef SourceFileName,
SwiftInterfaceGenMap &Contexts,
std::shared_ptr<EditorConsumer> Consumer) :
Name(Name), SourceFileName(SourceFileName), Contexts(Contexts),
Consumer(Consumer) {}
void failed(StringRef Error) override {
Consumer->handleRequestError(Error.data());
}
void handlePrimaryAST(ASTUnitRef AstUnit) override {
std::string Error;
auto IFaceGenRef = SwiftInterfaceGenContext::createForSwiftSource(Name,
SourceFileName, AstUnit, Error);
if (!Error.empty())
Consumer->handleRequestError(Error.data());
Contexts.set(Name, IFaceGenRef);
IFaceGenRef->reportEditorInfo(*Consumer);
}
};
void SwiftLangSupport::editorOpenSwiftSourceInterface(StringRef Name,
StringRef SourceName,
ArrayRef<const char *> Args,
std::shared_ptr<EditorConsumer> Consumer) {
std::string Error;
auto Invocation = ASTMgr->getInvocation(Args, SourceName, Error);
if (!Invocation) {
Consumer->handleRequestError(Error.c_str());
return;
}
trace::TracedOperation TracedOp;
if (trace::enabled()) {
trace::SwiftInvocation SwiftArgs;
SwiftArgs.Args.Args.assign(Args.begin(), Args.end());
// NOTE: do not use primary file
// NOTE: do not use files
TracedOp.start(trace::OperationKind::OpenInterface, SwiftArgs,
{std::make_pair("Name", Name),
std::make_pair("SourceName", SourceName)});
}
auto AstConsumer = std::make_shared<PrimaryFileInterfaceConsumer>(Name,
SourceName, IFaceGenContexts, Consumer);
static const char OncePerASTToken = 0;
getASTManager().processASTAsync(Invocation, AstConsumer, &OncePerASTToken);
}
void SwiftLangSupport::editorOpenHeaderInterface(EditorConsumer &Consumer,
StringRef Name,
StringRef HeaderName,
ArrayRef<const char *> Args) {
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
CompilerInvocation Invocation;
std::string Error;
if (getASTManager().initCompilerInvocation(Invocation, llvm::None, CI.getDiags(),
StringRef(), Error)) {
Consumer.handleRequestError(Error.c_str());
return;
}
if (initInvocationByClangArguments(Args, Invocation, Error)) {
Consumer.handleRequestError(Error.c_str());
return;
}
trace::TracedOperation TracedOp;
if (trace::enabled()) {
trace::SwiftInvocation SwiftArgs;
SwiftArgs.Args.Args.assign(Args.begin(), Args.end());
// NOTE: do not use primary file
// NOTE: do not use files
TracedOp.start(trace::OperationKind::OpenHeaderInterface, SwiftArgs,
{std::make_pair("Name", Name),
std::make_pair("HeaderName", HeaderName)});
}
Invocation.getClangImporterOptions().ImportForwardDeclarations = true;
auto IFaceGenRef = SwiftInterfaceGenContext::create(Name,
/*IsModule=*/false,
HeaderName,
Invocation,
Error);
if (!IFaceGenRef) {
Consumer.handleRequestError(Error.c_str());
return;
}
IFaceGenContexts.set(Name, IFaceGenRef);
IFaceGenRef->reportEditorInfo(Consumer);
}
void SwiftLangSupport::findInterfaceDocument(StringRef ModuleName,
ArrayRef<const char *> Args,
std::function<void(const InterfaceDocInfo &)> Receiver) {
InterfaceDocInfo Info;
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
CompilerInvocation Invocation;
std::string Error;
if (getASTManager().initCompilerInvocation(Invocation, Args, CI.getDiags(),
StringRef(), Error)) {
Info.Error = Error;
return Receiver(Info);
}
if (auto IFaceGenRef = IFaceGenContexts.find(ModuleName, Invocation))
Info.ModuleInterfaceName = IFaceGenRef->getDocumentName();
SmallString<128> Buf;
SmallVector<std::pair<unsigned, unsigned>, 16> ArgOffs;
auto addArgPair = [&](StringRef Arg, StringRef Val) {
assert(!Arg.empty());
if (Val.empty())
return;
unsigned ArgBegin = Buf.size();
Buf += Arg;
unsigned ArgEnd = Buf.size();
unsigned ValBegin = Buf.size();
Buf += Val;
unsigned ValEnd = Buf.size();
ArgOffs.push_back(std::make_pair(ArgBegin, ArgEnd));
ArgOffs.push_back(std::make_pair(ValBegin, ValEnd));
};
auto addSingleArg = [&](StringRef Arg) {
assert(!Arg.empty());
unsigned ArgBegin = Buf.size();
Buf += Arg;
unsigned ArgEnd = Buf.size();
ArgOffs.push_back(std::make_pair(ArgBegin, ArgEnd));
};
addArgPair("-target", Invocation.getTargetTriple());
const auto &SPOpts = Invocation.getSearchPathOptions();
addArgPair("-sdk", SPOpts.SDKPath);
for (auto &Path : SPOpts.FrameworkSearchPaths)
addArgPair("-F", Path);
for (auto &Path : SPOpts.ImportSearchPaths)
addArgPair("-I", Path);
const auto &ClangOpts = Invocation.getClangImporterOptions();
addArgPair("-module-cache-path", ClangOpts.ModuleCachePath);
for (auto &ExtraArg : ClangOpts.ExtraArgs)
addArgPair("-Xcc", ExtraArg);
if (Invocation.getFrontendOptions().ImportUnderlyingModule)
addSingleArg("-import-underlying-module");
addArgPair("-import-objc-header",
Invocation.getFrontendOptions().ImplicitObjCHeaderPath);
SmallVector<StringRef, 16> NewArgs;
for (auto Pair : ArgOffs) {
NewArgs.push_back(StringRef(Buf.begin()+Pair.first, Pair.second-Pair.first));
}
Info.CompilerArgs = NewArgs;
return Receiver(Info);
}