parent
1aede6d311
commit
c6a8bd264e
2 changed files with 43 additions and 3 deletions
|
|
@ -1266,7 +1266,7 @@ proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode =
|
||||||
result.typ = makeTypeDesc(c, semTypeNode(c, n, nil))
|
result.typ = makeTypeDesc(c, semTypeNode(c, n, nil))
|
||||||
#result = symNodeFromType(c, semTypeNode(c, n, nil), n.info)
|
#result = symNodeFromType(c, semTypeNode(c, n, nil), n.info)
|
||||||
of tyTuple:
|
of tyTuple:
|
||||||
checkSonsLen(n, 2)
|
if n.len != 2: return nil
|
||||||
n.sons[0] = makeDeref(n.sons[0])
|
n.sons[0] = makeDeref(n.sons[0])
|
||||||
c.p.bracketExpr = n.sons[0]
|
c.p.bracketExpr = n.sons[0]
|
||||||
# [] operator for tuples requires constant expression:
|
# [] operator for tuples requires constant expression:
|
||||||
|
|
@ -1276,9 +1276,9 @@ proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode =
|
||||||
var idx = getOrdValue(n.sons[1])
|
var idx = getOrdValue(n.sons[1])
|
||||||
if idx >= 0 and idx < sonsLen(arr): n.typ = arr.sons[int(idx)]
|
if idx >= 0 and idx < sonsLen(arr): n.typ = arr.sons[int(idx)]
|
||||||
else: localError(n.info, errInvalidIndexValueForTuple)
|
else: localError(n.info, errInvalidIndexValueForTuple)
|
||||||
else:
|
|
||||||
localError(n.info, errIndexTypesDoNotMatch)
|
|
||||||
result = n
|
result = n
|
||||||
|
else:
|
||||||
|
result = nil
|
||||||
else:
|
else:
|
||||||
let s = if n.sons[0].kind == nkSym: n.sons[0].sym
|
let s = if n.sons[0].kind == nkSym: n.sons[0].sym
|
||||||
elif n[0].kind in nkSymChoices: n.sons[0][0].sym
|
elif n[0].kind in nkSymChoices: n.sons[0][0].sym
|
||||||
|
|
|
||||||
40
tests/tuples/tuple_subscript.nim
Normal file
40
tests/tuples/tuple_subscript.nim
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
discard """
|
||||||
|
output: '''5
|
||||||
|
5
|
||||||
|
str2
|
||||||
|
str2
|
||||||
|
4'''
|
||||||
|
"""
|
||||||
|
|
||||||
|
proc`[]` (t: tuple, key: string): string =
|
||||||
|
for name, field in fieldPairs(t):
|
||||||
|
if name == key:
|
||||||
|
return $field
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
proc`[]` [A,B](t: tuple, key: string, op: (proc(x: A): B)): B =
|
||||||
|
for name, field in fieldPairs(t):
|
||||||
|
when field is A:
|
||||||
|
if name == key:
|
||||||
|
return op(field)
|
||||||
|
|
||||||
|
proc`[]=`[T](t: var tuple, key: string, val: T) =
|
||||||
|
for name, field in fieldPairs(t):
|
||||||
|
when field is T:
|
||||||
|
if name == key:
|
||||||
|
field = val
|
||||||
|
|
||||||
|
var tt = (a: 1, b: "str1")
|
||||||
|
|
||||||
|
# test built in operator
|
||||||
|
tt[0] = 5
|
||||||
|
echo tt[0]
|
||||||
|
echo `[]`(tt, 0)
|
||||||
|
|
||||||
|
|
||||||
|
# test overloaded operator
|
||||||
|
tt["b"] = "str2"
|
||||||
|
echo tt["b"]
|
||||||
|
echo `[]`(tt, "b")
|
||||||
|
echo tt["b", proc(s: string) : int = s.len]
|
||||||
Loading…
Add table
Add a link
Reference in a new issue