1{-# OPTIONS_GHC -Wall #-}
2{-# LANGUAGE OverloadedStrings #-}
10import qualified Data.Map.Strict as Map
11import Data.Map.Strict ((!))
12import qualified Data.Vector as Vector
13import qualified Data.Vector.Mutable as MVector
15import qualified AST.Canonical as Can
16import qualified Elm.Name as N
17import qualified Reporting.Annotation as A
18import qualified Reporting.Error.Type as Error
19import qualified Type.Occurs as Occurs
20import Type.Constraint as Con
21import Type.Type as Type
22import qualified Type.Unify as Unify
23import qualified Type.UnionFind as UF
30run :: Constraint -> IO (Either [Error.Error] (Map.Map N.Name Can.Annotation))
32 do pools <- MVector.replicate 8 []
34 (State env _ errors) <-
35 solve Map.empty outermostRank pools emptyState constraint
39 Right <$> traverse Type.toAnnotation env
46{-# NOINLINE emptyState #-}
49 State Map.empty (nextMark noMark) []
57 Map.Map N.Name Variable
61 MVector.IOVector [Variable]
68 , _errors :: [Error.Error]
72solve :: Env -> Int -> Pools -> State -> Constraint -> IO State
73solve env rank pools state constraint =
78 CSaveTheEnvironment ->
79 return (state { _env = env })
81 CEqual region category tipe expectation ->
82 do actual <- typeToVariable rank pools tipe
83 expected <- expectedToVariable rank pools expectation
84 answer <- Unify.unify actual expected
87 do introduce rank pools vars
90 Unify.Err vars actualType expectedType ->
91 do introduce rank pools vars
92 return $ addError state $
94 (Error.BadExpr region category actualType)
95 (Con.typeReplace expectation expectedType)
97 CLocal region name expectation ->
98 do actual <- makeCopy rank pools (env ! name)
99 expected <- expectedToVariable rank pools expectation
100 answer <- Unify.unify actual expected
103 do introduce rank pools vars
106 Unify.Err vars actualType expectedType ->
107 do introduce rank pools vars
108 return $ addError state $
110 (Error.BadLocal region name actualType)
111 (Con.typeReplace expectation expectedType)
113 CForeign region name (Can.Forall freeVars srcType) expectation ->
114 do actual <- srcTypeToVariable rank pools freeVars srcType
115 expected <- expectedToVariable rank pools expectation
116 answer <- Unify.unify actual expected
119 do introduce rank pools vars
122 Unify.Err vars actualType expectedType ->
123 do introduce rank pools vars
124 return $ addError state $
126 (Error.BadForeign region name actualType)
127 (Con.typeReplace expectation expectedType)
129 CPattern region category tipe expectation ->
130 do actual <- typeToVariable rank pools tipe
131 expected <- patternExpectationToVariable rank pools expectation
132 answer <- Unify.unify actual expected
135 do introduce rank pools vars
138 Unify.Err vars actualType expectedType ->
139 do introduce rank pools vars
140 return $ addError state $
141 Error.BadPattern region category actualType
142 (Con.ptypeReplace expectation expectedType)
145 foldM (solve env rank pools) state constraints
147 CBranch a b eqCon makeNotEqCon ->
148 do aVar <- typeToVariable rank pools a
149 bVar <- typeToVariable rank pools b
150 answer <- Unify.unify aVar bVar
153 do introduce rank pools vars
154 solve env rank pools state eqCon
156 Unify.Err vars _ _ ->
157 do introduce rank pools vars
158 solve env rank pools state =<< makeNotEqCon
160 CLet [] flexs _ headerCon CTrue ->
161 do introduce rank pools flexs
162 solve env rank pools state headerCon
164 CLet [] [] header headerCon subCon ->
165 do state1 <- solve env rank pools state headerCon
166 locals <- traverse (A.traverse (typeToVariable rank pools)) header
167 let newEnv = Map.union env (Map.map A.toValue locals)
168 state2 <- solve newEnv rank pools state1 subCon
169 foldM occurs state2 $ Map.toList locals
171 CLet rigids flexs header headerCon subCon ->
173 -- work in the next pool to localize header
174 let nextRank = rank + 1
175 let poolsLength = MVector.length pools
177 if nextRank < poolsLength
179 else MVector.grow pools poolsLength
181 -- introduce variables
182 let vars = rigids ++ flexs
184 UF.modify var $ \(Descriptor content _ mark copy) ->
185 Descriptor content nextRank mark copy
186 MVector.write nextPools nextRank vars
188 -- run solver in next pool
189 locals <- traverse (A.traverse (typeToVariable nextRank nextPools)) header
190 (State savedEnv mark errors) <-
191 solve env nextRank nextPools state headerCon
194 let visitMark = nextMark youngMark
195 let finalMark = nextMark visitMark
198 generalize youngMark visitMark nextRank nextPools
199 MVector.write nextPools nextRank []
201 -- check that things went well
202 mapM_ isGeneric rigids
204 let newEnv = Map.union env (Map.map A.toValue locals)
205 let tempState = State savedEnv finalMark errors
206 newState <- solve newEnv rank nextPools tempState subCon
208 foldM occurs newState (Map.toList locals)
211-- Check that a variable has rank == noRank, meaning that it can be generalized.
212isGeneric :: Variable -> IO ()
214 do (Descriptor _ rank _ _) <- UF.get var
219 "You ran into a compiler bug!\n\n\
220 \I was unable to generalize a type variable during type inference. It was ranked.\n\n\
221 \Please create an <http://sscce.org/> and report it at <https://github.com/elm-lang/elm-compiler/issues>\n\n"
225-- EXPECTATIONS TO VARIABLE
228expectedToVariable :: Int -> Pools -> Expected Type -> IO Variable
229expectedToVariable rank pools expectation =
230 typeToVariable rank pools $
232 NoExpectation tipe ->
235 FromContext _ _ tipe ->
238 FromAnnotation _ _ _ tipe ->
242patternExpectationToVariable :: Int -> Pools -> PExpected Type -> IO Variable
243patternExpectationToVariable rank pools expectation =
244 typeToVariable rank pools $
246 PNoExpectation tipe ->
249 PFromContext _ _ tipe ->
257addError :: State -> Error.Error -> State
258addError (State savedEnv rank errors) err =
259 State savedEnv rank (err:errors)
266occurs :: State -> (N.Name, A.Located Variable) -> IO State
267occurs state (_name, A.At _region variable) =
268 do hasOccurred <- Occurs.occurs variable
271 do overallType <- Type.toSrcType variable
272 (Descriptor _ rank mark copy) <- UF.get variable
273 UF.set variable (Descriptor (Error "∞") rank mark copy)
274 return $ state { _errors = Error.InfiniteType overallType : _errors state }
283{-| Every variable has rank less than or equal to the maxRank of the pool.
284This sorts variables into the young and old pools accordingly.
286generalize :: Mark -> Mark -> Int -> Pools -> IO ()
287generalize youngMark visitMark youngRank pools =
288 do youngVars <- MVector.read pools youngRank
289 rankTable <- poolToRankTable youngMark youngRank youngVars
291 -- get the ranks right for each entry.
292 -- start at low ranks so that we only have to pass
293 -- over the information once.
295 (\rank table -> mapM_ (adjustRank youngMark visitMark rank) table)
298 -- For variables that have rank lowerer than youngRank, register them in
299 -- the appropriate old pool if they are not redundant.
300 Vector.forM_ (Vector.unsafeInit rankTable) $ \vars ->
302 do isRedundant <- UF.redundant var
306 do (Descriptor _ rank _ _) <- UF.get var
307 MVector.modify pools (var:) rank
309 -- For variables with rank youngRank
310 -- If rank < youngRank: register in oldPool
311 -- otherwise generalize
312 forM_ (Vector.unsafeLast rankTable) $ \var ->
313 do isRedundant <- UF.redundant var
317 do (Descriptor content rank mark copy) <- UF.get var
319 then MVector.modify pools (var:) rank
320 else UF.set var $ Descriptor content noRank mark copy
323poolToRankTable :: Mark -> Int -> [Variable] -> IO (Vector.Vector [Variable])
324poolToRankTable youngMark youngRank youngInhabitants =
325 do mutableTable <- MVector.replicate (youngRank + 1) []
327 -- Sort the youngPool variables into buckets by rank.
328 forM_ youngInhabitants $ \var ->
329 do (Descriptor content rank _ copy) <- UF.get var
330 UF.set var (Descriptor content rank youngMark copy)
331 MVector.modify mutableTable (var:) rank
333 Vector.unsafeFreeze mutableTable
340-- Adjust variable ranks such that ranks never increase as you move deeper.
341-- This way the outermost rank is representative of the entire structure.
343adjustRank :: Mark -> Mark -> Int -> Variable -> IO Int
344adjustRank youngMark visitMark groupRank var =
345 {-# SCC elm_compiler_type_adjust #-}
346 do (Descriptor content rank mark copy) <- UF.get var
347 if mark == youngMark then
348 do -- Set the variable as marked first because it may be cyclic.
349 UF.set var $ Descriptor content rank visitMark copy
350 maxRank <- adjustRankContent youngMark visitMark groupRank content
351 UF.set var $ Descriptor content maxRank visitMark copy
354 else if mark == visitMark then
358 do let minRank = min groupRank rank
359 -- TODO how can minRank ever be groupRank?
360 UF.set var $ Descriptor content minRank visitMark copy
364adjustRankContent :: Mark -> Mark -> Int -> Content -> IO Int
365adjustRankContent youngMark visitMark groupRank content =
367 go = adjustRank youngMark visitMark groupRank
382 Structure flatType ->
385 foldM (\rank arg -> max rank <$> go arg) outermostRank args
388 max <$> go arg <*> go result
391 -- THEORY: an empty record never needs to get generalized
394 Record1 fields extension ->
395 do extRank <- go extension
396 foldM (\rank field -> max rank <$> go field) extRank fields
399 -- THEORY: a unit never needs to get generalized
410 max (max ma mb) <$> go c
413 -- THEORY: anything in the realVar would be outermostRank
414 foldM (\rank (_, argVar) -> max rank <$> go argVar) outermostRank args
424introduce :: Int -> Pools -> [Variable] -> IO ()
425introduce rank pools variables =
426 do MVector.modify pools (variables++) rank
427 forM_ variables $ \var ->
428 UF.modify var $ \(Descriptor content _ mark copy) ->
429 Descriptor content rank mark copy
436typeToVariable :: Int -> Pools -> Type -> IO Variable
437typeToVariable rank pools tipe =
438 typeToVar rank pools Map.empty tipe
441typeToVar :: Int -> Pools -> Map.Map N.Name Variable -> Type -> IO Variable
442typeToVar rank pools aliasDict tipe =
443 let go = typeToVar rank pools aliasDict in
448 AppN home name args ->
449 do argVars <- traverse go args
450 register rank pools (Structure (App1 home name argVars))
455 register rank pools (Structure (Fun1 aVar bVar))
457 AliasN home name args aliasType ->
458 do argVars <- traverse (traverse go) args
459 aliasVar <- typeToVar rank pools (Map.fromList argVars) aliasType
460 register rank pools (Alias home name argVars aliasVar)
463 return (aliasDict ! name)
465 RecordN fields ext ->
466 do fieldVars <- traverse go fields
468 register rank pools (Structure (Record1 fieldVars extVar))
471 register rank pools emptyRecord1
474 register rank pools unit1
479 cVar <- traverse go c
480 register rank pools (Structure (Tuple1 aVar bVar cVar))
483register :: Int -> Pools -> Content -> IO Variable
484register rank pools content =
485 do var <- UF.fresh (Descriptor content rank noMark Nothing)
486 MVector.modify pools (var:) rank
490{-# NOINLINE emptyRecord1 #-}
491emptyRecord1 :: Content
493 Structure EmptyRecord1
496{-# NOINLINE unit1 #-}
503-- SOURCE TYPE TO VARIABLE
506srcTypeToVariable :: Int -> Pools -> Map.Map N.Name () -> Can.Type -> IO Variable
507srcTypeToVariable rank pools freeVars srcType =
510 UF.fresh (Descriptor (FlexVar (Just name)) rank noMark Nothing)
512 do flexVars <- Map.traverseWithKey makeVar freeVars
513 MVector.modify pools (Map.elems flexVars ++) rank
514 srcTypeToVar rank pools flexVars srcType
517srcTypeToVar :: Int -> Pools -> Map.Map N.Name Variable -> Can.Type -> IO Variable
518srcTypeToVar rank pools flexVars srcType =
519 let go = srcTypeToVar rank pools flexVars in
521 Can.TLambda argument result ->
522 do argVar <- go argument
523 resultVar <- go result
524 register rank pools (Structure (Fun1 argVar resultVar))
527 return (flexVars ! name)
529 Can.TType home name args ->
530 do argVars <- traverse go args
531 register rank pools (Structure (App1 home name argVars))
533 Can.TRecord fields maybeExt ->
534 do fieldVars <- traverse go fields
535 extVar <- maybe (register rank pools emptyRecord1) go maybeExt
536 register rank pools (Structure (Record1 fieldVars extVar))
539 register rank pools unit1
544 cVar <- traverse go c
545 register rank pools (Structure (Tuple1 aVar bVar cVar))
547 Can.TAlias home name args aliasType ->
548 do argVars <- traverse (traverse go) args
552 srcTypeToVar rank pools (Map.fromList argVars) tipe
557 register rank pools (Alias home name argVars aliasVar)
564makeCopy :: Int -> Pools -> Variable -> IO Variable
565makeCopy rank pools var =
566 do copy <- makeCopyHelp rank pools var
571makeCopyHelp :: Int -> Pools -> Variable -> IO Variable
572makeCopyHelp maxRank pools variable =
573 do (Descriptor content rank _ maybeCopy) <- UF.get variable
580 if rank /= noRank then
584 do let makeDescriptor c = Descriptor c maxRank noMark Nothing
585 copy <- UF.fresh $ makeDescriptor content
586 MVector.modify pools (copy:) maxRank
588 -- Link the original variable to the new variable. This lets us
589 -- avoid making multiple copies of the variable we are instantiating.
591 -- Need to do this before recursively copying to avoid looping.
593 Descriptor content rank noMark (Just copy)
595 -- Now we recursively copy the content of the variable.
596 -- We have already marked the variable as copied, so we
597 -- will not repeat this work or crawl this variable again.
600 do newTerm <- traverseFlatType (makeCopyHelp maxRank pools) term
601 UF.set copy $ makeDescriptor (Structure newTerm)
611 do UF.set copy $ makeDescriptor $ FlexVar (Just name)
614 RigidSuper super name ->
615 do UF.set copy $ makeDescriptor $ FlexSuper super (Just name)
618 Alias home name args realType ->
619 do newArgs <- mapM (traverse (makeCopyHelp maxRank pools)) args
620 newRealType <- makeCopyHelp maxRank pools realType
621 UF.set copy $ makeDescriptor (Alias home name newArgs newRealType)
632restore :: Variable -> IO ()
634 do (Descriptor content _ _ maybeCopy) <- UF.get variable
640 do UF.set variable $ Descriptor content noRank noMark Nothing
641 restoreContent content
644restoreContent :: Content -> IO ()
645restoreContent content =
671 Record1 fields ext ->
672 do mapM_ restore fields
685 Alias _ _ args var ->
686 do mapM_ (traverse restore) args
697traverseFlatType :: (Variable -> IO Variable) -> FlatType -> IO FlatType
698traverseFlatType f flatType =
700 App1 home name args ->
701 liftM (App1 home name) (traverse f args)
704 liftM2 Fun1 (f a) (f b)
709 Record1 fields ext ->
710 liftM2 Record1 (traverse f fields) (f ext)
716 liftM3 Tuple1 (f a) (f b) (traverse f cs)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list