Пример #1
0
        public AplusScope(AplusScope parent,
            string name,
            Aplus runtime = null,
            DLR.ParameterExpression runtimeParam = null,
            DLR.ParameterExpression moduleParam = null,
            DLR.LabelTarget returnTarget = null,
            bool isEval = false,
            bool isMethod = false,
            bool isAssignment = false)
        {
            this.parent = parent;
            this.name = name;
            this.runtime = runtime;
            this.runtimeParam = runtimeParam;
            this.moduleParam = moduleParam;

            this.returnTarget = returnTarget;

            this.variables = new Dictionary<string, DLR.ParameterExpression>();

            this.callbackInfo = new CallbackInfoStorage();

            this.iseval = isEval;

            this.ismethod = isMethod;
            this.isAssignment = isAssignment;

            InheritProperties(parent);
        }
Пример #2
0
        public override AType Execute(AType rightArgument, AType leftArgument, Aplus environment = null)
        {
            if (leftArgument.Type != ATypes.AInteger)
            {
                throw new Error.Type(this.TypeErrorText);
            }

            AType left = Function.Monadic.MonadicFunctionInstance.Ravel.Execute(leftArgument);
            AType right = Function.Monadic.MonadicFunctionInstance.Ravel.Execute(rightArgument);

            AType result;

            switch (CheckVector(left))
            {
                case State.NullFound:
                    // Found a zero in the list, create an emtpy list with correct shape
                    result = CreateResult(left, right);
                    result.Shape = new List<int>(left.Select(item => { return item.asInteger; }));
                    result.Rank = result.Shape.Count;
                    result.Length = result.Shape[0];
                    break;
                case State.DomainError:
                    throw new Error.Domain(this.DomainErrorText);
                case State.MaxRankError:
                    throw new Error.MaxRank(this.MaxRankErrorText);

                default:
                case State.OK:
                    result = CreateResult(left, right);
                    break;
            }

            return result;
        }
Пример #3
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            if (left.Rank < 1 || right.Rank < 1)
            {
                throw new Error.Rank(this.RankErrorText);
            }

            if (left.Shape[left.Shape.Count - 1] != right.Shape[0])
            {
                throw new Error.Length(this.LengthErrorText);
            }

            // Calculate the axes for the right argument: (-1 rot iota rho rho right)
            AType targetAxes = DyadicFunctionInstance.Rotate.Execute(
                Enumerable.Range(0, right.Rank).ToAArray(), AInteger.Create(-1), environment);

            AType transposedRight = DyadicFunctionInstance.TransposeAxis.Execute(right, targetAxes, environment);

            AType result = WalkItems(left, transposedRight, environment);

            // by observation it seems that the reference implementation always returns float
            // we behave the same
            result.ConvertToFloat();

            if (result.Length == 0)
            {
                result.Shape = new List<int>(left.Shape.GetRange(0, left.Shape.Count - 1));
                if (right.Shape.Count > 1)
                {
                    result.Shape.AddRange(right.Shape.GetRange(1, right.Shape.Count - 1));
                }
            }
            
            return result;
        }
Пример #4
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            // First we check if one side is an ANull
            if (right.Type == ATypes.ANull)
            {
                return AArray.Create(left.Type, left.Clone());
            }
            else if (left.Type == ATypes.ANull)
            {
                return AArray.Create(right.Type, right.Clone());
            }

            // Type check
            if(!Utils.IsSameGeneralType(left, right))
            {
                throw new Error.Type(this.TypeErrorText);
            }

            AType result = CreateResult(right, left);

            // Convert to float if one of the arguments is an AFloat and the other is an AInteger
            if (Utils.DifferentNumberType(left, right))
            {
                result.ConvertToFloat();
            }

            return result;
        }
Пример #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <param name="env"></param>
        private AType WalkItems(AType left, AType right, Aplus env)
        {
            AType result;
            if (left.Rank > 1)
            {
                result = AArray.Create(ATypes.AArray);
                foreach (AType a in left)
                {
                    result.Add(WalkItems(a, right, env));
                }
            }
            else if (right.Rank > 1)
            {
                result = AArray.Create(ATypes.AArray);
                foreach (AType b in right)
                {
                    result.Add(WalkItems(left, b, env));
                }
            }
            else
            {
                result = Calculate(left, right, env);
            }

            return result;
        }
        private static AType PermissiveIndexingSubIndex(
            AType index, AType array, AType defaultItem, Aplus environment)
        {
            AType result = AArray.Create(array.Type);

            if (index.IsArray)
            {
                for (int i = 0; i < index.Length; i++)
                {
                    result.Add(PermissiveIndexingSubIndex(index[i], array, defaultItem, environment));
                }
            }
            else if (index.asInteger > array.Length - 1 || index.asInteger < 0)
            {
                if (defaultItem.Rank == 0 && array[0].Rank != 0)
                {
                    result = DyadicFunctionInstance.Reshape.Execute(defaultItem, array[0].Shape.ToAArray(), environment);
                }
                else
                {
                    result = defaultItem;
                }
            }
            else
            {
                result = array[index];
            }

            return result;
        }
Пример #7
0
        public static AType Import(Aplus environment, AType argument)
        {
            if (argument.Type != ATypes.AChar)
            {
                throw new Error.Type("sys.imp");
            }

            if (argument.Rank > 1)
            {
                throw new Error.Rank("sys.imp");
            }

            List<byte> toConvert = new List<byte>();

            if (argument.Rank == 0)
            {
                throw new Error.Domain("sys.imp"); // One character can't be a valid message.
            }

            foreach (AType item in argument)
            {
                toConvert.Add((byte)item.asChar);
            }

            return SysImp.Instance.Import(toConvert.ToArray());
        }
Пример #8
0
        public override AType Execute(AType argument, Aplus environment = null)
        {
            SetVariables(argument);

            AType result;

            //First dimension equal with zero case (as Null).
            if (argument.Length == 0)
            {
                result = argument.Clone();
                result.Type = this.type;
            }
            else
            {
                //Accepted types are float and integer.
                if (argument.Type != ATypes.AFloat && argument.Type != ATypes.AInteger)
                {
                    throw new Error.Type(TypeErrorText);
                }

                result = argument.IsArray ? ScanAlgorithm(argument) : PreProcess(argument);
            }

            return result;
        }
        internal static AType StringSearchandReplace(Aplus environment, AType replaceWith, AType replaceWhat, AType replaceIn)
        {
            if (replaceIn.Type != ATypes.AChar || replaceWhat.Type != ATypes.AChar || replaceWith.Type != ATypes.AChar)
            {
                throw new Error.Type("_ssr");
            }

            string withString = Monadic.MonadicFunctionInstance.Ravel.Execute(replaceWith, environment).ToString();
            string whatString = Monadic.MonadicFunctionInstance.Ravel.Execute(replaceWhat, environment).ToString();
            AType argument = (withString.Length == whatString.Length)
                ? replaceIn.Clone() : Monadic.MonadicFunctionInstance.Ravel.Execute(replaceIn, environment);

            Queue<string> rows = new Queue<string>();
            ExtractRows(argument, rows);

            Queue<string> replacedRows = new Queue<string>();

            foreach (string item in rows)
            {
                string replaced = item.Replace(whatString, withString);
                replacedRows.Enqueue(replaced);
            }

            AType result = BuildAType(replacedRows, argument.Shape);
            return result;

        }
