示例#1
0
        //public List<TaskVariable> Variables { get; set ; }

        public int Execute()
        {
            string[] files;

            if (IncludeSubfolder)
            {
                files = Directory.GetFiles(FolderPath, FileFilter, SearchOption.AllDirectories);
            }
            else
            {
                files = Directory.GetFiles(FolderPath, FileFilter, SearchOption.TopDirectoryOnly);
            }



            Variables.Add(new ListVariable()
            {
                Value        = files.ToList(),
                VariableName = Var_StoreRetrievedFilesInto,
                RobotAction  = this
            });


            return(files.Count());
        }
示例#2
0
        public InlineCode(params AnyExpression[] expressions) : base(Expression.Empty())
        {
            foreach (var expression in expressions)
            {
                switch (expression)
                {
                case null:
                    continue;

                case InlineCode code:
                    code.Parameters.ForEach(Parameters.Add);
                    code.Variables.ForEach(Variables.Add);
                    code.Statements.ForEach(Statements.Add);
                    break;

                default:
                    switch (expression.Inner)
                    {
                    case ParameterExpression param1 when expression.Type == ConstructedType.Parameter:
                        Parameters.Add(param1);
                        break;

                    case ParameterExpression param2 when expression.Type == ConstructedType.Var:
                        Variables.Add(param2);
                        break;

                    default:
                        Statements.Add(expression);
                        break;
                    }

                    break;
                }
            }
        }
示例#3
0
        /// <summary>
        /// Add new control points
        /// </summary>
        /// <param name="LabelName">Label</param>
        /// <param name="Type">Optional Type, defaults to VARS</param>
        public void Add(string LabelName, IdentifierTypes Type = IdentifierTypes.VARS)
        {
            ControlPointInfo newControlPoint = new ControlPointInfo(LabelName, Type);

            switch (Type)
            {
            case IdentifierTypes.VARS:
                Variables.Add(newControlPoint);
                break;

            case IdentifierTypes.INS:
                Inputs.Add(newControlPoint);
                break;

            case IdentifierTypes.OUTS:
                Outputs.Add(newControlPoint);
                break;

            case IdentifierTypes.PRGS:
                Programs.Add(newControlPoint);
                break;

            case IdentifierTypes.SCHS:
                Schedules.Add(newControlPoint);
                break;

            case IdentifierTypes.HOLS:
                Holidays.Add(newControlPoint);
                break;

            default:
                break;
            }
        }
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="source">Source model definition  to create the execution context factory for</param>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null</exception>
        /// <exception cref="ArgumentException">No decisions in the source definition</exception>
        /// <exception cref="ArgumentException">No variables in the source definition</exception>
        protected DmnExecutionContextFactory(DmnDefinition source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (source.Decisions == null || source.Decisions.Count < 1)
            {
                throw new ArgumentException("No decisions in the source definition");
            }
            if (source.Variables == null || source.Variables.Count < 1)
            {
                throw new ArgumentException("No variables in the source definition");
            }

            //Decisions reference
            foreach (var sourceDecision in source.Decisions)
            {
                Decisions.Add(sourceDecision.Key, sourceDecision.Value);
            }

            //Init runtime (execution) variables
            foreach (var sourceVariable in source.Variables.Values)
            {
                var variable = new DmnExecutionVariable(sourceVariable);
                Variables.Add(variable.Name, variable);
                if (variable.IsInputParameter)
                {
                    InputData.Add(variable.Name, variable);
                }
            }
        }
        /// <summary>
        /// Constructor.  lvt will be null when creating a new entry.
        /// </summary>
        public EditLocalVariableTable(Window owner, DisasmProject project, Formatter formatter,
                                      LocalVariableTable lvt, int offset)
        {
            InitializeComponent();
            Owner       = owner;
            DataContext = this;

            mProject     = project;
            mFormatter   = formatter;
            mSymbolTable = project.SymbolTable;
            mOffset      = NewOffset = offset;

            if (lvt != null)
            {
                mWorkTable     = new LocalVariableTable(lvt);
                mIsNotNewTable = true;
            }
            else
            {
                mWorkTable = new LocalVariableTable();
            }

            for (int i = 0; i < mWorkTable.Count; i++)
            {
                DefSymbol defSym = mWorkTable[i];
                Variables.Add(CreateFormattedSymbol(defSym));
            }
        }
