示例#1
0
        private IExpression ParseHashLiteral()
        {
            var hash = new HashLiteral {
                Token = _curToken, Pairs = new Dictionary <IExpression, IExpression>()
            };

            while (!PeekTokenIs(TokenType.RBrace))
            {
                NextToken();
                var key = ParseExpression(PrecedenceLevel.Lowest);

                if (!ExpectPeek(TokenType.Colon))
                {
                    return(null);
                }

                NextToken();
                var value = ParseExpression(PrecedenceLevel.Lowest);
                hash.Pairs.Add(key, value);

                if (!PeekTokenIs(TokenType.RBrace) && !ExpectPeek(TokenType.Comma))
                {
                    return(null);
                }
            }

            if (!ExpectPeek(TokenType.RBrace))
            {
                return(null);
            }

            return(hash);
        }
示例#2
0
        private static IMonkeyObject EvalHashLiteral(HashLiteral node, MonkeyEnvironment env)
        {
            var pairs = new Dictionary <HashKey, HashPair>();

            foreach (var kv in node.Pairs)
            {
                var key = Eval(kv.Key, env);
                if (IsError(key))
                {
                    return(key);
                }

                if (key is IHashable k)
                {
                    var value = Eval(kv.Value, env);
                    if (IsError(value))
                    {
                        return(value);
                    }

                    var hashKey  = k.HashKey();
                    var hashPair = new HashPair {
                        Key = key, Value = value
                    };
                    pairs.Add(hashKey, hashPair);
                }
                else
                {
                    return(NewError($"Unusable as hash key: {key.GetType()}"));
                }
            }

            return(new MonkeyHash {
                Pairs = pairs
            });
        }