Ejemplo n.º 1
0
        /// <summary>
        ///     try to resolve simple case like for(int i=0; i<10; i++)
        /// </summary>
        private static IPyStatement[] TrySimpleForLoop(
            PyAssignExpression[] pyDeclarations,
            IPyStatement[]       incrementors,
            IPyValue condition,
            IPyStatement statement)
        {
            if (pyDeclarations.Length != 1 || incrementors.Length != 1)
            {
                return(null);
            }
            var dec = pyDeclarations[0];

            if (!(dec.Left is PyVariableExpression controlVariable))
            {
                return(null);
            }
            if (!(condition is PyBinaryOperatorExpression binCondition))
            {
                return(null);
            }
            binCondition = VariableOnLeft(binCondition, controlVariable.VariableName);

            var loopIncrement = FindIncrement(controlVariable, incrementors[0]);

            if (loopIncrement == null)
            {
                return(null);
            }

            var loopStart = pyDeclarations[0].Right;

            IPyStatement[] Q(object incrementValue)
            {
                var range          = new PyMethodCallExpression("range");
                var isOneIncrement = ValueHelper.EqualsNumericOne(incrementValue) ?? false;

                if (!IsConstZero(loopStart) || !isOneIncrement)
                {
                    range.Arguments.Add(new PyMethodInvokeValue(loopStart));
                }
                range.Arguments.Add(new PyMethodInvokeValue(binCondition.Right));
                if (!isOneIncrement)
                {
                    range.Arguments.Add(
                        new PyMethodInvokeValue(new PyConstValue(incrementValue)));
                }
                var foreachStatement =
                    new PyForEachStatement(controlVariable.VariableName, range, statement);

                return(new IPyStatement[] { foreachStatement });
            }

            if (loopIncrement is PyConstValue constLoopIncrement)
            {
                switch (binCondition.Operator)
                {
                case "<":
                {
                    if (ValueHelper.IsGreaterThanZero(constLoopIncrement.Value) ?? false)
                    {
                        return(Q(constLoopIncrement.Value));
                    }
                }
                break;

                case ">":
                {
                    if (ValueHelper.IsLowerThanZero(constLoopIncrement.Value) ?? false)
                    {
                        return(Q(constLoopIncrement.Value));
                    }
                }
                break;
                }
            }
            var result = new PyForStatement(pyDeclarations.ToArray(), condition, statement, incrementors);

            return(new IPyStatement[] { result });
        }