Skip to content

Commit

Permalink
[osh-language] Tighten up behavior of assoc arrays inside (( )).
Browse files Browse the repository at this point in the history
That string keys on the LHS but not the RHS seems like a quirk.  But it
makes sense if you remember that (( )) tries to coerce everything to an
integer.

Related to issue #207.
  • Loading branch information
Andy Chu committed Jul 14, 2019
1 parent 1bafc7a commit f2e405c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
20 changes: 8 additions & 12 deletions osh/expr_eval.py
Expand Up @@ -498,10 +498,6 @@ def Eval(self, node):

rhs = self.Eval(node.right) # eager evaluation for the rest

# TODO:
# - More type checks
# - How do we blame arith_expr? Really we need the OPERATOR.

if op_id == Id.Arith_LBracket:
# StrArray or AssocArray
if isinstance(lhs, list):
Expand All @@ -516,15 +512,15 @@ def Eval(self, node):
# TODO: Should be None for Undef instead? Or ''?
return 0

# Quirk: (( A[$key] = 42 )) works
# (( x = A[$key] )) doesn't work because $key is coerced to
# an integer
# We could relax this restriction by using value_t here instead of the
# None/int/list representation.

elif isinstance(lhs, dict):
try:
item = lhs[str(rhs)] # 0 -> '0'
except KeyError:
if self.exec_opts.nounset:
e_die('Invalid key %r' % rhs)
else:
# TODO: Should be None for Undef instead? Or ''?
return 0
e_die("Can't evaluate associative arrays in arithmetic contexts")

else:
# TODO: Add error context
e_die('Expected array in index expression, got %s', lhs)
Expand Down
6 changes: 5 additions & 1 deletion spec/assoc.test.sh
Expand Up @@ -331,7 +331,7 @@ echo ${assoc[1]} ${assoc[2]} ${assoc}
## N-I osh stdout-json: ""
## N-I osh status: 1
#### Associative array expressions inside (( ))
#### Associative array expressions inside (( )) with keys that look like numbers
declare -A assoc
assoc[0]=42
(( var = ${assoc[0]} ))
Expand All @@ -342,6 +342,10 @@ echo $var
42
42
## END
## N-I osh status: 1
## N-I osh STDOUT:
42
## END
#### (( A[5] += 42 ))
declare -A A
Expand Down

0 comments on commit f2e405c

Please sign in to comment.