Skip to content

Commit

Permalink
add type check for default fields (nim-lang#20652)
Browse files Browse the repository at this point in the history
  • Loading branch information
ringabout authored and bung87 committed Jul 29, 2023
1 parent 133ec48 commit d2ff23c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
12 changes: 10 additions & 2 deletions compiler/semtypes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,11 @@ proc semTuple(c: PContext, n: PNode, prev: PType): PType =
var hasDefaultField = a[^1].kind != nkEmpty
if hasDefaultField:
a[^1] = semConstExpr(c, a[^1])
typ = a[^1].typ
if a[^2].kind != nkEmpty:
typ = semTypeNode(c, a[^2], nil)
typ = fitNodeConsiderViewType(c, typ, a[^1], a[^1].info).typ
else:
typ = a[^1].typ
elif a[^2].kind != nkEmpty:
typ = semTypeNode(c, a[^2], nil)
if c.graph.config.isDefined("nimPreviewRangeDefault") and typ.skipTypes(abstractInst).kind == tyRange:
Expand Down Expand Up @@ -820,7 +824,11 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var IntSet, pos: var int,
var hasDefaultField = n[^1].kind != nkEmpty
if hasDefaultField:
n[^1] = semConstExpr(c, n[^1])
typ = n[^1].typ
if n[^2].kind != nkEmpty:
typ = semTypeNode(c, n[^2], nil)
typ = fitNodeConsiderViewType(c, typ, n[^1], n[^1].info).typ
else:
typ = n[^1].typ
propagateToOwner(rectype, typ)
elif n[^2].kind == nkEmpty:
localError(c.config, n.info, errTypeExpected)
Expand Down
22 changes: 22 additions & 0 deletions tests/objects/tdefaultfieldscheck.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
discard """
cmd: "nim check --hints:off $file"
errormsg: ""
nimout:
'''
tdefaultfieldscheck.nim(17, 17) Error: type mismatch: got <string> but expected 'int'
tdefaultfieldscheck.nim(18, 20) Error: type mismatch: got <int literal(12)> but expected 'string'
tdefaultfieldscheck.nim(20, 16) Error: type mismatch: got <float64> but expected 'int'
tdefaultfieldscheck.nim(17, 5) Error: type mismatch: got <string> but expected 'int'
tdefaultfieldscheck.nim(18, 5) Error: type mismatch: got <int literal(12)> but expected 'string'
tdefaultfieldscheck.nim(20, 5) Error: type mismatch: got <float64> but expected 'int'
'''
"""

type
Date* = object
name: int = "string"
time: string = 12
goal: float = 7
fun: int = 1.4

echo default(Date)

0 comments on commit d2ff23c

Please sign in to comment.