Esempio n. 1
0
        /// <summary>
        /// Creates the fibonacci function
        /// </summary>
        private static Function CreateFibFunction(Win64Container container, bool optimize = false)
        {
            var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);

            var def = new FunctionDefinition("fib", Enumerable.Repeat(intType, 1).ToList(), intType);

            var instructions = new List<Instruction>();
            instructions.Add(new Instruction(OpCodes.LoadArgument, 0));
            instructions.Add(new Instruction(OpCodes.LoadInt, 1));
            instructions.Add(new Instruction(OpCodes.BranchGreaterThan, 5));
            instructions.Add(new Instruction(OpCodes.LoadArgument, 0));
            instructions.Add(new Instruction(OpCodes.Ret));

            instructions.Add(new Instruction(OpCodes.LoadArgument, 0));
            instructions.Add(new Instruction(OpCodes.LoadInt, 2));
            instructions.Add(new Instruction(OpCodes.SubInt));
            instructions.Add(new Instruction(OpCodes.Call, "fib", Enumerable.Repeat(intType, 1).ToList()));

            instructions.Add(new Instruction(OpCodes.LoadArgument, 0));
            instructions.Add(new Instruction(OpCodes.LoadInt, 1));
            instructions.Add(new Instruction(OpCodes.SubInt));
            instructions.Add(new Instruction(OpCodes.Call, "fib", Enumerable.Repeat(intType, 1).ToList()));

            instructions.Add(new Instruction(OpCodes.AddInt));
            instructions.Add(new Instruction(OpCodes.Ret));

            return new Function(def, instructions, new List<VMType>())
            {
                Optimize = optimize
            };
        }
Esempio n. 2
0
        public static FScheme.Expression CompileFunction( FunctionDefinition definition )
        {
            IEnumerable<string> ins = new List<string>();
            IEnumerable<string> outs = new List<string>();

            return CompileFunction(definition, ref ins, ref outs);
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a loop call add function
        /// </summary>
        private static Function CreateLoopCallAdd(Win64Container container, int count, bool optimize = false)
        {
            var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);

            var def = new FunctionDefinition("main", new List<VMType>(), intType);

            var instructions = new List<Instruction>();

            instructions.Add(new Instruction(OpCodes.LoadInt, count));
            instructions.Add(new Instruction(OpCodes.StoreLocal, 0));

            instructions.Add(new Instruction(OpCodes.LoadInt, 1));
            instructions.Add(new Instruction(OpCodes.LoadLocal, 1));
            instructions.Add(new Instruction(OpCodes.Call, "add", Enumerable.Repeat(intType, 2).ToList()));
            instructions.Add(new Instruction(OpCodes.StoreLocal, 1));

            instructions.Add(new Instruction(OpCodes.LoadLocal, 0));
            instructions.Add(new Instruction(OpCodes.LoadInt, 1));
            instructions.Add(new Instruction(OpCodes.SubInt));
            instructions.Add(new Instruction(OpCodes.StoreLocal, 0));
            instructions.Add(new Instruction(OpCodes.LoadLocal, 0));

            instructions.Add(new Instruction(OpCodes.LoadInt, 0));
            instructions.Add(new Instruction(OpCodes.BranchGreaterThan, 2));

            instructions.Add(new Instruction(OpCodes.LoadLocal, 1));
            instructions.Add(new Instruction(OpCodes.Ret));

            return new Function(def, instructions, new List<VMType>() { intType, intType })
            {
                Optimize = optimize
            };
        }
        public void TestLocals1()
        {
            using (var container = new Win64Container())
            {
                var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);
                var funcDef = new FunctionDefinition("main", new List<VMType>(), intType);

                var instructions = new List<Instruction>();

                instructions.Add(new Instruction(OpCodes.LoadInt, 100));
                instructions.Add(new Instruction(OpCodes.StoreLocal, 0));

                instructions.Add(new Instruction(OpCodes.LoadInt, 200));
                instructions.Add(new Instruction(OpCodes.StoreLocal, 1));

                instructions.Add(new Instruction(OpCodes.LoadInt, 300));
                instructions.Add(new Instruction(OpCodes.StoreLocal, 2));

                instructions.Add(new Instruction(OpCodes.LoadInt, 400));
                instructions.Add(new Instruction(OpCodes.StoreLocal, 3));

                instructions.Add(new Instruction(OpCodes.LoadLocal, 3));
                instructions.Add(new Instruction(OpCodes.Ret));

                var func = new Function(funcDef, instructions, Enumerable.Repeat(intType, 4).ToList());
                container.LoadAssembly(Assembly.SingleFunction(func));
                Assert.AreEqual(400, container.Execute());
            }
        }
Esempio n. 5
0
 public PackageItemRootViewModel(FunctionDefinition def)
 {
     this.Height = 32;
     this.DependencyType = DependencyType.CustomNode;
     this.Definition = def;
     this.BuildDependencies(new HashSet<object>());
 }
        /// <summary>
        /// Creates a add function with that takes the given amount of arguments
        /// </summary>
        /// <param name="container">The container</param>
        /// <param name="numArgs">The number of arguments</param>
        public static Function AddFunction(Win64Container container, int numArgs)
        {
            var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);

            var parameters = new List<VMType>();
            for (int i = 0; i < numArgs; i++)
            {
                parameters.Add(intType);
            }

            var def = new FunctionDefinition("add", parameters, intType);

            var instructions = new List<Instruction>();
            instructions.Add(new Instruction(OpCodes.LoadArgument, 0));

            for (int i = 1; i < numArgs; i++)
            {
                instructions.Add(new Instruction(OpCodes.LoadArgument, i));
                instructions.Add(new Instruction(OpCodes.AddInt));
            }

            instructions.Add(new Instruction(OpCodes.Ret));

            return new Function(def, instructions, new List<VMType>());
        }
 public override Function CreateFunction(
     IEnumerable<string> inputs, 
     IEnumerable<string> outputs, 
     FunctionDefinition functionDefinition)
 {
     if (functionDefinition.WorkspaceModel.Nodes.Any(x => x is RevitTransactionNode)
         || functionDefinition.Dependencies.Any(d => d.WorkspaceModel.Nodes.Any(x => x is RevitTransactionNode)))
     {
         return new FunctionWithRevit(inputs, outputs, functionDefinition);
     }
     return base.CreateFunction(inputs, outputs, functionDefinition);
 }
Esempio n. 8
0
            public dynFunction(IEnumerable<string> inputs, IEnumerable<string> outputs, FunctionDefinition def)
                : base(def.FunctionId.ToString())
            {
                _def = def;

                //Set inputs and output
                SetInputs(inputs);
                foreach (var output in outputs)
                    OutPortData.Add(new PortData(output, "function output", typeof (object)));

                RegisterAllPorts();

                ArgumentLacing = LacingStrategy.Disabled;
            }
