Beispiel #1
0
 private void Emit(ArrayAccessExpression node)
 {
     Emit(node.ArrayExpression);
     AppendUnindented("[");
     EmitTuple(node.KeyExpressions.ToArray(), Emit, multiline: false);
     AppendUnindented("]");
 }
Beispiel #2
0
 public virtual void Visit(ArrayAccessExpression s)
 {
     foreach (var index in s._indices)
     {
         index.Accept(this);
     }
 }
Beispiel #3
0
        private AphidObject InterpretArrayAccessExpression(ArrayAccessExpression expression)
        {
            var    val   = ValueHelper.Unwrap(InterpretExpression(expression.ArrayExpression));
            var    index = Convert.ToInt32(ValueHelper.Unwrap(InterpretExpression(expression.KeyExpression)));
            var    array = val as List <AphidObject>;
            string str;

            if (array != null)
            {
                if (index < 0 || index >= array.Count)
                {
                    throw new AphidRuntimeException("Index out of range: {0}.", index);
                }

                return(array[index]);
            }
            else if ((str = val as string) != null)
            {
                return(new AphidObject(str[index].ToString()));
            }
            else
            {
                throw new AphidRuntimeException("Array access not supported by {0}.", val);
            }
        }
Beispiel #4
0
        public override Object Visit(ArrayAccessExpression node, Object obj)
        {
            node.FirstOperand.Accept(this, obj);
            node.SecondOperand.Accept(this, obj);

            return(null);
        }
Beispiel #5
0
 protected virtual void EmitArrayAccessExpression(ArrayAccessExpression expression, bool isStatement = false)
 {
     Emit(expression.ArrayExpression);
     Append("[");
     EmitTuple(expression.KeyExpressions);
     Append("]");
 }
Beispiel #6
0
        // . .$ :: ::$ call [ ]
        private Expression ParseScopeExpression()
        {
            Expression result = ParseConstructorExpression();

            SkipWhitespace();
            while (ConsumeIfType(out Token token, TokenType.Period, TokenType.PeriodDollarSign, TokenType.ColonColon, TokenType.ColonColonDollarSign, TokenType.OpenSquareBracket, TokenType.OpenParenthesis))
            {
                Expression rhs = null;
                if (token.Type == TokenType.OpenSquareBracket)
                {
                    Expression index = ParseExpression();
                    SkipWhitespace();
                    Token closeSquareBracket = Consume();
                    // TODO: Assert that that was actually a close square bracket
                    // once we have a proper panic & sync system
                    result = new ArrayAccessExpression(result.Span + closeSquareBracket.Span, result, index);
                }
                else if (token.Type == TokenType.OpenParenthesis)
                {
                    SkipWhitespace();
                    List <Expression> arguments = new List <Expression>();

                    bool isFirst = true;
                    while (Peek().Type != TokenType.CloseParenthesis)
                    {
                        SkipWhitespace();
                        if (!isFirst)
                        {
                            ConsumeType(TokenType.Comma, "Expected a comma between call arguments.", "LSS050");
                        }

                        Expression argument = ParseExpression();
                        arguments.Add(argument);

                        isFirst = false;
                        SkipWhitespace();
                    }

                    Token closeParenthesis = ConsumeType(TokenType.CloseParenthesis, "Expected a close parenthesis after function call.", "LSS051");
                    result = new CallExpression(result.Span + closeParenthesis.Span, result, arguments);
                }
                else
                {
                    // . :: .$, ::$
                    if (token.Type == TokenType.PeriodDollarSign || token.Type == TokenType.ColonColonDollarSign)
                    {
                        // Don't allow function calls as part of the lookup expression - this would be ambiguous, consider thing.$foo(bar), is '(bar)' part of the lookup expression, or calling the looked-up function?
                        rhs = ParseTerminalExpression();
                    }
                    else
                    {
                        rhs = ParseTerminalExpression();
                    }
                    result = new BinaryExpression(result, token, rhs);
                }
                SkipWhitespace();
            }
            return(result);
        }