Пример #10
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            bool resultFromBox;

            AType result = Compute(environment, right, left, out resultFromBox);
            return result;
        }
Пример #11
0
        /// <summary>
        /// Gets the absolute path for the supplied <see cref="pathArgument"/>.
        /// </summary>
        /// <remarks>
        /// The search for the file relies on the APATH environment variable.
        /// </remarks>
        /// <param name="environment"></param>
        /// <param name="pathArgument">Must be a Char or Symbol type.</param>
        /// <param name="expectedExtension"></param>
        /// <returns>The absolute path for the file or if not found null.</returns>
        internal static string GetPath(Aplus environment, AType pathArgument, string expectedExtension)
        {
            string path = GetFullPathOrValue(pathArgument, environment);
            string resultPath = null;

            if (path != null && !Path.IsPathRooted(path))
            {
                string apath = Environment.GetEnvironmentVariable("APATH", EnvironmentVariableTarget.User);
                string absolutePath;

                foreach (string item in apath.Split(';'))
                {
                    absolutePath = Path.Combine(item, path);

                    if (!Path.IsPathRooted(absolutePath))
                    {
                        absolutePath = Path.GetFullPath(absolutePath);
                    }

                    if (FileSearch(absolutePath, expectedExtension, out resultPath))
                    {
                        break;
                    }
                }
            }
            else
            {
                FileSearch(path, expectedExtension, out resultPath);
            }

            return resultPath;
        }
Пример #12
0
        public AType Execute(AType functionScalar, AType argument, Aplus environment = null)
        {
            //'Disclose' the function from functionscalar.
            AFunc function = (AFunc)functionScalar.NestedItem.Data;

            //Convert method to the correspond function format.
            if (function.IsBuiltin)
            {
                Func<Aplus, AType, AType, AType> primitiveFunction =
                    (Func<Aplus, AType, AType, AType>)function.Method;

                return primitiveFunction(environment, argument, null);
            }
            else
            {
                //If function is user defined, we check the valance.
                if (function.Valence - 1 != 1)
                {
                    throw new Error.Valence("Apply");
                }

                //Convert method to the correspond function format.
                Func<Aplus, AType, AType> userDefinedFunction =
                    (Func<Aplus, AType, AType>)function.Method;

                return userDefinedFunction(environment, argument);
            }
        }
Пример #13
0
        public PickAssignmentTarget AssignExecute(AType right, AType left, Aplus environment = null)
        {
            bool resultFromBox;

            AType result = Compute(environment, right, left, out resultFromBox);
            return new PickAssignmentTarget(result, resultFromBox);
        }
Пример #14
0
        public override AType Execute(AType argument, Aplus environment)
        {
            AType result;

            if (argument.SimpleArray())
            {
                result = argument.IsMemoryMappedFile ? argument : argument.Clone();
            }
            else
            {
                if (!argument.NestedArray())
                {
                    throw new Error.Domain(DomainErrorText);
                }

                switch (argument.Rank)
                {
                    case 0:
                        result = MonadicFunctionInstance.Disclose.Execute(argument);
                        break;
                    case 1:
                        result = NestedVector(argument);
                        break;
                    default:
                        throw new Error.Rank(RankErrorText);
                }
            }

            return result;
        }
Пример #15
0
        public static void InitContext(Aplus environment)
        {
            AipcService service = new AipcService(environment);
            service.StartNetworkLoop();

            environment.SetService<AipcService>(service);
        }
Пример #16
0
        internal static AType Items(Aplus environment, AType memoryMappedFileName, AType number)
        {
            string resultPath = Util.GetPath(environment, memoryMappedFileName, ".m");

            if (resultPath == null)
            {
                throw new Error.Domain("Items");
            }

            int newLeadingAxesLength = GetLeadingAxesLength(number);

            if (newLeadingAxesLength == -1)
            {
                return environment.MemoryMappedFileManager.GetLeadingAxesLength(resultPath);
            }
            else
            {
                if (environment.MemoryMappedFileManager.ExistMemoryMappedFile(resultPath))
                {
                    throw new Error.Invalid("Items");
                }

                return environment.MemoryMappedFileManager.ExpandOrDecrease(resultPath, newLeadingAxesLength);
            }
        }
Пример #17
0
        public AType Execute(AType function, AType n, AType right, AType left, Aplus environment = null)
        {
            if (!(function.Data is AFunc))
            {
                throw new Error.NonFunction("Rank");
            }

            AFunc func = (AFunc)function.Data;

            if (!func.IsBuiltin)
            {
                if (func.Valence - 1 != 2)
                {
                    throw new Error.Valence("Rank");
                }
            }

            int[] rankSpecifier = GetRankSpecifier(n, left, right, environment);
            RankJobInfo rankInfo = new RankJobInfo(rankSpecifier, func);

            AType result = Walker(left, right, environment, rankInfo);

            if (rankInfo.FloatConvert && result.IsArray)
            {
                result.ConvertToFloat();
            }

            return result;
        }
Пример #18
0
        private int GetNumber(AType argument, AType n, Aplus environment)
        {
            if (n.Type != ATypes.AInteger)
            {
                throw new Error.Type("Rank");
            }

            int length = n.Shape.Product();

            if (length > 3)
            {
                throw new Error.Length("Rank");
            }

            AType raveledArray = MonadicFunctionInstance.Ravel.Execute(n, environment);
            int result = raveledArray[0].asInteger;

            if (result < 0)
            {
                result = Math.Max(0, argument.Rank - Math.Abs(result));
            }
            else
            {
                result = Math.Min(result, argument.Rank);
            }

            return result;
        }
Пример #19
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            int desiredCount = PrepareDesiredCount(left);
            AType items = PrepareInputItems(right);

            return Compute(items, desiredCount);
        }
Пример #20
0
        /// <summary>
        /// Constructs a DLR Expression tree representing setting a variable inside a context.
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="variableContainer">The container where the lookup should be performed</param>
        /// <param name="contextParts">
        /// Contains 2 strings:
        ///  1. The name of the context
        ///  2. The name of the variable inside the context
        /// </param>
        /// <param name="value">Expression containing the value of the variable</param>
        /// <remarks>
        /// The returned DLR Expression tree will try to fetch the context inside the container.
        /// If the context does not exists, this will result an exception.
        /// If the exception occured, the context will be created inside the catch block.
        /// After this the context surely exists, so we can simply set the variable to the provided value.
        /// 
        /// </remarks>
        /// <returns>>Expression tree for setting a value for the given context parts</returns>
        internal static DLR.Expression SetVariable(Aplus runtime, DLR.Expression variableContainer, string[] contextParts, DLR.Expression value)
        {
            // Get the context
            DLR.Expression getContext =
                DLR.Expression.TryCatch(
                    DLR.Expression.Dynamic(
                        runtime.GetMemberBinder(contextParts[0]),
                        typeof(object),
                        variableContainer
                    ),
                    DLR.Expression.Catch(
                // Context not found, create one!
                        typeof(Error.Value),
                        DLR.Expression.Dynamic(
                            runtime.SetMemberBinder(contextParts[0]),
                            typeof(object),
                            variableContainer,
                            DLR.Expression.Constant(new ScopeStorage())
                        )
                    )
                );

            DLR.Expression setVariable = DLR.Expression.Dynamic(
                runtime.SetMemberBinder(contextParts[1]),
                typeof(object),
                getContext,
                value
            );
            return setVariable;
        }
