~jojo/Carth

8861bb65187b6097fabfe9fa41e672b33eff66f2 — JoJo 1 year, 9 months ago 1fc1ca2
Add error for duplicate var defs at top-level and in let
3 files changed, 18 insertions(+), 2 deletions(-)

M examples/err.carth
M src/Infer.hs
M src/TypeErr.hs
M examples/err.carth => examples/err.carth +7 -2
@@ 96,10 96,15 @@
;;     (Fun Int List)
;;   (undefined unit))

;; Duplicate definition
;; TODO: This is not an error, but should be
;; Conflicting definitions for variable
;; a)
;; (define foo +)
;; (define foo -)
;; b)
;; (define foo
;;   (let ((a 1)
;;         (a 2))
;;     a))

;; Helpers
(type (Wrap a) (Wrap a))

M src/Infer.hs => src/Infer.hs +8 -0
@@ 93,8 93,16 @@ checkExterns = fmap Map.fromList . mapM checkExtern

inferDefs :: [Ast.Def] -> Infer Defs
inferDefs defs = do
    checkNoDuplicateDefs defs
    let ordered = orderDefs defs
    inferDefsComponents ordered
  where
    checkNoDuplicateDefs = checkNoDuplicateDefs' Set.empty
    checkNoDuplicateDefs' already = \case
        (Id (WithPos p x), _) : ds -> if Set.member x already
            then throwError (ConflictingVarDef p x)
            else checkNoDuplicateDefs' (Set.insert x already) ds
        [] -> pure ()

-- For unification to work properly with mutually recursive functions,
-- we need to create a dependency graph of non-recursive /

M src/TypeErr.hs => src/TypeErr.hs +3 -0
@@ 35,6 35,7 @@ data TypeErr
    | WrongStartType (WithPos Scheme)
    | RecursiveVarDef (WithPos String)
    | TypeInstArityMismatch SrcPos String Int Int
    | ConflictingVarDef SrcPos String
    deriving Show

type Message = String


@@ 110,6 111,8 @@ printErr = \case
            $ ("Arity mismatch for instantiation of type `" ++ pretty t)
            ++ ("`.\nExpected " ++ show expected)
            ++ (", found " ++ show found)
    ConflictingVarDef p x ->
        posd p tokenTree $ "Conflicting definitions for variable `" ++ x ++ "`."
  where
    -- | Used to handle that the position of the generated nested lambdas of a
    --   definition of the form `(define (foo a b ...) ...)` is set to the