Skip to content

Improve error message when non-existent (and duplicate) labels are given to a value constructor

Summary

The error message Constructor ‘MkFoo’ does not have field ‘bar’ is replaced by Ambiguous occurrence ‘bar’ when bar is not a label of MkFoo, but of several other constructors (by DuplicateRecordFields).

Steps to reproduce

Put these files in the same directory, then run ghc main.hs:

Test.hs:

{-# LANGUAGE DuplicateRecordFields #-}

module Test where

data Foo = MkFoo { foo :: String } deriving Show

data FooWithBar = MkFooWithBar { foo :: String, bar :: Bool } deriving Show

data FooWithBarAndBaz = MkFooWithBarAndBaz { foo :: String, bar :: Bool, baz :: Int } deriving Show

main.hs:

{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings     #-}

import Test

main :: IO ()
main = print MkFoo { foo = "", bar = True }

Expected behavior

The error message should be like this (the actual message when FooWithBarAndBaz is deleted):

main.hs:7:14: error:
    • Constructor ‘MkFoo’ does not have field ‘bar’
    • In the first argument of ‘print’, namely
        ‘MkFoo {foo = "", bar = True}’
      In the expression: print MkFoo {foo = "", bar = True}
      In an equation for ‘main’:
          main = print MkFoo {foo = "", bar = True}
  |
7 | main = print MkFoo { foo = "", bar = True }
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

But the acutal error message is:

main.hs:7:32: error:
    Ambiguous occurrence ‘bar’
    It could refer to
       either the field ‘bar’,
              imported from ‘Test’ at main.hs:4:1-11
              (and originally defined at Test.hs:9:61-63)
           or the field ‘bar’,
              imported from ‘Test’ at main.hs:4:1-11
              (and originally defined at Test.hs:7:49-51)
  |
7 | main = print MkFoo { foo = "", bar = True }
  |                                ^^^

Which is confusing.

Environment

  • GHC version used: 8.8.1
Edited by Yuji Yamamoto
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information