Esempio n. 1
0
        private Statement ProcessForeachStatement(ForeachNode node)
        {
            TypeSymbol type = _symbolSet.ResolveType(node.Type, _symbolTable, _memberContext);

            Debug.Assert(type != null);

            bool dictionaryContainer = (type.Name == "DictionaryEntry") || (type.Name == "KeyValuePair`2");

            Expression collectionExpression = _expressionBuilder.BuildExpression(node.Container);

            if (collectionExpression is MemberExpression)
            {
                collectionExpression = _expressionBuilder.TransformMemberExpression((MemberExpression)collectionExpression);
            }

            ForInStatement statement;

            if (dictionaryContainer)
            {
                VariableSymbol dictionaryVariable = null;

                if (collectionExpression.Type != ExpressionType.Local)
                {
                    string dictionaryVariableName = _symbolTable.CreateSymbolName("dict");
                    dictionaryVariable = new VariableSymbol(dictionaryVariableName, _memberContext,
                                                            collectionExpression.EvaluatedType);
                }

                statement = new ForInStatement(collectionExpression, dictionaryVariable);

                string         keyVariableName = _symbolTable.CreateSymbolName("key");
                VariableSymbol keyVariable     = new VariableSymbol(keyVariableName, _memberContext,
                                                                    _symbolSet.ResolveIntrinsicType(IntrinsicType.String));
                statement.SetLoopVariable(keyVariable);
            }
            else
            {
                statement = new ForInStatement(collectionExpression);

                string         enumeratorVariableName = _symbolTable.CreateSymbolName("enum");
                VariableSymbol enumVariable           = new VariableSymbol(enumeratorVariableName, _memberContext,
                                                                           _symbolSet.ResolveIntrinsicType(IntrinsicType.IEnumerator));
                statement.SetLoopVariable(enumVariable);
            }

            _symbolTable.PushScope();

            VariableSymbol itemVariable = new VariableSymbol(node.Name.Name, _memberContext, type);

            _symbolTable.AddSymbol(itemVariable);
            statement.SetItemVariable(itemVariable);

            Statement body = BuildStatement((StatementNode)node.Body);

            statement.AddBody(body);

            _symbolTable.PopScope();

            return(statement);
        }
Esempio n. 2
0
 public JintForInForOfStatement(ForInStatement statement) : base(statement)
 {
     _leftNode        = statement.Left;
     _rightExpression = statement.Right;
     _forBody         = statement.Body;
     _iterationKind   = IterationKind.Enumerate;
 }
        public virtual Statement visit(ForInStatement forInStatement)
        {
            forInStatement.variable   = visitExpression(forInStatement.variable);
            forInStatement.expression = visitExpression(forInStatement.expression);
            forInStatement.statement  = visitStatement(forInStatement.statement);

            return(forInStatement);
        }
Esempio n. 4
0
        public virtual void VisitForInStatement(ForInStatement forInStatement)
        {
            Identifier identifier = forInStatement.Left.Type == Nodes.VariableDeclaration
                ? forInStatement.Left.As <VariableDeclaration>().Declarations.First().Id.As <Identifier>()
                : forInStatement.Left.As <Identifier>();

            VisitExpression(identifier);
            VisitExpression(forInStatement.Right);
            VisitStatement(forInStatement.Body);
        }
Esempio n. 5
0
 protected override void VisitForInStatement(ForInStatement forInStatement)
 {
     using (StartNodeObject(forInStatement))
     {
         Member("left", forInStatement.Left);
         Member("right", forInStatement.Right);
         Member("body", forInStatement.Body);
         Member("each", forInStatement.Each);
     }
 }
Esempio n. 6
0
 public JintForInForOfStatement(
     Engine engine,
     ForInStatement statement) : base(engine, statement)
 {
     _initialized     = false;
     _leftNode        = statement.Left;
     _rightExpression = statement.Right;
     _forBody         = statement.Body;
     _iterationKind   = IterationKind.Enumerate;
 }