Esempio n. 9
0
 public FunctionDefinition FromSPAGS(SPAGS.Function spagsFunc)
 {
     FunctionDefinition jsFunc = new FunctionDefinition();
     for (int i = 0; i < spagsFunc.ParameterVariables.Count; i++)
     {
         SPAGS.Parameter spagsParam = spagsFunc.ParameterVariables[i];
         Variable p = new Variable(spagsParam.Name, GetValueTypes(spagsParam.Type));
         AddReference(spagsParam, p);
         jsFunc.Parameters.Add(p);
     }
     foreach (SPAGS.Statement statement in spagsFunc.Body.ChildStatements)
     {
         jsFunc.Body.Add(FromSPAGS(spagsFunc, statement, jsFunc.Body));
     }
     return jsFunc;
 }
Esempio n. 10
0
        public void TestMul()
        {
            using (var container = new Win64Container())
            {
                var floatType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Float);
                var funcDef = new FunctionDefinition("floatMain", new List<VMType>(), floatType);

                var instructions = new List<Instruction>();

                instructions.Add(new Instruction(OpCodes.LoadFloat, 2.5f));
                instructions.Add(new Instruction(OpCodes.LoadFloat, 1.35f));
                instructions.Add(new Instruction(OpCodes.MulFloat));
                instructions.Add(new Instruction(OpCodes.Ret));

                var func = new Function(funcDef, instructions, new List<VMType>());
                container.LoadAssembly(Assembly.SingleFunction(func));
                Assert.AreEqual(2.5f * 1.35f, ExecuteFloatProgram(container), 1E-4);
            }
        }
Esempio n. 11
0
        public void TestMul()
        {
            using (var container = new Win64Container())
            {
                var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);
                var funcDef = new FunctionDefinition("main", new List<VMType>(), intType);

                var instructions = new List<Instruction>();

                instructions.Add(new Instruction(OpCodes.LoadInt, 2));
                instructions.Add(new Instruction(OpCodes.LoadInt, 3));
                instructions.Add(new Instruction(OpCodes.MulInt));
                instructions.Add(new Instruction(OpCodes.Ret));

                var func = new Function(funcDef, instructions, new List<VMType>());
                container.LoadAssembly(Assembly.SingleFunction(func));
                Assert.AreEqual(6, container.Execute());
            }
        }
        public void TestFloatDefaultValue()
        {
            using (var container = new Win64Container())
            {
                var floatType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Float);
                var funcDef = new FunctionDefinition("floatMain", new List<VMType>(), floatType);

                var instructions = new List<Instruction>();

                instructions.Add(new Instruction(OpCodes.LoadLocal, 0));
                instructions.Add(new Instruction(OpCodes.Ret));

                var func = new Function(funcDef, instructions, Enumerable.Repeat(floatType, 1).ToList());
                container.LoadAssembly(Assembly.SingleFunction(func));
                container.VirtualMachine.Compile();
                var mainFunc = Marshal.GetDelegateForFunctionPointer<FloatMain>(
                    container.VirtualMachine.Binder.GetFunction("floatMain()").EntryPoint);

                Assert.AreEqual(0.0f, mainFunc());
            }
        }
Esempio n. 13
0
        public void DefinitionOrder()
        {
            using (var container = new Win64Container())
            {
                var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);
                var assemblyFunctions = new List<Function>();

                Action testFn = () =>
                {
                    var def = new FunctionDefinition("test", new List<VMType>(), intType);

                    var instructions = new List<Instruction>();

                    instructions.Add(new Instruction(OpCodes.LoadInt, 1));
                    instructions.Add(new Instruction(OpCodes.LoadInt, 2));
                    instructions.Add(new Instruction(OpCodes.AddInt));
                    instructions.Add(new Instruction(OpCodes.Ret));

                    var func = new Function(def, instructions, new List<VMType>());
                    assemblyFunctions.Add(func);
                };

                Action mainFn = () =>
                {
                    var def = new FunctionDefinition("main", new List<VMType>(), intType);

                    var instructions = new List<Instruction>();
                    instructions.Add(new Instruction(OpCodes.Call, "test", new List<VMType>()));
                    instructions.Add(new Instruction(OpCodes.Ret));

                    var func = new Function(def, instructions, new List<VMType>());
                    assemblyFunctions.Add(func);
                };

                mainFn();
                testFn();
                container.LoadAssembly(new Assembly(assemblyFunctions));
                Assert.AreEqual(3, container.Execute());
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Creates an add function with that takes the given amount of arguments
        /// </summary>
        private static Function CreateAddFunction(Win64Container container, int numArgs, bool optimize = false)
        {
            var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);

            var def = new FunctionDefinition("add", Enumerable.Repeat(intType, numArgs).ToList(), intType);

            var instructions = new List<Instruction>();
            instructions.Add(new Instruction(OpCodes.LoadArgument, 0));

            for (int i = 1; i < numArgs; i++)
            {
                instructions.Add(new Instruction(OpCodes.LoadArgument, i));
                instructions.Add(new Instruction(OpCodes.AddInt));
            }

            instructions.Add(new Instruction(OpCodes.Ret));

            return new Function(def, instructions, new List<VMType>())
            {
                Optimize = optimize
            };
        }
Esempio n. 15
0
            public dynFunction(IEnumerable<string> inputs, IEnumerable<string> outputs, FunctionDefinition def)
                : base(def.FunctionId.ToString())
            {
                _def = def;

                //Set inputs and output
                SetInputs(inputs);
                foreach (var output in outputs)
                    OutPortData.Add(new PortData(output, "function output", typeof(object)));

                //Setup double-click behavior
                NodeUI.MouseDoubleClick += delegate
                {
                    Controller.ViewCustomNodeWorkspace(_def);
                };

                ((DropShadowEffect)NodeUI.elementRectangle.Effect).Opacity = 1;
                ((DropShadowEffect)NodeUI.elementRectangle.Effect).Color = Colors.WhiteSmoke;
                ((DropShadowEffect) NodeUI.elementRectangle.Effect).BlurRadius = 20;
                ((DropShadowEffect)NodeUI.elementRectangle.Effect).ShadowDepth = 0;

                NodeUI.RegisterAllPorts();
            }