示例#6
0
        public int Execute()
        {
            try
            {
                var data = CSVReader.ReadCsvFile(FilePath);

                if (VariableStorage.CSVVar.ContainsKey(Var_StoreTableInto))
                {
                    VariableStorage.CSVVar.Remove(Var_StoreTableInto);
                }

                VariableStorage.CSVVar.Add(Var_StoreTableInto, Tuple.Create(ID, data));

                Variables.Add(new DataTableVariable()
                {
                    RobotAction  = this,
                    Value        = data,
                    VariableName = Var_StoreTableInto
                });

                return(1);
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
        public VariableSetResource AddOrUpdateVariableValue(string name, string value, string description)
        {
            var existing = Variables.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase) &&
                                                    (x.Scope == null || x.Scope.Equals(new ScopeSpecification())));

            if (existing == null)
            {
                var template = new VariableResource
                {
                    Name        = name,
                    Value       = value,
                    Description = description
                };

                Variables.Add(template);
            }
            else
            {
                existing.Name        = name;
                existing.Value       = value;
                existing.Description = description;
            }

            return(this);
        }
示例#8
0
 public TurretSet(int numTurrets, Team team, int radius, Grid grid)
 {
     for (int i = 0; i < numTurrets; ++i)
     {
         Variables.Add(new Turret(team, radius, grid, this));
     }
 }
示例#9
0
 public void AddVariable(Variable variable, int userPermissionLevel = 0)
 {
     #region Preconditions
     if (string.IsNullOrEmpty(variable.Name))
     {
         throw new InvalidOperationException("Cannot add variable with empty Name");
     }
     if (variable.Driver == null)
     {
         throw new InvalidOperationException("Cannot add variable with unassigned Driver");
     }
     if (userPermissionLevel < MinUserLevelToInteract)
     {
         throw new SecurityException("Cannot add variable. User have not enough permissions.");
     }
     if (Started)
     {
         throw new InvalidOperationException("Experiment already started and not add variable");
     }
     if (Variables.Values.Any(x => x.Name == variable.Name))
     {
         throw new InvalidOperationException(string.Format("Dupplicate variable name: {0}", variable.Name));
     }
     #endregion
     Variables.Add(variable.ID, variable);
 }
        public VariableSetResource AddOrUpdateVariableValue(string name, string value, ScopeSpecification scope, bool isSensitive)
        {
            var existing = Variables.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase) && x.Scope.Equals(scope));

            if (existing == null)
            {
                var template = new VariableResource
                {
                    Name        = name,
                    Value       = value,
                    Scope       = scope,
                    IsSensitive = isSensitive
                };

                Variables.Add(template);
            }
            else
            {
                existing.Name        = name;
                existing.Value       = value;
                existing.Scope       = scope;
                existing.IsSensitive = isSensitive;
            }

            return(this);
        }
        public VariablesViewModel()
        {
            Title = "Variables";

            var variables = ServiceLocator.Current.GetInstance <IVariableStore>();

            foreach (var key in variables.Select(variable => variable.Key))
            {
                Variables.Add(new VariableViewModel(key));
            }

            variables.CollectionChanged += (sender, args) =>
            {
                if (args.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (var key in args.NewItems.Cast <string>())
                    {
                        Variables.Add(new VariableViewModel(key));
                    }
                }
                else if (args.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (var key in args.OldItems.Cast <string>())
                    {
                        var viewModel = Variables.FirstOrDefault(vm => vm.Key == key);

                        if (viewModel != null)
                        {
                            Variables.Remove(viewModel);
                        }
                    }
                }
            };
        }
