Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
332 changes: 252 additions & 80 deletions src/nimony/sem.nim

Large diffs are not rendered by default.

47 changes: 26 additions & 21 deletions src/nimony/semcall.nim
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,8 @@ type
source: TransformedCallSource
## type of expression the call was transformed from
argsScopeClosed: bool
sumType: TypeCursor
## `T` of `T.Branch(...)`, a sum type constructor that names its type

proc leaveCall(dest: var TokenBuf; it: var Item; cs: CallState) =
## Closes the call tree in `dest` and advances `it.n` past the call
Expand Down Expand Up @@ -603,41 +605,42 @@ proc semObjConstrFromCall(c: var SemContext; dest: var TokenBuf; it: var Item; c

proc semSumTypeConstrFromCall(c: var SemContext; dest: var TokenBuf;
it: var Item; cs: var CallState) =
## `Branch(field: value, ...)` and `T.Branch(field: value, ...)`.
it.n = cs.scope; skip it.n
let info = cs.callNodeInfo
let expected = it.typ
assert cs.fn.n.isSymbol
let efldSym = cs.fn.n.symId
if cs.source == MethodCall and cs.args.len > 0 and cs.args[0].typ.typeKind == TypedescT:
# `T.Branch(...)` where `Branch` is a branch of another sum type than `T`:
buildErr c, dest, info, "undeclared sum type branch: " & pool.strings[symToIdent(efldSym)]
return
var objBuf = createTokenBuf(32)
objBuf.addParLe(OconstrX, info)
if expected.typeKind == AutoT:
# Use ident so semObjConstr can do generic type inference:
let efldName = symToIdent(efldSym)
objBuf.addIdent(efldName, info)
if cursorIsNil(cs.sumType):
objBuf.addIdent(symToIdent(efldSym), info) # the expected type picks it
else:
objBuf.addSubtree expected
let kindName = pool.strings.getOrIncl("`kind")
objBuf.addParLe(KvU, info)
objBuf.addIdent(kindName, info)
objBuf.addSymUse(efldSym, info)
objBuf.addParRi()
for arg in cs.args:
let orig = arg.orig
if orig.substructureKind == VvU:
var scan = orig
inc scan
var scan = sub(orig)
objBuf.addParLe(KvU, orig.info)
objBuf.addSubtree scan
skip scan
objBuf.addSubtree scan
objBuf.takeTree scan
objBuf.takeTree scan
objBuf.addParRi()
else:
buildErr c, dest, orig.info, "sum type constructor requires named arguments"
return
objBuf.addSubtree orig # reported by `semObjConstr`
objBuf.addParRi()
var objConstr = Item(n: cursorAt(objBuf, 0), typ: it.typ)
semObjConstr c, dest, objConstr
it.typ = objConstr.typ
if cursorIsNil(cs.sumType):
var objConstr = Item(n: cursorAt(objBuf, 0), typ: it.typ)
semObjConstr c, dest, objConstr
it.typ = objConstr.typ
else:
let expected = it.typ
let beforeExpr = dest.len
var objConstr = Item(n: cursorAt(objBuf, 0), typ: cs.sumType)
semObjConstr c, dest, objConstr
it.typ = objConstr.typ
commonType c, dest, it, beforeExpr, expected

func anyArgTypeIsError(cs: CallState): bool =
## True when an argument already carries an `(err)` type, i.e. semchecking it
Expand Down Expand Up @@ -1603,6 +1606,8 @@ proc semCall(c: var SemContext; dest: var TokenBuf; it: var Item; flags: set[Sem
# now interpret the dot expression:
let dotState = tryBuiltinDot(c, dest, cs.fn, lhs, fieldName, dotInfo,
dotFlags, dotAccessToken)
if dotState == MatchedDotSym and cs.fn.kind == EfldY and lhs.typ.typeKind == TypedescT:
cs.sumType = lhs.typ.childCursor
if dotState == FailedDot and dotLhsModuleSym(lhs) != SymId(0):
# `m.nosuchproc(...)`: a module qualifier has no UFCS fallback, so the
# miss is simply an error. Report it and leave instead of running the
Expand Down
7 changes: 7 additions & 0 deletions src/nimony/semdata.nim
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ type
InGenericConstraint, InInvokeHead,
InTypeValue ## a type name used as an expression: a `typedesc` value

OpenInvoke* = object
## `T[A, _]` as a constructor's type: the generic type `T`, set iff an
## argument is `_`, and the arguments written, keyed by `T`'s typevars.
## The constructor's fields determine the rest.
head*: SymId
written*: Table[SymId, Cursor]

CrucialPragma* = object
## Pragma summary collected while sem-checking a routine/type's pragmas.
## Fields are exported so the pragma module (sempragmas) and the sem core
Expand Down
35 changes: 34 additions & 1 deletion src/nimony/semtypes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,11 @@ proc semMagicInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor; kind:
var m = cursorAt(typeBuf, 0)
semLocalTypeImpl c, dest, m, InLocalDecl

proc semInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor; context = InLocalDecl) =
proc semInvokeImpl(c: var SemContext; dest: var TokenBuf; n: var Cursor;
context: TypeDeclContext; open: var OpenInvoke; allowWildcards: bool) =
## `allowWildcards`: `n` is a constructor's type, whose arguments written `_`
## the constructor infers from its fields; when there is one, `dest` gets
## the bare generic type and `open` the arguments that were written.
let typeStart = dest.len
let info = n.info
dest.addParLe(n.cursorTagId, n.info) # copy `at`
Expand Down Expand Up @@ -596,11 +600,17 @@ proc semInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor; context = I
let beforeArgs = dest.len
var argErr = ""
var argErrInfo = info
var hasWildcard = false
if ok:
for (v, kind, elemType) in genericParams(headId):
inc paramCount
if n.hasMore:
inc argCount
if allowWildcards and n.isIdent and pool.strings[n.strId] == "_":
# left open: the constructor's fields determine it
hasWildcard = true
inc n
continue
let argInfo = n.info
var argBuf = createTokenBuf(16)
semLocalTypeImpl c, argBuf, n, AllowValues
Expand Down Expand Up @@ -652,6 +662,17 @@ proc semInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor; context = I
dest.shrink typeStart
c.buildErr dest, argErrInfo, argErr
return
if hasWildcard:
# No instance without every argument; the constructor completes it:
open.head = headId
for (v, _, _) in genericParams(headId):
if m.inferred.hasKey(v):
var argBuf = createTokenBuf(8)
argBuf.addSubtree m.inferred.getOrQuit(v)
open.written[v] = typeToCursor(c, argBuf, 0)
dest.shrink typeStart
dest.addSymUse(headId, info)
return

if isConcrete or
# structural types are inlined even with generic arguments
Expand Down Expand Up @@ -706,6 +727,18 @@ proc semInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor; context = I
assert sym.name != SymId(0)
semTypeSym c, dest, sym, info, typeStart, context

proc semInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor; context = InLocalDecl) =
var open = OpenInvoke()
semInvokeImpl c, dest, n, context, open, allowWildcards = false

proc semConstrInvoke(c: var SemContext; dest: var TokenBuf; n: var Cursor;
open: var OpenInvoke): TypeCursor =
## The type `T[A, B]` of a constructor `T[A, B](...)` or `T[A, B].Branch(...)`,
## which may write `_` for an argument; see `OpenInvoke`.
let insertPos = dest.len
semInvokeImpl c, dest, n, InInvokeHead, open, allowWildcards = true
result = typeToCursor(c, dest, insertPos)

proc isSymbolicLength(n: Cursor): bool =
## In an `array` index slot that still mentions generic parameters, tell a
## symbolic *length* (`array[N, T]` for `N: static[int]`, `array[2*N, T]`)
Expand Down
101 changes: 101 additions & 0 deletions tests/nimony/object/tsumtype_qualified.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import std/[syncio, assertions]

type
Res[T, E] = object
case
of Ok: v: T
of Err: e: E

# `Ok` is also a branch of `Res`: the type before the dot says which.
Flip = object
case
of Ok: n: int
of Bad: msg: string

Tree[T] = ref object
case
of Leaf: val: T
of Node: left, right: Tree[T]

Shape = object
case
of Dot: x: int
of Line: a, b: int

IntRes = Res[int, string]

proc show(r: Res[int, string]): string =
case r
of Ok(v): result = "ok " & $v
of Err(e): result = "err " & e

proc flipShow(f: Flip): string =
case f
of Ok(n): result = "flip ok " & $n
of Bad(msg): result = "flip bad " & msg

proc total(t: Tree[int]): int =
case t
of Leaf(val): result = val
of Node(left, right): result = total(left) + total(right)

proc area(s: Shape): int =
case s
of Dot(x): result = x
of Line(a, b): result = b - a

# The type is written at the constructor, so a call argument needs no expected
# type from the callee:
assert show(Res[int, string].Ok(v: 5)) == "ok 5"
assert show(Res[int, string].Err(e: "no")) == "err no"

# An alias names the type as well as an instance does:
assert show(IntRes.Ok(v: 6)) == "ok 6"
assert show(IntRes.Err(e: "alias")) == "err alias"

let r = Res[int, string].Ok(v: 7)
assert show(r) == "ok 7"

# `Ok` of `Flip`, not of `Res`:
assert flipShow(Flip.Ok(n: 1)) == "flip ok 1"
assert flipShow(Flip.Bad(msg: "x")) == "flip bad x"

# A `ref` sum type and a type that is not generic:
assert total(Tree[int].Node(left: Tree[int].Leaf(val: 1), right: Tree[int].Leaf(val: 2))) == 3
assert area(Shape.Line(a: 2, b: 9)) == 7
assert area(Shape.Dot(x: 4)) == 4

# `_` stands for a type argument the fields determine, as `Ok(v: 5)` does
# for the `T` of `Res[T, E]`; only what the fields cannot tell is written:
assert show(Res[_, string].Ok(v: 8)) == "ok 8"
assert show(Res[int, _].Err(e: "wild")) == "err wild"

type
Both[A, B] = object
case
of Pair:
a: A
b: B
of Empty: discard

proc pairText(p: Both[int, string]): string =
case p
of Pair(a, b): result = $a & b
of Empty: result = "empty"

assert pairText(Both[_, _].Pair(a: 1, b: "x")) == "1x"
assert pairText(Both[int, _].Pair(a: 2, b: "y")) == "2y"
assert pairText(Both[int, string].Empty()) == "empty"

# A literal takes the type written for it:
proc byteText(p: Both[uint8, string]): string =
case p
of Pair(a, b): result = $a & b
of Empty: result = "empty"

assert byteText(Both[uint8, _].Pair(a: 5, b: "z")) == "5z"

# also for a `ref` sum type:
assert total(Tree[_].Leaf(val: 5)) == 5

echo "tsumtype_qualified: OK"
1 change: 1 addition & 0 deletions tests/nimony/object/tsumtype_qualified.output
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tsumtype_qualified: OK
7 changes: 7 additions & 0 deletions tests/nimony/object/tsumtype_qualified_errors.msgs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
tests/nimony/object/tsumtype_qualified_errors.nim(13, 63) Error: type mismatch: got: int64 but wanted: string
tests/nimony/object/tsumtype_qualified_errors.nim(16, 60) Error: undeclared sum type branch: Bad
tests/nimony/object/tsumtype_qualified_errors.nim(19, 59) Error: sum type constructor requires named arguments
tests/nimony/object/tsumtype_qualified_errors.nim(22, 55) Error: cannot infer type parameter 'E' of the sum type of branch `Ok`; write it instead of `_`
tests/nimony/object/tsumtype_qualified_errors.nim(26, 59) Error: type mismatch: got: string but wanted: int64
tests/nimony/object/tsumtype_qualified_errors.nim(36, 53) Error: type mismatch: got: string but wanted: int64
tests/nimony/object/tsumtype_qualified_errors.nim(38, 39) Error: wrong amount of generic parameters for type Res, expected 2 but got 3
38 changes: 38 additions & 0 deletions tests/nimony/object/tsumtype_qualified_errors.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
type
Res[T, E] = object
case
of Ok: v: T
of Err: e: E

Flip = object
case
of Ok: n: int
of Bad: msg: string

# The mismatch is reported on the field, as for `let r: Res[int, string] = Err(e: 5)`.
proc wrongField(): Res[int, string] = Res[int, string].Err(e: 5)

# A branch of another sum type is not a branch of this one.
proc otherBranch(): Res[int, string] = Res[int, string].Bad(msg: "x")

# The branch is named, not positional.
proc positional(): Res[int, string] = Res[int, string].Ok(5)

# A type argument left as `_` that no field determines is named.
proc undetermined(): Res[int, string] = Res[int, _].Ok(v: 5)

# A field that contradicts a written argument is reported on the field, also
# while another parameter is still open.
proc contradicted(): Res[int, string] = Res[int, _].Ok(v: "x")

# A written type argument is not overridden by the fields.
type
Both[A, B] = object
case
of Pair:
a: A
b: B

proc clash(): Both[int, int] = Both[int, _].Pair(a: "x", b: 1)

proc tooMany(): Res[int, string] = Res[_, _, _].Ok(v: 5)
Loading