Esempio n. 16
0
        public ExtractMethodResult GetExtractionResult()
        {
            bool           isStaticMethod = false, isClassMethod = false;
            var            parameters = new List <Parameter>();
            NameExpression selfParam  = null;

            if (_targetScope is ClassDefinition)
            {
                var fromScope = _scopes[_scopes.Count - 1] as FunctionDefinition;
                Debug.Assert(fromScope != null);  // we don't allow extracting from classes, so we have to be coming from a function
                if (fromScope != null)
                {
                    if (fromScope.Decorators != null)
                    {
                        foreach (var decorator in fromScope.Decorators.Decorators)
                        {
                            NameExpression name = decorator as NameExpression;
                            if (name != null)
                            {
                                if (name.Name == "staticmethod")
                                {
                                    isStaticMethod = true;
                                }
                                else if (name.Name == "classmethod")
                                {
                                    isClassMethod = true;
                                }
                            }
                        }
                    }

                    if (!isStaticMethod)
                    {
                        if (fromScope.Parameters.Count > 0)
                        {
                            selfParam = fromScope.Parameters[0].NameExpression;
                            parameters.Add(new Parameter(selfParam, ParameterKind.Normal));
                        }
                    }
                }
            }

            foreach (var param in _parameters)
            {
                var paramName = new NameExpression(param);
                if (parameters.Count > 0)
                {
                    paramName.AddPreceedingWhiteSpace(_ast, " ");
                }
                var newParam = new Parameter(paramName, ParameterKind.Normal);
                parameters.Add(newParam);
            }

            // include any non-closed over parameters as well...
            foreach (var input in _inputVars)
            {
                var variableScope = input.Scope;
                var parentScope   = _targetScope;

                // are these variables a child of the target scope so we can close over them?
                while (parentScope != null && parentScope != variableScope)
                {
                    parentScope = parentScope.Parent;
                }

                if (parentScope == null && input.Name != selfParam?.Name)
                {
                    // we can either close over or pass these in as parameters, add them to the list
                    var paramName = new NameExpression(input.Name);
                    if (parameters.Count > 0)
                    {
                        paramName.AddPreceedingWhiteSpace(_ast, " ");
                    }
                    var newParam = new Parameter(paramName, ParameterKind.Normal);
                    parameters.Add(newParam);
                }
            }

            var body        = _target.GetBody();
            var isCoroutine = IsCoroutine(body);

            // reset leading indentation to single newline + indentation, this
            // strips out any proceeding comments which we don't extract
            var leading = _newline + _target.IndentationLevel;

            body.SetLeadingWhiteSpace(_ast, leading);

            if (_outputVars.Count > 0)
            {
                // need to add a return statement
                Expression   retValue;
                Expression[] names       = new Expression[_outputVars.Count];
                int          outputIndex = 0;
                foreach (var name in _outputVars)
                {
                    var nameExpr = new NameExpression(name.Name);
                    nameExpr.AddPreceedingWhiteSpace(_ast, " ");
                    names[outputIndex++] = nameExpr;
                }
                var tuple = new TupleExpression(false, names);
                tuple.RoundTripHasNoParenthesis(_ast);
                retValue = tuple;

                var retStmt = new ReturnStatement(retValue);
                retStmt.SetLeadingWhiteSpace(_ast, leading);

                body = new SuiteStatement(
                    new Statement[] {
                    body,
                    retStmt
                }
                    );
            }
            else
            {
                // we need a SuiteStatement to give us our colon
                body = new SuiteStatement(new Statement[] { body });
            }

            DecoratorStatement decorators = null;

            if (isStaticMethod)
            {
                decorators = new DecoratorStatement(new[] { new NameExpression("staticmethod") });
            }
            else if (isClassMethod)
            {
                decorators = new DecoratorStatement(new[] { new NameExpression("classmethod") });
            }

            var res = new FunctionDefinition(new NameExpression(_name), parameters.ToArray(), body, decorators);

            res.IsCoroutine = isCoroutine;

            StringBuilder newCall = new StringBuilder();

            newCall.Append(_target.IndentationLevel);
            var method = res.ToCodeString(_ast);

            // fix up indentation...
            for (int curScope = 0; curScope < _scopes.Count; curScope++)
            {
                if (_scopes[curScope] == _targetScope)
                {
                    // this is our target indentation level.
                    var indentationLevel = _scopes[curScope].Body.GetIndentationLevel(_ast);
                    var lines            = method.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                    int minWhiteSpace    = Int32.MaxValue;
                    for (int curLine = decorators == null ? 1 : 2; curLine < lines.Length; curLine++)
                    {
                        var line = lines[curLine];

                        for (int i = 0; i < line.Length; i++)
                        {
                            if (!Char.IsWhiteSpace(line[i]))
                            {
                                minWhiteSpace = Math.Min(minWhiteSpace, i);
                                break;
                            }
                        }
                    }

                    StringBuilder newLines = new StringBuilder();
                    newLines.Append(indentationLevel);
                    newLines.Append(lines[0]);
                    if (decorators != null)
                    {
                        newLines.Append(_newline);
                        newLines.Append(indentationLevel);
                        newLines.Append(lines[1]);
                    }

                    // don't include a bunch of blank lines...
                    int endLine = lines.Length - 1;
                    for (; endLine >= 0 && String.IsNullOrWhiteSpace(lines[endLine]); endLine--)
                    {
                    }

                    newLines.Append(_newline);
                    for (int curLine = decorators == null ? 1 : 2; curLine <= endLine; curLine++)
                    {
                        var line = lines[curLine];

                        newLines.Append(indentationLevel);
                        if (_insertTabs)
                        {
                            newLines.Append('\t');
                        }
                        else
                        {
                            newLines.Append(' ', _indentSize);
                        }

                        if (line.Length > minWhiteSpace)
                        {
                            newLines.Append(line, minWhiteSpace, line.Length - minWhiteSpace);
                        }
                        newLines.Append(_newline);
                    }
                    newLines.Append(_newline);
                    method = newLines.ToString();
                    break;
                }
            }

            string comma;

            if (_outputVars.Count > 0)
            {
                comma = "";
                foreach (var outputVar in _outputVars)
                {
                    newCall.Append(comma);
                    newCall.Append(outputVar.Name);
                    comma = ", ";
                }
                newCall.Append(" = ");
            }
            else if (_target.ContainsReturn)
            {
                newCall.Append("return ");
            }

            if (isCoroutine)
            {
                newCall.Append("await ");
            }

            if (_targetScope is ClassDefinition)
            {
                var fromScope = _scopes[_scopes.Count - 1] as FunctionDefinition;
                Debug.Assert(fromScope != null);  // we don't allow extracting from classes, so we have to be coming from a function

                if (isStaticMethod)
                {
                    newCall.Append(_targetScope.Name);
                    newCall.Append('.');
                }
                else if (fromScope != null && fromScope.Parameters.Count > 0)
                {
                    newCall.Append(fromScope.Parameters[0].Name);
                    newCall.Append('.');
                }
            }

            newCall.Append(_name);
            newCall.Append('(');

            comma = "";
            foreach (var param in parameters)
            {
                if (param.Name != selfParam?.Name)
                {
                    newCall.Append(comma);
                    newCall.Append(param.Name);
                    comma = ", ";
                }
            }

            newCall.Append(')');

            return(new ExtractMethodResult(
                       method,
                       newCall.ToString()
                       ));
        }
Esempio n. 17
0
 public ContractDefinition GetContractByFunction(FunctionDefinition funcDef)
 {
     Debug.Assert(FunctionToContractMap.ContainsKey(funcDef));
     return(FunctionToContractMap[funcDef]);
 }
Esempio n. 18
0
 public override bool Walk(FunctionDefinition node)
 {
     _names.Add(node.Name);
     return(base.Walk(node));
 }
Esempio n. 19
0
 /// <summary>
 /// Defines the given macro function
 /// </summary>
 /// <param name="functionDefinition">The signature of the macro</param>
 /// <param name="macroFunction">The macro function</param>
 public void DefineMacroFunction(FunctionDefinition functionDefinition, MacroFunction macroFunction)
 {
     this.macroFunctions.Add(this.virtualMachine.Binder.FunctionSignature(functionDefinition), macroFunction);
 }