示例#12
0
        public int Execute()
        {
            try
            {
                FileInfo fileInfo = new FileInfo(FilePath);
                Variables.Add(new StringVariable()
                {
                    VariableName = Var_Extension, Value = fileInfo.Extension
                });
                Variables.Add(new StringVariable()
                {
                    VariableName = Var_Directory, Value = fileInfo.DirectoryName
                });
                Variables.Add(new StringVariable()
                {
                    VariableName = Var_RootPath, Value = fileInfo.Directory.Root.FullName
                });
                Variables.Add(new StringVariable()
                {
                    VariableName = Var_FileName, Value = fileInfo.Name
                });
                Variables.Add(new StringVariable()
                {
                    VariableName = Var_FileNameWithoutExtension, Value = fileInfo.Name.Replace("." + fileInfo.Extension, "")
                });

                return(1);
            }
            catch (Exception)
            {
                return(0);
            }
        }
示例#13
0
        public void AddMacro(MacroVar macro, FileDiagnostics diagnostics, DocRange range, bool checkConflicts = true)
        {
            if (macro == null)
            {
                throw new ArgumentNullException(nameof(macro));
            }
            if (Variables.Contains(macro))
            {
                throw new Exception("macro reference is already in scope.");
            }

            if (checkConflicts && HasConflict(macro))
            {
                string message = "A macro with the same name and parameter types was already defined in this scope.";

                if (diagnostics != null && range != null)
                {
                    diagnostics.Error(message, range);
                    return;
                }
                else
                {
                    throw new Exception(message);
                }
            }

            Variables.Add(macro);
        }
示例#14
0
        public int Execute()
        {
            try
            {
                List <string> values = new List <string>();

                foreach (var file in FilesToCopy)
                {
                    System.IO.File.Copy(file.FilePath, Path.Combine(Destination, file.FileName), OverWriteIfFilesExixts);

                    values.Add(file.FilePath);
                }

                Variables.Add(new ListVariable()
                {
                    RobotAction  = this,
                    Value        = values,
                    VariableName = Var_StoreCopiedFiles
                });

                return(1);
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
示例#15
0
        public CodeBlock(params AnyExpression[] expressions) : base(Expression.Empty())
        {
            foreach (var expression in expressions)
            {
                if (expression is InlineCode code)
                {
                    code.Parameters.ForEach(Parameters.Add);
                    code.Variables.ForEach(Variables.Add);
                    code.Statements.ForEach(Statements.Add);
                }
                else
                {
                    switch (expression.Inner)
                    {
                    case ParameterExpression param1 when expression.Type == ConstructedType.Parameter:
                        Parameters.Add(param1);
                        break;

                    case ParameterExpression param2 when expression.Type == ConstructedType.Var:
                        Variables.Add(param2);
                        break;

                    default:
                        Statements.Add(expression);
                        break;
                    }
                }
            }
        }
示例#16
0
        /// <summary>
        /// Adds a variable to the current scope.
        /// When handling variables added by the user, supply the diagnostics and range to show the syntax error at.
        /// When handling variables added internally, have the diagnostics and range parameters be null. An exception will be thrown instead if there is a syntax error.
        /// </summary>
        /// <param name="variable">The variable that will be added to the current scope. If the object reference is already in the direct scope, an exception will be thrown.</param>
        /// <param name="diagnostics">The file diagnostics to throw errors with. Should be null when adding variables internally.</param>
        /// <param name="range">The document range to throw errors at. Should be null when adding variables internally.</param>
        public void AddVariable(IVariable variable, FileDiagnostics diagnostics, DocRange range)
        {
            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }
            if (Variables.Contains(variable))
            {
                throw new Exception("variable reference is already in scope.");
            }

            if (IsVariable(variable.Name))
            {
                string message = string.Format("A variable of the name {0} was already defined in this scope.", variable.Name);

                if (diagnostics != null && range != null)
                {
                    diagnostics.Error(message, range);
                }
                else
                {
                    throw new Exception(message);
                }
            }
            else
            {
                Variables.Add(variable);
            }
        }
示例#17
0
        private void Reload()
        {
            var dtReader = new DataTableReader(testCaseCollectionManager.Scope.Content);

            //Reset the state of the DataTable
            //Remove the Sort Order or you'll be in troubles when loading the datatable
            TestCases.DefaultView.Sort = String.Empty;
            TestCases.Rows.Clear();
            TestCases.Columns.Clear();
            TestCases.RejectChanges();

            //Load it
            TestCases.Load(dtReader, LoadOption.PreserveChanges);
            OnPropertyChanged("TestCases");

            //Take care of variables
            Variables.Clear();
            foreach (var v in testCaseCollectionManager.Scope.Variables)
            {
                Variables.Add(v);
            }

            if (VariableSelectedIndex < 0 && Variables.Count > 0)
            {
                VariableSelectedIndex = 0;
            }
        }
示例#18
0
        private void InspectActivity(Activity root)
        {
            IEnumerator <Activity> activities =
                WorkflowInspectionServices.GetActivities(root).GetEnumerator();


            while (activities.MoveNext())
            {
                PropertyInfo propVars = activities.Current.GetType().GetProperties().FirstOrDefault(p => p.Name == "Variables" && p.PropertyType == typeof(Collection <Variable>));
                if (propVars != null)
                {
                    try
                    {
                        Collection <Variable> variables = (Collection <Variable>)propVars.GetValue(activities.Current, null);
                        variables.ToList().ForEach(v =>
                        {
                            Variables.Add(v.Name);
                        });
                    }
                    catch
                    {
                    }
                }
                InspectActivity(activities.Current);
            }
        }
示例#19
0
        void AddField(FieldDeclarationSyntax fieldDecl)
        {
            if (fieldDecl.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword)))
            {
                return;
            }

            foreach (var varDecl in fieldDecl.Declaration.Variables)
            {
                if (varDecl.Initializer != null)
                {
                    continue;
                }

                var symbol = SemanticModel.GetDeclaredSymbol(varDecl);
                if (symbol == null)
                {
                    continue;
                }

                var isReadOnly         = fieldDecl.Modifiers.Any(m => m.IsKind(SyntaxKind.ReadOnlyKeyword));
                var isPublic           = symbol.DeclaredAccessibility == Accessibility.Public;
                var canBeUninitialized = !isReadOnly && isPublic;

                Variables.Add(symbol, new MemberVariable(symbol, canBeUninitialized));
            }
        }