Пример #21
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            ValidateInput(left, right);

            List<FormatInfo> formaters = new List<FormatInfo>();
            ExtractFormatInfo(left, formaters);
            return FormatArray(right, formaters);
        }
Пример #22
0
        public static AType ListenNP(Aplus environment, AType protocol, AType name, AType function)
        {
            if (protocol.Type != ATypes.ASymbol || name.Type != ATypes.ASymbol || function.Type != ATypes.AFunc)
            {
                return AInteger.Create(-1);
            }

            return environment.GetService<AipcService>().Listen(function, name, protocol);
        }
Пример #23
0
 public override AType ExecutePrimitive(AFloat argument, Aplus environment = null)
 {
     int result;
     if(argument.ConvertToRestrictedWholeNumber(out result))
     {
         return calculateNot(result);
     }
     throw new Error.Type(TypeErrorText);
 }
Пример #24
0
        internal AipcService(Aplus environment)
        {
            this.environment = environment;

            this.actualHandleNumber = 3210000;
            this.roster = new Dictionary<int, AipcConnection>();
            this.retryList = new HashSet<AipcConnection>();
            this.mutex = new object();
        }
Пример #25
0
        public override AType Execute(AType argument, Aplus environment = null)
        {
            if (argument.Type != ATypes.AChar)
            {
                throw new Error.Type(TypeErrorText);
            }

            return Compute(argument);
        }
Пример #26
0
        public override AType ExecutePrimitive(AFloat argument, Aplus environment = null)
        {
            int number;
            if (!argument.ConvertToRestrictedWholeNumber(out number))
            {
                throw new Error.Type("Bitwise not");
            }

            return AInteger.Create(~number);
        }
Пример #27
0
        public override AType Execute(AType argument, Aplus environment = null)
        {
            string message;
            if (ExtractString(argument, out message))
            {
                throw new Error.Signal(message);
            }

            throw new Error.Domain(this.DomainErrorText);
        }
Пример #28
0
        public override AType Execute(AType right, AType left, Aplus environment)
        {
            int[] transposeVector;
            int[] duplicateItems;
            ExtractData(left, right, out transposeVector, out duplicateItems);
            
            LinkedList<int> newShape = ComputeNewShape(right, transposeVector, duplicateItems);

            return CreateArray(right, newShape, new List<int>(), transposeVector);
        }
Пример #29
0
        /// <summary>
        /// Reconduct Choose to Bracket indexing.
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            //If the left side is Null then we clone the right side.
            if (left.Type == ATypes.ANull)
            {
                return right;
            }

            return right[GetIndexes(left, right)];
        }
Пример #30
0
        public AType Assign(AType right, AType left, Aplus environment)
        {
            //If the left side is Null then we clone the right side.
            if (left.Type == ATypes.ANull)
            {
                return right;
            }

            return right.Indexing(GetIndexes(left,right),0, true, right.IsMemoryMappedFile);
        }
Пример #31
0
 /// <summary>
 /// Execute the Monadic function.
 /// </summary>
 /// <param name="argument"></param>
 /// <returns></returns>
 abstract public AType Execute(AType argument, Aplus environment = null);
Пример #32
0
 public override AType ExecutePrimitive(AFloat argument, Aplus environment = null)
 {
     return(calculateReciprocal(argument.asFloat));
 }
Пример #33
0
        public override DLR.Expression Generate(AplusScope scope)
        {
            DLR.Expression result;
            Aplus          runtime = scope.GetRuntime();

            if (this.Type == IdentifierType.SystemName && runtime.SystemFunctions.ContainsKey(this.Name))
            {
                // Check if the name is a system function's name and we have such system function
                // and return it
                result = DLR.Expression.Constant(runtime.SystemFunctions[this.Name]);

                return(result);
            }

            DLR.Expression variableContainer = scope.GetModuleExpression();
            string[]       contextParts      = CreateContextNames(runtime.CurrentContext);

            // Check if the scope is a method
            if (scope.IsMethod)
            {
                DLR.Expression parentVariableContainer = scope.Parent.GetModuleExpression();

                // Check for variable in method scope
                // (maybe the variable is defined in the method header)
                DLR.Expression localVariable = scope.FindIdentifier(this.variableName);
                if (localVariable != null)
                {
                    // Found a variable defined in the method's header
                    return(localVariable);
                }

                if (this.type == IdentifierType.UnQualifiedName)
                {
                    // 1). we check if the variable exists in the function's scope
                    // 2). check if the variable exits in the current context (error if not found)
                    //
                    // if(((IDictionary<String, Object>)($FunctionScope).ContainsKey($VARIABLE))
                    // {
                    //      return $FunctionScope.$VARIABLE;
                    // }
                    // else
                    // {
                    //      return $GlobalScope.$VARIABLE
                    // }
                    //
                    DLR.Expression getVariable = DLR.Expression.Condition(
                        DLR.Expression.Call(
                            DLR.Expression.Convert(variableContainer, typeof(IDictionary <string, object>)),
                            typeof(IDictionary <string, object>).GetMethod("ContainsKey"),
                            DLR.Expression.Constant(this.variableName)
                            ),
                        // True case:
                        DLR.Expression.Dynamic(
                            runtime.GetMemberBinder(this.variableName),
                            typeof(object),
                            variableContainer
                            ),
                        // False case:
                        BuildGlobalAccessor(scope, runtime, parentVariableContainer, contextParts),
                        // resulting type
                        typeof(object)
                        );

                    result = DLR.Expression.Dynamic(
                        runtime.ConvertBinder(typeof(AType)),
                        typeof(AType),
                        getVariable
                        );

                    return(result);
                }
                else if (this.type == IdentifierType.QualifiedName)
                {
                    // Found a variable like: .var
                    // for this check the parent's variables
                    variableContainer = parentVariableContainer;
                    // Fallback to the non-method case
                }
            }

            result = Tools.CloneMemoryMappedFile(BuildGlobalAccessor(scope, runtime, variableContainer, contextParts));

            return(result);
        }
Пример #34
0
 protected override AType Calculate(AType left, AType right, Aplus env)
 {
     return(DyadicFunctionInstance.Min.Execute(right, left, env));
 }