Esempio n. 20
0
 // FunctionDefinition
 public override bool Walk(FunctionDefinition node) { return false; }
        public void MapExpression(string srcAlias, string destProperty, bool createIfNotExists)
        {
            var      dstCls           = Parent.TargetClass;
            TreeNode exprNode         = _node.Nodes[srcAlias];
            ExpressionMappingInfo map = (ExpressionMappingInfo)exprNode.Tag;

            if (destProperty != null)
            {
                if (dstCls != null)
                {
                    PropertyDefinition     dst = dstCls.Properties[destProperty];
                    DataPropertyDefinition dp  = dst as DataPropertyDefinition;

                    if (string.IsNullOrEmpty(map.Expression))
                    {
                        throw new MappingException("Cannot map alias. There is no expression defined");
                    }

                    Expression expr = null;
                    try
                    {
                        expr = Expression.Parse(map.Expression);
                    }
                    catch (OSGeo.FDO.Common.Exception ex)
                    {
                        throw new MappingException("Cannot map alias. Invalid expression: " + ex.Message);
                    }

                    if (typeof(Function).IsAssignableFrom(expr.GetType()))
                    {
                        Function      func = expr as Function;
                        FdoConnection conn = Parent.GetSourceConnection();
                        FunctionDefinitionCollection funcDefs = (FunctionDefinitionCollection)conn.Capability.GetObjectCapability(CapabilityType.FdoCapabilityType_ExpressionFunctions);
                        FunctionDefinition           funcDef  = null;

                        //Shouldn't happen because Expression Editor ensures a valid function
                        if (!funcDefs.Contains(func.Name))
                        {
                            throw new MappingException("Cannot map alias. Expression contains unsupported function: " + func.Name);
                        }

                        //Try to get the return type
                        foreach (FunctionDefinition fd in funcDefs)
                        {
                            if (fd.Name == func.Name)
                            {
                                funcDef = fd;
                                break;
                            }
                        }

                        if (funcDef.ReturnPropertyType != dst.PropertyType)
                        {
                            throw new MappingException("Cannot map alias. Expression evaluates to an un-mappable property type");
                        }

                        if (funcDef.ReturnPropertyType == PropertyType.PropertyType_GeometricProperty)
                        {
                        }
                        else if (funcDef.ReturnPropertyType == PropertyType.PropertyType_DataProperty)
                        {
                            if (!ValueConverter.IsConvertible(funcDef.ReturnType, dp.DataType))
                            {
                                throw new MappingException("Cannot map alias to property " + dst.Name + ". Expression evaluates to a data type that cannot be mapped to " + dp.DataType);
                            }
                        }
                        else //Association, Object, Raster
                        {
                            throw new MappingException("Cannot map alias. Expression evaluates to an un-mappable property type");
                        }
                    }
                    else if (typeof(BinaryExpression).IsAssignableFrom(expr.GetType()))
                    {
                        if (dp == null)
                        {
                            throw new MappingException("Cannot map alias. Expression evaluates to an un-mappable property type");
                        }

                        //We're assuming that this evalutes to a boolean value
                        if (!ValueConverter.IsConvertible(DataType.DataType_Boolean, dp.DataType))
                        {
                            throw new MappingException("Cannot map alias to property " + dst.Name + ". Expression evaluates to a data type that cannot be mapped to " + dp.DataType);
                        }
                    }
                    else if (typeof(DataValue).IsAssignableFrom(expr.GetType()))
                    {
                        if (dp == null)
                        {
                            throw new MappingException("Cannot map alias. Expression evaluates to an un-mappable property type");
                        }

                        DataValue dv = (DataValue)expr;
                        if (!ValueConverter.IsConvertible(dv.DataType, dp.DataType))
                        {
                            throw new MappingException("Cannot map alias to property " + dst.Name + ". Expression evaluates to a data type that cannot be mapped to " + dp.DataType);
                        }
                    }
                    //else if (expr.GetType() == typeof(Identifier))
                    //{
                    //    //TODO: use the property type of the referenced property
                    //}
                    else //Cannot be evaluated
                    {
                        throw new MappingException("Cannot map alias. Expression evaluates to an un-mappable value");
                    }
                }
                else
                {
                    if (!createIfNotExists)
                    {
                        throw new MappingException("Cannot map alias. The specified target property " + destProperty + " does not exist and the \"create if necessary\" option was not specified");
                    }
                }
            }
            //All good
            exprNode.Text      = srcAlias + " ( => " + destProperty + " )";
            map.TargetProperty = destProperty;
            if (destProperty != null)
            {
                exprNode.Text = exprNode.Name + " => " + destProperty;
            }
            else
            {
                exprNode.Text = exprNode.Name;
            }

            GetConversionRule(srcAlias).CreateIfNotExists = createIfNotExists;
        }
Esempio n. 22
0
 public override void PostWalk(FunctionDefinition node)
 {
     _scopes.Add(node);
     base.PostWalk(node);
 }
Esempio n. 23
0
 public Package GetOwnerPackage(FunctionDefinition def)
 {
     return GetOwnerPackage(def.WorkspaceModel.FileName);
 }
Esempio n. 24
0
 internal FunctionInfo AddFunction(FunctionDefinition node, AnalysisUnit outerUnit)
 {
     return(AddFunction(node, outerUnit, _scope));
 }
Esempio n. 25
0
 public override bool Walk(FunctionDefinition node)
 {
     return(false);
 }
Esempio n. 26
0
 public GeneratorFunction(Context context, FunctionDefinition generator)
     : base(context, generator)
 {
     RequireNewKeywordLevel = RequireNewKeywordLevel.WithoutNewOnly;
 }
Esempio n. 27
0
 public bool IsMethodInIgnoredSet(FunctionDefinition func, ContractDefinition contract)
 {
     return(IgnoreMethods.Any(x => x.Item2.Equals(contract.Name) && (x.Item1.Equals("*") || x.Item1.Equals(func.Name))));
 }
Esempio n. 28
0
        public void AddFunctionToDynamicType(string funcSig, ContractDefinition dynamicType, FunctionDefinition funcDef)
        {
            if (!FuncSigResolutionMap.ContainsKey(funcSig))
            {
                FuncSigResolutionMap[funcSig] = new Dictionary <ContractDefinition, FunctionDefinition>();
            }

            // may potentially override the previous value due to inheritance
            FuncSigResolutionMap[funcSig][dynamicType] = funcDef;
        }
Esempio n. 29
0
 public dynFunctionWithRevit(IEnumerable<string> inputs, IEnumerable<string> outputs, FunctionDefinition functionDefinition)
     : base(inputs, outputs, functionDefinition)
 {
 }
Esempio n. 30
0
        public AstPythonFunction(PythonAst ast, IPythonModule declModule, IPythonType declType, FunctionDefinition def, string doc)
        {
            DeclaringModule = declModule;
            DeclaringType   = declType;

            Name          = def.Name;
            Documentation = doc;

            foreach (var dec in (def.Decorators?.Decorators).MaybeEnumerate().OfType <NameExpression>())
            {
                if (dec.Name == "classmethod")
                {
                    IsClassMethod = true;
                }
                else if (dec.Name == "staticmethod")
                {
                    IsStatic = true;
                }
            }

            _overloads = new List <AstPythonFunctionOverload> {
                new AstPythonFunctionOverload(Documentation, "", MakeParameters(ast, def), MakeReturns(def))
            };
        }