示例#20
0
        public void LoadDataFromNsi(IEnumerable <string> lines)
        {
            Variables.Clear();

            var filteredLines = lines.Where(x => x.ToLower().Contains("!define "));

            var defineLength = "!define ".Length;

            foreach (var line in filteredLines)
            {
                var temp = line.Remove(0, defineLength).Trim();
                if (line.ToLower().Contains("\""))
                {
                    var name  = temp.Substring(0, temp.IndexOf(' '));
                    var value = temp.Replace(name, "").Replace("\"", "").Trim();
                    Variables.Add(new VariableModel
                    {
                        VariableName  = name,
                        VariableValue = value,
                        UserDefined   = true
                    });
                }
                else
                {
                    Variables.Add(new VariableModel
                    {
                        VariableName  = temp,
                        VariableValue = null,
                        UserDefined   = false
                    });
                }
            }
        }
示例#21
0
 /// <summary>
 /// Adds variables to the configuration which will be substituted for every script
 /// </summary>
 /// <param name="newVariables">The variables </param>
 public void AddVariables(IDictionary <string, string> newVariables)
 {
     foreach (var variable in newVariables)
     {
         Variables.Add(variable.Key, variable.Value);
     }
 }
示例#22
0
        void AddPropertyAsMemberVariable(PropertyDeclarationSyntax propertyDecl, IPropertySymbol symbol)
        {
            if (propertyDecl.ExpressionBody != null)
            {
                return;
            }
            if (propertyDecl.Initializer != null)
            {
                return;
            }

            if (propertyDecl.AccessorList == null)
            {
                return;
            }
            if (propertyDecl.AccessorList.Accessors.Any(a => a.Body != null))
            {
                return;
            }

            if (symbol.IsAbstract || symbol.IsStatic || symbol.IsIndexer)
            {
                return;
            }

            var hasNonprivateSetter =
                symbol.SetMethod != null &&
                symbol.SetMethod.DeclaredAccessibility != Accessibility.Private;

            Variables.Add(symbol, new MemberVariable(symbol, canBeUninitialized: hasNonprivateSetter));
        }
