preferLocals'
    :: R.Region
    -> Env.Environment
    -> (a -> Var.Canonical)
    -> String
    -> [a]
    -> String
    -> Result.ResultErr a
preferLocals' region env extract kind possibilities var =
    case filter (isLocal (Env._home env) . extract) possibilities of
      [] ->
          ambiguous possibilities

      [v] ->
          Result.var' extract v

      --Local vars shadow top-level vars
      [v1, v2]
          | isTopLevel (extract v1) ->
              Result.var' extract v2

          | isTopLevel (extract v2) ->
              Result.var' extract v1

      locals ->
          ambiguous locals
    where
      ambiguous possibleVars =
          Result.err (A.A region (Error.variable kind var Error.Ambiguous vars))
        where
          vars = map (Var.toString . extract) possibleVars
preferLocals'
    :: R.Region
    -> Env.Environment
    -> (a -> Var.Canonical)
    -> String
    -> [a]
    -> String
    -> Result.ResultErr a
preferLocals' region env extract kind possibilities var =
    case filter (isLocal (Env._home env) . extract) possibilities of
      [] ->
          ambiguous possibilities

      [v] ->
          Result.var' extract v

      --Local vars shadow top-level vars
      [v1, v2]
          | isTopLevel (extract v1) ->
              Result.var' extract v2

          | isTopLevel (extract v2) ->
              Result.var' extract v1

      locals ->
          ambiguous locals
    where
      ambiguous possibleVars =
          Result.err (A.A region (Error.variable kind var Error.Ambiguous vars))
        where
          vars = map (Var.toString . extract) possibleVars
preferLocals' region env extract kind possibilities var =
    case filter (isLocal (Env._home env) . extract) possibilities of
      [] ->
          ambiguous possibilities

      [v] ->
          Result.var' extract v

      --Local vars shadow top-level vars
      [v1, v2]
          | isTopLevel (extract v1) ->
              Result.var' extract v2

          | isTopLevel (extract v2) ->
              Result.var' extract v1

      locals ->
          ambiguous locals
    where
      ambiguous possibleVars =
          Result.err (A.A region (Error.variable kind var Error.Ambiguous vars))
        where
          vars = map (Var.toString . extract) possibleVars