Пример #35
0
        private AType Walker(AType left, AType right, Aplus environment, RankJobInfo rankInfo)
        {
            int tx = Math.Min(rankInfo.RankSpecifier[2], right.Rank - rankInfo.RankSpecifier[1]);
            int ty = Math.Min(rankInfo.RankSpecifier[2], left.Rank - rankInfo.RankSpecifier[0]);

            int lx = Math.Max(0, right.Rank - (rankInfo.RankSpecifier[1] + tx));
            int ly = Math.Max(0, left.Rank - (rankInfo.RankSpecifier[0] + ty));

            AType result;

            if (ly > 0)
            {
                result = LeftSideWalk(left, right, environment, rankInfo);
                result.UpdateInfo();
            }
            else if (lx > 0)
            {
                result = RightSideWalk(left, right, environment, rankInfo);
                result.UpdateInfo();
            }
            else if (ty != tx)
            {
                result = (ty > tx)
                    ? LeftSideWalk(left, right, environment, rankInfo)
                    : RightSideWalk(left, right, environment, rankInfo);

                result.UpdateInfo();
            }
            else
            {
                if (ty > 0)
                {
                    List <int> tyShape = left.Shape.GetRange(0, ty);
                    List <int> txShape = right.Shape.GetRange(0, tx);

                    if (!tyShape.SequenceEqual(txShape))
                    {
                        throw new Error.Mismatch("Rank");
                    }
                }

                if (ty != 0)
                {
                    result = AArray.Create(ATypes.ANull);
                    AType temp;

                    for (int i = 0; i < left.Length; i++)
                    {
                        temp = Walker(left[i], right[i], environment, rankInfo);
                        TypeCheck(temp.Type, rankInfo);
                        result.AddWithNoUpdate(temp);
                    }

                    result.UpdateInfo();
                }
                else
                {
                    result = rankInfo.Method(environment, right, left);
                }
            }

            return(result);
        }
Пример #36
0
 public override AType Execute(AType argument, Aplus environment = null)
 {
     return(Compute(argument));
 }
Пример #37
0
 public override AType Execute(AType right, AType left, Aplus environment = null)
 {
     this.ErrorCheck(right, left);
     return(SolveEquation(left, right));
 }
Пример #38
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            EncodeInformation arguments = ExtractEncodeInformation(left, right);

            return(Compute(left, right, arguments));
        }
Пример #39
0
        public override DLR.Expression Generate(AplusScope scope)
        {
            PreprocessVariables(scope);

            DLR.Expression result  = null;
            Aplus          runtime = scope.GetRuntime();

            if (scope.IsEval && scope.IsMethod)
            {
                // override the original scope
                // create a top level scope
                scope = new AplusScope(null, "_EVAL_DEP_SCOPE_",
                                       scope.GetRuntime(),
                                       scope.GetRuntimeExpression(),
                                       scope.Parent.GetModuleExpression(),
                                       scope.ReturnTarget,
                                       isEval: true
                                       );
            }

            // 1. Create a function scope
            string     dependencyName  = this.variable.BuildQualifiedName(runtime.CurrentContext);
            string     scopename       = String.Format("__dependency_{0}_scope__", this.variable.Name);
            AplusScope dependencyScope = new AplusScope(scope, scopename,
                                                        runtimeParam: scope.GetRuntimeExpression(),
                                                        moduleParam: DLR.Expression.Parameter(typeof(DYN.ExpandoObject), scopename),
                                                        returnTarget: DLR.Expression.Label(typeof(AType), "RETURN"),
                                                        isMethod: true
                                                        );
            // 1.5. Method for registering dependencies
            MethodInfo registerMethod;

            // 2. Prepare the method arguments (RuntimeExpression)
            DLR.ParameterExpression[] methodParameters;

            if (this.IsItemwise)
            {
                DLR.ParameterExpression index =
                    DLR.Expression.Parameter(typeof(AType), string.Format("__INDEX[{0}]__", this.Indexer.Name));
                dependencyScope.Variables.Add(this.Indexer.Name, index);

                methodParameters = new DLR.ParameterExpression[] { dependencyScope.RuntimeExpression, index };
                registerMethod   = typeof(DependencyManager).GetMethod("RegisterItemwise");
            }
            else
            {
                methodParameters = new DLR.ParameterExpression[] { dependencyScope.RuntimeExpression };
                registerMethod   = typeof(DependencyManager).GetMethod("Register");
            }

            // 2.5  Create a result parameter
            DLR.ParameterExpression resultParameter = DLR.Expression.Parameter(typeof(AType), "__RESULT__");

            // 2.75 Get the dependency informations
            DLR.Expression dependencyInformation =
                DLR.Expression.Call(
                    DLR.Expression.Property(dependencyScope.GetRuntimeExpression(), "DependencyManager"),
                    typeof(DependencyManager).GetMethod("GetDependency"),
                    DLR.Expression.Constant(dependencyName)
                    );

            // 3. Build the method
            DLR.LambdaExpression method = DLR.Expression.Lambda(
                DLR.Expression.Block(
                    new DLR.ParameterExpression[] { dependencyScope.ModuleExpression, resultParameter },
                    // Add the local scope's store
                    DLR.Expression.Assign(dependencyScope.ModuleExpression, DLR.Expression.Constant(new DYN.ExpandoObject())),
                    // set AplusEnviroment's function scope reference
                    DLR.Expression.Assign(
                        DLR.Expression.Property(dependencyScope.RuntimeExpression, "FunctionScope"),
                        dependencyScope.ModuleExpression
                        ),
                    // Mark the dependency as under evaluation
                    DLR.Expression.Call(
                        dependencyInformation,
                        typeof(DependencyItem).GetMethod("Mark"),
                        DLR.Expression.Constant(DependencyState.Evaluating)
                        ),
                    // Calculate the result of the defined function
                    DLR.Expression.Assign(
                        resultParameter,
                        DLR.Expression.Label(dependencyScope.ReturnTarget, this.functionBody.Generate(dependencyScope))
                        ),
                    // Mark the dependency as valid
                    DLR.Expression.Call(
                        dependencyInformation,
                        typeof(DependencyItem).GetMethod("Mark"),
                        DLR.Expression.Constant(DependencyState.Valid)
                        ),
                    // reset  AplusEnviroment's function scope reference
                    DLR.Expression.Assign(
                        DLR.Expression.Property(dependencyScope.RuntimeExpression, "FunctionScope"),
                        DLR.Expression.Constant(null, typeof(DYN.ExpandoObject))
                        ),
                    // Return the result
                    resultParameter
                    ),
                dependencyName,
                methodParameters
                );

            DLR.Expression wrappedLambda = DLR.Expression.Call(
                typeof(AFunc).GetMethod("Create"),
                DLR.Expression.Constant(dependencyName),
                method,
                DLR.Expression.Constant(methodParameters.Length),
                DLR.Expression.Constant(this.codeText)
                );

            // 3.5 Build dependant set
            // filter out the variables from the dependant set if it is a local variable
            HashSet <string> dependents = new HashSet <string>(
                from pair in this.variables.Accessing                           // get all variables
                where !this.variables.LocalAssignment.ContainsKey(pair.Key)     // but skip the local variables
                select pair.Value[0].BuildQualifiedName(runtime.CurrentContext) // then build the correct name
                );

            // 4. Register the method for the Dependency manager
            DLR.ParameterExpression dependencyMethodParam = DLR.Expression.Parameter(typeof(AType), "__DEP._METHOD__");
            DLR.Expression          dependencyManager     = DLR.Expression.Property(scope.GetRuntimeExpression(), "DependencyManager");
            result = DLR.Expression.Block(
                new DLR.ParameterExpression[] { dependencyMethodParam },
                DLR.Expression.Assign(dependencyMethodParam, wrappedLambda),
                DLR.Expression.Call(
                    dependencyManager,
                    registerMethod,
                    DLR.Expression.Constant(dependencyName, typeof(string)),
                    DLR.Expression.Constant(dependents, typeof(HashSet <string>)),
                    dependencyMethodParam
                    ),
                dependencyMethodParam
                );

            return(result);
        }
