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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 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
//
//===----------------------------------------------------------------------===//
import SwiftIfConfig
import SwiftSyntax
@_spi(Experimental) extension SyntaxProtocol {
/// Parent scope of this syntax node, or scope introduced by this syntax node.
var scope: ScopeSyntax? {
if let scopeSyntax = Syntax(self).asProtocol(SyntaxProtocol.self) as? ScopeSyntax {
return scopeSyntax
} else {
return self.parent?.scope
}
}
/// This node's line and column separated by `:`.
var debugLineWithColumnDescription: String {
let location = SourceLocationConverter(fileName: "", tree: root).location(for: position)
return "\(location.line):\(location.column)"
}
}
@_spi(Experimental) extension SourceFileSyntax: SequentialScopeSyntax {
/// File Scope doesn't introduce any names.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"FileScope"
}
/// In file scope, introduce only from `guard`.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
return statements.flatMap { codeBlockItem in
if let guardStmt = codeBlockItem.item.as(GuardStmtSyntax.self) {
return guardStmt.lookupFromSequentialParent(
identifier,
at: lookUpPosition,
with: config
)
} else {
return []
}
}
}
}
@_spi(Experimental) extension CodeBlockSyntax: SequentialScopeSyntax {
/// Names introduced in the code block scope
/// accessible after their declaration.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
statements.flatMap { codeBlockItem in
LookupName.getNames(from: codeBlockItem.item, accessibleAfter: codeBlockItem.endPosition)
}
}
@_spi(Experimental) public var scopeDebugName: String {
"CodeBlockScope"
}
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
sequentialLookup(
in: statements,
identifier,
at: lookUpPosition,
with: config
)
}
}
@_spi(Experimental) extension ForStmtSyntax: ScopeSyntax {
/// Names introduced in the `for` body.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
LookupName.getNames(from: pattern)
}
@_spi(Experimental) public var scopeDebugName: String {
"ForStmtScope"
}
/// Returns results with names matching lookup.
/// Doesn't include names introduced at this scope
/// if lookup started inside it's `pattern` or `sequence`.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
if pattern.range.contains(lookUpPosition) || sequence.range.contains(lookUpPosition) {
return lookupInParent(identifier, at: lookUpPosition, with: config)
} else {
return defaultLookupImplementation(identifier, at: lookUpPosition, with: config)
}
}
}
@_spi(Experimental) extension ClosureExprSyntax: SequentialScopeSyntax {
/// Closure capture names introduced in this closure expression.
var captureNames: [LookupName] {
signature?.capture?.items.flatMap { element in
LookupName.getNames(from: element)
} ?? []
}
/// Parameter names introduced in this closure expression.
var parameterNames: [LookupName] {
signature?.parameterClause?.children(viewMode: .sourceAccurate).flatMap { parameter in
if let parameterList = parameter.as(ClosureParameterListSyntax.self) {
return parameterList.children(viewMode: .sourceAccurate).flatMap { parameter in
LookupName.getNames(from: parameter)
}
} else {
return LookupName.getNames(from: parameter)
}
} ?? []
}
/// Names introduced sequentially in body.
var introducedNamesInBody: [LookupName] {
statements.flatMap { codeBlockItem in
LookupName.getNames(from: codeBlockItem.item, accessibleAfter: codeBlockItem.endPosition)
}
}
/// Capture, parameter and body names introduced in this scope.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
captureNames + parameterNames + introducedNamesInBody
}
@_spi(Experimental) public var scopeDebugName: String {
"ClosureExprScope"
}
/// All names introduced by the closure signature and its body.
/// Could be closure captures, (shorthand) parameters or
/// sequential results from the body.
///
/// ### Example
/// ```swift
/// let x = { [weak self, a] b, _ in
/// let c = 42
/// // <--
/// let d = 42
/// }
/// ```
/// During lookup, names available at the marked place are:
/// `self`, `a`, `b` and `c`.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
let sequentialResults = sequentialLookup(
in: statements,
identifier,
at: lookUpPosition,
with: config,
propagateToParent: false
)
guard !config.finishInSequentialScope else { return sequentialResults }
let signatureResults: [LookupResult]
if signature?.range.contains(lookUpPosition) ?? false {
signatureResults = []
} else if parameterNames.isEmpty {
let filteredCaptureNames = captureNames.filter { name in
checkIdentifier(identifier, refersTo: name, at: lookUpPosition)
}
if let identifier, identifier.isDollarIdentifier {
signatureResults = LookupResult.getResultArray(
for: self,
withNames: filteredCaptureNames + [LookupName.dollarIdentifier(self, strRepresentation: identifier.name)]
)
} else {
signatureResults =
LookupResult.getResultArray(for: self, withNames: filteredCaptureNames)
+ [.mightIntroduceDollarIdentifiers(self)]
}
} else {
signatureResults = LookupResult.getResultArray(
for: self,
withNames: (captureNames + parameterNames).filter { name in
checkIdentifier(identifier, refersTo: name, at: lookUpPosition)
}
)
}
return sequentialResults + signatureResults + lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
@_spi(Experimental) extension WhileStmtSyntax: ScopeSyntax {
/// Names introduced by the `while` loop by its conditions.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
conditions.reversed().flatMap { element in
LookupName.getNames(from: element.condition, accessibleAfter: element.endPositionBeforeTrailingTrivia)
}
}
@_spi(Experimental) public var scopeDebugName: String {
"WhileStmtScope"
}
}
@_spi(Experimental) extension IfExprSyntax: ScopeSyntax {
/// Parent scope, omitting ancestor `if` statements if part of their `else if` clause.
@_spi(Experimental) public var parentScope: ScopeSyntax? {
getParent(for: self.parent, previousIfElse: self.elseKeyword == nil)
}
/// Finds parent scope, omitting ancestor `if` statements if part of their `else if` clause.
///
/// ### Example
/// ```swift
/// func foo() {
/// if let a = x {
/// // <--
/// } else if let b {
/// // <--
/// } else if y == 1 {
/// // <--
/// }
/// }
/// ```
/// For each of the marked scopes, resulting parent
/// is the enclosing code block scope associated with
/// the function body.
private func getParent(for syntax: Syntax?, previousIfElse: Bool) -> ScopeSyntax? {
guard let syntax else { return nil }
if let lookedUpScope = syntax.scope, lookedUpScope.id != self.id {
if let currentIfExpr = lookedUpScope.as(IfExprSyntax.self), previousIfElse {
return getParent(for: syntax.parent, previousIfElse: currentIfExpr.elseKeyword == nil)
} else {
return lookedUpScope
}
} else {
return getParent(for: syntax.parent, previousIfElse: previousIfElse)
}
}
/// Names introduced by the `if` optional binding conditions.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
conditions.reversed().flatMap { element in
LookupName.getNames(from: element.condition, accessibleAfter: element.endPosition)
}
}
@_spi(Experimental) public var scopeDebugName: String {
"IfExprScope"
}
/// Returns names matching lookup.
/// Lookup triggered from inside of `else`
/// clause is immediately forwarded to parent scope.
///
/// ### Example
/// ```swift
/// if let a = x {
/// // <-- a is visible here
/// } else {
/// // <-- a is not visible here
/// }
/// ```
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
if let elseBody, elseBody.range.contains(lookUpPosition) {
return lookupInParent(identifier, at: lookUpPosition, with: config)
} else {
return defaultLookupImplementation(identifier, at: lookUpPosition, with: config)
}
}
}
@_spi(Experimental) extension MemberBlockSyntax: ScopeSyntax {
/// Member Block Scope doesn't introduce any results.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"MemberBlockScope"
}
/// Creates a result from associated type declarations
/// made by it's members.
func lookupAssociatedTypeDeclarations(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
let filteredNames = members.flatMap { member in
guard member.decl.kind == .associatedTypeDecl else { return [LookupName]() }
return LookupName.getNames(from: member.decl)
}.filter { name in
checkIdentifier(identifier, refersTo: name, at: lookUpPosition)
}
return LookupResult.getResultArray(for: self, withNames: filteredNames)
}
}
@_spi(Experimental) extension GuardStmtSyntax: IntroducingToSequentialParentScopeSyntax {
/// Names introduced in `guard` conditions to the sequential parent.
var namesIntroducedToSequentialParent: [LookupName] {
conditions.reversed().flatMap { element in
LookupName.getNames(from: element.condition, accessibleAfter: element.endPosition)
}
}
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"GuardStmtScope"
}
/// Returns results matching lookup that should be
/// interleaved with sequential parent's results.
/// Lookup triggered from within of the `else` body
/// returns no names.
///
/// ### Example
/// ```swift
/// guard let a = x else {
/// return // a is not visible here
/// }
/// // a is visible here
/// ```
func lookupFromSequentialParent(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
guard !body.range.contains(lookUpPosition) else { return [] }
let filteredNames = namesIntroducedToSequentialParent.filter { introducedName in
checkIdentifier(identifier, refersTo: introducedName, at: lookUpPosition)
}
return LookupResult.getResultArray(for: self, withNames: filteredNames)
}
}
@_spi(Experimental) extension ActorDeclSyntax: NominalTypeDeclSyntax {
@_spi(Experimental) public var scopeDebugName: String {
"ActorDeclScope"
}
}
@_spi(Experimental) extension ClassDeclSyntax: NominalTypeDeclSyntax {
@_spi(Experimental) public var scopeDebugName: String {
"ClassDeclScope"
}
}
@_spi(Experimental) extension StructDeclSyntax: NominalTypeDeclSyntax {
@_spi(Experimental) public var scopeDebugName: String {
"StructDeclScope"
}
}
@_spi(Experimental) extension EnumDeclSyntax: NominalTypeDeclSyntax {
@_spi(Experimental) public var scopeDebugName: String {
"EnumDeclScope"
}
}
@_spi(Experimental) extension ExtensionDeclSyntax: LookInMembersScopeSyntax {
@_spi(Experimental) public var lookupMembersPosition: AbsolutePosition {
if let memberType = extendedType.as(MemberTypeSyntax.self) {
return memberType.name.positionAfterSkippingLeadingTrivia
}
return extendedType.positionAfterSkippingLeadingTrivia
}
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"ExtensionDeclScope"
}
/// Returns results matching lookup, including implicit `Self`,
/// `lookInGenericParametersOfExtendedType` and `lookInMembers` depending on `lookupPosition`.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
if memberBlock.range.contains(lookUpPosition) {
let implicitSelf: [LookupName] = [.implicit(.Self(self))]
.filter { name in
checkIdentifier(identifier, refersTo: name, at: lookUpPosition)
}
return LookupResult.getResultArray(for: self, withNames: implicitSelf)
+ [.lookInGenericParametersOfExtendedType(self)]
+ defaultLookupImplementation(identifier, at: lookUpPosition, with: config, propagateToParent: false)
+ [.lookInMembers(self)]
+ lookupInParent(identifier, at: lookUpPosition, with: config)
} else if !extendedType.range.contains(lookUpPosition), let genericWhereClause {
if genericWhereClause.range.contains(lookUpPosition) {
return [.lookInGenericParametersOfExtendedType(self)] + [.lookInMembers(self)]
+ defaultLookupImplementation(identifier, at: lookUpPosition, with: config)
}
return [.lookInGenericParametersOfExtendedType(self)]
+ defaultLookupImplementation(identifier, at: lookUpPosition, with: config)
}
return [.lookInGenericParametersOfExtendedType(self)]
+ lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
@_spi(Experimental) extension AccessorDeclSyntax: ScopeSyntax {
/// Implicit and/or explicit names introduced within the accessor.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
if let parameters {
return LookupName.getNames(from: parameters)
} else {
switch accessorSpecifier.tokenKind {
case .keyword(.set), .keyword(.willSet):
return [.implicit(.newValue(self))]
case .keyword(.didSet):
return [.implicit(.oldValue(self))]
default:
return []
}
}
}
@_spi(Experimental) public var scopeDebugName: String {
"AccessorDeclScope"
}
/// Returns result with matching names from
/// this scope and passes result with implicit `self`
/// to be introduced after the `subscript`
/// declaration scope grandparent.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
guard let parentScope,
let canInterleaveLaterScope = Syntax(parentScope).asProtocol(SyntaxProtocol.self)
as? CanInterleaveResultsLaterScopeSyntax
else {
return defaultLookupImplementation(identifier, at: lookUpPosition, with: config)
}
let implicitSelf: [LookupName] = [.implicit(.self(self))]
.filter { name in
checkIdentifier(identifier, refersTo: name, at: lookUpPosition) && !attributes.range.contains(lookUpPosition)
}
return defaultLookupImplementation(
identifier,
at: lookUpPosition,
with: config,
propagateToParent: false
)
+ canInterleaveLaterScope.lookupWithInterleavedResults(
identifier,
at: lookUpPosition,
with: config,
resultsToInterleave: implicitSelf.isEmpty ? [] : [.fromScope(self, withNames: implicitSelf)]
)
}
}
@_spi(Experimental) extension CatchClauseSyntax: ScopeSyntax {
/// Name introduced by the catch clause.
///
/// `defaultIntroducedNames` contains implicit `error` name if
/// no names are declared in catch items and they don't contain any expression patterns.
/// Otherwise, `defaultIntroducedNames` contains names introduced by the clause.
///
/// ### Example
/// ```swift
/// do {
/// // ...
/// } catch SomeError, .x(let a) {
/// // <-- lookup here, result: [a]
/// } catch .x(let a) {
/// // <-- lookup here, result: [a]
/// } catch SomeError {
/// // <-- lookup here, result: [empty]
/// } catch {
/// // <-- lookup here, result: implicit(error)
/// }
/// ```
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
var containsExpressionSyntax = false
let extractedNames = catchItems.flatMap { item in
guard let pattern = item.pattern else { return [LookupName]() }
if !containsExpressionSyntax && pattern.is(ExpressionPatternSyntax.self) {
containsExpressionSyntax = true
}
return LookupName.getNames(from: pattern)
}
return extractedNames.isEmpty && !containsExpressionSyntax ? [.implicit(.error(self))] : extractedNames
}
@_spi(Experimental) public var scopeDebugName: String {
"CatchClauseScope"
}
/// Returns results matching lookup. Includes names possibly introduced by this scope
/// if `lookupPosition` is either in body or one of the where clauses of catch items.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
if body.range.contains(lookUpPosition) || isLookupFromWhereClause(lookUpPosition) {
return defaultLookupImplementation(
identifier,
at: lookUpPosition,
with: config
)
} else {
return lookupInParent(
identifier,
at: lookUpPosition,
with: config
)
}
}
/// Returns `true` if `checkedPosition` is in one
/// of the catch items' where clauses and `false` otherwise.
func isLookupFromWhereClause(
_ checkedPosition: AbsolutePosition
) -> Bool {
catchItems.contains { item in
item.whereClause?.range.contains(checkedPosition) ?? false
}
}
}
@_spi(Experimental) extension SwitchCaseSyntax: SequentialScopeSyntax {
/// Names introduced within `case` items.
var namesFromLabel: [LookupName] {
label.as(SwitchCaseLabelSyntax.self)?.caseItems.flatMap { child in
if let exprPattern = child.pattern.as(ExpressionPatternSyntax.self) {
return LookupName.getNames(from: exprPattern.expression)
} else {
return LookupName.getNames(from: child.pattern)
}
} ?? []
}
/// Names introduced within `case` items
/// as well as sequential names from inside this case.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
statements.flatMap { codeBlockItem in
LookupName.getNames(from: codeBlockItem.item, accessibleAfter: codeBlockItem.endPosition)
} + namesFromLabel
}
@_spi(Experimental) public var scopeDebugName: String {
"SwitchCaseScope"
}
/// Returns results with names matching lookup.
/// Includes names introduced in it's label and sequentially
/// introduced names from inside this case.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
let filteredNamesFromLabel = namesFromLabel.filter { name in
checkIdentifier(identifier, refersTo: name, at: lookUpPosition)
}
if label.range.contains(lookUpPosition) {
return config.finishInSequentialScope ? [] : lookupInParent(identifier, at: lookUpPosition, with: config)
} else if config.finishInSequentialScope {
return sequentialLookup(
in: statements,
identifier,
at: lookUpPosition,
with: config,
propagateToParent: false
)
} else {
return sequentialLookup(
in: statements,
identifier,
at: lookUpPosition,
with: config,
propagateToParent: false
)
+ LookupResult.getResultArray(for: self, withNames: filteredNamesFromLabel)
+ lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
}
@_spi(Experimental) extension ProtocolDeclSyntax: ScopeSyntax, LookInMembersScopeSyntax {
/// Protocol declarations don't introduce names by themselves.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[.implicit(.Self(self))]
}
@_spi(Experimental) public var lookupMembersPosition: AbsolutePosition {
name.positionAfterSkippingLeadingTrivia
}
@_spi(Experimental) public var scopeDebugName: String {
"ProtocolDeclScope"
}
/// For the lookup initiated from inside primary
/// associated type clause, this function also finds
/// all associated type declarations made inside the
/// protocol member block.
///
/// ### Example
/// ```swift
/// class A {}
///
/// protocol Foo<A/*<-- lookup here>*/> {
/// associatedtype A
/// class A {}
/// }
/// ```
/// For the lookup started at the primary associated type `A`,
/// the function returns exactly two results. First associated with the member
/// block that consists of the `associatedtype A` declaration and
/// the latter one from the file scope and `class A` exactly in this order.
public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
var results: [LookupResult] = []
if let primaryAssociatedTypeClause,
primaryAssociatedTypeClause.range.contains(lookUpPosition)
{
results = memberBlock.lookupAssociatedTypeDeclarations(
identifier,
at: lookUpPosition,
with: config
)
}
let lookInMembers: [LookupResult]
if !(inheritanceClause?.range.contains(lookUpPosition) ?? false) {
lookInMembers = [.lookInMembers(self)]
} else {
lookInMembers = []
}
return results
+ defaultLookupImplementation(
identifier,
at: lookUpPosition,
with: config,
propagateToParent: false
) + lookInMembers + lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
@_spi(Experimental) extension GenericParameterClauseSyntax: GenericParameterScopeSyntax {
/// Generic parameter names introduced by this clause.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
parameters.children(viewMode: .fixedUp).flatMap { child in
LookupName.getNames(from: child)
}
}
@_spi(Experimental) public var scopeDebugName: String {
"GenericParameterClauseScope"
}
}
@_spi(Experimental) extension FunctionDeclSyntax: FunctionScopeSyntax {
@_spi(Experimental) public var scopeDebugName: String {
"FunctionDeclScope"
}
}
@_spi(Experimental) extension InitializerDeclSyntax: FunctionScopeSyntax {
@_spi(Experimental) public var scopeDebugName: String {
"InitializerDeclScope"
}
}
@_spi(Experimental) extension MacroDeclSyntax: WithGenericParametersScopeSyntax {
public var defaultIntroducedNames: [LookupName] {
signature.parameterClause.parameters.flatMap { parameter in
LookupName.getNames(from: parameter)
}
}
@_spi(Experimental) public var scopeDebugName: String {
"MacroDeclScope"
}
}
@_spi(Experimental)
extension SubscriptDeclSyntax: WithGenericParametersScopeSyntax, CanInterleaveResultsLaterScopeSyntax {
/// Parameters introduced by this subscript and possibly `self` keyword.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
let parameters = parameterClause.parameters.flatMap { parameter in
LookupName.getNames(from: parameter)
}
if let accessorBlock, case .getter = accessorBlock.accessors {
return parameters + [.implicit(.self(self))]
} else {
return parameters
}
}
@_spi(Experimental) public var scopeDebugName: String {
"SubscriptDeclScope"
}
/// Lookup results from this subscript scope.
/// Routes to generic parameter clause scope if exists.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
lookupWithInterleavedResults(
identifier,
at: lookUpPosition,
with: config,
resultsToInterleave: []
)
}
/// Lookup names in this scope and add `resultsToInterleave`
/// after results from this scope.
///
/// It's used to handle implicit `self` introduction
/// at the boundaries of accessors in this subscript.
/// ```swift
/// class X {
/// subscript(self: Int) -> Int {
/// get {
/// self // <-- lookup here
/// }
/// }
/// }
/// ```
/// In this case, the `self` reference references the `self`
/// function parameter which shadows implicit `self`
/// introduced at the boundary of the getter. That's why
/// this function needs to ensure the implicit `self` passed
/// from inside the accessor block is added after `subscript` parameters.
func lookupWithInterleavedResults(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig,
resultsToInterleave: [LookupResult]
) -> [LookupResult] {
var thisScopeResults: [LookupResult] = []
if accessorBlock?.range.contains(lookUpPosition) ?? false {
thisScopeResults = defaultLookupImplementation(
identifier,
at: position,
with: config,
propagateToParent: false
)
}
return thisScopeResults + resultsToInterleave
+ lookupThroughGenericParameterScope(
identifier,
at: lookUpPosition,
with: config
)
}
}
@_spi(Experimental) extension AccessorBlockSyntax: SequentialScopeSyntax, CanInterleaveResultsLaterScopeSyntax {
/// Names from the accessors or
/// getters of this accessor block scope.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
switch accessors {
case .getter(let codeBlockItems):
return codeBlockItems.flatMap { codeBlockItem in
LookupName.getNames(from: codeBlockItem.item)
}
case .accessors:
return []
}
}
@_spi(Experimental) public var scopeDebugName: String {
"AccessorBlockScope"
}
/// Names introduced in this accessir block scope.
/// If `accessor` is of `.getter` kind, introduced
/// it's items sequentially. Otherwise, propagate to parent.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
switch accessors {
case .getter(let codeBlockItems):
return sequentialLookup(in: codeBlockItems, identifier, at: lookUpPosition, with: config)
case .accessors:
return lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
/// Used by children accessors to interleave
/// their results with parent `subscript` declaration scope.
func lookupWithInterleavedResults(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig,
resultsToInterleave: [LookupResult]
) -> [LookupResult] {
guard let parentScope,
let canInterleaveLaterScope = Syntax(parentScope).asProtocol(SyntaxProtocol.self)
as? CanInterleaveResultsLaterScopeSyntax
else {
return lookupInParent(identifier, at: lookUpPosition, with: config)
}
return canInterleaveLaterScope.lookupWithInterleavedResults(
identifier,
at: lookUpPosition,
with: config,
resultsToInterleave: resultsToInterleave
)
}
}
@_spi(Experimental) extension TypeAliasDeclSyntax: WithGenericParametersScopeSyntax {
/// Type alias doesn't introduce any names to it's children.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"TypeAliasDeclScope"
}
}
@_spi(Experimental) extension VariableDeclSyntax: CanInterleaveResultsLaterScopeSyntax {
/// Variable decl scope doesn't introduce any
/// names unless it is a member and is looked
/// up from inside it's accessor block.
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"VariableDeclScope"
}
/// If a member and looked up from inside
/// it's accessor block, introduce implicit
/// `self` and propagate the lookup further.
@_spi(Experimental) public func lookup(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
if bindings.first?.accessorBlock?.range.contains(lookUpPosition) ?? false {
return defaultLookupImplementation(
in: (isMember ? [.implicit(.self(self))] : LookupName.getNames(from: self)),
identifier,
at: lookUpPosition,
with: config
)
} else {
return lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
/// If a member, introduce results passed in `resultsToInterleave`
/// and then pass lookup to the parent. Otherwise, perform `lookup`.
func lookupWithInterleavedResults(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig,
resultsToInterleave: [LookupResult]
) -> [LookupResult] {
guard isMember else {
return lookup(identifier, at: lookUpPosition, with: config)
}
return resultsToInterleave + lookupInParent(identifier, at: lookUpPosition, with: config)
}
}
@_spi(Experimental) extension DeinitializerDeclSyntax: ScopeSyntax {
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[.implicit(.self(self))]
}
@_spi(Experimental) public var scopeDebugName: String {
"DeinitializerScope"
}
}
@_spi(Experimental) extension IfConfigDeclSyntax: IntroducingToSequentialParentScopeSyntax, SequentialScopeSyntax {
/// Names from all clauses.
var namesIntroducedToSequentialParent: [LookupName] {
clauses.flatMap { clause in
clause.elements.flatMap { element in
LookupName.getNames(from: element, accessibleAfter: element.endPosition)
} ?? []
}
}
/// Performs sequential lookup in the active clause.
/// Active clause is determined by the `BuildConfiguration`
/// inside `config`. If not specified, defaults to the `#else` clause.
func lookupFromSequentialParent(
_ identifier: Identifier?,
at lookUpPosition: AbsolutePosition,
with config: LookupConfig
) -> [LookupResult] {
let clause: IfConfigClauseSyntax?
if let configuredRegions = config.configuredRegions {
clause = configuredRegions.activeClause(for: self)
} else {
clause =
clauses
.first { clause in
clause.poundKeyword.tokenKind == .poundElse
}
}
return sequentialLookup(
in: clause?.elements?.as(CodeBlockItemListSyntax.self) ?? [],
identifier,
at: lookUpPosition,
with: config,
ignoreNamedDecl: true,
propagateToParent: false
)
}
/// Returns all `NamedDeclSyntax` nodes in the active clause specified
/// by `BuildConfiguration` in `config` from bottom-most to top-most.
func getNamedDecls(for config: LookupConfig) -> [NamedDeclSyntax] {
let clause: IfConfigClauseSyntax?
if let configuredRegions = config.configuredRegions {
clause = configuredRegions.activeClause(for: self)
} else {
clause =
clauses
.first { clause in
clause.poundKeyword.tokenKind == .poundElse
}
}
guard let clauseElements = clause?.elements?.as(CodeBlockItemListSyntax.self) else { return [] }
var result: [NamedDeclSyntax] = []
for elem in clauseElements.reversed() {
if let namedDecl = elem.item.asProtocol(NamedDeclSyntax.self) {
result.append(namedDecl)
} else if let ifConfigDecl = elem.item.as(IfConfigDeclSyntax.self) {
result += ifConfigDecl.getNamedDecls(for: config)
}
}
return result
}
@_spi(Experimental) public var defaultIntroducedNames: [LookupName] {
[]
}
@_spi(Experimental) public var scopeDebugName: String {
"IfConfigScope"
}
}
|