Beispiel #7
0
 public object VisitArrayAccessExpression(ArrayAccessExpression expr, object context)
 {
     expr.Array.AcceptVisitor(this, context);
     StringBuilder.Append("[");
     expr.Index.AcceptVisitor(this, context);
     StringBuilder.Append("]");
     return(null);
 }
 public override object Visit(ArrayAccessExpression node, object obj)
 {
     if (node.Location == ((AstNode)obj).Location || found)
     {
         found = true;
         return(this.table);
     }
     return(base.Visit(node, obj));
 }
        public void GetSecondElement()
        {
            Vector      vector  = new Vector(new object[] { 1, 2, 3 });
            IExpression arrexpr = new ConstantExpression(vector);
            IExpression indexpr = new ConstantExpression(1);

            IExpression expr = new ArrayAccessExpression(arrexpr, new IExpression[] { indexpr });

            Assert.AreEqual(2, expr.Evaluate(null));
        }
Beispiel #10
0
        public override object Visit(ArrayAccessExpression node, object obj)
        {
            if (node.Location > (Location)obj)
            {
                return(null);
            }
            arrayStack.Push(node);

            return(base.Visit(node, obj));
        }
Beispiel #11
0
        public override Object Visit(ArrayAccessExpression node, Object obj)
        {
            int indent = Convert.ToInt32(obj);

            this.printIndentation(indent);
            this.output.WriteLine("ArrayAccessExpression Type: {0} [{1}:{2}]", printType(node.ExpressionType), node.Location.Line, node.Location.Column);
            node.FirstOperand.Accept(this, indent + 1);
            node.SecondOperand.Accept(this, indent + 1);
            return(null);
        }
Beispiel #12
0
        public override Object Visit(ArrayAccessExpression node, Object obj)
        {
            Expression            clonedFirstOperand          = (Expression)node.FirstOperand.Accept(this, obj);
            Expression            clonedSecondOperand         = (Expression)node.SecondOperand.Accept(this, obj);
            ArrayAccessExpression clonedArrayAccessExpression = new ArrayAccessExpression(clonedFirstOperand, clonedSecondOperand, node.Location);

            if (node.ExpressionType != null)
            {
                clonedArrayAccessExpression.ExpressionType = node.ExpressionType.CloneType(this.typeVariableMappings, this.typeExpresionVariableMapping);
            }
            return(clonedArrayAccessExpression);
        }
Beispiel #13
0
        /// <summary>
        /// Returns expression from parser's <see cref="CQLParser.ComplexFactorContext"/>.
        /// Represents complex factors like array access, property lookup or function call.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override IExpression VisitComplexFactor([NotNull] CQLParser.ComplexFactorContext context)
        {
            var primary = Visit(context.pe);

            foreach (var element in context.chain_element())
            {
                if (element is ArrayAccessContext)
                {
                    var arrayAccess = element as ArrayAccessContext;
                    var indices     = exprListVisitor.Visit(arrayAccess.elems);
                    primary = new ArrayAccessExpression((ParserLocation)arrayAccess, primary, indices);
                }
                else if (element is MemberCallContext)
                {
                    var memberCall = element as MemberCallContext;
                    var memberName = nameVisitor.Visit(memberCall.id);
                    var delimiter  = IdDelimiter.Dot;
                    switch (memberCall.sep.Text)
                    {
                    case "$": delimiter = IdDelimiter.Dollar; break;

                    case ".": delimiter = IdDelimiter.Dot; break;

                    case "#": delimiter = IdDelimiter.Hash; break;

                    case "->": delimiter = IdDelimiter.SingleArrow; break;

                    case "/": delimiter = IdDelimiter.Slash; break;
                    }
                    primary = new MemberExpression((ParserLocation)memberCall, primary, delimiter, memberName);
                }
                else if (element is MethodCallContext)
                {
                    var methodCall = element as MethodCallContext;
                    IEnumerable <IExpression> parameters = Enumerable.Empty <IExpression>();
                    if (methodCall.@params != null)
                    {
                        parameters = exprListVisitor.Visit(methodCall.@params);
                    }
                    primary = new FunctionCallExpression((ParserLocation)methodCall, primary, parameters);
                }
                else
                {
                    throw new InvalidOperationException("Unhandled chain element!");
                }
            }
            return(primary);
        }
        public static Result Run(ArrayAccessExpression expression, Scope scope)
        {
            Result res = Result.NULL;

            Resolve(expression, scope, (arr, key) =>
            {
                if (arr.TryGetValue(key, out ArrayItem item))
                {
                    res = new Result(item.Value);
                }
                else
                {
                    Log.Debug($"Undefined index: {key}, array: {arr}, scope: {scope}");
                    Log.Error($"  existing indexes: {arr.GetAll ().Select (f => f.Key).Join (", ")}");
                }
            });
            return(res);
        }