Пример #40
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            LaminateJobInfo arguments = CreateLaminateJob(right, left);

            return(Compute(arguments));
        }
Пример #41
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            int dropCounter = GetDropCounter(left);

            return(Compute(right, dropCounter));
        }
Пример #42
0
        public override DLR.Expression Generate(AplusScope scope)
        {
            Aplus runtime = scope.GetRuntime();

            if (scope.IsEval && scope.IsMethod)
            {
                // we are inside a function and an eval block.

                // override the original eval scope
                // create a top level scope
                scope = new AplusScope(null, "_EVAL_FUNC_SCOPE_",
                                       scope.GetRuntime(),
                                       scope.GetRuntimeExpression(),
                                       scope.Parent.GetModuleExpression(),
                                       scope.ReturnTarget,
                                       isEval: true
                                       );
            }

            string methodName = this.name.BuildQualifiedName(runtime.CurrentContext);

            // 1. Create a new scope for the function
            string     scopename   = String.Format("__method_{0}_scope__", this.name.Name);
            AplusScope methodScope = new AplusScope(scope, scopename,
                                                    runtimeParam: DLR.Expression.Parameter(typeof(Aplus), "_EXTERNAL_RUNTIME_"),
                                                    moduleParam: DLR.Expression.Parameter(typeof(DYN.ExpandoObject), scopename),
                                                    returnTarget: DLR.Expression.Label(typeof(AType), "RETURN"),
                                                    isMethod: true
                                                    );

            // 1.5 Create a result parameter
            DLR.ParameterExpression resultParameter = DLR.Expression.Parameter(typeof(AType), "__RESULT__");

            // 2. Create function's parameters
            LinkedList <DLR.ParameterExpression> methodParameters = new LinkedList <DLR.ParameterExpression>();

            foreach (Node parameter in this.parameters.Items)
            {
                string parameterName = ((Identifier)parameter).Name;
                DLR.ParameterExpression parameterExpression = DLR.Expression.Parameter(typeof(AType), parameterName);

                // Add parameter to the scope's variable list
                methodScope.Variables[parameterName] = parameterExpression;

                // Add parameters in !reverse! order
                methodParameters.AddFirst(parameterExpression);
            }

            // Add parameter for AplusEnviroment
            methodParameters.AddFirst(methodScope.RuntimeExpression);

            // Create a return label for exiting from the function
            //methodScope.ReturnTarget = ;

            // 3. Create the lambda method for the function
            DLR.LambdaExpression method = DLR.Expression.Lambda(
                DLR.Expression.Block(
                    new DLR.ParameterExpression[] { methodScope.ModuleExpression, resultParameter },
                    // Add the local scope's store
                    DLR.Expression.Assign(methodScope.ModuleExpression, DLR.Expression.Constant(new DYN.ExpandoObject())),
                    // set AplusEnviroment's function scope reference
                    DLR.Expression.Assign(
                        DLR.Expression.Property(methodScope.RuntimeExpression, "FunctionScope"),
                        methodScope.ModuleExpression
                        ),
                    // Calculate the result of the defined function
                    DLR.Expression.Assign(
                        resultParameter,
                        DLR.Expression.Label(methodScope.ReturnTarget, this.codeblock.Generate(methodScope))
                        ),
                    // reset  AplusEnviroment's function scope reference
                    DLR.Expression.Assign(
                        DLR.Expression.Property(methodScope.RuntimeExpression, "FunctionScope"),
                        DLR.Expression.Constant(null, typeof(DYN.ExpandoObject))
                        ),
                    // Return the result
                    resultParameter
                    ),
                methodName,
                methodParameters
                );

            // 3.5. Wrap the lambda method inside an AFunc
            DLR.Expression wrappedLambda = DLR.Expression.Call(
                typeof(AFunc).GetMethod("Create", new Type[] { typeof(string), typeof(object), typeof(int), typeof(string) }),
                DLR.Expression.Constant(methodName),
                method,
                DLR.Expression.Constant(methodParameters.Count),
                DLR.Expression.Constant(this.code)
                );

            // 4. Set the variable to the lambda function
            DLR.Expression setMethod = VariableHelper.SetVariable(
                runtime,
                scope.ModuleExpression,
                this.name.CreateContextNames(runtime.CurrentContext),
                wrappedLambda
                );

            // ensure the result type to be an AType
            DLR.Expression result = DLR.Expression.Convert(setMethod, typeof(AType));

            return(result);
        }
Пример #43
0
 /// <summary>
 /// Returns the shape of the argument
 /// </summary>
 /// <remarks>
 /// The shape of a scalar is Null (scalar does not have axes).
 /// For a nonscalar the i-th element of the result is the i-th dimension of the argument.
 /// </remarks>
 public override AType Execute(AType argument, Aplus environment = null)
 {
     return(argument.Shape.ToAArray());
 }
Пример #44
0
        public override AType ExecutePrimitive(AInteger argument, Aplus environment)
        {
            int seed = GetSeed(environment);

            return(generateRandomNumber(seed, argument.asInteger));
        }
Пример #45
0
 public override AType ExecutePrimitive(AInteger argument, Aplus environment = null)
 {
     return(calculateLog(argument.asFloat));
 }
Пример #46
0
 /// <summary>
 /// <see cref="MonadicTypeAlternate"/>
 /// </summary>
 public static AType DyadicTypeAlternate(Aplus env, AType number, AType ignored)
 {
     return(MonadicTypeAlternate(env, number));
 }