示例#23
0
        private void PostLoad(ConfigFile parent, string file, string[] macros = null)
        {
            FilePath = file;
            Parent   = parent;

            Variables.Add(new KeyValue("THIS_CONFIG_PATH", Path.GetDirectoryName(AbsoluteFilePath)));

            // Load all dependencies
            foreach (var dependFile in Files)
            {
                var dependFilePath = ExpandString(dependFile, false);
                if (!Path.IsPathRooted(dependFilePath))
                {
                    dependFilePath = Path.Combine(Path.GetDirectoryName(AbsoluteFilePath), dependFilePath);
                }

                var subMapping = Load(this, dependFilePath, macros);
                if (subMapping != null)
                {
                    subMapping.FilePath = dependFile;
                    References.Add(subMapping);
                }
            }

            // Clear all depends file
            Files.Clear();

            // Add this mapping file
            GetRoot().MapIdToFile.Add(Id, this);
        }
示例#24
0
 public void TryAddVariable(string variableName)
 {
     if (!Variables.Add(variableName))
     {
         throw new SemanticsException($"Variable {variableName} already exists in the scope.");
     }
 }
示例#25
0
        /// <summary>
        /// Adds a variable
        /// </summary>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public VariableDefinition AddVariable(TypeReference type, string name = "")
        {
            VariableDefinition def = new VariableDefinition(name, type);

            Variables.Add(def);
            return(def);
        }
示例#26
0
 public Package(string name, NLUEngine engine, Controller controller, CancellationToken ct, params Package[] subPackages) : base(ct)
 {
     Name       = name;
     NLUEngine  = engine;
     Controller = controller;
     Intents.Add("info", Info);
     Intents.Add("help", Help);
     Intents.Add("menu", Menu);
     Intents.Add("enable", Enable);
     Intents.Add("disable", Disable);
     Intents.Add("back", Back);
     Intents.Add("page", Page);
     Intents.Add("list", List);
     if (subPackages != null && subPackages.Length > 0)
     {
         SubPackages = subPackages.ToList();
     }
     foreach (var vn in VariableNames)
     {
         Variables.Add(Prefixed(vn), null);
     }
     foreach (var i in ItemNames)
     {
         Items.Add(Prefixed(i), null);
     }
     foreach (var m in MenuNames)
     {
         Menus.Add(Prefixed(m), null);
     }
 }
示例#27
0
        public ObjectVariable AddAbility(string abilityName)
        {
            var ability = new ObjectVariable(VariableTypes.Ability, abilityName, 0);

            Variables.Add(ability);
            return(ability);
        }
示例#28
0
 private void btnOk_Click(object sender, EventArgs e)
 {
     txtVariableName.Text = new VariableName(txtVariableName.Text)
                            .GetCleanName();
     txtVariableValue.Text = new VariableName(txtVariableValue.Text)
                             .GetCleanValue();
     if (string.IsNullOrWhiteSpace(txtVariableName.Text))
     {
         MessageBox.Show(
             @"The variable must have a valid name.",
             Text,
             MessageBoxButtons.OK,
             MessageBoxIcon.Information
             );
         return;
     }
     if (Variables.HasVariable(txtVariableName.Text))
     {
         MessageBox.Show(
             @"The variable name already exists.",
             Text,
             MessageBoxButtons.OK,
             MessageBoxIcon.Information
             );
         return;
     }
     Variables.Add(txtVariableName.Text, txtVariableValue.Text);
     DialogResult = DialogResult.OK;
 }