Beispiel #15
0
        public override Object Visit(ArrayAccessExpression node, Object obj)
        {
            Object aux = null;

            //node.FirstOperand.LeftExpression = node.LeftExpression;
            node.FirstOperand.LeftExpression  = false;
            node.SecondOperand.LeftExpression = false;
            if ((aux = node.FirstOperand.Accept(this, false)) is SingleIdentifierExpression)
            {
                node.FirstOperand = (SingleIdentifierExpression)aux;
            }
            if ((aux = node.SecondOperand.Accept(this, false)) is SingleIdentifierExpression)
            {
                node.SecondOperand = (SingleIdentifierExpression)aux;
            }
            node.FirstOperand.LeftExpression = node.LeftExpression;
            return(null);
        }
        public static void Resolve(ArrayAccessExpression expression, Scope scope, Action <IArray, ArrayKey> action)
        {
            FinalExpression key_expr = Interpreters.Execute(expression.Index, scope).ResultValue;
            ArrayKey        key      = new ArrayKey(key_expr.GetStringValue());

            FinalExpression array_expr = Interpreters.Execute(expression.Array, scope).ResultValue;

            if (array_expr is ArrayPointerExpression pointer)
            {
                if (pointer.Array is IArray arr)
                {
                    action(arr, key);
                }
                else
                {
                    Log.Error($"Array could not be found: {pointer.Array.Name}, key: '{key}', scope: {scope}");
                }
            }
            else
            {
                Log.Error($"Array access of key '{key}' is not performed on an array, but on: {array_expr}, scope: {scope}");
            }
        }
Beispiel #17
0
        private IExpression ReadArrayAccess(Predicate <TokenMarker> terminatingPredicate, DslToken token, Stack <IExpression> previousExpressions)
        {
            var expArray = new ArrayAccessExpression();

            Reader.DiscardToken();
            var left = previousExpressions.Pop();

            expArray.Object = left;
            var marker         = Reader.Marker.Clone();
            var fnEndPredicate = DonutSyntaxReader.Filters.IndexArgumentsEnd(marker);

            while (!Reader.IsComplete && !fnEndPredicate(Reader.Marker))
            {
                ParameterExpression fnParameter = ReadIndexParameter();
                expArray.Parameters.Add(fnParameter);
                if (Reader.Current.TokenType == TokenType.Comma)
                {
                    Reader.DiscardToken();
                }
            }
            Reader.DiscardToken(TokenType.CloseBracket);
            return(expArray);
        }
        private Expression ParseArrayAccessExpression(Expression hint)
        {
            List <Expression> arguments = new List <Expression>();

            MakeBlock(() =>
            {
                arguments.Add(ParseExpression());
                while (_current == TokenKind.Comma)
                {
                    Take(TokenKind.Comma);
                    arguments.Add(ParseExpression());
                }
            }, TokenKind.LeftBrace, TokenKind.RightBrace);

            var expr = new ArrayAccessExpression(CreateSpan(hint), hint, arguments);

            if (_current == TokenKind.Dot)
            {
                return(ParseReferenceExpression(expr));
            }

            return(expr);
        }
Beispiel #19
0
 private CodeExpression GenerateImperativeExpression(ArrayAccessExpression node) => new CodeArrayIndexerExpression(
     GenerateImperativeExpression(node.ArrayExpression),
     node.KeyExpressions.Select(x => GenerateImperativeExpression(x)).ToArray());
Beispiel #20
0
 public override void Visit(ArrayAccessExpression s)
 {
     base.Visit(s);
     Console.WriteLine(s._variable);
 }
Beispiel #21
0
 private System.Linq.Expressions.Expression EvaluateArrayAccessExpression(ArrayAccessExpression arrayAccessExpression)
 {
     return(System.Linq.Expressions.Expression.ArrayAccess(Evaluate(arrayAccessExpression.Target), Evaluate(arrayAccessExpression.Index)));
 }