Esempio n. 7
0
        protected override void VisitForInStatement(ForInStatement tree)
        {
            _TrySetResult(tree);
            if (_result != null)
            {
                return;
            }

            VisitAnySyntaxTree(tree.name_list);
            VisitAnySyntaxTree(tree.exp_list);
            VisitAnySyntaxTree(tree.block);
        }
 public void Visit(ForInStatement node)
 {
     if (node != null)
     {
         if (node.Body == null || node.Body.Count == 0)
         {
             DoesRequire = false;
         }
         else
         {
             node.Body.Accept(this);
         }
     }
 }
Esempio n. 9
0
 public virtual object Walk(ForInStatement node)
 {
     if (Enter(node))
     {
         if (node.VariableDeclaration != null)
         {
             node.VariableDeclaration.Accept(this);
         }
         else
         {
             node.LeftHandSideExpression.Accept(this);
         }
         node.Collection.Accept(this);
         node.Body.Accept(this);
     }
     Exit(node);
     return(null);
 }
Esempio n. 10
0
        public override object Walk(ForInStatement node)
        {
            var collection = node.Collection.Accept(this);

            if (collection == null)
            {
                throw ErrorFactory.CreateNullError("Collection");
            }
            if (!typeof(IEnumerable).IsAssignableFrom(collection.GetType()))
            {
                throw ErrorFactory.CreateTypeError(string.Format("Object {0} is not enumerable", collection));
            }

            string id;
            bool   hasDeclaration = false;

            if (node.VariableDeclaration == null)
            {
                id = ((Identifier)node.LeftHandSideExpression.Accept(this)).Value;
            }
            else
            {
                id             = node.VariableDeclaration.Identifier.Value;
                hasDeclaration = true;
            }

            object result = null;
            Action body   = delegate
            {
                foreach (var element in (IEnumerable)collection)
                {
                    Context.CurrentFrame.Assign(id, element);
                    try { result = node.Body.Accept(this); }
                    catch (Break) { break; }
                    catch (Next) { continue; }
                }
            };
            Action <ScopeFrame> init = scopeFrame => scopeFrame.Define(id, null);

            Context.OpenScopeFor(body, withInit: init, when: hasDeclaration);
            return(result);
        }
Esempio n. 11
0
        public virtual void Visit(ForInStatement node)
        {
            if (node != null)
            {
                if (node.Variable != null)
                {
                    node.Variable.Accept(this);
                }

                if (node.Collection != null)
                {
                    node.Collection.Accept(this);
                }

                if (node.Body != null)
                {
                    node.Body.Accept(this);
                }
            }
        }
        private UstStmts.ForeachStatement VisitForInStatement(ForInStatement forInStatement)
        {
            UstTokens.IdToken name = null;
            var left = Visit(forInStatement.Left);

            if (left is UstTokens.IdToken token)
            {
                name = token;
            }
            else if (left is UstStmts.ExpressionStatement exprStmt &&
                     exprStmt.Expression is UstExprs.VariableDeclarationExpression varDecl &&
                     varDecl.Variables.Count > 0 &&
                     varDecl.Variables[0].Left is UstTokens.IdToken idToken)
            {
                name = idToken;
            }
            var inExpression = VisitExpression(forInStatement.Right);
            var body         = VisitStatement(forInStatement.Body);

            return(new UstStmts.ForeachStatement(null, name, inExpression, body, GetTextSpan(forInStatement)));
        }
Esempio n. 13
0
        // 5.6
        int IStatementVisitor <int> .VisitForIn(ForInStatement statement)
        {
            _Writer.Write("for (");
            WriteForInitializer(statement.Variable);
            _Writer.Write(" in ");
            statement.Value.Accept(this);
            _Writer.WriteLine(") {");

            if (statement.HasStatement)
            {
                _Writer.Indent++;
                foreach (var s in statement.Statements)
                {
                    s.Accept(this);
                }
                _Writer.Indent--;
            }

            _Writer.WriteLine('}');

            return(0);
        }