Esempio n. 31
0
 public virtual Function CreateFunction(IEnumerable<string> inputs, IEnumerable<string> outputs,
                                              FunctionDefinition functionDefinition)
 {
     return new Function(inputs, outputs, functionDefinition);
 }
Esempio n. 32
0
 internal void AddOverload(PythonAst ast, FunctionDefinition def)
 {
     _overloads.Add(new AstPythonFunctionOverload(def.Documentation, "", MakeParameters(ast, def), MakeReturns(def)));
 }
Esempio n. 33
0
 // FunctionDefinition
 public virtual bool Walk(FunctionDefinition node) { return true; }
Esempio n. 34
0
 private static IEnumerable <IPythonType> MakeReturns(FunctionDefinition def)
 {
     yield break;
 }
Esempio n. 35
0
 public override string GenerateCodeForFunction(AbstractTranslator translator, FunctionDefinition funcDef)
 {
     return(this.ParentPlatform.GenerateCodeForFunction(translator, funcDef));
 }
Esempio n. 36
0
 public FunctionScopeNode(FunctionDefinition func)
 {
     _func = func;
 }
 public void tearDown()
 {
     E = null;
 }
Esempio n. 38
0
 public void AddConstructorToContract(ContractDefinition contract, FunctionDefinition ctor)
 {
     Debug.Assert(ctor.IsConstructor, $"{ctor.Name} is not a constructor");
     Debug.Assert(!ContractToConstructorMap.ContainsKey(contract), $"Multiple constructors are defined for {contract.Name}");
     ContractToConstructorMap[contract] = ctor;
 }
Esempio n. 39
0
 public override void PostWalk(FunctionDefinition node)
 {
     EndScope(false);
     Debug.Assert(_head != null);
     base.PostWalk(node);
 }
Esempio n. 40
0
 /// <summary>
 ///     Attempt to upload PackageUpload
 /// </summary>
 /// <param name="packageUpload"> The PackageUpload object - the payload </param>
 /// <param name="funDef">
 ///     The function definition for the user-defined node - necessary to
 ///     update the LoadedPackageHeaders array on load
 /// </param>
 public void Publish(PackageUpload packageUpload, FunctionDefinition funDef)
 {
     ThreadStart start = () =>
         {
             try
             {
                 ResponseWithContentBody<PackageHeader> ret =
                     Client.ExecuteAndDeserializeWithContent<PackageHeader>(packageUpload);
                 dynSettings.Bench.Dispatcher.BeginInvoke((Action) (() =>
                     {
                         dynSettings.Controller.DynamoViewModel.Log("Message form server: " + ret.message);
                         LoadedPackageHeaders.Add(funDef, ret.content);
                         SavePackageHeader(ret.content);
                     }));
             }
             catch
             {
                 dynSettings.Bench.Dispatcher.BeginInvoke(
                     (Action) (() => dynSettings.Controller.DynamoViewModel.Log("Failed to publish package.")));
             }
         };
     new Thread(start).Start();
 }
        private static IEnumerable <FunctionDefinition> GetFunctionDefinitionsFromParameterCombinations(FunctionDefinition functionDefinition, IEnumerable <IEnumerable <ParameterDefinition> > parametersCombinations)
        {
            var functionDefinitions = new List <FunctionDefinition>();

            foreach (var parameterCombination in parametersCombinations)
            {
                var newFunctionDefinition = SerializationHelper.DeserializeTo <FunctionDefinition>(functionDefinition);
                newFunctionDefinition.FunctionParameters = parameterCombination;
                functionDefinitions.Add(newFunctionDefinition);
            }
            return(functionDefinitions);
        }
        /// <summary>
        /// Handles the return value from a function
        /// </summary>
        /// <param name="compilationData">The compilation data</param>
        /// <param name="toCall">The function to call</param>
        /// <param name="returnValueRegister">The register to store the return value</param>
        public void HandleReturnValue(CompilationData compilationData, FunctionDefinition toCall, VirtualRegister returnValueRegister)
        {
            //If we have passed arguments via the stack, adjust the stack pointer.
            int numStackArgs = this.CalculateStackArguments(toCall.Parameters);
            var virtualAssembler = compilationData.VirtualAssembler;

            if (numStackArgs > 0)
            {
                Assembler.Add(
                    compilationData.Function.GeneratedCode,
                    Register.SP,
                    numStackArgs * Assembler.RegisterSize);
            }

            if (!toCall.ReturnType.IsPrimitiveType(PrimitiveTypes.Void))
            {
                if (toCall.ReturnType.IsPrimitiveType(PrimitiveTypes.Float))
                {
                    virtualAssembler.GenerateTwoRegisterFixedSourceInstruction(
                        returnValueRegister,
                        FloatRegister.XMM0,
                        Assembler.Move,
                        Assembler.Move,
                        true);
                }
                else
                {
                    virtualAssembler.GenerateTwoRegisterFixedSourceInstruction(
                        returnValueRegister,
                        Register.AX,
                        Assembler.Move,
                        Assembler.Move,
                        true);
                }
            }
        }
Esempio n. 43
0
        private BoogieStmtList GenerateBodyOfFallbackDispatch(List <BoogieVariable> inParams, string fbUnknownProcName)
        {
            // Perform the payable logic to transfer balance
            //
            // Fallback(from, to, amount)
            //
            // foreach contract C that is not Lib/VeriSol
            //    if (DT[this] == C)
            //       if C has a fallback f
            //            call ret := fallBack_C(this=to, sender=from, msg.value)
            //       else
            //            assume msg.value == 0;
            // else
            //    if stubModel == callback
            //     call fallBack_unknownType(from, to, amout) //we switch the order of first two parameters to ease callbacks
            //    else if stubmodel == havoc
            //      havoc all global state, except local state of this contract
            //    else
            //      skip //default
            BoogieIfCmd ifCmd = null;

            Debug.Assert(context.ContractDefinitions.Count >= 1, "There should be at least one contract");

            List <BoogieIdentifierExpr> outParams = new List <BoogieIdentifierExpr>();

            List <BoogieExpr> unkwnFnArgs = new List <BoogieExpr>()
            {
                new BoogieIdentifierExpr(inParams[0].Name),
                new BoogieIdentifierExpr(inParams[1].Name),
                new BoogieIdentifierExpr(inParams[2].Name)
            };

            // fbUnknown(from, to, amount)
            BoogieStmtList noMatchCase = BoogieStmtList.MakeSingletonStmtList(
                new BoogieCallCmd(fbUnknownProcName, unkwnFnArgs, outParams));

            foreach (var contract in context.ContractDefinitions)
            {
                if (contract.ContractKind == EnumContractKind.LIBRARY)
                {
                    continue;
                }

                FunctionDefinition function = context.ContractToFallbackMap.ContainsKey(contract) ?
                                              context.ContractToFallbackMap[contract] : null;
                BoogieExpr lhs   = new BoogieMapSelect(new BoogieIdentifierExpr("DType"), new BoogieIdentifierExpr(inParams[1].Name));
                BoogieExpr rhs   = new BoogieIdentifierExpr(contract.Name);
                BoogieExpr guard = new BoogieBinaryOperation(BoogieBinaryOperation.Opcode.EQ, lhs, rhs);


                BoogieStmtList thenBody = null;

                if (function != null)
                {
                    List <BoogieExpr> arguments = new List <BoogieExpr>()
                    {
                        new BoogieIdentifierExpr(inParams[1].Name),
                        new BoogieIdentifierExpr(inParams[0].Name),
                        new BoogieIdentifierExpr(inParams[2].Name)
                    };

                    string callee = TransUtils.GetCanonicalFunctionName(function, context);
                    // to.fallback(from, amount), thus need to switch param0 and param1
                    thenBody = BoogieStmtList.MakeSingletonStmtList(new BoogieCallCmd(callee, arguments, outParams));
                }
                else
                {
                    // No fallback means not payable (amount == 0)
                    thenBody = BoogieStmtList.MakeSingletonStmtList(
                        new BoogieAssumeCmd(
                            new BoogieBinaryOperation(
                                BoogieBinaryOperation.Opcode.EQ,
                                new BoogieIdentifierExpr(inParams[2].Name),
                                new BoogieLiteralExpr(BigInteger.Zero)))
                        );
                }

                BoogieStmtList elseBody = ifCmd == null ? noMatchCase : BoogieStmtList.MakeSingletonStmtList(ifCmd);

                ifCmd = new BoogieIfCmd(guard, thenBody, elseBody);
            }

            return(BoogieStmtList.MakeSingletonStmtList(ifCmd));
        }