Пример #47
0
        /// <summary>
        /// Search the <see cref="left"/> argument in the <see cref="right"/> argument.
        /// </summary>
        /// <param name="right">The data where the search should be performed.</param>
        /// <param name="left">Element to search in the right argument.</param>
        /// <param name="environment"></param>
        /// <returns></returns>
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            if (right.Length == 0)
            {
                switch (left.Rank)
                {
                case 0:
                    return(AInteger.Create(0));

                default:
                    return(DyadicFunctionInstance.Reshape.Execute(AInteger.Create(0), left.Shape.ToAArray()));
                }
            }
            else if (!(left.IsNumber && right.IsNumber) && (right.Type != left.Type))
            {
                throw new Error.Type(this.TypeErrorText);
            }

            SearchInfo searchInfo = new SearchInfo()
            {
                // convert the right argument to an array (make life easier..)
                SearchWhere = right.IsArray ? right : AArray.Create(right.Type, right),
                ErrorText   = this.LengthErrorText
            };

            if (left.Rank < searchInfo.SearchWhere[0].Rank)
            {
                // The item we are looking for have a lesser rank than the items of the right argument
                throw new Error.Rank(this.RankErrorText);
            }

            AType result;

            if (!left.IsArray)
            {
                // Process a simple scalar
                result = ProcessScalar(left, searchInfo);
            }
            else
            {
                searchInfo.Result = AArray.Create(ATypes.AInteger);

                ProcessMatrix(left, searchInfo);

                searchInfo.Result.UpdateInfo();

                // Check how many elements we need to return
                int elementCount = left.Shape.Count - Math.Max(right.Rank - 1, 0);

                if ((elementCount == 0) && searchInfo.Result.TryFirstScalar(out result))
                {
                    // need to return a simple scalar
                    // 'result' contains the desired value
                }
                else
                {
                    // reshape the result to the required shape
                    List <int> desiredShape = left.Shape.GetRange(0, elementCount);
                    result = DyadicFunctionInstance.Reshape.Execute(searchInfo.Result, desiredShape.ToAArray());
                }
            }

            return(result);
        }
Пример #48
0
        /// <summary>
        /// CASE 3: Slotfiller right argument and simple symbol left argument.
        /// </summary>
        /// <param name="symbol">Symbol to use for selecting from a slotfiller</param>
        /// <param name="items">Slotfiller</param>
        /// <returns></returns>
        private AType SimpleSymbolConstant2SlotFiller(AType symbol, AType items, Aplus environment)
        {
            if (!items.IsSlotFiller(true))
            {
                throw new Error.Domain(DomainErrorText);
            }

            AType result;
            AType keys   = MonadicFunctionInstance.Disclose.Execute(items[0], environment);
            AType values = MonadicFunctionInstance.Disclose.Execute(items[1], environment);

            if (keys.IsArray)
            {
                if (keys.Rank > 1)
                {
                    keys = MonadicFunctionInstance.Ravel.Execute(keys);
                }

                if (values.Rank > 1)
                {
                    values = MonadicFunctionInstance.Ravel.Execute(values);
                }

                int index = -1;

                // TODO: refactor, remove 'i' use the 'index' variable
                for (int i = 0; i < keys.Length; i++)
                {
                    if (keys[i].IsBox)
                    {
                        throw new Error.Domain(DomainErrorText);
                    }

                    if (keys[i].CompareTo(symbol) == 0)
                    {
                        index = i;
                        break;
                    }
                }

                if (index == -1)
                {
                    //y is a symbol and is not a member of the vector of symbol s in x.
                    throw new Error.Index(IndexErrorText);
                }

                if (values[index].IsPrimitiveFunction() || !values[index].IsBox)
                {
                    throw new Error.Domain(DomainErrorText);
                }

                result = MonadicFunctionInstance.Disclose.Execute(values[index], environment);
            }
            else
            {
                // We have only one item in the keys list
                if (symbol.CompareTo(keys) != 0)
                {
                    throw new Error.Index(IndexErrorText);
                }

                if (values.IsPrimitiveFunction() || !values.IsBox)
                {
                    throw new Error.Domain(DomainErrorText);
                }

                result = MonadicFunctionInstance.Disclose.Execute(values, environment);
            }

            return(result);
        }
Пример #49
0
 public override AType ExecutePrimitive(AInteger argument, Aplus environment = null)
 {
     return(AInteger.Create(~argument.asInteger));
 }
Пример #50
0
        /// <summary>
        /// CASE 6: Nested right argument and nested left argument.
        /// </summary>
        /// <param name="pathBox"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        private AType NestedPathNumber2NestedArray(AType pathBox, AType items, Aplus environment)
        {
            AType path = MonadicFunctionInstance.Disclose.Execute(pathBox, environment);

            if (path.IsFunctionScalar)
            {
                throw new Error.Domain(DomainErrorText);
            }

            //Nested scalar or vector whose items are simple scalar or vector of integers.
            if (path.IsBox)
            {
                throw new Error.Type(TypeErrorText);
            }

            //Right argument is ().
            if (items.Type == ATypes.ANull)
            {
                throw new Error.Index(IndexErrorText);
            }

            if (path.Type == ATypes.ANull)
            {
                if (!items.IsBox)
                {
                    throw new Error.Domain(DomainErrorText);
                }

                AType result;

                if (!items.TryFirstScalar(out result, true))
                {
                    throw new Error.Domain(DomainErrorText);
                }

                return(MonadicFunctionInstance.Disclose.Execute(result, environment));
            }
            else if (path.Type == ATypes.AInteger)
            {
                if (path.Rank > 1)
                {
                    throw new Error.Rank(RankErrorText);
                }

                if (path.Length == 1)
                {
                    // Case 5
                    return(PathNumber2NestedVector(path.IsArray ? path[0] : path, items));
                }

                // The 'path' variable must be an AArray after this point.
                // so we treat it like that

                if (!items.IsBox)
                {
                    throw new Error.Domain(DomainErrorText);
                }

                //Length: 0
                if (path.Length != items.Rank || path.Length == 0)
                {
                    throw new Error.Rank(RankErrorText);
                }

                List <int> shape = items.Shape;
                int        index;

                for (int i = 0; i < path.Length; i++)
                {
                    index = path[i].asInteger;

                    if (index < 0 || index >= shape[i])
                    {
                        throw new Error.Index(IndexErrorText);
                    }

                    items = items[index];
                }

                return(MonadicFunctionInstance.Disclose.Execute(items, environment));
            }
            else if (path.Type == ATypes.ASymbol)
            {
                // Case 3
                return(ItemSelectWalker(SymbolConstant2SlotFillerDelegate, path, items, environment));
            }
            else if (path.Type == ATypes.AChar)
            {
                throw new Error.Domain(DomainErrorText);
            }
            else
            {
                throw new Error.Type(TypeErrorText);
            }
        }
