Commit Graph

1366 Commits

Author SHA1 Message Date
Rintaro Ishizaki
bd4f20dd5f [CodeCompletion][NFC] Move collectArgumentExpectation()
These functions are only used by CodeCompletionTypeContextAnalyzer.
Move them into it.
2018-11-26 20:06:38 +09:00
Rintaro Ishizaki
5df5711b67 [CodeCompletion] Rework getOperatorCompletions() (#20632)
In postfix completion, for operator completion, we do:

  1. Type check the operand without applying it, but set the resolved
     type to the root of the expression.
  2. For each possible operators:
      i. Build temporary binary/postfix expression
      ii. Perform type checking to see whether the operator is applicable 

This could be very slow especially if the operand is complex.

* Introduce `ReusePrecheckedType` option to constraint system. With
  this option, CSGen respects pre-stored types in expressions and doesn't
  take its sub-expressions into account.
  * Improve type checking performance because type variables aren't
     generated for sub-expressions of LHS (45511835)
  * Guarantee that the operand is not modified by the type checker because
     expression walkers in `CSGen` doesn't walk into the operand.

* Introduce `TypeChecker::findLHS()` to find LHS for a infix operator from
  pre-folded expression. We used to `foldSequence()` temporary
  `SequenceExpr` and find 'CodeCompletionExpr' for each attempt.
  * No need to flatten folded expression after initial type-checking.
  * Save memory of temporary `BinaryExpr` which used to be allocated by
    `foldSequence()`.
  * Improve accuracy of the completion. `foldSequence()` recovers invalid
    combination of operators by `left` associative manner (with
    diagnostics). This used to cause false-positive results. For instance,
    `a == b <HERE>` used to suggest `==` operator. `findLHS()` returns
    `nullptr` for such invalid combination.

rdar://problem/45511835
https://bugs.swift.org/browse/SR-9061
2018-11-22 21:20:51 +09:00
Arnold Schwaighofer
2ac6cda9a7 Make sure the code completion takes both private imports and testable
imports into account separately.
2018-11-12 14:53:56 -08:00
Pavel Yaskevich
b3f86259a8 [CodeCompletion] Add isAutoClosure flag to parameter builder 2018-11-10 11:59:28 -08:00
Arnold Schwaighofer
6cc3d377ff Refactor part2 2018-11-08 18:16:17 -08:00
Rintaro Ishizaki
8d1dca822e [CodeCompletion] Revert: "Restrict ancestor search to brace"
(part of 63356a2f48)

NFC because `ParentFarthest` result isn't used from anywhere.
2018-11-05 17:33:36 +09:00
Brent Royal-Gordon
9bd1a26089 Implementation for SE-0228: Fix ExpressibleByStringInterpolation (#20214)
* [CodeCompletion] Restrict ancestor search to brace

This change allows ExprParentFinder to restrict certain searches for parents to just AST nodes within the nearest surrounding BraceStmt. In the string interpolation rework, BraceStmts can appear in new places in the AST; this keeps code completion from looking at irrelevant context.

NFC in this commit, but keeps code completion from crashing once TapExpr is introduced.

* Remove test relying on ExpressibleByStringInterpolation being deprecated

Since soon enough, it won’t be anymore.

* [AST] Introduce TapExpr

TapExpr allows a block of code to to be inserted between two expressions, accessing and potentially mutating the result of its subexpression before giving it to its parent expression. It’s roughly equivalent to this function:

  func _tap<T>(_ value: T, do body: (inout T) throws -> Void) rethrows -> T {
    var copy = value
    try body(&copy)
    return copy
  }

Except that it doesn’t use a closure, so no variables are captured and no call frame is (even notionally) added.

This commit does not include tests because nothing in it actually uses TapExpr yet. It will be used by string interpolation.

* SE-0228: Fix ExpressibleByStringInterpolation

This is the bulk of the implementation of the string interpolation rework. It includes a redesigned AST node, new parsing logic, new constraints and post-typechecking code generation, and new standard library types and members.

* [Sema] Rip out typeCheckExpressionShallow()

With new string interpolation in place, it is no longer used by anything in the compiler.

* [Sema] Diagnose invalid StringInterpolationProtocols

StringInterpolationProtocol informally requires conforming types to provide at least one method with the base name “appendInterpolation” with no (or a discardable) return value and visibility at least as broad as the conforming type’s. This change diagnoses an error when a conforming type does not have a method that meets those criteria.

* [Stdlib] Fix map(String.init) source break

Some users, including some in the source compatibility suite, accidentally used init(stringInterpolationSegment:) by writing code like `map(String.init)`. Now that these intializers have been removed, the remaining initializers often end up tying during overload resolution. This change adds several overloads of `String.init(describing:)` which will break these ties in cases where the compiler previously selected `String.init(stringInterpolationSegment:)`.

* [Sema] Make callWitness() take non-mutable arrays

It doesn’t actually need to mutate them.

* [Stdlib] Improve floating-point interpolation performance

This change avoids constructing a String when interpolating a Float, Double, or Float80. Instead, we write the characters to a fixed-size buffer and then append them directly to the string’s storage.

This seems to improve performance for all three types, but especially for Double and Float80, which cannot always fit into a small string when stringified.

* [NameLookup] Improve MemberLookupTable invalidation

In rare cases usually involving generated code, an overload added by an extension in the middle of a file would not be visible below it if the type had lazy members and the same base name had already been referenced above the extension. This change essentially dirties a type’s member lookup table whenever an extension is added to it, ensuring the entries in it will be updated.

This change also includes some debugging improvements for NameLookup.

* [SILOptimizer] XFAIL dead object removal failure

The DeadObjectRemoval pass in SILOptimizer does not currently remove reworked string interpolations as well as the old design because their effects cannot be described by @_effects(readonly). That causes a test failure on Linux. This change temporarily silences that test. The SILOptimizer issue has been filed as SR-9008.

* Confess string interpolation’s source stability sins

* [Parser] Parse empty interpolations

Previously, the parser had an odd asymmetry which caused the same function to accept foo(), but reject “\()”. This change fixes the issue.

Already tested by test/Parse/try.swift, which uses this construct in one of its throwing interpolation tests.

* [Sema] Fix batch-mode-only lazy var bug

The temporary variable used by string interpolation needs to be recontextualized when it’s inserted into a synthesized getter. Fixes a compilation failure in Alamofire.

I’ll probably follow up on this bug a bit more after merging.
2018-11-02 19:16:03 -07:00
Rintaro Ishizaki
9df8b2f2a6 [CodeCompletion] Preserve completion status in 'let' pattern
Also, stop context type analysis at outer most expression that matches
the position. It seems that that produces more appropriate results.

rdar://problem/30103287
2018-10-30 19:14:03 +09:00
Rintaro Ishizaki
74356d655c [CodeCompletion] Implement context type analysis at subscript position
This improves completion for index part of subscript expression.

rdar://problem/38920581
2018-10-30 10:58:32 +09:00
Rintaro Ishizaki
c84ea2b281 [CodeCompletion] Improve context type analysis for overloaded method
For:

    class MyClass {
        func foo(x: SomeType)
        func foo(x: OtherType)
    }

    func test(obj: MyClass) {
        obj.foo(x: <HERE>)
    }

Type checker doesn't keep overloaded choices for 'obj.foo' in the AST
after typechecking. Code completion need to lookup members to collect
possible parameter types.
2018-10-30 09:02:00 +09:00
Rintaro Ishizaki
b0c8fc5709 Merge pull request #19953 from rintaro/ide-completion-unresolvemember-polish
[CodeCompletion] Polish unresolved member completion
2018-10-23 08:16:27 +09:00
Rintaro Ishizaki
04aba4465b [CodeCompletion] Don't emit member type construction for the same type
in unresolved member completion. e.g.

  struct Node {
    typealias Child = Node
    init(children: [Child]) {}
  }
  let node: Node = .#^COMPLETE^#

This used to emit `.init(children:)` and `.Child(children:)`.
2018-10-19 19:21:39 +09:00
Rintaro Ishizaki
54f2aa3147 [CodeCompletion] Tiny optimization for unresolved member compilation
* Early exit for operators
* Early exit for equal types
2018-10-19 19:21:39 +09:00
Rintaro Ishizaki
459e07fc73 [CodeCompletion] Don't emit failable initialization for member types
in unresolved member completion.
2018-10-19 19:21:39 +09:00
Rintaro Ishizaki
90fe0a7e86 [CodeCompletion] Implement completion for 'get', 'set', 'willSet', 'didSet'
Implement 'get', 'set', 'willSet', 'didSet' completion at the beginning
of accessor position.

  var value: Ty {
    <HERE> // 'get', 'set', 'willSet' and 'didSet' along with normal
           // completion.
  }

  var value: Ty {
    get { return ... }
    <HERE> // 'get', 'set', 'willSet' and 'didSet' only.
  }

rdar://problem/20957182
2018-10-19 14:28:56 +09:00
Rintaro Ishizaki
b1ae8efd77 [CodeCompletion] Enable case enum pattern completion in top level
rdar://problem/21001526
2018-10-12 16:56:52 +09:00
Rintaro Ishizaki
8d37c79ed6 Merge pull request #17649 from AnthonyLatsis/code-compl-precedencegroups
[Parse][CodeCompletion] Completions for precedencegroup decls
2018-10-11 15:45:17 +09:00
Doug Gregor
264b680e96 Merge branch 'master' into immortal-type-checker 2018-10-10 20:36:23 -07:00
Doug Gregor
599e07e5d9 [Type checker] Keep the type checker alive as long as the ASTContext is.
It is possible for the SIL optimizers, IRGen, etc. to request information
from the AST that only the type checker can provide, but the type checker
is typically torn down after the “type checking” phase. This can lead to
various crashes late in the compilation cycle.

Keep the type checker instance around as long as the ASTContext is alive
or until someone asks for it to be destroyed.

Fixes SR-285 / rdar://problem/23677338.
2018-10-10 16:44:42 -07:00
Anthony Latsis
f2ff87e652 Merge branch 'master' into code-compl-precedencegroups 2018-10-09 18:08:16 +03:00
Rintaro Ishizaki
f5f4fa6d15 [CodeCompletion] Handle TupleShuffleExpr in completion context analyzer
(and TupleExpr at non-call argument position).
Now, unresolved member completion in array literal should work.

Also, Don't calculate convertibility to 'Any' type. That would be a
noise to type relation because anything is convertible to 'Any'.

rdar://problem/43302814
2018-10-09 20:41:40 +09:00
Rintaro Ishizaki
3d80635cf4 [CodeCompletion] Fix completion for local decls in trailing closure
Previously, local decls in trailing closure didn't show up if the
closure had preceding arguments and the completion was triggered at
beginning position of expression context. like:

   funcName(x: arg1) {
      var localVar = 12
      if <HERE>
   }

The completion mode used to be overwritten in 'completeCallArg()' which
is called from 'parseExprCallSuffix(). We should detect completion for
immediate argument position in 'parseExprList()'.

rdar://problem/41869885
2018-10-04 16:56:07 +09:00
fischertony
d2e7c785bb Create utility function for Associativity spelling 2018-10-04 00:38:20 +03:00
fischertony
e505d417fa [Parse][CodeCompletion] Completions for precedencegroup decls
Added the 'Module::getPrecedenceGroups' API to separate precedence group lookup
from 'Module::lookupVisibleDecls', which together with 'FileUnit::lookupVisibleDecls',
to which the former is forwarded, are expected to look up only 'ValueDecl'. In particular, this
prevents completions like Module.PrecedenceGroup.
2018-10-03 22:12:20 +03:00
Rintaro Ishizaki
e5d8113eee [CodeCompletion] Pre-remove argument labels from function types
Before checking type relation between candidate types and expected
types. In normal compilation, this removal is done in CSGen. However,
since code-completion directly uses Constraint System, we have to
manually remove argument labels before checking convertibility.

We can remove argument labels unconditionally because function types as
as value cannot have argument labels. (i.e. `let f: (a: Int) -> Int` is
illegal). That means, expected types shouldn't have any argument labels.

This fixes regression revealed in 5e75b1ad3b
rdar://problem/41496748
2018-10-01 17:31:20 +09:00
Rintaro Ishizaki
f40c3b19c8 [CodeCompletion] Improve accuracy of unresolved member completion
* Handle generic base types
* Suggest '.some' and '.none' for optional types
* Don't look through too many parameter lists for function types
* Include members with convertible type result

rdar://problem/44803439
2018-09-28 15:36:11 +09:00
Ben Langmuir
cad921d2fd Merge pull request #19567 from benlangmuir/complete-unresolved-optional
[codecomplete] Fix unresolved member completion for T within Optional<T>
2018-09-27 08:51:59 -07:00
Ben Langmuir
4deb2d6de3 [codecomplete] Fix unresolved member completion for T within Optional<T>
We need to look through the optional and find the members of T when
doing completion in Optional<T>.

let x: Foo? = .foo

We still don't correctly complete .some/.none, which requires
reconciling the unbound generic type we get from the decl with the real
bound generic type.

rdar://44767478
2018-09-26 11:52:48 -07:00
Slava Pestov
3b60ae153d AST: Rename AnyFunctionType::Param::getType() to getOldType() 2018-09-26 11:05:23 -07:00
Michael Gottesman
c62f31f5dc Inject llvm::SmallBitVector into namespace swift;
I also eliminated all llvm:: before SmallBitVector in the code base.
2018-09-21 09:49:25 -07:00
Slava Pestov
e520dd613b IDE: Remove hasAccess() checks 2018-09-05 16:51:42 -07:00
Harlan
dc1bc823e6 [InterfaceGen] Remove #ifs from default arguments (#19075)
* [InterfaceGen] Remove #ifs from default args

This patch removes all #if configs form the bodies of default arguments,
which can contain multiline closures, while preserving the bodies of the
clauses that are active.

This code is generalized and should "just work" for inlinable function
bodies, which will come in a later patch.

* Address review comments

* Fix and test CharSourceRange.overlaps

* Fix CharSourceRange::print to respect half-open ranges
2018-08-31 20:18:48 -07:00
Rintaro Ishizaki
4797a7caf6 Merge pull request #18919 from rintaro/ide-complete-pound
[CodeCompletion] Implement completion for # directives
2018-08-31 10:50:40 +09:00
Rintaro Ishizaki
de0599a11b Merge pull request #18884 from rintaro/ide-complete-keypath
[CodeCompletion] Improve completion for Swift keypath expression
2018-08-31 09:44:28 +09:00
Brent Royal-Gordon
9893c392ec [IDE] Correct uninitialized boolean
CompletionLookup::IsStaticMetatype was not explicitly initialized during construction, so it could sometimes have garbage values. This caused UBSan to error out on IDE/complete_enum_elements.swift and IDE/complete_unresolved_members.swift.
2018-08-29 22:53:40 -07:00
Rintaro Ishizaki
deb4aa84e0 [CodeCompletion] Add completion for platform condition
* 'true'/'false' keyword
* 'os(<name>)', 'canImport(<module>)' etc.
* Custom flags specified with '-D'

rdar://problem/19572779
2018-08-24 12:24:54 +09:00
Rintaro Ishizaki
5ef5f5ed84 [CodeCompletion] Implement completion for # directives
rdar://problem/29976235
2018-08-24 12:24:54 +09:00
Rintaro Ishizaki
bce3326840 [CodeCompletion] Rename completeAfterPound() to completeAfterPoundExpr()
Also, `CompletionKind::AfterPound` to `CompletionKind::AfterPoundExpr`.
2018-08-24 11:12:48 +09:00
Rintaro Ishizaki
2052d4bc83 [CodeCompleiton] Enable after '#' completion in arbitrary expr position
Previously, it's enabled only at stmt condition position.
2018-08-24 11:12:48 +09:00
Rintaro Ishizaki
814476ad98 [CodeCompletion] Rename CompletionKind::SwiftKeyPath to KeyPathExprSwift 2018-08-22 11:08:53 +09:00
Rintaro Ishizaki
1ac6afb3cf [CodeCompletion] Improve completion for Swift keypath expression
* Handle completion in 'parseExprKeyPath()' instead of
  'parseExprPostfixSuffix()'.
* Fix a crash for implicit type keypath. e.g. '\.path.<complete>'. (SR-8042).
* Use 'completeExprKeyPath()' callback.
* Implement completion without '.'. e.g. '\Ty.path<complete>'
* Improved handling for 'subscript' in completion.
* Improved handling for optional unwrapping in completion.

https://bugs.swift.org/browse/SR-8042
rdar://problem/41262612
2018-08-22 11:08:53 +09:00
Rintaro Ishizaki
8467203b9e [CodeCompletion][NFC] Tweak completion for ObjC keyPath expression
* Consolidate CompletionKind::KeyPathExpr and CompletionKind::KeyPathExprDot
  to CompletionKind::KeyPathExprObjC
* Make completeKeyPath() to receive DotLoc.
2018-08-22 11:08:53 +09:00
Rintaro Ishizaki
36ee937412 Merge pull request #18786 from rintaro/parse-istypecontext
[Parse] Don't use getAsNominalTypeOrNominalTypeExtensionContext in Parse
2018-08-18 15:41:07 +09:00
Rintaro Ishizaki
32da3c3cf2 Merge pull request #18787 from rintaro/ide-complete-declintro
[CodeCompletion] Don't suggest keywords after decl introducer
2018-08-18 15:17:27 +09:00
Rintaro Ishizaki
682fc12c39 [Parse] Don't use getAsNominalTypeOrNominalTypeExtensionContext in Parse
`getAsNominalTypeOrNominalTypeExtensionContext()` requires fully parsed
AST. Use `isTypeContext()` instead.

https://bugs.swift.org/browse/SR-8554
rdar://problem/43394866
2018-08-18 12:48:13 +09:00
Jordan Rose
537954fb93 [AST] Rename several DeclContext methods to be clearer and shorter (#18798)
- getAsDeclOrDeclExtensionContext -> getAsDecl

This is basically the same as a dyn_cast, so it should use a 'getAs'
name like TypeBase does.

- getAsNominalTypeOrNominalTypeExtensionContext -> getSelfNominalTypeDecl
- getAsClassOrClassExtensionContext -> getSelfClassDecl
- getAsEnumOrEnumExtensionContext -> getSelfEnumDecl
- getAsStructOrStructExtensionContext -> getSelfStructDecl
- getAsProtocolOrProtocolExtensionContext -> getSelfProtocolDecl
- getAsTypeOrTypeExtensionContext -> getSelfTypeDecl (private)

These do /not/ return some form of 'this'; instead, they get the
extended types when 'this' is an extension. They started off life with
'is' names, which makes sense, but changed to this at some point.  The
names I went with match up with getSelfInterfaceType and
getSelfTypeInContext, even though strictly speaking they're closer to
what getDeclaredInterfaceType does. But it didn't seem right to claim
that an extension "declares" the ClassDecl here.

- getAsProtocolExtensionContext -> getExtendedProtocolDecl

Like the above, this didn't return the ExtensionDecl; it returned its
extended type.

This entire commit is a mechanical change: find-and-replace, followed
by manual reformatted but no code changes.
2018-08-17 14:05:24 -07:00
Rintaro Ishizaki
70fba3f38d [CodeCompletion] Don't suggest keywords after decl introducer
If any decl introducers (e.g. 'func', 'let', 'typealias', etc.) are
included in parsed keywords, don't emit any keywords in completion.
2018-08-17 19:54:31 +09:00
Rintaro Ishizaki
5753e122cf Merge pull request #18721 from rintaro/ide-rdar41224316
[CodeCompletion] Remove unresolved type in prepareForRetypechecking()
2018-08-16 15:46:51 +09:00
Rintaro Ishizaki
c68157a27d [CodeCompletion] Remove unresolved type in prepareForRetypechecking()
Unresolved type attached to expressions may fail re-typechecking.
Also, disallow unresolved type in typeCheckCompletionSequence(). It doesn't
provide useful completions to developers.

rdar://problem/41224316
2018-08-15 20:39:12 +09:00
Doug Gregor
58d60e268f [Code completion] Delete redundant code handling declarations.
A significant chunk of the handling for LookupKind::ValueExpr
was duplicated in the handling for the ValueInDeclContext and
ImportFromModule cases. Use a fall through to unify the
code paths here.
2018-08-14 08:31:01 -07:00