Esempio n. 44
0
 public void AddFallbackToContract(ContractDefinition contract, FunctionDefinition fallback)
 {
     Debug.Assert(fallback.IsFallback, $"{fallback.Name} is not a fallback function");
     Debug.Assert(!ContractToFallbackMap.ContainsKey(contract), $"Multiple fallbacks are defined for {contract.Name}");
     ContractToFallbackMap[contract] = fallback;
 }
Esempio n. 45
0
        /// <summary>
        ///     Attempts to load a PackageHeader from the Packages directory, if successful, stores the PackageHeader
        /// </summary>
        /// <param name="funcDef"> The FunctionDefinition to which the loaded user-defined node is to be assigned </param>
        /// <param name="name">
        ///     The name of the package, necessary for looking it up in Packages. Note that
        ///     two package version cannot exist side by side.
        /// </param>
        public void LoadPackageHeader(FunctionDefinition funcDef, string name)
        {
            try
            {
                string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string pluginsPath = Path.Combine(directory, "packages");

                // find the file matching the expected name
                string[] files = Directory.GetFiles(pluginsPath, name + ".json");

                if (files.Length == 1) // There can only be one!
                {
                    // open and deserialize to a PackageHeader object
                    // this is a bit hacky looking, but does the job
                    var proxyResponse = new RestResponse();
                    proxyResponse.Content = File.ReadAllText(files[0]);
                    var jsonDes = new JsonDeserializer();
                    var packageHeader = jsonDes.Deserialize<PackageHeader>(proxyResponse);
                    dynSettings.Controller.DynamoViewModel.Log("Loading package control information for " + name + " from packages");
                    LoadedPackageHeaders.Add(funcDef, packageHeader);
                }
            }
            catch (Exception ex)
            {
                dynSettings.Controller.DynamoViewModel.Log("Failed to open the package header information.");
                dynSettings.Controller.DynamoViewModel.Log(ex);
                Debug.WriteLine(ex.Message + ":" + ex.StackTrace);
            }
        }
Esempio n. 46
0
 /// <summary>
 /// Initializes a new <see cref="WorkflowActivityProcessor"/>
 /// </summary>
 /// <param name="serviceProvider">The current <see cref="IServiceProvider"/></param>
 /// <param name="loggerFactory">The service used to create <see cref="ILogger"/>s</param>
 /// <param name="context">The current <see cref="IWorkflowRuntimeContext"/></param>
 /// <param name="activityProcessorFactory">The service used to create <see cref="IWorkflowActivityProcessor"/>s</param>
 /// <param name="options">The service used to access the current <see cref="ApplicationOptions"/></param>
 /// <param name="activity">The <see cref="V1WorkflowActivity"/> to process</param>
 /// <param name="action">The <see cref="ActionDefinition"/> to process</param>
 /// <param name="function">The <see cref="FunctionDefinition"/> to process</param>
 public FunctionProcessor(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, IWorkflowRuntimeContext context, IWorkflowActivityProcessorFactory activityProcessorFactory,
                          IOptions <ApplicationOptions> options, V1WorkflowActivity activity, ActionDefinition action, FunctionDefinition function)
     : base(loggerFactory, context, activityProcessorFactory, options, activity, action)
 {
     this.ServiceProvider = serviceProvider;
     this.Function        = function;
 }
 /// <summary>
 /// Handles the given function call arguments
 /// </summary>
 /// <param name="compilationData">The compilation data</param>
 /// <param name="argumentRegisters">The virtual registers for the arguments</param>
 /// <param name="aliveRegistersStack">The alive registers stack</param>
 /// <param name="toCall">The function to call</param>
 public void CallFunctionArguments(
     CompilationData compilationData,
     IReadOnlyList<VirtualRegister> argumentRegisters,
     IDictionary<HardwareRegister, int> aliveRegistersStack, FunctionDefinition toCall)
 {
     for (int arg = toCall.Parameters.Count - 1; arg >= 0; arg--)
     {
         this.CallFunctionArgument(compilationData, arg, toCall.Parameters[arg], argumentRegisters, aliveRegistersStack, toCall);
     }
 }