示例#29
0
        public int ActionRun(ActionEvent ev, HistoryEntry he = null, Variables additionalvars = null,
                             string flagstart = null, bool now = false)                                            //set flagstart to be the first flag of the actiondata..
        {
            List <ActionFileList.MatchingSets> ale = actionfiles.GetMatchingConditions(ev.TriggerName, flagstart); // look thru all actions, find matching ones

            if (ale.Count > 0)
            {
                Variables eventvars = new Variables();
                Actions.ActionVars.TriggerVars(eventvars, ev.TriggerName, ev.TriggerType);
                Actions.ActionVars.HistoryEventVars(eventvars, he, "Event");                      // if HE is null, ignored
                Actions.ActionVars.ShipBasicInformation(eventvars, he?.ShipInformation, "Event"); // if He null, or si null, ignore
                Actions.ActionVars.SystemVars(eventvars, he?.System, "Event");
                eventvars.Add(additionalvars);                                                    // adding null is allowed

                //System.Diagnostics.Debug.WriteLine("Dispatch Program with" + Environment.NewLine + eventvars.ToString(prefix:".. ", separ: Environment.NewLine));

                Variables testvars = new Variables(Globals);
                testvars.Add(eventvars);

                Functions functions = new Functions(testvars, null);

                if (actionfiles.CheckActions(ale, he?.journalEntry, testvars, functions) > 0)
                {
                    actionfiles.RunActions(now, ale, actionrunasync, eventvars); // add programs to action run

                    actionrunasync.Execute();                                    // See if needs executing
                }
            }

            return(ale.Count);
        }