Beispiel #22
0
 protected abstract void VisitArrayAccess(ArrayAccessExpression expression);
 protected virtual void VisitArrayAccessExpression(ArrayAccessExpression arrayAccessExpression)
 {
     Visit(arrayAccessExpression.Target);
     Visit(arrayAccessExpression.Index);
 }
 public abstract Object Visit(ArrayAccessExpression node, Object obj);
        /// <summary>
        /// Reads an array access expression.
        /// </summary>
        /// <param name="array">The array being accessed.</param>
        /// <param name="previousPrecedence">The precedence of the previous expression.</param>
        /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param>
        /// <returns>Returns the expression.</returns>
        private ArrayAccessExpression GetArrayAccessExpression(
            Expression array, ExpressionPrecedence previousPrecedence, bool unsafeCode)
        {
            Param.AssertNotNull(array, "array");
            Param.Ignore(previousPrecedence);
            Param.Ignore(unsafeCode);

            ArrayAccessExpression expression = null;

            if (this.CheckPrecedence(previousPrecedence, ExpressionPrecedence.Primary))
            {
                // The next symbol will be the opening bracket.
                Bracket openingBracket = this.GetBracketToken(CsTokenType.OpenSquareBracket, SymbolType.OpenSquareBracket);
                Node<CsToken> openingBracketNode = this.tokens.InsertLast(openingBracket);

                // Get the argument list now.
                ICollection<Expression> argumentList = this.GetArgumentList(SymbolType.CloseSquareBracket, unsafeCode);

                // Get the closing bracket.
                Bracket closingBracket = this.GetBracketToken(CsTokenType.CloseSquareBracket, SymbolType.CloseSquareBracket);
                Node<CsToken> closingBracketNode = this.tokens.InsertLast(closingBracket);

                openingBracket.MatchingBracketNode = closingBracketNode;
                closingBracket.MatchingBracketNode = openingBracketNode;

                // Pull out the first token from the array.
                Node<CsToken> firstTokenNode = array.Tokens.First;

                // Create the token list for the method invocation expression.
                CsTokenList partialTokens = new CsTokenList(this.tokens, firstTokenNode, this.tokens.Last);

                // Create and return the expression.
                expression = new ArrayAccessExpression(partialTokens, array, argumentList);
            }

            return expression;
        }
Beispiel #26
0
 public virtual void VisitArrayAccessExpression(ArrayAccessExpression node) => DefaultVisit(node);
 public ArrayAssignmentStatement(ArrayAccessExpression array, IExpression expression)
 {
     _array      = array;
     _expression = expression;
 }
Beispiel #28
0
        private Statement assignmentStatement()
        {
            Token current = null;

            if (match(TokenType.DESTRUCT))
            {
                return(destructuringAssignment());
            }

            if ((match(TokenType.CONST) || match(TokenType.LET)) && match(TokenType.LBRACE))
            {
                Dictionary <string, Value> variables = new Dictionary <string, Value>();
                while (!match(TokenType.RBRACE))
                {
                    var varname = consume(TokenType.WORD).getText();
                    consume(TokenType.EQ);
                    Value value = expression().eval();
                    variables.Add(varname, value);
                }
                return(new VarEnumerableAssignmentStatement(variables));
            }

            if (match(TokenType.LET))
            {
                current = get(0);

                if (match(TokenType.WORD) && get(0).getType() == TokenType.EQ)
                {
                    string variable = current.getText();
                    consume(TokenType.EQ);
                    return(new AssignmentStatement(variable, expression()));
                }

                if (current.getType() == TokenType.WORD)
                {
                    string variable = current.getText();
                    return(new AssignmentStatement(variable, null));
                }
            }

            if (match(TokenType.CONST))
            {
                current = get(0);

                if (match(TokenType.WORD) && get(0).getType() == TokenType.EQ)
                {
                    string variable = current.getText();
                    consume(TokenType.EQ);
                    return(new AssignmentStatement(variable, expression()));
                }
            }
            else
            {
                current = get(0);

                if (lookMatch(0, TokenType.WORD) && lookMatch(1, TokenType.EQ))
                {
                    string variable = consume(TokenType.WORD).getText();
                    consume(TokenType.EQ);
                    return(new AssignmentStatement(variable, expression()));
                }

                // Проверка для массивов
                if (lookMatch(0, TokenType.WORD) && lookMatch(1, TokenType.LBRACKET))
                {
                    ArrayAccessExpression array = element();
                    consume(TokenType.EQ);
                    return(new ArrayAssignmentStatement(array, expression()));
                }
            }
            throw new Exception("Unknown statement");
        }