Esempio n. 48
0
 internal SimpleFunction(Context context, FunctionDefinition creator)
     : base(context, creator)
 {
 }
        /// <summary>
        /// Handles the given function call argument
        /// </summary>
        /// <param name="compilationData">The compilation data</param>
        /// <param name="argumentIndex">The index of the argument</param>
        /// <param name="argumentType">The type of the argument</param>
        /// <param name="argumentRegisters">The virtual registers for the arguments</param>
        /// <param name="aliveRegistersStack">The alive registers stack</param>
        /// <param name="toCall">The function to call</param>
        public void CallFunctionArgument(
            CompilationData compilationData,
            int argumentIndex, VMType argumentType,
            IReadOnlyList<VirtualRegister> argumentRegisters,
            IDictionary<HardwareRegister, int> aliveRegistersStack,
            FunctionDefinition toCall)
        {
            var virtualAssembler = compilationData.VirtualAssembler;
            var regAlloc = compilationData.RegisterAllocation;
            var generatedCode = compilationData.Function.GeneratedCode;
            int thisNumArgs = compilationData.Function.Definition.Parameters.Count;
            int numArgs = toCall.Parameters.Count;

            int argsStart = 1 + compilationData.StackSize / Assembler.RegisterSize;

            if (virtualAssembler.NeedSpillRegister)
            {
                argsStart += 1;
            }

            int alignment = this.CalculateStackAlignment(compilationData, toCall.Parameters, aliveRegistersStack.Count);

            var virtualReg = argumentRegisters[numArgs - 1 - argumentIndex];
            var virtualRegStack = regAlloc.GetStackIndex(virtualReg);

            //Check if to pass argument by via the stack
            if (argumentIndex >= numRegisterArguments)
            {
                //Move arguments to the stack
                HardwareRegister spillReg;
                int stackOffset = 0;

                if (argumentType.IsPrimitiveType(PrimitiveTypes.Float))
                {
                    spillReg = virtualAssembler.GetFloatSpillRegister();

                    if (!virtualRegStack.HasValue)
                    {
                        stackOffset = aliveRegistersStack[virtualAssembler.GetFloatRegisterForVirtual(virtualReg).Value];
                    }
                }
                else
                {
                    spillReg = virtualAssembler.GetIntSpillRegister();

                    if (!virtualRegStack.HasValue)
                    {
                        stackOffset = aliveRegistersStack[virtualAssembler.GetIntRegisterForVirtual(virtualReg).Value];
                    }
                }

                var argMemory = new MemoryOperand();

                if (virtualRegStack.HasValue)
                {
                    argMemory = new MemoryOperand(
                        Register.BP,
                        virtualAssembler.CalculateStackOffset(virtualRegStack.Value));
                }
                else
                {
                    argMemory = new MemoryOperand(
                        Register.BP,
                        -(argsStart + stackOffset)
                        * Assembler.RegisterSize);
                }

                Assembler.Move(generatedCode, spillReg, argMemory);
                Assembler.Push(generatedCode, spillReg);
            }
            else
            {
                HardwareRegister argReg;
                int stackOffset = 0;

                if (argumentType.IsPrimitiveType(PrimitiveTypes.Float))
                {
                    argReg = floatArgumentRegisters[argumentIndex];

                    if (!virtualRegStack.HasValue)
                    {
                        stackOffset = aliveRegistersStack[virtualAssembler.GetFloatRegisterForVirtual(virtualReg).Value];
                    }
                }
                else
                {
                    argReg = intArgumentRegisters[argumentIndex];

                    if (!virtualRegStack.HasValue)
                    {
                        stackOffset = aliveRegistersStack[virtualAssembler.GetIntRegisterForVirtual(virtualReg).Value];
                    }
                }

                var argMemory = new MemoryOperand();

                if (virtualRegStack.HasValue)
                {
                    argMemory = new MemoryOperand(
                        Register.BP,
                        virtualAssembler.CalculateStackOffset(virtualRegStack.Value));
                }
                else
                {
                    argMemory = new MemoryOperand(
                        Register.BP,
                        -(argsStart + stackOffset)
                        * Assembler.RegisterSize);
                }

                Assembler.Move(generatedCode, argReg, argMemory);
            }
        }
 /// <summary>
 /// Creates a new unresolved call
 /// </summary>
 /// <param name="addressMode">The address mode</param>
 /// <param name="function">The function</param>
 /// <param name="callSiteOffset">The offset in the function that makes the call</param>
 public UnresolvedFunctionCall(FunctionCallAddressMode addressMode, FunctionDefinition function, int callSiteOffset)
 {
     this.AddressMode    = addressMode;
     this.Function       = function;
     this.CallSiteOffset = callSiteOffset;
 }
Esempio n. 51
0
        /// <summary>
        ///     Change the currently visible workspace to a custom node's workspace
        /// </summary>
        /// <param name="symbol">The function definition for the custom node workspace to be viewed</param>
        internal void FocusCustomNodeWorkspace(FunctionDefinition symbol)
        {
            if (symbol == null)
            {
                throw new Exception("There is a null function definition for this node.");
            }

            if (_model.CurrentWorkspace is CustomNodeWorkspaceModel)
            {
                var customNodeWorkspace = _model.CurrentWorkspace as CustomNodeWorkspaceModel;
                if (customNodeWorkspace.FunctionDefinition.FunctionId
                    == symbol.WorkspaceModel.FunctionDefinition.FunctionId)
                {
                    return;
                }
            }

            var newWs = symbol.WorkspaceModel;

            if (!this._model.Workspaces.Contains(newWs))
                this._model.Workspaces.Add(newWs);

            CurrentSpaceViewModel.CancelActiveState();

            _model.CurrentWorkspace = newWs;
            _model.CurrentWorkspace.OnDisplayed();

            //set the zoom and offsets events
            var vm = dynSettings.Controller.DynamoViewModel.Workspaces.First(x => x.Model == newWs);
            vm.OnCurrentOffsetChanged(this, new PointEventArgs(new Point(newWs.X, newWs.Y)));
            vm.OnZoomChanged(this, new ZoomEventArgs(newWs.Zoom));
        }
Esempio n. 52
0
        private void StartFunctionArgs(string funcName, int allStartPos, int argStartPos, Span nameSpan,
                                       DataType returnDataType, FunctionPrivacy privacy, bool isExtern)
        {
            var localArgStartPos = _source.GetFilePosition(argStartPos);
            var argScope         = new CodeScope(localArgStartPos.Position);
            int argEndPos        = 0;
            var args             = new List <ArgumentDescriptor>();
            var argDefList       = new List <Definition>();

            // Read the arguments
            while (true)
            {
                if (_code.ReadExact(')'))
                {
                    argEndPos = _code.Position;
                    break;
                }
                if (_code.ReadExact(','))
                {
                    continue;
                }
                if (TryReadFunctionArgument(argScope, !_visible || localArgStartPos.PrimaryFile, args, argDefList))
                {
                    continue;
                }
                return;
            }

            int    bodyStartPos;
            string description;

            if (!ReadFunctionAttributes(funcName, out bodyStartPos, out description, isExtern))
            {
                return;
            }

            if (isExtern)
            {
                var localPos = _source.GetFilePosition(nameSpan.Start);

                var sig = new FunctionSignature(true, privacy, returnDataType, _className, funcName, description, args);
                sig.ApplyDocumentation(localPos.FileName);
                var def = new FunctionDefinition(sig, localPos, 0, 0, 0, Span.Empty);
                _externFuncs[funcName] = def;
                AddGlobalDefinition(def);
                return;
            }

            // Read the variables at the start of the function.
            var       localBodyStartPos = _source.GetFilePosition(bodyStartPos);
            CodeScope funcScope         = null;
            var       varList           = new List <Definition>();

            if (!_visible || localBodyStartPos.PrimaryFile)             // Don't worry about saving variables if this function isn't in this file anyway.
            {
                funcScope = new CodeScope(argScope, bodyStartPos);
                while (!_code.EndOfFile)
                {
                    if (!TryReadVariableDeclaration(funcScope, varList))
                    {
                        break;
                    }
                }

                //// Add the arguments to the body as well, so they are accessible inside the function.
                //foreach (var def in argDefList)
                //{
                //	_defProv.AddLocalDefinition(localBodyStartPos.Position, def);
                //}
            }

            var statementsStartPos = _code.Position;

            ReadFunctionBody();
            var bodyEndPos = _code.Position;

            var bodyStartLocalPos  = _source.GetPrimaryFilePosition(bodyStartPos);
            var nameActualPos      = _source.GetFilePosition(nameSpan.Start);
            var argStartPrimaryPos = _source.GetPrimaryFilePosition(argStartPos);
            var argEndPrimaryPos   = _source.GetPrimaryFilePosition(argEndPos);
            var entireSpan         = _source.GetPrimaryFileSpan(new Span(allStartPos, bodyEndPos));

            var funcDef = new FunctionDefinition(new FunctionSignature(false, privacy, returnDataType, _className, funcName, description, args),
                                                 nameActualPos, argStartPrimaryPos, argEndPrimaryPos, bodyStartLocalPos, entireSpan);

            _localFuncs.Add(new LocalFunction(funcDef, nameSpan, statementsStartPos, bodyEndPos, argDefList, varList));
            AddGlobalDefinition(funcDef);

            // Add the definitions for the argument list
            Span argEffect;

            if (_visible)
            {
                argEffect = new Span(localArgStartPos.Position, _source.GetPrimaryFilePosition(bodyEndPos));
            }
            else
            {
                argEffect = new Span(argStartPos, bodyEndPos);
            }

            _defProv.AddLocal(argEffect, argDefList);

            // Add the definitions for the declared variables
            if (varList != null)
            {
                Span varEffect;
                if (_visible)
                {
                    varEffect = new Span(bodyStartLocalPos, _source.GetPrimaryFilePosition(bodyEndPos));
                }
                else
                {
                    varEffect = new Span(bodyStartPos, bodyEndPos);
                }

                _defProv.AddLocal(varEffect, varList);
            }
        }