Пример #51
0
        private DLR.Expression BuildGlobalAccessor(
            AplusScope scope, Aplus runtime, DLR.Expression variableContainer, string[] contextParts)
        {
            DLR.ParameterExpression environment       = scope.GetRuntimeExpression();
            DLR.Expression          name              = DLR.Expression.Constant(BuildQualifiedName(runtime.CurrentContext));
            DLR.Expression          dependencyManager = DLR.Expression.Property(scope.GetRuntimeExpression(), "DependencyManager");
            // Build the ET for getting the dependecy for the variable
            DLR.Expression dependencyInformation =
                DLR.Expression.Call(
                    dependencyManager,
                    typeof(DependencyManager).GetMethod("GetDependency"),
                    name
                    );

            // Build the ET for invoking the dependecy.
            DLR.Expression dependencyEvaulate =
                DLR.Expression.Condition(
                    dependencyInformation.Property("IsItemwise"),
                    AST.UserDefInvoke.BuildInvoke(
                        runtime,
                        new DLR.Expression[]
            {
                dependencyInformation.Property("Function"),
                environment,
                dependencyInformation.Property("InvalidIndex")
            }
                        ),
                    AST.UserDefInvoke.BuildInvoke(
                        runtime,
                        new DLR.Expression[]
            {
                DLR.Expression.Property(dependencyInformation, "Function"),
                environment
            }
                        )
                    );

            /*
             * Simplified code of the resulting ET:
             *
             * result = $runtime.DependecyManager.IsInvalid($$variable)
             *          ? { $$value = $runtime.DependencyManager.GetDependency($$name).Function()
             *              path, index = Utils.ANull();
             *              $$nonPresetvalue = $$value.IsMemoryMappedFile ? $$value : $$value.Clone();
             *              $$qualifiedName = qualifiedname;
             *              $$value = presetCallback($$value);
             *              $$variable = $$value
             *              $$nonPresetvalue
             *          : $$variable
             */

            DLR.ParameterExpression errorParam     = DLR.Expression.Parameter(typeof(Error.Signal));
            DLR.ParameterExpression value          = DLR.Expression.Parameter(typeof(AType));
            DLR.Expression          callback       = AST.Assign.BuildCallbackCall(scope, value);
            DLR.Expression          presetCallback = AST.Assign.BuildPresetCallbackCall(scope, value);

            string qualifiedName = this.BuildQualifiedName(scope.GetRuntime().CurrentContext);

            DLR.Expression temp =
                DLR.Expression.Block(
                    new DLR.ParameterExpression[] { value },
                    DLR.Expression.Condition(
                        DLR.Expression.Call(
                            dependencyManager,
                            typeof(DependencyManager).GetMethod("IsInvalid"),
                            name
                            ),
                        DLR.Expression.Block(
                            new DLR.ParameterExpression[] { scope.CallbackInfo.QualifiedName, scope.CallbackInfo.NonPresetValue,
                                                            scope.CallbackInfo.Path, scope.CallbackInfo.Index },
                            DLR.Expression.Assign(value, dependencyEvaulate),
                            DLR.Expression.Assign(scope.CallbackInfo.Path, DLR.Expression.Constant(Utils.ANull())),
                            DLR.Expression.Assign(scope.CallbackInfo.Index, DLR.Expression.Constant(Utils.ANull())),
                            DLR.Expression.Assign(
                                scope.CallbackInfo.NonPresetValue,
                                DLR.Expression.Condition(
                                    DLR.Expression.Property(value, "IsMemoryMappedFile"),
                                    value,
                                    DLR.Expression.Call(
                                        value,
                                        typeof(AType).GetMethod("Clone")
                                        )
                                    )
                                ),
                            DLR.Expression.Assign(
                                scope.CallbackInfo.QualifiedName,
                                DLR.Expression.Constant(qualifiedName)
                                ),
                            DLR.Expression.TryCatch(
                                DLR.Expression.Block(
                                    typeof(void),
                                    DLR.Expression.Assign(value, presetCallback)
                                    ),
                                DLR.Expression.Catch(
                                    errorParam,
                                    DLR.Expression.Empty()
                                    )
                                ),
                            VariableHelper.SetVariable(
                                runtime,
                                variableContainer,
                                contextParts,
                                value
                                ),
                            scope.CallbackInfo.NonPresetValue
                            ),
                        VariableHelper.GetVariable(
                            runtime,
                            variableContainer,
                            contextParts
                            ),
                        typeof(object)
                        )
                    ).ToAType(runtime);

            DLR.Expression result = temp;

            if (scope.IsAssignment)
            {
                result =
                    DLR.Expression.Block(
                        DLR.Expression.Assign(
                            scope.CallbackInfo.QualifiedName,
                            DLR.Expression.Constant(qualifiedName)
                            ),
                        temp
                        );
            }

            return(result);
        }
Пример #52
0
 public override AType ExecutePrimitive(AFloat argument, Aplus environment = null)
 {
     return(AFloat.Create(-argument.asFloat));
 }
Пример #53
0
        public override DLR.Expression Generate(AplusScope scope)
        {
            Aplus runtime = scope.GetRuntime();

            // arguments for the dynamic method call
            LinkedList <DLR.Expression> callArguments = new LinkedList <DLR.Expression>();

            if (scope.IsAssignment)
            {
                // Generate the paramters differently for assignment

                // f{...;x} := value  <=> i := f{...; iota rho x}; (,x)[i] := value

                List <Node> items = new List <Node>(this.arguments.Items);
                // 2. Add the parameters in !reverse! order except the last one
                for (int i = 0; i < items.Count - 1; i++)
                {
                    callArguments.AddFirst(items[i].Generate(scope));
                }

                Node lastItem = items[items.Count - 1];
                bool isPick   = Node.TestDyadicToken(lastItem, Grammar.Tokens.PICK);
                bool isRavel  = Node.TestMonadicToken(lastItem, Grammar.Tokens.RAVEL);

                if (!(lastItem is Identifier || isPick || isRavel))
                {
                    throw new ParseException("user-def invoke assign", false);
                }

                DLR.Expression indexList = AST.Assign.BuildIndicesList(scope, lastItem.Generate(scope));

                callArguments.AddFirst(indexList);
            }
            else
            {
                // 2. Add the parameters in !reverse! order
                foreach (Node item in this.arguments.Items)
                {
                    callArguments.AddFirst(item.Generate(scope));
                }
            }

            // 0. Add A+ environment as first argument for user defined functions
            callArguments.AddFirst(scope.GetRuntimeExpression());

            // 1. Construct the method body
            callArguments.AddFirst(this.method.Generate(scope));

            DLR.Expression result;
            if (scope.IsAssignment)
            {
                // (,x)[f{...;iota rho x}]
                result = AST.Assign.BuildIndexing(
                    scope,
                    this.arguments.Items.Last.Value.Generate(scope),
                    BuildInvoke(runtime, callArguments)
                    );
            }
            else
            {
                // 3. Dynamic invoke of method
                // Order of arguments:
                //  (method, Enviroment, argN, ... arg1, arg0)
                result = BuildInvoke(runtime, callArguments);
            }

            return(result);
        }
Пример #54
0
 public override AType ExecutePrimitive(AInteger argument, Aplus environment = null)
 {
     return(Utils.CreateATypeResult(-argument.asFloat));
 }
