-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSyntaxModel.cpp
1729 lines (1539 loc) · 61.8 KB
/
SyntaxModel.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
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SyntaxModel.cpp - Routines for IDE syntax model ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/SyntaxModel.h"
#include "swift/Basic/Defer.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Module.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Token.h"
#include "swift/Config.h"
#include "swift/Subsystems.h"
#include "clang/Basic/CharInfo.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/MemoryBuffer.h"
#include <vector>
#include <regex>
using namespace swift;
using namespace ide;
void SyntaxModelWalker::anchor() {}
struct SyntaxModelContext::Implementation {
SourceFile &SrcFile;
const LangOptions &LangOpts;
const SourceManager &SrcMgr;
std::vector<SyntaxNode> TokenNodes;
Implementation(SourceFile &SrcFile)
: SrcFile(SrcFile),
LangOpts(SrcFile.getASTContext().LangOpts),
SrcMgr(SrcFile.getASTContext().SourceMgr) {}
};
/// Matches the tokens in the argument of an image or file literal expression if
/// its argument is itself a literal string, e.g:
/// #imageLiteral(resourceName: "foo.png")
/// #fileLiteral(resourceName: "foo.txt")
/// 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 std::optional<Located<unsigned>>
matchImageOrFileLiteralArg(ArrayRef<Token> Tokens) {
const unsigned NUM_TOKENS = 5;
if (Tokens.size() < NUM_TOKENS)
return std::nullopt;
const tok kinds[NUM_TOKENS] = {
tok::l_paren,
tok::identifier, tok::colon, tok::string_literal,
tok::r_paren
};
for (unsigned i = 0; i < NUM_TOKENS; ++i) {
// FIXME: some editors don't handle multi-line object literals very well,
// so don't report them as object literals for now.
if (Tokens[i].getKind() != kinds[i] || Tokens[i].isAtStartOfLine())
return std::nullopt;
}
if (Tokens[1].getText() != "resourceName")
return std::nullopt;
auto EndToken = Tokens[NUM_TOKENS-1];
return Located<unsigned>(NUM_TOKENS, EndToken.getLoc().getAdvancedLoc(EndToken.getLength()));
}
/// Matches the tokens in the argument of an image literal expression if its
/// arguments are themselves number literals, e.g:
/// #colorLiteral(red: 1.0, green: 1.0, blue: 0.5, alpha: 1.0)
/// 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 std::optional<Located<unsigned>>
matchColorLiteralArg(ArrayRef<Token> Tokens) {
const unsigned NUM_TOKENS = 17;
if (Tokens.size() < NUM_TOKENS)
return std::nullopt;
const tok kinds[NUM_TOKENS] = {
tok::l_paren,
tok::identifier, tok::colon, tok::floating_literal, tok::comma,
tok::identifier, tok::colon, tok::floating_literal, tok::comma,
tok::identifier, tok::colon, tok::floating_literal, tok::comma,
tok::identifier, tok::colon, tok::floating_literal,
tok::r_paren
};
for (unsigned i = 0; i < NUM_TOKENS; ++i) {
auto Kind = Tokens[i].getKind();
if (Kind == tok::integer_literal)
Kind = tok::floating_literal;
// FIXME: some editors don't handle multi-line object literals very well,
// so don't report them as object literals for now.
if (Kind != kinds[i] || Tokens[i].isAtStartOfLine())
return std::nullopt;
}
if (Tokens[1].getText() != "red" || Tokens[5].getText() != "green" ||
Tokens[9].getText() != "blue" || Tokens[13].getText() != "alpha")
return std::nullopt;
auto EndToken = Tokens[NUM_TOKENS-1];
return Located<unsigned>(NUM_TOKENS, EndToken.getLoc().getAdvancedLoc(EndToken.getLength()));
}
SyntaxModelContext::SyntaxModelContext(SourceFile &SrcFile)
: Impl(*new Implementation(SrcFile)) {
const bool IsPlayground = Impl.LangOpts.Playground;
const SourceManager &SM = Impl.SrcMgr;
ArrayRef<Token> Tokens = SrcFile.getAllTokens();
std::vector<SyntaxNode> Nodes;
SourceLoc AttrLoc;
SourceLoc UnaryMinusLoc;
for (unsigned I = 0, E = Tokens.size(); I != E; ++I) {
auto &Tok = Tokens[I];
// Ignore empty string literals between interpolations, e.g. "\(1)\(2)"
if (!Tok.getLength())
continue;
SyntaxNodeKind Kind;
SourceLoc Loc;
std::optional<unsigned> Length;
if (AttrLoc.isValid()) {
// This token is following @, see if it's a known attribute name.
// Type attribute, decl attribute, or '@unknown' for swift case statement.
if (TypeAttribute::getAttrKindFromString(Tok.getText()).has_value() ||
DeclAttribute::getAttrKindFromString(Tok.getText()).has_value() ||
Tok.getText() == "unknown") {
// It's a known attribute, so treat it as a syntactic attribute node for
// syntax coloring. If swift gets user attributes then all identifiers
// will be treated as syntactic attribute nodes.
Loc = AttrLoc;
Length = SM.getByteDistance(Loc, Tok.getLoc()) + Tok.getLength();
Kind = SyntaxNodeKind::AttributeId;
}
AttrLoc = SourceLoc();
}
if (!Loc.isValid()) {
Loc = Tok.getLoc();
Length = Tok.getLength();
switch(Tok.getKind()) {
#define KEYWORD(X) case tok::kw_##X:
#include "swift/AST/TokenKinds.def"
#undef KEYWORD
case tok::contextual_keyword:
Kind = SyntaxNodeKind::Keyword;
break;
// Note: the below only handles object literals where each argument is a
// single literal. If the arguments are more complex than that we rely on
// there being an ObjectLiteralExpr in the AST and convert the individual
// tokens within its range into a single object literal in
// ModelASTWalker. We only bother with the below so that in the most
// common cases we still present object literals as object literals when
// the ObjectLiteralExpr doesn't appear in the AST (which can happen when
// they appear within an invalid expression).
case tok::pound_fileLiteral:
case tok::pound_imageLiteral:
if (auto Match = matchImageOrFileLiteralArg(Tokens.slice(I+1))) {
Kind = SyntaxNodeKind::ObjectLiteral;
Length = SM.getByteDistance(Loc, Match->Loc);
// skip over the extra matched tokens
I += Match->Item - 1;
} else {
Kind = SyntaxNodeKind::Keyword;
}
break;
case tok::pound_colorLiteral:
if (auto Match = matchColorLiteralArg(Tokens.slice(I+1))) {
Kind = SyntaxNodeKind::ObjectLiteral;
Length = SM.getByteDistance(Loc, Match->Loc);
// skip over the matches tokens
I += Match->Item - 1;
} else {
Kind = SyntaxNodeKind::Keyword;
}
break;
#define POUND_COND_DIRECTIVE_KEYWORD(Name) case tok::pound_##Name:
#include "swift/AST/TokenKinds.def"
Kind = SyntaxNodeKind::BuildConfigKeyword;
break;
#define POUND_DIRECTIVE_KEYWORD(Name) case tok::pound_##Name:
#define POUND_COND_DIRECTIVE_KEYWORD(Name)
#include "swift/AST/TokenKinds.def"
Kind = SyntaxNodeKind::PoundDirectiveKeyword;
break;
#define POUND_OBJECT_LITERAL(Name, Desc, Proto)
#define POUND_DIRECTIVE_KEYWORD(Name)
#define POUND_KEYWORD(Name) case tok::pound_##Name:
#include "swift/AST/TokenKinds.def"
Kind = SyntaxNodeKind::Keyword;
break;
case tok::identifier:
if (Tok.getText().startswith("<#"))
Kind = SyntaxNodeKind::EditorPlaceholder;
else
Kind = SyntaxNodeKind::Identifier;
break;
case tok::dollarident: Kind = SyntaxNodeKind::DollarIdent; break;
case tok::string_literal: Kind = SyntaxNodeKind::String; break;
case tok::integer_literal:
Kind = SyntaxNodeKind::Integer;
if (UnaryMinusLoc.isValid()) {
Loc = UnaryMinusLoc;
Length = *Length + SM.getByteDistance(UnaryMinusLoc, Tok.getLoc());
}
break;
case tok::floating_literal:
Kind = SyntaxNodeKind::Floating;
if (UnaryMinusLoc.isValid()) {
Loc = UnaryMinusLoc;
Length = *Length + SM.getByteDistance(UnaryMinusLoc, Tok.getLoc());
}
break;
case tok::oper_prefix:
if (Tok.getText() == "-" && I != E &&
(Tokens[I+1].getKind() == tok::integer_literal ||
Tokens[I+1].getKind() == tok::floating_literal)) {
UnaryMinusLoc = Loc;
continue;
} else {
Kind = SyntaxNodeKind::Operator;
break;
}
case tok::oper_postfix:
case tok::oper_binary_spaced:
case tok::oper_binary_unspaced:
Kind = SyntaxNodeKind::Operator;
break;
case tok::comment:
if (Tok.getText().startswith("///") ||
(IsPlayground && Tok.getText().startswith("//:")))
Kind = SyntaxNodeKind::DocCommentLine;
else if (Tok.getText().startswith("/**") ||
(IsPlayground && Tok.getText().startswith("/*:")))
Kind = SyntaxNodeKind::DocCommentBlock;
else if (Tok.getText().startswith("//"))
Kind = SyntaxNodeKind::CommentLine;
else
Kind = SyntaxNodeKind::CommentBlock;
break;
case tok::at_sign:
// Set the location of @ and continue. Next token should be the
// attribute name.
AttrLoc = Tok.getLoc();
continue;
case tok::string_interpolation_anchor: {
Kind = SyntaxNodeKind::StringInterpolationAnchor;
break;
}
case tok::unknown: {
if (Tok.getRawText().ltrim('#').startswith("\"")) {
// This is likely an invalid single-line ("), multi-line ("""),
// or raw (#", ##", #""", etc.) string literal.
Kind = SyntaxNodeKind::String;
break;
}
continue;
}
default:
continue;
}
}
UnaryMinusLoc = SourceLoc(); // Reset.
assert(Loc.isValid());
assert(Nodes.empty() || SM.isBeforeInBuffer(Nodes.back().Range.getStart(),
Loc));
Nodes.emplace_back(Kind, CharSourceRange(Loc, Length.value()));
}
Impl.TokenNodes = std::move(Nodes);
}
SyntaxModelContext::~SyntaxModelContext() {
delete &Impl;
}
namespace {
using ASTNodeType = ASTWalker::ParentTy;
struct StructureElement {
SyntaxStructureNode StructureNode;
ASTNodeType ASTNode;
StructureElement(const SyntaxStructureNode &StructureNode,
const ASTNodeType &ASTNode)
:StructureNode(StructureNode), ASTNode(ASTNode) { }
};
static const std::vector<std::string> URLProtocols = {
// Use RegexStrURL:
"acap", "afp", "afs", "cid", "data", "fax", "feed", "file", "ftp", "go",
"gopher", "http", "https", "imap", "ldap", "mailserver", "mid", "modem",
"news", "nntp", "opaquelocktoken", "pop", "prospero", "rdar", "rtsp", "service",
"sip", "soap.beep", "soap.beeps", "tel", "telnet", "tip", "tn3270", "urn",
"vemmi", "wais", "xcdoc", "z39.50r","z39.50s",
// Use RegexStrMailURL:
"mailto", "im",
// Use RegexStrRadarURL:
"radar"
};
static const char *const RegexStrURL =
"(acap|afp|afs|cid|data|fax|feed|file|ftp|go|"
"gopher|http|https|imap|ldap|mailserver|mid|modem|news|nntp|opaquelocktoken|"
"pop|prospero|rdar|rtsp|service|sip|soap\\.beep|soap\\.beeps|tel|telnet|tip|"
"tn3270|urn|vemmi|wais|xcdoc|z39\\.50r|z39\\.50s)://"
"([a-zA-Z0-9\\-_.]+/)?[a-zA-Z0-9;/?:@\\&=+$,\\-_.!~*'()%#]+";
static const char *const RegexStrMailURL =
"(mailto|im):[a-zA-Z0-9\\-_]+@[a-zA-Z0-9\\-_\\.!%]+";
static const char *const RegexStrRadarURL =
"radar:[a-zA-Z0-9;/?:@\\&=+$,\\-_.!~*'()%#]+";
class ModelASTWalker : public ASTWalker {
ArrayRef<Token> AllTokensInFile;
const LangOptions &LangOpts;
const SourceManager &SM;
unsigned BufferID;
ASTContext &Ctx;
std::vector<StructureElement> SubStructureStack;
SourceLoc LastLoc;
static const std::regex &getURLRegex(StringRef Protocol);
std::optional<SyntaxNode> parseFieldNode(StringRef Text, StringRef OrigText,
SourceLoc OrigLoc);
llvm::DenseSet<ASTNode> NodesVisitedBefore;
/// When non-zero, we should avoid passing tokens as syntax nodes since a parent of several tokens
/// is considered as one, e.g. object literal expression.
uint8_t AvoidPassingSyntaxToken = 0;
class InactiveClauseRAII {
const bool wasInInactiveClause;
bool &isInInactiveClause;
public:
InactiveClauseRAII(bool &isInInactiveClauseArg, bool enteringInactiveClause)
: wasInInactiveClause(isInInactiveClauseArg),
isInInactiveClause(isInInactiveClauseArg) {
isInInactiveClause |= enteringInactiveClause;
}
~InactiveClauseRAII() { isInInactiveClause = wasInInactiveClause; }
};
friend class InactiveClauseRAII;
bool inInactiveClause = false;
public:
SyntaxModelWalker &Walker;
ArrayRef<SyntaxNode> TokenNodes;
ModelASTWalker(const SourceFile &File, SyntaxModelWalker &Walker)
: AllTokensInFile(File.getAllTokens()),
LangOpts(File.getASTContext().LangOpts),
SM(File.getASTContext().SourceMgr),
BufferID(File.getBufferID().value()),
Ctx(File.getASTContext()),
Walker(Walker) { }
// FIXME: Remove this
bool shouldWalkAccessorsTheOldWay() override { return true; }
/// Only walk the arguments of a macro, to represent the source as written.
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
void visitSourceFile(SourceFile &SrcFile, ArrayRef<SyntaxNode> Tokens);
PreWalkAction walkToArgumentPre(const Argument &Arg) override;
PreWalkResult<Expr *> walkToExprPre(Expr *E) override;
PostWalkResult<Expr *> walkToExprPost(Expr *E) override;
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override;
PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override;
PreWalkAction walkToDeclPre(Decl *D) override;
PostWalkAction walkToDeclPost(Decl *D) override;
QualifiedIdentTypeReprWalkingScheme
getQualifiedIdentTypeReprWalkingScheme() const override {
return QualifiedIdentTypeReprWalkingScheme::SourceOrderRecursive;
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override;
bool shouldWalkIntoGenericParams() override { return true; }
private:
static bool findUrlStartingLoc(StringRef Text, unsigned &Start,
std::regex& Regex);
bool annotateIfConfigConditionIdentifiers(Expr *Cond);
bool handleAttrs(const ParsedDeclAttributes &Attrs);
bool handleAttrs(ArrayRef<TypeOrCustomAttr> Attrs);
using DeclAttributeAndRange = std::pair<const DeclAttribute *, SourceRange>;
bool handleSpecialDeclAttribute(const DeclAttribute *Decl,
ArrayRef<Token> Toks);
bool handleAttrRanges(ArrayRef<DeclAttributeAndRange> DeclRanges);
bool shouldPassBraceStructureNode(BraceStmt *S);
enum PassNodesBehavior {
/// Pass all nodes up to but not including the location.
ExcludeNodeAtLocation,
/// Pass all nodes up to and including the location.
IncludeNodeAtLocation,
/// Like ExcludeNodeAtLocation, and skip past any node at the location.
DisplaceNodeAtLocation
};
struct PassUntilResult {
bool shouldContinue;
std::optional<SyntaxNode> MatchedToken;
};
PassUntilResult
passTokenNodesUntil(SourceLoc Loc, PassNodesBehavior Pass);
bool passNonTokenNode(const SyntaxNode &Node);
bool passNode(const SyntaxNode &Node);
bool pushStructureNode(const SyntaxStructureNode &Node,
const ASTNodeType& ASTNode);
bool popStructureNode();
bool processComment(CharSourceRange Range);
bool searchForURL(CharSourceRange Range);
bool findFieldsInDocCommentLine(SyntaxNode Node);
bool findFieldsInDocCommentBlock(SyntaxNode Node);
bool isVisitedBefore(ASTNode Node) {
return NodesVisitedBefore.count(Node) > 0;
}
};
const std::regex &ModelASTWalker::getURLRegex(StringRef Pro) {
static const std::regex Regexes[3] = {
std::regex{ RegexStrURL, std::regex::ECMAScript | std::regex::nosubs },
std::regex{ RegexStrMailURL, std::regex::ECMAScript | std::regex::nosubs },
std::regex{ RegexStrRadarURL, std::regex::ECMAScript | std::regex::nosubs }
};
static const auto MailToPosition = std::find(URLProtocols.begin(),
URLProtocols.end(),
"mailto");
static const auto RadarPosition = std::find(URLProtocols.begin(),
URLProtocols.end(),
"radar");
auto Found = std::find(URLProtocols.begin(), URLProtocols.end(), Pro);
assert(Found != URLProtocols.end() && "bad protocol name");
if (Found < MailToPosition)
return Regexes[0];
else if (Found < RadarPosition)
return Regexes[1];
else
return Regexes[2];
}
SyntaxStructureKind syntaxStructureKindFromNominalTypeDecl(NominalTypeDecl *N) {
if (isa<ClassDecl>(N))
return SyntaxStructureKind::Class;
else if (isa<StructDecl>(N))
return SyntaxStructureKind::Struct;
else if (isa<ProtocolDecl>(N))
return SyntaxStructureKind::Protocol;
else {
// All other known NominalTypeDecl derived classes covered, so assert() here.
assert(isa<EnumDecl>(N));
return SyntaxStructureKind::Enum;
}
}
CharSourceRange charSourceRangeFromSourceRange(const SourceManager &SM,
const SourceRange &SR) {
return Lexer::getCharSourceRangeFromSourceRange(SM, SR);
}
CharSourceRange innerCharSourceRangeFromSourceRange(const SourceManager &SM,
const SourceRange &SR) {
if (SR.isInvalid())
return CharSourceRange();
SourceLoc SRS = Lexer::getLocForEndOfToken(SM, SR.Start);
return CharSourceRange(SM, SRS, (SR.End != SR.Start) ? SR.End : SRS);
}
static void setDecl(SyntaxStructureNode &N, Decl *D) {
N.Dcl = D;
N.Attrs = D->getParsedAttrs();
N.DocRange = D->getRawComment().getCharSourceRange();
}
} // anonymous namespace
bool SyntaxModelContext::walk(SyntaxModelWalker &Walker) {
ModelASTWalker ASTWalk(Impl.SrcFile, Walker);
ASTWalk.visitSourceFile(Impl.SrcFile, Impl.TokenNodes);
return true;
}
void ModelASTWalker::visitSourceFile(SourceFile &SrcFile,
ArrayRef<SyntaxNode> Tokens) {
TokenNodes = Tokens;
SrcFile.walk(*this);
// Pass the rest of the token nodes.
for (auto &TokNode : TokenNodes)
passNode(TokNode);
}
static bool shouldTreatAsSingleToken(const SyntaxStructureNode &Node,
const SourceManager &SM) {
// Avoid passing the individual syntax tokens corresponding to single-line
// object literal expressions, as they will be reported as a single token.
return Node.Kind == SyntaxStructureKind::ObjectLiteralExpression &&
SM.getLineAndColumnInBuffer(Node.Range.getStart()).first ==
SM.getLineAndColumnInBuffer(Node.Range.getEnd()).first;
}
ASTWalker::PreWalkAction
ModelASTWalker::walkToArgumentPre(const Argument &Arg) {
if (isVisitedBefore(Arg.getExpr()))
return Action::SkipNode();
auto *Elem = Arg.getExpr();
if (isa<DefaultArgumentExpr>(Elem))
return Action::Continue();
auto NL = Arg.getLabelLoc();
auto Name = Arg.getLabel();
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::Argument;
SN.BodyRange = charSourceRangeFromSourceRange(SM, Elem->getSourceRange());
if (NL.isValid() && !Name.empty()) {
SN.NameRange = CharSourceRange(NL, Name.getLength());
SN.Range = charSourceRangeFromSourceRange(
SM, SourceRange(NL, Elem->getEndLoc()));
passTokenNodesUntil(NL, ExcludeNodeAtLocation);
} else {
SN.Range = SN.BodyRange;
}
pushStructureNode(SN, Elem);
return Action::Continue();
}
ASTWalker::PreWalkResult<Expr *> ModelASTWalker::walkToExprPre(Expr *E) {
if (isVisitedBefore(E))
return Action::SkipNode(E);
if (E->isImplicit())
return Action::Continue(E);
auto addExprElem = [&](const Expr *Elem, SyntaxStructureNode &SN) {
if (isa<ErrorExpr>(Elem))
return;
SourceRange R = Elem->getSourceRange();
if (R.isInvalid())
return;
SN.Elements.emplace_back(SyntaxStructureElementKind::Expr,
charSourceRangeFromSourceRange(SM, R));
};
if (auto *CE = dyn_cast<CallExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::CallExpression;
SN.Range = charSourceRangeFromSourceRange(SM, E->getSourceRange());
if (CE->getFn() && CE->getFn()->getSourceRange().isValid())
SN.NameRange = charSourceRangeFromSourceRange(SM,
CE->getFn()->getSourceRange());
if (CE->getArgs()->getSourceRange().isValid())
SN.BodyRange = innerCharSourceRangeFromSourceRange(
SM, CE->getArgs()->getSourceRange());
pushStructureNode(SN, CE);
} else if (auto *SE = dyn_cast<SubscriptExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::CallExpression;
SN.Range = charSourceRangeFromSourceRange(SM, E->getSourceRange());
SN.NameRange =
charSourceRangeFromSourceRange(SM, SE->getBase()->getSourceRange());
if (SE->getArgs()->getSourceRange().isValid())
SN.BodyRange = innerCharSourceRangeFromSourceRange(
SM, SE->getArgs()->getSourceRange());
pushStructureNode(SN, SE);
} else if (auto *ObjectE = dyn_cast<ObjectLiteralExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::ObjectLiteralExpression;
SN.Range = charSourceRangeFromSourceRange(SM, ObjectE->getSourceRange());
SourceLoc NRStart = ObjectE->getSourceLoc().getAdvancedLoc(1);
SourceLoc NREnd =
NRStart.getAdvancedLoc(ObjectE->getLiteralKindRawName().size());
SN.NameRange = CharSourceRange(SM, NRStart, NREnd);
SN.BodyRange =
innerCharSourceRangeFromSourceRange(SM, ObjectE->getSourceRange());
// Consider the object literal as a single syntax token for highlighting if
// it spans a single line.
if (shouldTreatAsSingleToken(SN, SM))
passNonTokenNode({SyntaxNodeKind::ObjectLiteral, SN.Range});
pushStructureNode(SN, E);
} else if (auto *ArrayE = dyn_cast<ArrayExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::ArrayExpression;
SN.Range = charSourceRangeFromSourceRange(SM, E->getSourceRange());
for (auto *Elem : ArrayE->getElements())
addExprElem(Elem, SN);
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, E->getSourceRange());
pushStructureNode(SN, E);
} else if (auto *DictE = dyn_cast<DictionaryExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::DictionaryExpression;
SN.Range = charSourceRangeFromSourceRange(SM, E->getSourceRange());
for (auto *Elem : DictE->getElements()) {
if (auto *TupleE = dyn_cast<TupleExpr>(Elem)) {
for (auto *TE : TupleE->getElements())
addExprElem(TE, SN);
} else {
addExprElem(Elem, SN);
}
}
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, E->getSourceRange());
pushStructureNode(SN, E);
} else if (auto *Tup = dyn_cast<TupleExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::TupleExpression;
SN.Range = charSourceRangeFromSourceRange(SM, Tup->getSourceRange());
SN.BodyRange =
innerCharSourceRangeFromSourceRange(SM, Tup->getSourceRange());
for (auto *Elem : Tup->getElements()) {
addExprElem(Elem, SN);
}
pushStructureNode(SN, Tup);
} else if (auto *Closure = dyn_cast<ClosureExpr>(E)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::ClosureExpression;
SN.Range = charSourceRangeFromSourceRange(SM, E->getSourceRange());
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, E->getSourceRange());
if (Closure->hasExplicitResultType())
SN.TypeRange = charSourceRangeFromSourceRange(SM,
Closure->getExplicitResultTypeRepr()->getSourceRange());
pushStructureNode(SN, Closure);
} else if (auto SE = dyn_cast<SequenceExpr>(E)) {
// In SequenceExpr, explicit cast expressions (e.g. 'as', 'is') appear
// twice. Skip pointers we've already seen.
SmallPtrSet<Expr *, 5> seenExpr;
for (auto subExpr : SE->getElements()) {
if (!seenExpr.insert(subExpr).second) {
continue;
}
llvm::SaveAndRestore<ASTWalker::ParentTy> SetParent(Parent, E);
subExpr->walk(*this);
}
// We already visited the children.
return Action::SkipChildren(SE);
} else if (auto *ISL = dyn_cast<InterpolatedStringLiteralExpr>(E)) {
// Don't visit the child expressions directly. Instead visit the arguments
// of each appendStringLiteral/appendInterpolation CallExpr so we don't
// try to output structure nodes for those calls.
llvm::SaveAndRestore<ASTWalker::ParentTy> SetParent(Parent, E);
ISL->forEachSegment(Ctx, [&](bool isInterpolation, CallExpr *CE) {
if (isInterpolation) {
for (auto arg : *CE->getArgs())
arg.getExpr()->walk(*this);
}
});
return Action::SkipChildren(E);
}
return Action::Continue(E);
}
ASTWalker::PostWalkResult<Expr *> ModelASTWalker::walkToExprPost(Expr *E) {
while (!SubStructureStack.empty() &&
SubStructureStack.back().ASTNode.getAsExpr() == E)
popStructureNode();
return Action::Continue(E);
}
ASTWalker::PreWalkResult<Stmt *> ModelASTWalker::walkToStmtPre(Stmt *S) {
if (isVisitedBefore(S)) {
return Action::SkipNode(S);
}
auto addExprElem = [&](SyntaxStructureElementKind K, const Expr *Elem,
SyntaxStructureNode &SN) {
if (isa<ErrorExpr>(Elem))
return;
SourceRange R = Elem->getSourceRange();
if (R.isInvalid())
return;
SN.Elements.emplace_back(K, charSourceRangeFromSourceRange(SM, R));
};
if (auto *ForEachS = dyn_cast<ForEachStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::ForEachStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
if (ForEachS->getPattern()) {
auto Pat = ForEachS->getPattern();
if (!Pat->isImplicit()) {
SourceRange ElemRange = Pat->getSourceRange();
SN.Elements.emplace_back(SyntaxStructureElementKind::Id,
charSourceRangeFromSourceRange(SM, ElemRange));
}
}
if (auto *S = ForEachS->getParsedSequence())
addExprElem(SyntaxStructureElementKind::Expr, S, SN);
pushStructureNode(SN, S);
} else if (auto *WhileS = dyn_cast<WhileStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::WhileStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
if (!WhileS->getCond().empty()) {
auto Conds = WhileS->getCond();
SourceRange ElemRange = SourceRange(Conds.front().getSourceRange().Start,
Conds.back().getSourceRange().End);
SN.Elements.emplace_back(SyntaxStructureElementKind::ConditionExpr,
charSourceRangeFromSourceRange(SM, ElemRange));
}
pushStructureNode(SN, S);
} else if (auto *RepeatWhileS = dyn_cast<RepeatWhileStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::RepeatWhileStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
if (RepeatWhileS->getCond()) {
addExprElem(SyntaxStructureElementKind::Expr, RepeatWhileS->getCond(), SN);
}
pushStructureNode(SN, S);
} else if (auto *IfS = dyn_cast<IfStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::IfStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
if (!IfS->getCond().empty()) {
auto Conds = IfS->getCond();
SourceRange ElemRange = SourceRange(Conds.front().getSourceRange().Start,
Conds.back().getSourceRange().End);
SN.Elements.emplace_back(SyntaxStructureElementKind::ConditionExpr,
charSourceRangeFromSourceRange(SM, ElemRange));
}
pushStructureNode(SN, S);
} else if (auto *GS = dyn_cast<GuardStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::GuardStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
if (!GS->getCond().empty()) {
auto Conds = GS->getCond();
SourceRange ElemRange = SourceRange(Conds.front().getSourceRange().Start,
Conds.back().getSourceRange().End);
SN.Elements.emplace_back(SyntaxStructureElementKind::ConditionExpr,
charSourceRangeFromSourceRange(SM, ElemRange));
}
pushStructureNode(SN, S);
} else if (auto *SwitchS = dyn_cast<SwitchStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::SwitchStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
if (SwitchS->getSubjectExpr()) {
addExprElem(SyntaxStructureElementKind::Expr, SwitchS->getSubjectExpr(),
SN);
}
pushStructureNode(SN, S);
} else if (auto *CaseS = dyn_cast<CaseStmt>(S)) {
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::CaseStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
for (const CaseLabelItem &Item : CaseS->getCaseLabelItems()) {
SN.Elements.emplace_back(SyntaxStructureElementKind::Pattern,
charSourceRangeFromSourceRange(SM,
Item.getSourceRange()));
}
pushStructureNode(SN, S);
} else if (isa<BraceStmt>(S) && shouldPassBraceStructureNode(cast<BraceStmt>(S))) {
// Pass BraceStatement structure node.
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::BraceStatement;
SN.Range = charSourceRangeFromSourceRange(SM, S->getSourceRange());
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM,
S->getSourceRange());
pushStructureNode(SN, S);
} else if (auto *SW = dyn_cast<SwitchStmt>(S)) {
if (SW->getLBraceLoc().isValid() && SW->getRBraceLoc().isValid()) {
SourceRange BraceRange(SW->getLBraceLoc(), SW->getRBraceLoc());
SyntaxStructureNode SN;
SN.Kind = SyntaxStructureKind::BraceStatement;
SN.Range = charSourceRangeFromSourceRange(SM, BraceRange);
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, BraceRange);
pushStructureNode(SN, SW);
}
} else if (auto *DeferS = dyn_cast<DeferStmt>(S)) {
// Since 'DeferStmt::getTempDecl()' is marked as implicit, we manually walk
// into the body.
if (auto *FD = DeferS->getTempDecl()) {
if (auto *Body = FD->getBody()) {
auto *RetS = Body->walk(*this);
assert(RetS == Body);
(void)RetS;
}
}
// Already walked children.
return Action::SkipChildren(DeferS);
}
return Action::Continue(S);
}
ASTWalker::PostWalkResult<Stmt *> ModelASTWalker::walkToStmtPost(Stmt *S) {
while (!SubStructureStack.empty() &&
SubStructureStack.back().ASTNode.getAsStmt() == S)
popStructureNode();
return Action::Continue(S);
}
ASTWalker::PreWalkAction ModelASTWalker::walkToDeclPre(Decl *D) {
if (isVisitedBefore(D))
return Action::SkipNode();
if (D->isImplicit())
return Action::SkipNode();
// The attributes of EnumElementDecls and VarDecls are handled when visiting
// their parent EnumCaseDecl/PatternBindingDecl (which the attributes are
// attached to syntactically).
if (!isa<EnumElementDecl>(D) &&
!(isa<VarDecl>(D) && cast<VarDecl>(D)->getParentPatternBinding())) {
if (!handleAttrs(D->getParsedAttrs()))
return Action::SkipNode();
}
if (isa<AccessorDecl>(D)) {
// Don't push structure nodes for accessors.
} else if (auto *AFD = dyn_cast<AbstractFunctionDecl>(D)) {
// Pass Function / Method structure node.
SyntaxStructureNode SN;
setDecl(SN, D);
const DeclContext *DC = AFD->getDeclContext();
auto *FD = dyn_cast<FuncDecl>(AFD);
if (DC->isTypeContext()) {
if (FD && FD->isStatic()) {
if (FD->getStaticSpelling() == StaticSpellingKind::KeywordClass)
SN.Kind = SyntaxStructureKind::ClassFunction;
else
SN.Kind = SyntaxStructureKind::StaticFunction;
} else {
SN.Kind = SyntaxStructureKind::InstanceFunction;
}
}
else
SN.Kind = SyntaxStructureKind::FreeFunction;
SN.Range = charSourceRangeFromSourceRange(SM, AFD->getSourceRange());
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM,
AFD->getBodySourceRange());
SN.NameRange = charSourceRangeFromSourceRange(SM,
AFD->getSignatureSourceRange());
if (FD) {
SN.TypeRange = charSourceRangeFromSourceRange(SM,
FD->getResultTypeSourceRange());
}
pushStructureNode(SN, AFD);
} else if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
SyntaxStructureNode SN;
setDecl(SN, D);
SN.Kind = syntaxStructureKindFromNominalTypeDecl(NTD);
SN.Range = charSourceRangeFromSourceRange(SM, NTD->getSourceRange());
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, NTD->getBraces());
SourceLoc NRStart = NTD->getNameLoc();
SourceLoc NREnd = NRStart.getAdvancedLoc(NTD->getName().getLength());
SN.NameRange = CharSourceRange(SM, NRStart, NREnd);
for (const TypeLoc &TL : NTD->getInherited().getEntries()) {
CharSourceRange TR = charSourceRangeFromSourceRange(SM,
TL.getSourceRange());
SN.InheritedTypeRanges.push_back(TR);
SN.Elements.emplace_back(SyntaxStructureElementKind::TypeRef, TR);
}
pushStructureNode(SN, NTD);
} else if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
SyntaxStructureNode SN;
setDecl(SN, D);
SN.Kind = SyntaxStructureKind::Extension;
SN.Range = charSourceRangeFromSourceRange(SM, ED->getSourceRange());
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, ED->getBraces());
SourceRange NSR = SourceRange();
if (auto *repr = ED->getExtendedTypeRepr())
NSR = repr->getSourceRange();
SN.NameRange = charSourceRangeFromSourceRange(SM, NSR);
for (const TypeLoc &TL : ED->getInherited().getEntries()) {
CharSourceRange TR = charSourceRangeFromSourceRange(SM,
TL.getSourceRange());
SN.InheritedTypeRanges.push_back(TR);
SN.Elements.emplace_back(SyntaxStructureElementKind::TypeRef, TR);
}
pushStructureNode(SN, ED);
} else if (auto *PD = dyn_cast<ParamDecl>(D)) {
SyntaxStructureNode SN;
SN.Dcl = D;
SN.Kind = SyntaxStructureKind::Parameter;
if (!PD->getArgumentName().empty()) {
SourceLoc ArgStart = PD->getSourceRange().Start;
SN.NameRange = CharSourceRange(ArgStart, PD->getArgumentName().getLength());
passTokenNodesUntil(ArgStart, PassNodesBehavior::ExcludeNodeAtLocation);
}
SN.Range = charSourceRangeFromSourceRange(SM, PD->getSourceRange());
SN.Attrs = PD->getParsedAttrs();
SN.TypeRange = charSourceRangeFromSourceRange(SM,
PD->getTypeSourceRangeForDiagnostics());
pushStructureNode(SN, PD);
} else if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
// Process the attributes of one of the contained VarDecls. Attributes that
// are syntactically attached to the PatternBindingDecl end up on the
// contained VarDecls.
VarDecl *Contained = nullptr;
for (auto idx : range(PBD->getNumPatternEntries())) {
PBD->getPattern(idx)->forEachVariable([&](VarDecl *VD) -> void {
Contained = VD;
});
if (Contained) {
if (!handleAttrs(Contained->getParsedAttrs()))
return Action::SkipNode();
break;
}
}
} else if (auto *VD = dyn_cast<VarDecl>(D)) {
const DeclContext *DC = VD->getDeclContext();
SyntaxStructureNode SN;
setDecl(SN, D);
SourceRange SR;
if (auto *PBD = VD->getParentPatternBinding())
SR = PBD->getSourceRange();
else
SR = VD->getSourceRange();
SN.Range = charSourceRangeFromSourceRange(SM, SR);
auto bracesRange = VD->getBracesRange();
if (bracesRange.isValid())
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, bracesRange);
SourceLoc NRStart = VD->getNameLoc();
SourceLoc NREnd = (!VD->getName().empty()
? NRStart.getAdvancedLoc(VD->getName().getLength())
: NRStart);
SN.NameRange = CharSourceRange(SM, NRStart, NREnd);
SN.TypeRange = charSourceRangeFromSourceRange(SM,
VD->getTypeSourceRangeForDiagnostics());
if (DC->isLocalContext()) {
SN.Kind = SyntaxStructureKind::LocalVariable;
} else if (DC->isTypeContext()) {
if (VD->isStatic()) {
StaticSpellingKind Spell = StaticSpellingKind::KeywordStatic;
if (auto *PBD = VD->getParentPatternBinding())
Spell = PBD->getStaticSpelling();
if (Spell == StaticSpellingKind::KeywordClass)
SN.Kind = SyntaxStructureKind::ClassVariable;
else
SN.Kind = SyntaxStructureKind::StaticVariable;
} else {
SN.Kind = SyntaxStructureKind::InstanceVariable;
}
} else {