Esempio n. 53
0
 /// <summary>
 /// Adds a parameter to the definition of this external function with the given
 /// name, type and linkage. Parameters must be added in the exact order in which
 /// they are defined in the external function.
 /// </summary>
 /// <param name="name">The parameter name.</param>
 /// <param name="type">A SymType representing the parameter type.</param>
 /// <param name="linkage">A SymLinkage representing the parameter linkage.</param>
 /// <param name="include">Specifies whether this parameter should be included in ParametersNode.</param>
 public void Add(string name, SymType type, SymLinkage linkage, bool include = true)
 {
     FunctionDefinition definition = new FunctionDefinition();
     definition.Name = name;
     definition.Symbol = new Symbol(name, new SymFullType(type), SymClass.VAR, null, 0);
     definition.Symbol.Linkage = linkage;
     definition.Include = include;
     _definitions.Add(definition);
     _paramList.Add(name);
 }
Esempio n. 54
0
        public static IEnumerable <FunctionTerm> GetDerivatives(this FunctionTerm term)
        {
            if (term is Sum)
            {
                Variable x = new Variable(1, "x");
                Variable y = new Variable(1, "y");

                return(Enumerables.Create
                       (
                           Term.Constant(1).Abstract(x, y),
                           Term.Constant(1).Abstract(x, y)
                       ));
            }
            if (term is Product)
            {
                Variable x = new Variable(1, "x");
                Variable y = new Variable(1, "y");

                return(Enumerables.Create
                       (
                           y.Abstract(x, y),
                           x.Abstract(x, y)
                       ));
            }
            if (term is Exponentiation)
            {
                Variable x = new Variable(1, "x");
                Variable y = new Variable(1, "y");

                return(Enumerables.Create
                       (
                           Term.Product(y, Term.Exponentiation(x, Term.Difference(y, Term.Constant(1)))).Abstract(x, y),
                           Term.Product(Term.Logarithm(x), Term.Exponentiation(x, y)).Abstract(x, y)
                       ));
            }
            if (term is Logarithm)
            {
                Variable x = new Variable(1, "x");

                return(Enumerables.Create(Term.Invert(x).Abstract(x)));
            }
            if (term is FunctionDefinition)
            {
                FunctionDefinition functionDefinitionTerm = (FunctionDefinition)term;

                IEnumerable <FunctionTerm> derivatives = GetDerivatives(functionDefinitionTerm.Function).ToArray();

                return
                    ((
                         from index in Enumerable.Range(0, derivatives.Count())
                         let derivative = derivatives.ElementAt(index)
                                          select new FunctionDefinition
                                          (
                             string.Format("{0}_d{1}", functionDefinitionTerm.Name, index),
                             Rewriting.CompleteNormalization.Rewrite(derivative),
                             new BasicSyntax(string.Format("{0}'{1}", functionDefinitionTerm.Syntax.GetText(), index.ToString().ToSuperscript()))
                                          )
                         )
                     .ToArray());
            }
            if (term is Abstraction)
            {
                Abstraction abstractionTerm = (Abstraction)term;

                return
                    ((
                         from variable in abstractionTerm.Variables
                         from derivative in GetDerivatives(abstractionTerm.Term, variable)
                         select derivative.Abstract(abstractionTerm.Variables)
                         )
                     .ToArray());
            }

            throw new InvalidOperationException();
        }
Esempio n. 55
0
 public bool IsUnderPackageControl(FunctionDefinition def)
 {
     return IsUnderPackageControl(def.WorkspaceModel.FileName);
 }
Esempio n. 56
0
 public virtual void Optimize(ref CodeNode _this, FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
 {
 }
Esempio n. 57
0
 public virtual void PostWalk(FunctionDefinition node) { }
Esempio n. 58
0
 public AddFunction(string calculatorId, FunctionDefinition definition) : base(calculatorId)
 {
     Definition = definition;
 }
Esempio n. 59
0
 public override void PostWalk(FunctionDefinition node) { }
        private Value Function(FunctionNode exp)
        {
            List <FunctionDefinition> funcList;

            try
            {
                funcList = functionTable[exp.FunctionName];
            }
            catch (Exception)
            {
                throw new ModelInterpreterException($"Неизвестная функция \"{exp.FunctionName}\"")
                      {
                          Line     = exp.Line,
                          Position = exp.Position
                      };
            }
            List <Constant> args = new List <Constant>();

            foreach (ExpressionNode expNode in exp.Arguments)
            {
                Constant obj = Eval(expNode).GetRValue();
                args.Add(obj);
            }
            Exception lastExc = null;

            foreach (FunctionDefinition fd in funcList)
            {
                try
                {
                    return(FunctionDefinition.Compute(fd, args));
                }
                catch (Exception exc)
                {
                    lastExc = exc;
                }
            }
            if (lastExc != null)
            {
                throw new ModelInterpreterException(lastExc.Message)
                      {
                          Line     = exp.Line,
                          Position = exp.Position
                      };
            }
            string exceptionMessage = $"Не существует подходящего определения для функции {exp.FunctionName} ( ";
            int    i = 0;

            foreach (var arg in args)
            {
                if (i != 0)
                {
                    exceptionMessage += ", ";
                }
                exceptionMessage += arg.ConstantType.ToString();
            }
            exceptionMessage += ")";
            throw new ModelInterpreterException(exceptionMessage)
                  {
                      Line     = exp.Line,
                      Position = exp.Position
                  };
        }