Esempio n. 14
0
        public ForInStatement ParseForInStatement()
        {
            var forInStatement = new ForInStatement {
                Token = Next()
            };

            Match(TokenType.For);
            Match(TokenType.LeftParen);
            if (Next().Is(TokenType.Var))
            {
                Match(TokenType.Var);
                forInStatement.VariableDeclaration = ParseVariableDeclaration();
            }
            else
            {
                forInStatement.LeftHandSideExpression = ParseLeftHandSideExpression();
            }
            Match(TokenType.In);
            forInStatement.Collection = ParseAssignmentExpression();
            Match(TokenType.RightParen);
            forInStatement.Body = ParseStatement();
            return(forInStatement);
        }
Esempio n. 15
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4
        /// </summary>
        /// <param name="forInStatement"></param>
        /// <returns></returns>
        public Completion ExecuteForInStatement(ForInStatement forInStatement)
        {
            Identifier identifier = forInStatement.Left.Type == SyntaxNodes.VariableDeclaration
                                        ? forInStatement.Left.As <VariableDeclaration>().Declarations.First().Id
                                        : forInStatement.Left.As <Identifier>();

            var varRef     = _engine.EvaluateExpression(identifier) as Reference;
            var exprRef    = _engine.EvaluateExpression(forInStatement.Right);
            var experValue = _engine.GetValue(exprRef);

            if (experValue == Undefined.Instance || experValue == Null.Instance)
            {
                return(new Completion(Completion.Normal, null, null));
            }


            var     obj = TypeConverter.ToObject(_engine, experValue);
            JsValue v   = Null.Instance;

            // keys are constructed using the prototype chain
            var cursor        = obj;
            var processedKeys = new HashSet <string>();

            while (cursor != null)
            {
                var keys = cursor.GetOwnProperties().Select(x => x.Key).ToArray();
                foreach (var p in keys)
                {
                    if (processedKeys.Contains(p))
                    {
                        continue;
                    }

                    processedKeys.Add(p);

                    // collection might be modified by inner statement
                    if (!cursor.HasOwnProperty(p))
                    {
                        continue;
                    }

                    var value = cursor.GetOwnProperty(p);
                    if (!value.Enumerable.HasValue || !value.Enumerable.Value)
                    {
                        continue;
                    }

                    _engine.PutValue(varRef, p);

                    var stmt = ExecuteStatement(forInStatement.Body);
                    if (stmt.Value.HasValue)
                    {
                        v = stmt.Value.Value;
                    }
                    if (stmt.Type == Completion.Break)
                    {
                        return(new Completion(Completion.Normal, v, null));
                    }
                    if (stmt.Type != Completion.Continue)
                    {
                        if (stmt.Type != Completion.Normal)
                        {
                            return(stmt);
                        }
                    }
                }

                cursor = cursor.Prototype;
            }

            return(new Completion(Completion.Normal, v, null));
        }
Esempio n. 16
0
 public virtual void VisitForInStatement(ForInStatement forinStatement)
 {
     VisitStatement(forinStatement.Each);
     VisitExpression(forinStatement.Enumerable);
     VisitStatement(forinStatement.Body);
 }
Esempio n. 17
0
 protected internal override void VisitForInStatement(ForInStatement forInStatement)
 {
     VisitingForInStatement?.Invoke(this, forInStatement);
     base.VisitForInStatement(forInStatement);
     VisitedForInStatement?.Invoke(this, forInStatement);
 }
Esempio n. 18
0
 public override bool Enter(ForInStatement node)
 {
     Print("ForInStatement");
     level++;
     return true;
 }
Esempio n. 19
0
 public virtual bool Enter(ForInStatement node)
 {
     return true;
 }
Esempio n. 20
0
 public void Visit(ForInStatement node)
 {
     Debug.Fail("shouldn't get here");
 }
 public virtual void Exit(ForInStatement node)
 {
 }
Esempio n. 22
0
 public void Visit(ForInStatement node)
 {
     // not applicable; terminate
 }