Пример #55
0
        public override DLR.Expression Generate(AplusScope scope)
        {
            Aplus runtime = scope.GetRuntime();

            if (scope.IsEval && scope.IsMethod)
            {
                // we are inside a function and an eval block.

                // override the original eval scope
                // create a top level scope
                scope = new AplusScope(null, "_EVAL_FUNC_SCOPE_",
                                       scope.GetRuntime(),
                                       scope.GetRuntimeExpression(),
                                       scope.Parent.GetModuleExpression(),
                                       scope.ReturnTarget,
                                       isEval: true
                                       );
            }

            string operatorName = this.name.BuildQualifiedName(runtime.CurrentContext);

            string     scopename   = String.Format("__operator_{0}_scope__", this.name.Name);
            AplusScope methodScope = new AplusScope(scope, scopename,
                                                    runtimeParam: DLR.Expression.Parameter(typeof(Aplus), "_EXTERNAL_RUNTIME_"),
                                                    moduleParam: DLR.Expression.Parameter(typeof(DYN.ExpandoObject), scopename),
                                                    returnTarget: DLR.Expression.Label(typeof(AType), "RETURN"),
                                                    isMethod: true
                                                    );

            // create a result parameter
            DLR.ParameterExpression resultParameter = DLR.Expression.Parameter(typeof(AType), "__RESULT__");

            // create function's parameters
            LinkedList <DLR.ParameterExpression> methodParameters = new LinkedList <DLR.ParameterExpression>();

            // add parameters to the linkedlist
            BuildParameterExpression(methodScope, methodParameters, leftArgument);
            BuildParameterExpression(methodScope, methodParameters, function);
            BuildParameterExpression(methodScope, methodParameters, condition);
            BuildParameterExpression(methodScope, methodParameters, rightArgument);

            // add parameter for AplusEnviroment
            methodParameters.AddFirst(methodScope.RuntimeExpression);

            // create the lambda method for the function
            DLR.LambdaExpression method = DLR.Expression.Lambda(
                DLR.Expression.Block(
                    new DLR.ParameterExpression[] { methodScope.ModuleExpression, resultParameter },
                    // add the local scope's store
                    DLR.Expression.Assign(methodScope.ModuleExpression, DLR.Expression.Constant(new DYN.ExpandoObject())),
                    // set AplusEnviroment's function scope reference
                    DLR.Expression.Assign(
                        DLR.Expression.Property(methodScope.RuntimeExpression, "FunctionScope"),
                        methodScope.ModuleExpression
                        ),
                    // calculate the result of the defined function
                    DLR.Expression.Assign(
                        resultParameter,
                        DLR.Expression.Label(methodScope.ReturnTarget, this.codeblock.Generate(methodScope))
                        ),
                    // reset  AplusEnviroment's function scope reference
                    DLR.Expression.Assign(
                        DLR.Expression.Property(methodScope.RuntimeExpression, "FunctionScope"),
                        DLR.Expression.Constant(null, typeof(DYN.ExpandoObject))
                        ),
                    // return the result
                    resultParameter
                    ),
                operatorName,
                methodParameters
                );

            // wrap the lambda method inside an AFunc
            DLR.Expression wrappedLambda = DLR.Expression.Call(
                typeof(AFunc).GetMethod("CreateUserOperator"),
                DLR.Expression.Constant(operatorName),
                DLR.Expression.Constant(this.IsDyadicOperator),
                method,
                DLR.Expression.Constant(methodParameters.Count),
                DLR.Expression.Constant(this.codeText)
                );

            // set the variable to the lambda function
            DLR.Expression setMethod = VariableHelper.SetVariable(
                runtime,
                scope.ModuleExpression,
                this.name.CreateContextNames(runtime.CurrentContext),
                wrappedLambda
                );

            // ensure the result type to be an AType
            DLR.Expression result = DLR.Expression.Convert(setMethod, typeof(AType));

            return(result);
        }
Пример #56
0
 public override AType Execute(AType right, AType left, Aplus environment = null)
 {
     return(AInteger.Create(left.Equals(right) ? 1 : 0));
 }
Пример #57
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            ReplicateJobInfo replicateInfo = CreateReplicateJobInfo(right, left);

            return(Compute(replicateInfo));
        }
Пример #58
0
        public override AType Execute(AType right, AType left, Aplus environment = null)
        {
            AType typeToCast;

            if (!left.TryFirstScalar(out typeToCast, true))
            {
                throw new Error.Domain(this.DomainErrorText);
            }

            int sourceTypeSize = GetTypeSize(right.Type);

            ATypes            typeToConvert;
            ConverterFunction converterFunction;
            int destinationTypeSize;

            switch (typeToCast.asString)
            {
            case "int":
                converterFunction = ConvertToInt;
                typeToConvert     = ATypes.AInteger;
                break;

            case "float":
                converterFunction = ConvertToFloat;
                typeToConvert     = ATypes.AFloat;
                break;

            case "char":
                converterFunction = ConvertToChar;
                typeToConvert     = ATypes.AChar;
                break;

            default:
                throw new Error.Domain(this.DomainErrorText);
            }

            destinationTypeSize = GetTypeSize(typeToConvert);
            int    convertSizeRatio;
            double shapeModifier;

            if (sourceTypeSize >= destinationTypeSize)
            {
                convertSizeRatio = sourceTypeSize / destinationTypeSize;
                shapeModifier    = sourceTypeSize / destinationTypeSize;
            }
            else
            {
                convertSizeRatio = destinationTypeSize / sourceTypeSize;

                // check if the last dimension of the right argument is convertable to the type specified in the left argument
                if (right.Shape.Count == 0 || right.Shape[right.Shape.Count - 1] % convertSizeRatio != 0)
                {
                    throw new Error.Length(this.LengthErrorText);
                }

                shapeModifier = destinationTypeSize / sourceTypeSize;
            }

            AType result;

            if (right.Shape.Contains(0))
            {
                List <int> desiredShape = new List <int>(right.Shape);
                int        length       = desiredShape.Count - 1;
                desiredShape[length] = (int)(desiredShape[length] * shapeModifier);
                AType reshapeShape = desiredShape.ToAArray();

                result = Utils.FillElement(typeToConvert, reshapeShape);
            }
            else
            {
                result = converterFunction(right);
            }

            return(result);
        }
Пример #59
0
 public AplusScriptCode(Aplus aplus, string code, SourceUnit sourceunit)
     : base(sourceunit)
 {
     this.aplus  = aplus;
     this.lambda = ParseToLambda(code.Trim());
 }
Пример #60
0
        private AType ExecuteRecursion(AType argument, ATypes currentType, Aplus environment)
        {
            AType result;

            if (argument.IsArray)
            {
                uint  floatTypeCounter = 0;
                AType currentItem;

                result = AArray.Create(ATypes.AArray);

                for (int i = 0; i < argument.Length; i++)
                {
                    currentItem       = ExecuteRecursion(argument[i], currentType, environment);
                    floatTypeCounter += (uint)((currentItem.Type == ATypes.AFloat) ? 1 : 0);

                    result.AddWithNoUpdate(currentItem);
                }

                result.UpdateInfo();

                if ((floatTypeCounter != result.Length) && (floatTypeCounter != 0))
                {
                    result.ConvertToFloat();
                }
            }
            else
            {
                switch (currentType)
                {
                case ATypes.AInteger:
                    result = ExecutePrimitive((AInteger)argument.Data, environment);
                    break;

                case ATypes.AFloat:
                    result = ExecutePrimitive((AFloat)argument.Data, environment);
                    break;

                case ATypes.AChar:
                    result = ExecutePrimitive((AChar)argument.Data, environment);
                    break;

                case ATypes.ASymbol:
                    result = ExecutePrimitive((ASymbol)argument.Data, environment);
                    break;

                case ATypes.ABox:
                    result = ExecutePrimitive((ABox)argument.Data, environment);
                    break;

                case ATypes.AType:
                    result = ExecuteDefault((AType)argument.Data, environment);
                    break;

                default:
                    throw new Error.Invalid("Something really went wrong...");
                }
            }

            return(result);
        }