示例#30
0
        /// <summary>
        /// Given a C declaration, adds it to the symbol table
        /// as a function or a type declaration.
        /// </summary>
        /// <param name="decl"></param>
        public List <SerializedType> AddDeclaration(Decl decl)
        {
            var types = new List <SerializedType>();

            if (decl is FunctionDecl fndec)
            {
                return(types);
            }

            IEnumerable <DeclSpec> declspecs = decl.decl_specs;
            var isTypedef = false;

            if (decl.decl_specs[0] is StorageClassSpec scspec &&
                scspec.Type == CTokenType.Typedef)
            {
                declspecs = decl.decl_specs.Skip(1);
                isTypedef = true;
            }

            var ntde = new NamedDataTypeExtractor(platform, declspecs, this, pointerSize);

            foreach (var declarator in decl.init_declarator_list)
            {
                var nt      = ntde.GetNameAndType(declarator.Declarator);
                var serType = nt.DataType !;

                if (nt.DataType is SerializedSignature sSig)
                {
                    sSig.Convention ??= GetCallingConventionFromAttributes(decl.attribute_list);
                    if (sSig.ReturnValue != null)
                    {
                        sSig.ReturnValue.Kind = ntde.GetArgumentKindFromAttributes(
                            "returns", decl.attribute_list);
                    }
                    var sProc = MakeProcedure(nt.Name !, sSig, decl.attribute_list);
                    Procedures.Add(sProc);
                    types.Add(sSig);
                }
                else if (!isTypedef)
                {
                    var variable = new GlobalDataItem_v2
                    {
                        Name     = nt.Name,
                        DataType = serType,
                    };
                    Variables.Add(variable);
                    types.Add(serType);
                }
                if (isTypedef)
                {
                    //$REVIEW: should make sure that if the typedef already exists,
                    // then the types match but a real compiler would have validated that.
                    var typedef = new SerializedTypedef
                    {
                        Name     = nt.Name,
                        DataType = serType
                    };
                    Types.Add(typedef);
                    //$REVIEW: do we really need to check for consistence?
                    NamedTypes[typedef.Name !] = serType;
示例#31
0
        protected override object EvalExpression(ParseTree tree, params object[] paramlist)
        {
            // if only left hand side available, this is not an assignment, simple evaluate expression
            if (nodes.Count == 1)
                return this.GetValue(tree, TokenType.AssignmentExpression, 0); // return the result

            if (nodes.Count != 3)
            {
                tree.Errors.Add(new ParseError("Illegal EvalExpression format", 1092, this));
                return null;
            }

            // ok, this is an assignment so declare the function or variable
                // assignment only allowed to function or to a variable
                ParseNode v = GetFunctionOrVariable(nodes[0]);
                if (v == null)
                {
                    tree.Errors.Add(new ParseError("Can only assign to function or variable", 1020, this));
                    return null;
                }

                ParseTreeEvaluator root = tree as ParseTreeEvaluator;
                if (root == null)
                {
                    tree.Errors.Add(new ParseError("Invalid parser used", 1040, this));
                    return null;
                }

                if (root.Context == null)
                {
                    tree.Errors.Add(new ParseError("No context defined", 1041, this));
                    return null;
                }

                if (v.Token.Type == TokenType.VARIABLE)
                {

                    // simply overwrite any previous defnition
                    string key = v.Token.Text;
                    root.Context.Globals[key] = this.GetValue(tree, TokenType.AssignmentExpression, 1);
                    return null;
                }
                else if (v.Token.Type == TokenType.Function)
                {

                    string key = v.Nodes[0].Token.Text;

                    // function lookup is case insensitive
                    if (root.Context.Functions.ContainsKey(key.ToLower()))
                        if (!(root.Context.Functions[key.ToLower()] is DynamicFunction))
                        {
                            tree.Errors.Add(new ParseError("Built in functions cannot be overwritten", 1050, this));
                            return null;
                        }

                    // lets determine the input variables.
                    // functions must be of te form f(x;y;z) = x+y*z;
                    // check the function parameters to be of type Variable, error otherwise
                    Variables vars = new Variables();
                    ParseNode paramsNode = v.Nodes[2];
                    if (paramsNode.Token.Type == TokenType.Params)
                    {   // function has parameters, so check if they are all variable declarations
                        for (int i = 0; i < paramsNode.Nodes.Count; i += 2)
                        {
                            ParseNode varNode = GetFunctionOrVariable(paramsNode.Nodes[i]);
                            if (varNode == null || varNode.Token.Type != TokenType.VARIABLE)
                            {
                                tree.Errors.Add(new ParseError("Function declaration may only contain variables", 1051, this));
                                return null;
                            }
                            // simply declare the variable, no need to evaluate the value of it at this point.
                            // evaluation will be done when the function is executed
                            // note, variables are Case Sensitive (!)
                            vars.Add(varNode.Token.Text, null);
                        }
                    }
                    // we have all the info we need to know to declare the dynamicly defined function
                    // pass on nodes[2] which is the Right Hand Side (RHS) of the assignment
                    // nodes[2] will be evaluated at runtime when the function is executed.
                    DynamicFunction dynf = new DynamicFunction(key, nodes[2], vars, vars.Count, vars.Count);
                    root.Context.Functions[key.ToLower()] = dynf;
                    return null;
                }

            // in an assignment, dont return any result (basically void)
            return null;
        }
示例#32
0
        public Variables GetVariableValues(Document document, ISchema schema, VariableDefinitions variableDefinitions, Inputs inputs)
        {
            var variables = new Variables();
            variableDefinitions.Apply(v =>
            {
                var variable = new Variable();
                variable.Name = v.Name;

                object variableValue = null;
                inputs?.TryGetValue(v.Name, out variableValue);
                variable.Value = GetVariableValue(document, schema, v, variableValue);

                variables.Add(variable);
            });
            return variables;
        }
示例#33
0
        public Variables GetVariableValues(ISchema schema, VariableDefinitions variableDefinitions, Inputs inputs)
        {
            var variables = new Variables();
            variableDefinitions.Apply(v =>
            {
                var variable = new Variable();
                variable.Name = v.Name;

                object variableValue;
                if (inputs != null && inputs.TryGetValue(v.Name, out variableValue))
                {
                    var valueAst = variableValue.AstFromValue(schema, v.Type.GraphTypeFromType(schema));
                    variable.Value = GetVariableValue(schema, v, valueAst);
                }
                else
                {
                    variable.Value = GetVariableValue(schema, v, v.DefaultValue);
                }

                variables.Add(variable);
            });
            return variables;
        }