Esempio n. 23
0
        public override object Walk(ForInStatement node)
        {
            var collection = node.Collection.Accept(this);
            if (collection == null)
                throw ErrorFactory.CreateNullError("Collection");
            if (!typeof(IEnumerable).IsAssignableFrom(collection.GetType()))
                throw ErrorFactory.CreateTypeError(string.Format("Object {0} is not enumerable", collection));

            string id;
            bool hasDeclaration = false;
            if (node.VariableDeclaration == null)
            {
                id = ((Identifier)node.LeftHandSideExpression.Accept(this)).Value;
            }
            else
            {
                id = node.VariableDeclaration.Identifier.Value;
                hasDeclaration = true;
            }

            object result = null;
            Action body = delegate
                              {
                                  foreach (var element in (IEnumerable)collection)
                                  {
                                      Context.CurrentFrame.Assign(id, element);
                                      try { result = node.Body.Accept(this); }
                                      catch (Break) { break; }
                                      catch (Next) { continue; }
                                  }
                              };
            Action<ScopeFrame> init = scopeFrame => scopeFrame.Define(id, null);
            Context.OpenScopeFor(body, withInit: init, when: hasDeclaration);
            return result;
        }
Esempio n. 24
0
    // $ANTLR start "forInStatement"
    // JavaScript.g:143:1: forInStatement : 'for' ( LT )* '(' ( LT )* forInStatementInitialiserPart ( LT )* 'in' ( LT )* expression ( LT )* ')' ( LT )* statement ;
    public JavaScriptParser.forInStatement_return forInStatement() // throws RecognitionException [1]
    {   
        JavaScriptParser.forInStatement_return retval = new JavaScriptParser.forInStatement_return();
        retval.Start = input.LT(1);

        object root_0 = null;

        IToken string_literal139 = null;
        IToken LT140 = null;
        IToken char_literal141 = null;
        IToken LT142 = null;
        IToken LT144 = null;
        IToken string_literal145 = null;
        IToken LT146 = null;
        IToken LT148 = null;
        IToken char_literal149 = null;
        IToken LT150 = null;
        JavaScriptParser.forInStatementInitialiserPart_return forInStatementInitialiserPart143 = default(JavaScriptParser.forInStatementInitialiserPart_return);

        JavaScriptParser.expression_return expression147 = default(JavaScriptParser.expression_return);

        JavaScriptParser.statement_return statement151 = default(JavaScriptParser.statement_return);


        object string_literal139_tree=null;
        object LT140_tree=null;
        object char_literal141_tree=null;
        object LT142_tree=null;
        object LT144_tree=null;
        object string_literal145_tree=null;
        object LT146_tree=null;
        object LT148_tree=null;
        object char_literal149_tree=null;
        object LT150_tree=null;

        try 
    	{
            // JavaScript.g:144:2: ( 'for' ( LT )* '(' ( LT )* forInStatementInitialiserPart ( LT )* 'in' ( LT )* expression ( LT )* ')' ( LT )* statement )
            // JavaScript.g:144:4: 'for' ( LT )* '(' ( LT )* forInStatementInitialiserPart ( LT )* 'in' ( LT )* expression ( LT )* ')' ( LT )* statement
            {
            	root_0 = (object)adaptor.GetNilNode();

            	string_literal139=(IToken)Match(input,52,FOLLOW_52_in_forInStatement1152); if (state.failed) return retval;
            	if ( state.backtracking == 0 )
            	{string_literal139_tree = new ForInStatement(string_literal139) ;
            		root_0 = (object)adaptor.BecomeRoot(string_literal139_tree, root_0);
            	}
            	// JavaScript.g:144:29: ( LT )*
            	do 
            	{
            	    int alt74 = 2;
            	    int LA74_0 = input.LA(1);

            	    if ( (LA74_0 == LT) )
            	    {
            	        alt74 = 1;
            	    }


            	    switch (alt74) 
            		{
            			case 1 :
            			    // JavaScript.g:144:29: LT
            			    {
            			    	LT140=(IToken)Match(input,LT,FOLLOW_LT_in_forInStatement1158); if (state.failed) return retval;

            			    }
            			    break;

            			default:
            			    goto loop74;
            	    }
            	} while (true);

            	loop74:
            		;	// Stops C# compiler whining that label 'loop74' has no statements

            	char_literal141=(IToken)Match(input,42,FOLLOW_42_in_forInStatement1162); if (state.failed) return retval;
            	// JavaScript.g:144:39: ( LT )*
            	do 
            	{
            	    int alt75 = 2;
            	    int LA75_0 = input.LA(1);

            	    if ( (LA75_0 == LT) )
            	    {
            	        alt75 = 1;
            	    }


            	    switch (alt75) 
            		{
            			case 1 :
            			    // JavaScript.g:144:39: LT
            			    {
            			    	LT142=(IToken)Match(input,LT,FOLLOW_LT_in_forInStatement1165); if (state.failed) return retval;

            			    }
            			    break;

            			default:
            			    goto loop75;
            	    }
            	} while (true);

            	loop75:
            		;	// Stops C# compiler whining that label 'loop75' has no statements

            	PushFollow(FOLLOW_forInStatementInitialiserPart_in_forInStatement1169);
            	forInStatementInitialiserPart143 = forInStatementInitialiserPart();
            	state.followingStackPointer--;
            	if (state.failed) return retval;
            	if ( state.backtracking == 0 ) adaptor.AddChild(root_0, forInStatementInitialiserPart143.Tree);
            	// JavaScript.g:144:74: ( LT )*
            	do 
            	{
            	    int alt76 = 2;
            	    int LA76_0 = input.LA(1);

            	    if ( (LA76_0 == LT) )
            	    {
            	        alt76 = 1;
            	    }


            	    switch (alt76) 
            		{
            			case 1 :
            			    // JavaScript.g:144:74: LT
            			    {
            			    	LT144=(IToken)Match(input,LT,FOLLOW_LT_in_forInStatement1171); if (state.failed) return retval;

            			    }
            			    break;

            			default:
            			    goto loop76;
            	    }
            	} while (true);

            	loop76:
            		;	// Stops C# compiler whining that label 'loop76' has no statements

            	string_literal145=(IToken)Match(input,53,FOLLOW_53_in_forInStatement1175); if (state.failed) return retval;
            	// JavaScript.g:144:85: ( LT )*
            	do 
            	{
            	    int alt77 = 2;
            	    int LA77_0 = input.LA(1);

            	    if ( (LA77_0 == LT) )
            	    {
            	        alt77 = 1;
            	    }


            	    switch (alt77) 
            		{
            			case 1 :
            			    // JavaScript.g:144:85: LT
            			    {
            			    	LT146=(IToken)Match(input,LT,FOLLOW_LT_in_forInStatement1178); if (state.failed) return retval;

            			    }
            			    break;

            			default:
            			    goto loop77;
            	    }
            	} while (true);

            	loop77:
            		;	// Stops C# compiler whining that label 'loop77' has no statements

            	PushFollow(FOLLOW_expression_in_forInStatement1182);
            	expression147 = expression();
            	state.followingStackPointer--;
            	if (state.failed) return retval;
            	if ( state.backtracking == 0 ) adaptor.AddChild(root_0, expression147.Tree);
            	// JavaScript.g:144:101: ( LT )*
            	do 
            	{
            	    int alt78 = 2;
            	    int LA78_0 = input.LA(1);

            	    if ( (LA78_0 == LT) )
            	    {
            	        alt78 = 1;
            	    }


            	    switch (alt78) 
            		{
            			case 1 :
            			    // JavaScript.g:144:101: LT
            			    {
            			    	LT148=(IToken)Match(input,LT,FOLLOW_LT_in_forInStatement1184); if (state.failed) return retval;

            			    }
            			    break;

            			default:
            			    goto loop78;
            	    }
            	} while (true);

            	loop78:
            		;	// Stops C# compiler whining that label 'loop78' has no statements

            	char_literal149=(IToken)Match(input,44,FOLLOW_44_in_forInStatement1188); if (state.failed) return retval;
            	// JavaScript.g:144:111: ( LT )*
            	do 
            	{
            	    int alt79 = 2;
            	    int LA79_0 = input.LA(1);

            	    if ( (LA79_0 == LT) )
            	    {
            	        alt79 = 1;
            	    }


            	    switch (alt79) 
            		{
            			case 1 :
            			    // JavaScript.g:144:111: LT
            			    {
            			    	LT150=(IToken)Match(input,LT,FOLLOW_LT_in_forInStatement1191); if (state.failed) return retval;

            			    }
            			    break;

            			default:
            			    goto loop79;
            	    }
            	} while (true);

            	loop79:
            		;	// Stops C# compiler whining that label 'loop79' has no statements

            	PushFollow(FOLLOW_statement_in_forInStatement1195);
            	statement151 = statement();
            	state.followingStackPointer--;
            	if (state.failed) return retval;
            	if ( state.backtracking == 0 ) adaptor.AddChild(root_0, statement151.Tree);

            }

            retval.Stop = input.LT(-1);

            if ( (state.backtracking==0) )
            {	retval.Tree = (object)adaptor.RulePostProcessing(root_0);
            	adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);}
        }
        catch (RecognitionException re) 
    	{
            ReportError(re);
            Recover(input,re);
    	// Conversion of the second argument necessary, but harmless
    	retval.Tree = (object)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);

        }
        finally 
    	{
        }
        return retval;
    }
