Commit Graph

844 Commits

Author SHA1 Message Date
Hamish Knight
f8ab391737 Introduce type sugar for InlineArray (#80087)
* [CS] Decline to handle InlineArray in shrink

Previously we would try the contextual type `(<int>, <element>)`,
which is wrong. Given we want to eliminate shrink, let's just bail.

* [Sema] Sink `ValueMatchVisitor` into `applyUnboundGenericArguments`

Make sure it's called for sugar code paths too. Also let's just always
run it since it should be a pretty cheap check.

* [Sema] Diagnose passing integer to non-integer type parameter

This was previously missed, though would have been diagnosed later
as a requirement failure.

* [Parse] Split up `canParseType` 

While here, address the FIXME in `canParseTypeSimpleOrComposition`
and only check to see if we can parse a type-simple, including
`each`, `some`, and `any` for better recovery.

* Introduce type sugar for InlineArray

Parse e.g `[3 x Int]` as type sugar for InlineArray. Gated behind
an experimental feature flag for now.
2025-03-23 15:31:37 -07:00
Slava Pestov
34e7e824e9 Sema: Fix non-determinism with ConstraintSystem::ConstraintRestrictions
We iterate over the DenseMap and simplify both types appearing
in the key. If multiple keys simplify to the same type, later
keys overwrite earlier keys, so the outcome depends on hash
table order.

Fix this by introducing an arbitrary tie break: we prefer the
highest-numbered restriction.

Fixes rdar://146780049.
2025-03-17 14:35:10 -04:00
Pavel Yaskevich
1bd0cd7b94 Merge pull request #79928 from xedin/support-debug-constraints-on-line-for-result-builders
[ResultBuilders] NFC: Support `-debug-constraints{-on-line=}` for dec…
2025-03-12 00:29:41 -07:00
eeckstein
47b449372e Merge pull request #79917 from eeckstein/rename-opened-archetype-type
AST: rename OpenArchetypeType -> ExistentialArchetypeType
2025-03-12 06:01:10 +01:00
Slava Pestov
9e721a35f2 Merge pull request #79914 from slavapestov/retry-removing-one-way-equal
Sema: Mostly remove one-way constraints
2025-03-11 21:24:57 -04:00
Pavel Yaskevich
6197aab467 [ResultBuilders] NFC: Support -debug-constraints{-on-line=} for declaration transforms 2025-03-11 15:13:58 -07:00
Erik Eckstein
d225c47d25 AST: rename OpenArchetypeType -> ExistentialArchetypeType
NFC
2025-03-11 20:21:46 +01:00
Slava Pestov
6d8b55a9f6 Sema: Split up gatherConstraints() into gatherAllConstraints() and gatherNearbyConstraints()
The two GatherKinds no longer share any implementation, so there's
no point keeping the logic together. Doing this also allows removing
the acceptConstraintFn from gatherAllConstraints(), which further
simplifies depthFirstSearch().
2025-03-11 13:55:40 -04:00
Slava Pestov
ada6f77655 Sema: Track solver arena size in statistics 2025-03-10 14:03:05 -04:00
Doug Gregor
6a4d1a41c4 Prohibit isolated conformances with Sendable(Metatype) constraints
Within the constraint system, introduce a new kind of conformance constraint,
a "nonisolated conforms-to" constraint, which can only be satisfied by
nonisolated conformances. Introduce this constraint instead of the normal
conforms-to constraint whenever the subject type is a type parameter that
has either a `Sendable` or `SendableMetatype` constraint, i.e., when the type
or its values can escape the current isolation domain.
2025-03-01 08:19:42 -08:00
Hamish Knight
29e9f429e3 [CS] NFC: Rename PackEnvironments -> PackElementExpansions
IMO "environment" is confusable for GenericEnvironment,
make it clearer it's referring to the parent
PackExpansionExpr.
2025-02-20 21:31:46 +00:00
Slava Pestov
521ea46d15 Sema: Don't record constraints containing UnboundGenericType from shrink()
Something changed here between the removal of shrink() and it's
re-introduction, and we now record constraints that contain
UnboundGenericType, which crashes in matchTypes().

As a narrow workaround, let's just ignore the contextual type if
contains an UnboundGenericType.

Fixes rdar://145092838.
2025-02-19 13:27:33 -05:00
Pavel Yaskevich
725bd910be [ConstraintSystem] Revert new disjunction favoring algorithm (#79128)
* Revert "[CSOptimizer] Look through `OptionalEvaluationExpr`s when dealing with unapplied disjunctions"

This reverts commit 72340f39b8.

* Revert "[CSOptimizer] Don't consider disabled overloads when checking whether disjunction is supported"

This reverts commit 6bc23b5057.

* Revert "[CSOptimizer] Disjunctions with IUO overload choices are unsupported"

This reverts commit 471ee21535.

* Revert "[CSOptimizer] MemberImportVisibility: Don't consider overloads that come from implicit imports"

This reverts commit aa4a2b9071.

* Revert "[CSOptimizer] Don't consider CGFloat widening when explicit initializer is used"

This reverts commit 3cc76eacdd.

* Revert "[CSOptimizer] Literal arguments should cause score reset only for operators"

This reverts commit e3987beffb.

* Revert "[CSOptimizer] NFC: check whether a choice is of operator instead of whole disjunction"

This reverts commit 6c82892c3c.

* Revert "[CSOptimizer/Tests] NFC: Add a perf test-case fixed by improved literal array handling"

This reverts commit cfd34e54c4.

* Revert "[CSOptimizer] Extend candidate/parameter matching to support array literals"

This reverts commit 8a304f88c6.

* Revert "[CSOptimizer] Favor choices that don't require application"

This reverts commit 0737542da8.

* Revert "[CSOptimizer] Disable CGFloat -> Double conversion for unary operators"

This reverts commit bc3a15fbe6.

* Revert "[CSOptimizer] Mark bitwise operators as supported"

This reverts commit 860ae08d1b.

* Revert "[CSOptimizer] Simplify handling of non-applied disjunctions"

This reverts commit 43ca7dfff9.

* Revert "[ConstraintSystem] Fix `getEffectiveOverloadType` handling of `mutating` methods"

This reverts commit c767f7aff7.

* Revert "[CSOptimizer] Reduce overload types before ranking"

This reverts commit 95b47aead6.

* Revert "[CSOptimizer] Implement special prioritization rules for result builder contexts"

This reverts commit 56d6635e46.

* Revert "[CSOptimizer] Allow only widening CGFloat->Double conversions while matching candidate arguments"

This reverts commit bf8ae3bc1b.

* Revert "[CSSimplify] CGFloat-Double: Rank narrowing correctly when result is injected into an optional"

This reverts commit cb876cbd9e.

* Revert "[CSBindings] Prevent `BindingSet::isViable` from dropping viable bindings (v2)"

This reverts commit b7e7493076.

* Revert "[CSOptimizer] Add support for chained members without arguments"

This reverts commit 87cd5f8733.

* Revert "[CSOptimizer] Mark compiler synthesized disjunctions as optimized"

This reverts commit 867e64182f.

* Revert "[CSOptimizer] Make a light-weight generic overload check if some requirements are unsatisfiable"

This reverts commit 15c773b9d7.

* Revert "[CSOptimizer] Fix `selectDisjunction` to use favored choices even if disjunction was not optimized"

This reverts commit c2a55886f0.

* Revert "[CSOptimizer] Limit "old" behavior compatibility to unlabeled unary arguments"

This reverts commit 9fb73143f6.

* Revert "[Tests] NFC: Update a couple of type-checker tests"

This reverts commit ff8663ff16.

* Revert "[Tests] NFC: Move simd related test-case from `slow` to `fast`"

This reverts commit 28396a6dce.

* Revert "[CSGen] NFC: Remove obsolete `ConstraintSystem::{get, set}FavoredType`"

This reverts commit 8bd288447f.

* Revert "[CSOptimizer] Allow literal arguments to match parameters that conform to `ExpressibleBy{Integer, Float}Literal`"

This reverts commit 2fdd4b6c35.

* Revert "[CSOptimizer] Adjust `scoreCandidateMatch` to indicate when match cannot be decided"

This reverts commit 9b62c84a4f.

* Revert "[CSOptimizer] Fix Double<->CGFloat implicit conversion support when arguments are literals"

This reverts commit 6caf1ccbb2.

* Revert "[CSOptimizer] A more comprehensive generic overload checking when candidates are fully resolved"

This reverts commit e30587bda4.

* Revert "[CSOptimizer] Restore old hack behavior which used to favor overloads based on arity matches"

This reverts commit a3a3ec4fe0.

* Revert "[CSOptimizer] Desugar types before checking for equality"

This reverts commit 802f5cd105.

* Revert "[ConstraintSystem] Narrowly disable `tryOptimizeGenericDisjunction` when some of the arguments are number literals"

This reverts commit 8d5cb112ef.

* Revert "[CSOptimizer] Infer argument candidates from calls to `Double` and CGFloat constructors"

This reverts commit f2a6677a6d.

* Revert "[CSOptimizer] Score all of the overload choices matching on literals uniformly"

This reverts commit 59109c2d60.

* Revert "[CSOptimizer] Enable ranking of `Int*`, `Float{80}` and `Double` initializers"

This reverts commit 6fb6d1cf90.

* Revert "[CSOptimizer] Rank disjunctions based on score only if both sides are supported"

This reverts commit 8818d399f9.

* Revert "[CSOptimizer] Rank results of operators regardless of whether anything is known about parameters"

This reverts commit 3996b25fbd.

* Revert "[Tests] NFC: Add more test-cases that were previously solved due to old hacks behavior"

This reverts commit d0ff6c81b8.

* Revert "[CSOptimizer] Average score should reflect number of defaulted parameters"

This reverts commit 23589add74.

* Revert "[Tests] NFC: Adjust a couple of improved tests"

This reverts commit 66981364fe.

* Revert "[CSOptimizer] Don't optimize (implicit) calls with code completion arguments"

This reverts commit 8a918e2369.

* Revert "[CSOptimizer] attempt to rank only standard/simd operators and fully concrete overload sets"

This reverts commit deca9b61c5.

* Revert "[CSOptimizer] Record best scores for each disjunction and use them in `selectDisjunction`"

This reverts commit 3819ddfb40.

* Revert "[CSOptimizer] Let `determineBestChoicesInContext` return the best disjunction if one is available"

This reverts commit cf05405eae.

* Revert "[CSOptimizer] Emulate old behavior related to favoring of unary calls to members"

This reverts commit 527de22bec.

* Revert "[Tests] NFC: Add a test-case for rdar://133340307 which is now fast"

This reverts commit 670127abd6.

* Revert "[CSOptimizer] Prefer homogeneous arithmetic operator overloads when argument(s) or result match"

This reverts commit d69b6a0594.

* Revert "[CSOptimizer] Remove an outdated optimization to compare resolved argument types with all else equal"

This reverts commit 1760bd1f1e.

* Revert "[CSOptimizer] NFC: Switch from llvm::Optional to std::optional post-rebase"

This reverts commit c429f5b9ec.

* Revert "[CSOptimizer] Increase score when type matches opaque type"

This reverts commit 2869dff995.

* Revert "[CSOptimizer] NFC: Switch to llvm::Optional"

This reverts commit 0fc6806922.

* Revert "[CSOptimizer] NFC: Adjust conformance check to use `ConstraintSystem::lookupConformance`"

This reverts commit da65333d41.

* Revert "[CSOptimizer] Treat all type parameters equally"

This reverts commit 957a5f4270.

* Revert "[CSStep] Remove disjunction pruning logic from DisjunctionStep"

This reverts commit 2c44e37948.

* Revert "[CSOptimizer] Relax candidate type requirements from equality to set of no-impact conversions"

This reverts commit 11b897b32f.

* Revert "[CSOptimizer] Use `matchCallArguments` to establish argument-to-parameter relationships"

This reverts commit cb1cb2018d.

* Revert "[CSOptimizer] Don't attempt to optimize calls with code completion token(s) in argument position"

This reverts commit 14e2a16fce.

* Revert "[CSOptimizer] Allow generic operator overloads without associated type parameters"

This reverts commit bc5f70a9a3.

* Revert "[CSOptimizer] Make sure that all parameters without arguments are defaulted"

This reverts commit 7c1c46d4e4.

* Revert "[CSStep] Don't favor choices until the disjunction is picked"

This reverts commit e404ed722a.

* Revert "[CSOptimizer] Keep track of mismatches while evaluating candidates"

This reverts commit a094c3ebb0.

* Revert "[CSOptimizer] Favor SIMD related arithmetic operator choices if argument is SIMD<N> type"

This reverts commit c2f7451c7b.

* Revert "[CSOptimizer] Initial implementation of disjunction choice favoring algorithm"

This reverts commit 672ae3d252.

* Revert "[ConstraintSystem] Add skeleton of constraint optimizer"

This reverts commit b5f08a4009.

* Revert "[CSGen] Remove ConstraintOptimizer and all favoring logic"

This reverts commit 4432c51f57.

* Revert "[ConstraintSystem] Remove `shrink`"

This reverts commit 757ca24e8a.

* [TypeChecker] NFC: Remove resurrected use of `SolverShrinkUnsolvedThreshold`

* [TypeChecker] Bring back `SolverDisableShrink`

* [Tests] NFC: Mark tests affected by solver-perf revert as slow

* [Tests] NFC: Adjust async tests that are affected by performance hacks
2025-02-13 08:06:24 -08:00
Slava Pestov
99595e615e Revert "Sema: Split up gatherConstraints() into gatherAllConstraints() and gatherNearbyConstraints()"
This reverts commit 2230c3a17e.
2025-02-02 00:43:15 -05:00
Slava Pestov
4ae57acaa2 Sema: Remove ConstraintSystem::ImplicitValueConversions 2025-01-27 17:28:19 -05:00
Slava Pestov
2230c3a17e Sema: Split up gatherConstraints() into gatherAllConstraints() and gatherNearbyConstraints()
The two GatherKinds no longer share any implementation, so there's
no point keeping the logic together. Doing this also allows removing
the acceptConstraintFn from gatherAllConstraints(), which further
simplifies depthFirstSearch().
2025-01-27 10:27:00 -05:00
Slava Pestov
881c4f775b Sema: Ignore inactive type variables in addTypeVariableConstraintsToWorkList()
Fixes a regression from commit 0c128e5db7.

The old depthFirstSearch() walked all adjacencies via the constraint graph,
and thus it would visit type variables that are currently inactive because
we're solving a conjunction element.

This was inconsistent with the new union-find which only formed the
connected components from the currently active type variables; adjacencies
involving inactive type variables are no longer considered.

Fix the inconsistency by changing gatherConstraints(), which used from
addTypeVariableConstraintsToWorkList(), to also skip inactive type
variables.

Fixes rdar://problem/143340082.
2025-01-27 10:26:59 -05:00
Pavel Yaskevich
8d5cb112ef [ConstraintSystem] Narrowly disable tryOptimizeGenericDisjunction when some of the arguments are number literals
Don't attempt this optimization if call has number literals.
This is intended to narrowly fix situations like:

```swift
func test<T: FloatingPoint>(_: T) { ... }
func test<T: Numeric>(_: T) { ... }

test(42)
```

The call should use `<T: Numeric>` overload even though the
`<T: FloatingPoint>` is a more specialized version because
selecting `<T: Numeric>` doesn't introduce non-default literal
types.
2024-12-17 11:36:40 -08:00
Pavel Yaskevich
672ae3d252 [CSOptimizer] Initial implementation of disjunction choice favoring algorithm
This algorithm attempts to ensure that the solver always picks a disjunction
it knows the most about given the previously deduced type information.

For example in chains of operators like: `let _: (Double) -> Void = { 1 * 2 + $0 - 5 }`

The solver is going to start from `2 + $0` because `$0` is known to be `Double` and
then proceed to `1 * ...` and only after that to `... - 5`.

The algorithm is pretty simple:

- Collect "candidate" types for each argument
  - If argument is bound then the set going to be represented by just one type
  - Otherwise:
    - Collect all the possible bindings
    - Add default literal type (if any)

- Collect "candidate" types for result

- For each disjunction in the current scope:
  - Compute a favoring score for each viable* overload choice:
    - Compute score for each parameter:
      - Match parameter flags to argument flags
      - Match parameter types to a set of candidate argument types
        - If it's an exact match
          - Concrete type: score = 1.0
          - Literal default: score = 0.3
        - Highest scored candidate type wins.
      - If none of the candidates match and they are all non-literal
        remove overload choice from consideration.

    - Average the score by dividing it by the number of parameters
      to avoid disfavoring disjunctions with fewer arguments.

    - Match result type to a set of candidates; add 1 to the score
      if one of the candidate types matches exactly.

  - The best choice score becomes a disjunction score

- Compute disjunction scores for all of the disjunctions in scope.

- Pick disjunction with the best overall score and favor choices with
  the best local candidate scores (if some candidates have equal scores).

- Viable overloads include:
  - non-disfavored
  - non-disabled
  - available
  - non-generic (with current exception to SIMD)
2024-12-17 11:36:38 -08:00
Pavel Yaskevich
b5f08a4009 [ConstraintSystem] Add skeleton of constraint optimizer 2024-12-17 11:36:38 -08:00
Pavel Yaskevich
757ca24e8a [ConstraintSystem] Remove shrink 2024-12-17 11:36:37 -08:00
Slava Pestov
25252cd683 Merge pull request #77728 from slavapestov/cg-cleanup
Sema: Small ConstraintGraph cleanup
2024-11-20 19:43:42 -05:00
Slava Pestov
7fef225c9f Sema: Allow turning off expression timer with -solver-expression-time-threshold=0 2024-11-20 13:46:19 -05:00
Slava Pestov
c8415aeac4 Sema: Record the trail step count in solver statistics
Also introduce two new frontend flags:

The -solver-scope-threshold flag sets the maximum number of scopes, which was
previously hardcoded to 1 million.

The -solver-trail-threshold flag sets the maximum number of trail steps,
which defaults to 64 million.
2024-11-20 13:46:19 -05:00
Slava Pestov
6ff8f55634 Sema: Fix handling of Solution::typeBindings in replaySolution() 2024-11-20 13:35:21 -05:00
Slava Pestov
f702e46751 Merge pull request #77475 from slavapestov/fix-rdar139237781
Sema: Fix handling of appliedPropertyWrappers in ConstraintSystem::replaySolution()
2024-11-08 15:15:27 -05:00
Slava Pestov
d67e89d89c Sema: Fix handling of appliedPropertyWrappers in ConstraintSystem::replaySolution()
When we replay a solution, we must record changes in the trail, so fix the
logic to do that. This fixes the first assertion failure with this test case.

The test case also exposed a second issue. We synthesize a CustomAttr in
applySolutionToClosurePropertyWrappers() with a type returned by simplifyType().
Eventually, CustomAttrNominalRequest::evaluate() looks at this type, and passes
it to directReferencesForType(). Unfortunately, this entry point does not
understand type aliases whose underlying type is a type parameter.
However, directReferencesForType() is the wrong thing to use here, and we
can just call getAnyNominal() instead.

Fixes rdar://139237781.
2024-11-08 10:46:07 -05:00
Pavel Yaskevich
392dac41f1 [CSSolver] DynamicMemberLookup: Ignore disabled choices while filtering disjunctions
`filterDisjunction` should ignore the choices that are already
disabled while attempting to optimize disjunctions related to
dynamic member lookup.

Resolves: rdar://139314763
2024-11-07 18:31:52 -08:00
Doug Gregor
720429daf4 [Constraint solver] Disable fallback diagnostic when error emitted into a transaction
When we are using diagnostic transactions to disable immediate emission
of diagnostics, `DiagnosticEngine::hadAnyError()` no longer accurately
reports whether an error occurred. Thread the DiagnosticTransaction
into the ConstraintSystem so we can also check whether it contains an
error before emitting the fallback diagnostic.

Fixes rdar://128272346.
2024-11-06 17:07:13 -08:00
Slava Pestov
38fe0696a4 Sema: Factor out clearScore() and replayScore() 2024-10-09 11:48:07 -04:00
Slava Pestov
c8db9f55e6 Sema: Remove last heap allocation of Scope 2024-10-09 11:48:07 -04:00
Slava Pestov
0b85ce6f00 Sema: Remove SolverScope::numFixes 2024-10-08 16:57:49 -04:00
Slava Pestov
5fdc1a81b8 Sema: Record retired constraints in the trail 2024-10-08 16:39:34 -04:00
Slava Pestov
90175400d2 Sema: Record generated constraints in the trail 2024-10-08 16:17:28 -04:00
Slava Pestov
1e2d4fbc59 Sema: Record score increases in the trail 2024-10-08 16:16:31 -04:00
Slava Pestov
877c60e3d0 Sema: Rename applySolution() to replaySolution() 2024-10-08 16:16:01 -04:00
Slava Pestov
4a82d384b7 Sema: Record synthesized conformances in the trail 2024-10-07 16:50:49 -04:00
Slava Pestov
12eb7cec26 Sema: Record implicit callAsFunction() roots in the trail 2024-10-07 16:50:49 -04:00
Slava Pestov
72a60728fc Sema: Record argument lists in the trail 2024-10-07 16:50:49 -04:00
Slava Pestov
f2412f318e Sema: Record key path expressions in the trail 2024-10-07 16:50:48 -04:00
Slava Pestov
881a0100b2 Sema: Record implicit value conversions in the trail 2024-10-07 16:50:48 -04:00
Slava Pestov
ac17292dfe Sema: Record preconcurrency closures in the trail 2024-10-07 16:50:48 -04:00
Slava Pestov
b961a7ec51 Sema: Record isolated parameters in the trail 2024-10-07 16:50:48 -04:00
Slava Pestov
1d177d0187 Sema: Record expression patterns in the trail 2024-10-07 16:50:48 -04:00
Slava Pestov
500acd122a Sema: Record potential throw sites in the trail 2024-10-07 16:50:47 -04:00
Slava Pestov
39d0eab275 Sema: Record case label items in the trail 2024-10-07 16:50:47 -04:00
Slava Pestov
8c8a385a4a Sema: Record SyntacticElementTargetKeys in the trail 2024-10-07 16:50:47 -04:00
Slava Pestov
516277f0fd Sema: Record contextual types in the trail 2024-10-07 16:50:47 -04:00
Slava Pestov
666361adf2 Sema: Record implied results in the trail 2024-10-07 16:50:47 -04:00
Slava Pestov
1d18cd07cf Sema: Record closure types in the trail 2024-10-07 16:50:47 -04:00