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 do (Descriptor content rank mark copy) <- UF.get var
346 if mark == youngMark then
347 do -- Set the variable as marked first because it may be cyclic.
348 UF.set var $ Descriptor content rank visitMark copy
349 maxRank <- adjustRankContent youngMark visitMark groupRank content
350 UF.set var $ Descriptor content maxRank visitMark copy
353 else if mark == visitMark then
357 do let minRank = min groupRank rank
358 -- TODO how can minRank ever be groupRank?
359 UF.set var $ Descriptor content minRank visitMark copy
363adjustRankContent :: Mark -> Mark -> Int -> Content -> IO Int
364adjustRankContent youngMark visitMark groupRank content =
366 go = adjustRank youngMark visitMark groupRank
381 Structure flatType ->
384 foldM (\rank arg -> max rank <$> go arg) outermostRank args
387 max <$> go arg <*> go result
390 -- THEORY: an empty record never needs to get generalized
393 Record1 fields extension ->
394 do extRank <- go extension
395 foldM (\rank field -> max rank <$> go field) extRank fields
398 -- THEORY: a unit never needs to get generalized
409 max (max ma mb) <$> go c
412 -- THEORY: anything in the realVar would be outermostRank
413 foldM (\rank (_, argVar) -> max rank <$> go argVar) outermostRank args
423introduce :: Int -> Pools -> [Variable] -> IO ()
424introduce rank pools variables =
425 do MVector.modify pools (variables++) rank
426 forM_ variables $ \var ->
427 UF.modify var $ \(Descriptor content _ mark copy) ->
428 Descriptor content rank mark copy
435typeToVariable :: Int -> Pools -> Type -> IO Variable
436typeToVariable rank pools tipe =
437 typeToVar rank pools Map.empty tipe
440typeToVar :: Int -> Pools -> Map.Map N.Name Variable -> Type -> IO Variable
441typeToVar rank pools aliasDict tipe =
442 let go = typeToVar rank pools aliasDict in
447 AppN home name args ->
448 do argVars <- traverse go args
449 register rank pools (Structure (App1 home name argVars))
454 register rank pools (Structure (Fun1 aVar bVar))
456 AliasN home name args aliasType ->
457 do argVars <- traverse (traverse go) args
458 aliasVar <- typeToVar rank pools (Map.fromList argVars) aliasType
459 register rank pools (Alias home name argVars aliasVar)
462 return (aliasDict ! name)
464 RecordN fields ext ->
465 do fieldVars <- traverse go fields
467 register rank pools (Structure (Record1 fieldVars extVar))
470 register rank pools emptyRecord1
473 register rank pools unit1
478 cVar <- traverse go c
479 register rank pools (Structure (Tuple1 aVar bVar cVar))
482register :: Int -> Pools -> Content -> IO Variable
483register rank pools content =
484 do var <- UF.fresh (Descriptor content rank noMark Nothing)
485 MVector.modify pools (var:) rank
489{-# NOINLINE emptyRecord1 #-}
490emptyRecord1 :: Content
492 Structure EmptyRecord1
495{-# NOINLINE unit1 #-}
502-- SOURCE TYPE TO VARIABLE
505srcTypeToVariable :: Int -> Pools -> Map.Map N.Name () -> Can.Type -> IO Variable
506srcTypeToVariable rank pools freeVars srcType =
509 UF.fresh (Descriptor (FlexVar (Just name)) rank noMark Nothing)
511 do flexVars <- Map.traverseWithKey makeVar freeVars
512 MVector.modify pools (Map.elems flexVars ++) rank
513 srcTypeToVar rank pools flexVars srcType
516srcTypeToVar :: Int -> Pools -> Map.Map N.Name Variable -> Can.Type -> IO Variable
517srcTypeToVar rank pools flexVars srcType =
518 let go = srcTypeToVar rank pools flexVars in
520 Can.TLambda argument result ->
521 do argVar <- go argument
522 resultVar <- go result
523 register rank pools (Structure (Fun1 argVar resultVar))
526 return (flexVars ! name)
528 Can.TType home name args ->
529 do argVars <- traverse go args
530 register rank pools (Structure (App1 home name argVars))
532 Can.TRecord fields maybeExt ->
533 do fieldVars <- traverse go fields
534 extVar <- maybe (register rank pools emptyRecord1) go maybeExt
535 register rank pools (Structure (Record1 fieldVars extVar))
538 register rank pools unit1
543 cVar <- traverse go c
544 register rank pools (Structure (Tuple1 aVar bVar cVar))
546 Can.TAlias home name args aliasType ->
547 do argVars <- traverse (traverse go) args
551 srcTypeToVar rank pools (Map.fromList argVars) tipe
556 register rank pools (Alias home name argVars aliasVar)
563makeCopy :: Int -> Pools -> Variable -> IO Variable
564makeCopy rank pools var =
565 do copy <- makeCopyHelp rank pools var
570makeCopyHelp :: Int -> Pools -> Variable -> IO Variable
571makeCopyHelp maxRank pools variable =
572 do (Descriptor content rank _ maybeCopy) <- UF.get variable
579 if rank /= noRank then
583 do let makeDescriptor c = Descriptor c maxRank noMark Nothing
584 copy <- UF.fresh $ makeDescriptor content
585 MVector.modify pools (copy:) maxRank
587 -- Link the original variable to the new variable. This lets us
588 -- avoid making multiple copies of the variable we are instantiating.
590 -- Need to do this before recursively copying to avoid looping.
592 Descriptor content rank noMark (Just copy)
594 -- Now we recursively copy the content of the variable.
595 -- We have already marked the variable as copied, so we
596 -- will not repeat this work or crawl this variable again.
599 do newTerm <- traverseFlatType (makeCopyHelp maxRank pools) term
600 UF.set copy $ makeDescriptor (Structure newTerm)
610 do UF.set copy $ makeDescriptor $ FlexVar (Just name)
613 RigidSuper super name ->
614 do UF.set copy $ makeDescriptor $ FlexSuper super (Just name)
617 Alias home name args realType ->
618 do newArgs <- mapM (traverse (makeCopyHelp maxRank pools)) args
619 newRealType <- makeCopyHelp maxRank pools realType
620 UF.set copy $ makeDescriptor (Alias home name newArgs newRealType)
631restore :: Variable -> IO ()
633 do (Descriptor content _ _ maybeCopy) <- UF.get variable
639 do UF.set variable $ Descriptor content noRank noMark Nothing
640 restoreContent content
643restoreContent :: Content -> IO ()
644restoreContent content =
670 Record1 fields ext ->
671 do mapM_ restore fields
684 Alias _ _ args var ->
685 do mapM_ (traverse restore) args
696traverseFlatType :: (Variable -> IO Variable) -> FlatType -> IO FlatType
697traverseFlatType f flatType =
699 App1 home name args ->
700 liftM (App1 home name) (traverse f args)
703 liftM2 Fun1 (f a) (f b)
708 Record1 fields ext ->
709 liftM2 Record1 (traverse f fields) (f ext)
715 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