Esempio n. 25
0
        private static void GenerateForInStatement(ScriptGenerator generator, MemberSymbol symbol, ForInStatement statement)
        {
            ScriptTextWriter writer = generator.Writer;

            if (statement.IsDictionaryEnumeration)
            {
                writer.Write("var ");
                writer.Write(statement.DictionaryVariable.GeneratedName);
                writer.WriteTrimmed(" = ");
                ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                writer.Write(";");
                writer.WriteNewLine();

                writer.WriteTrimmed("for ");
                writer.Write("(var ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write(" in ");
                writer.Write(statement.DictionaryVariable.GeneratedName);
                writer.WriteTrimmed(") ");
                writer.Write("{");
                writer.WriteNewLine();
                writer.Indent++;
                writer.Write("var ");
                writer.Write(statement.ItemVariable.GeneratedName);
                writer.WriteTrimmed(" = ");
                writer.WriteTrimmed("{ ");
                writer.WriteTrimmed("key: ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.WriteTrimmed(", ");
                writer.WriteTrimmed("value: ");
                writer.Write(statement.DictionaryVariable.GeneratedName);
                writer.Write("[");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write("]");
                writer.WriteTrimmed(" };");
                writer.WriteNewLine();
                GenerateStatement(generator, symbol, statement.Body);
                writer.Indent--;
                writer.Write("}");
                writer.WriteNewLine();
            }
            else
            {
                writer.Write("var ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.WriteTrimmed(" = ");

                writer.Write("ss.IEnumerator.getEnumerator(");
                ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                writer.Write(");");

                writer.WriteNewLine();

                writer.WriteTrimmed("while ");
                writer.Write("(");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.WriteTrimmed(".moveNext()) ");
                writer.Write("{");
                writer.WriteNewLine();
                writer.Indent++;

                writer.Write("var ");
                writer.Write(statement.ItemVariable.GeneratedName);
                writer.WriteTrimmed(" = ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write(".current;");
                writer.WriteNewLine();

                GenerateStatement(generator, symbol, statement.Body);

                writer.Indent--;
                writer.Write("}");
                writer.WriteNewLine();
            }
        }
Esempio n. 26
0
 public override bool Enter(ForInStatement node)
 {
     Print("ForInStatement");
     level++;
     return(true);
 }
Esempio n. 27
0
 protected abstract void Visit(ForInStatement node);
 public virtual bool Enter(ForInStatement node)
 {
     return(true);
 }
Esempio n. 29
0
 public ForInStatement ParseForInStatement()
 {
     var forInStatement = new ForInStatement { Token = Next() };
     Match(TokenType.For);
     Match(TokenType.LeftParen);
     if (Next().Is(TokenType.Var))
     {
         Match(TokenType.Var);
         forInStatement.VariableDeclaration = ParseVariableDeclaration();
     }
     else
     {
         forInStatement.LeftHandSideExpression = ParseLeftHandSideExpression();
     }
     Match(TokenType.In);
     forInStatement.Collection = ParseAssignmentExpression();
     Match(TokenType.RightParen);
     forInStatement.Body = ParseStatement();
     return forInStatement;
 }
Esempio n. 30
0
        private Statement ParseForStatement(ILabelSet labelSet)
        {
            var startPosition         = Lookahead.StartPosition;
            IterationStatement result = null;

            Match(TokenType.For);
            Match(TokenType.LParenthesis);
            var isVariableDeclaration = false;

            if (Lookahead.Type == TokenType.Var)
            {
                ReadNextToken();
                isVariableDeclaration = true;
            }
            if (Lookahead.Type == TokenType.Ident)
            {
                var variableName = Lookahead.Value;
                if (PeekNextToken().Type == TokenType.In)
                {
                    MoveForwardLookahead();
                    if (isVariableDeclaration)
                    {
                        if (!_currentFunction.DeclaredVariables.Contains(variableName))
                        {
                            _currentFunction.DeclaredVariables.Add(variableName);
                        }
                    }
                    result = new ForInStatement(startPosition.LineNo, variableName, ParseExpression(), labelSet);
                }
            }
            if (result == null)
            {
                Expression initialization = null;
                if (isVariableDeclaration)
                {
                    initialization = ParseVariableDeclarationList();
                }
                else
                {
                    if (Lookahead.Type != TokenType.Semicolon)
                    {
                        initialization = ParseExpression();
                    }
                }
                Match(TokenType.Semicolon);
                Expression condition = null;
                if (Lookahead.Type != TokenType.Semicolon)
                {
                    condition = ParseExpression();
                }
                Match(TokenType.Semicolon);
                Expression increment = null;
                if (Lookahead.Type != TokenType.RParenthesis)
                {
                    increment = ParseExpression();
                }
                result = new ForStatement(startPosition.LineNo, initialization, condition, increment, labelSet);
            }
            Match(TokenType.RParenthesis);
            result.Statement = ParseStatement(true);
            return(result);
        }
Esempio n. 31
0
 public virtual Statement visit(ForInStatement statement)
 {
     return(statement);
 }
Esempio n. 32
0
        private static void GenerateForInStatement(ScriptGenerator generator, MemberSymbol symbol,
                                                   ForInStatement statement)
        {
            ScriptTextWriter writer        = generator.Writer;
            TypeSymbol       evaluatedType = statement.CollectionExpression.EvaluatedType;

            if (statement.IsDictionaryEnumeration)
            {
                if (statement.DictionaryVariable != null)
                {
                    writer.Write("var ");
                    writer.Write(statement.DictionaryVariable.GeneratedName);
                    writer.Write(" = ");
                    ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                    writer.Write(";");
                    writer.WriteLine();
                }

                writer.Write("for (var ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write(" in ");

                if (statement.DictionaryVariable != null)
                {
                    writer.Write(statement.DictionaryVariable.GeneratedName);
                }
                else
                {
                    ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                }

                writer.WriteLine(") {");
                writer.Indent++;
                writer.Write("var ");
                writer.Write(statement.ItemVariable.GeneratedName);
                writer.Write(" = { key: ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write(", value: ");

                if (statement.DictionaryVariable != null)
                {
                    writer.Write(statement.DictionaryVariable.GeneratedName);
                }
                else
                {
                    ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                }

                writer.Write("[");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.WriteLine("] };");
                GenerateStatement(generator, symbol, statement.Body);
                writer.Indent--;
                writer.WriteLine("}");
            }
            else if (evaluatedType.IsNativeArray || evaluatedType.IsListType())
            {
                string dataSourceVariableName = statement.LoopVariable.GeneratedName;
                string indexVariableName      = dataSourceVariableName + "_index";

                // var $$ = ({CollectionExpression});
                writer.Write("var " + dataSourceVariableName + " = (");
                ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                writer.WriteLine(");");

                // for(var items_index = 0; items_index < items.length; ++items_index) {
                writer.WriteLine("for(var " + indexVariableName + " = 0; " + indexVariableName + " < " + dataSourceVariableName + ".length; ++" + indexVariableName + ") {");

                ++writer.Indent;

                if (evaluatedType.IsNativeArray)
                {
                    // var i = items[items_index];
                    writer.WriteLine("var " + statement.ItemVariable.GeneratedName + " = " + dataSourceVariableName + "[" + indexVariableName + "];");
                }
                else
                {
                    // var i = ss.getItem(items, items_index);
                    writer.WriteLine("var " + statement.ItemVariable.GeneratedName + " = ss.getItem(" + dataSourceVariableName + ", " + indexVariableName + ");");
                }

                GenerateStatement(generator, symbol, statement.Body);

                --writer.Indent;
                writer.WriteLine("}");
            }
            else
            {
                writer.Write("var ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write(" = ");

                writer.Write($"{DSharpStringResources.ScriptExportMember("enumerate")}(");
                ExpressionGenerator.GenerateExpression(generator, symbol, statement.CollectionExpression);
                writer.Write(");");

                writer.WriteLine();

                writer.Write("while (");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.WriteLine(".moveNext()) {");
                writer.Indent++;

                writer.Write("var ");
                writer.Write(statement.ItemVariable.GeneratedName);
                writer.Write(" = ");
                writer.Write(statement.LoopVariable.GeneratedName);
                writer.Write(".current;");
                writer.WriteLine();

                GenerateStatement(generator, symbol, statement.Body);

                writer.Indent--;
                writer.Write("}");
                writer.WriteLine();
            }
        }
Esempio n. 33
0
 public void Visit(ForInStatement node)
 {
     ReportError(node);
 }
Esempio n. 34
0
 public virtual void Exit(ForInStatement node)
 {
 }
Esempio n. 35
0
 public void Visit(ForInStatement node)
 {
     // starts with a 'for', so we don't care
 }
Esempio n. 36
0
 public override void Exit(ForInStatement node)
 {
     level--;
 }
Esempio n. 37
0
 public override void Exit(ForInStatement node)
 {
     level--;
 }
Esempio n. 38
0
        private static int RelocateForInVar(BlockStatement block, int insertAt, VarDeclaration varStatement, ForInStatement forIn)
        {
            // there should only be one decl in the for-in var statement. There should not be any initializer.
            // If not, then ignore it
            VariableDeclaration varDecl;

            if (varStatement.Count == 1 && (varDecl = varStatement[0]).Initializer == null)
            {
                // if there are more than three names, then we don't want to move them
                var bindingNames = BindingsVisitor.Bindings(varDecl.Binding);
                //if (bindingNames.Count < 3)
                {
                    // replace the varStatement in the for-in with a reference version of the binding
                    forIn.Variable = BindingTransform.FromBinding(varDecl.Binding);

                    // if this is a simple binding identifier, then leave it as-is. Otherwise we
                    // need to flatten it for the move to the front of the scope.
                    if (!(varDecl.Binding is BindingIdentifier))
                    {
                        // then flatten all the name in the binding and add them to the
                        var first = true;
                        foreach (var declName in bindingNames)
                        {
                            if (first)
                            {
                                varStatement[0] = new VariableDeclaration(declName.Context)
                                {
                                    Binding = new BindingIdentifier(declName.Context)
                                    {
                                        Name          = declName.Name,
                                        VariableField = declName.VariableField
                                    }
                                };
                                first = false;
                            }
                            else
                            {
                                // otherwise we want to insert a new one at the current position + 1
                                varStatement.Append(new VariableDeclaration(declName.Context)
                                {
                                    Binding = new BindingIdentifier(declName.Context)
                                    {
                                        Name          = declName.Name,
                                        VariableField = declName.VariableField
                                    }
                                });
                            }
                        }
                    }

                    // then move the var statement to the front of the scope
                    // if the statement at the insertion point is a var-statement already,
                    // then we just need to append our vardecls to it. Otherwise we'll insert our
                    // var statement at the right point
                    var existingVar = block[insertAt] as VarDeclaration;
                    if (existingVar != null)
                    {
                        // append the varstatement we want to move to the existing var, which will
                        // transfer all the vardecls to it.
                        existingVar.Append(varStatement);
                    }
                    else
                    {
                        // insert it at the insert point
                        block.Insert(insertAt, varStatement);
                    }
                }
            }

            return(insertAt);
        }
Esempio n. 39
0
 public virtual object Walk(ForInStatement node)
 {
     if (Enter(node))
     {
         if (node.VariableDeclaration != null)
             node.VariableDeclaration.Accept(this);
         else
             node.LeftHandSideExpression.Accept(this);
         node.Collection.Accept(this);
         node.Body.Accept(this);
     }
     Exit(node);
     return null;
 }