Exemple #1
0
        void loadTilesetsFromFile()
        {
            tilesetList = new Dictionary <string, Tileset>();

            string  name;
            Vector2 origin;
            int     spriteWidth, tileWidth, tileHeight;
            Func <String[, ], Vector2, string> mapParse;

            ScriptState state = Scripting.parse(modulePath + "/areas/tilesets.txt");

            for (int i = 0; i < state.Variables.Count(); i++)
            {
                ScriptVariable v = state.Variables[i];

                name   = (string)Scripting.getScriptValue("name", v);
                origin = (Vector2)Scripting.getScriptValue("origin", v);

                spriteWidth = (int)Scripting.getScriptValue("spriteWidth", v);
                tileWidth   = (int)Scripting.getScriptValue("tileWidth", v);
                tileHeight  = (int)Scripting.getScriptValue("tileHeight", v);

                mapParse = (Func <String[, ], Vector2, string>)Scripting.getScriptValue("mapParse", v);

                tilesetList.Add(name, new Tileset(name, origin, spriteWidth,
                                                  tileWidth, tileHeight, mapParse));
            }
        }
        public void Set(ScriptExecutionEnvironment environment, ScriptVariable value)
        {
            if (_variable == null)
            {
                environment.Console.Warn("Cannot use index for null variable");
                return;
            }
            if (_index == null)
            {
                environment.Console.Warn("Cannot use null as index");
                return;
            }
            ListVariable   list = _variable as ListVariable;
            StringVariable key  = _index as StringVariable;

            if (list != null && key != null)
            {
                list[key.Value] = value;
                return;
            }

            int indexInt = _index.ToInteger();

            if (!_variable.SetIndexedValue(indexInt, value))
            {
                environment.Console.Warn(string.Format("Invalid index : {0}", _index.ToString()));
            }
        }
Exemple #3
0
        public static void Load(XmlElement node)
        {
            ClearAll();

            try
            {
                foreach (XmlElement el in node.GetElementsByTagName("scriptvariable"))
                {
                    TargetInfo target = new TargetInfo
                    {
                        Type   = Convert.ToByte(el.GetAttribute("type")),
                        Flags  = Convert.ToByte(el.GetAttribute("flags")),
                        Serial = Convert.ToUInt32(Serial.Parse(el.GetAttribute("serial"))),
                        X      = Convert.ToUInt16(el.GetAttribute("x")),
                        Y      = Convert.ToUInt16(el.GetAttribute("y")),
                        Z      = Convert.ToUInt16(el.GetAttribute("z")),
                        Gfx    = Convert.ToUInt16(el.GetAttribute("gfx"))
                    };

                    ScriptVariable scriptVariable = new ScriptVariable(el.GetAttribute("name"), target);
                    ScriptVariableList.Add(scriptVariable);

                    RegisterVariable(scriptVariable.Name);
                }
            }
            catch
            {
                // ignored
            }
        }
        public override bool FromScriptVariable(SequenceProcEnv environment, ScriptVariable variable, ref string errorMessage)
        {
            if (variable.IsNull())
            {
                errorMessage = global::MotionDataHandler.Properties.Settings.Default.Msg_CannotSpecifyNull + ": " + this.ParamName;
                return(false);
            }
            this.Value = new Dictionary <string, string>();
            IList <ScriptVariable> list = variable.ToList();

            foreach (ScriptVariable row in list)
            {
                if (row.IsNull())
                {
                    continue;
                }
                IList <ScriptVariable> pair = row.ToList();
                if (pair.Count < 2)
                {
                    errorMessage = "各要素に二つの文字列が必要です";
                    return(false);
                }
                if (pair[0].IsNull() || pair[1].IsNull())
                {
                    errorMessage = "要素の文字列にnullを指定できません";
                    return(false);
                }
                this.Value[pair[0].ToString()] = pair[1].ToString();
            }
            return(true);
        }
Exemple #5
0
        public override TestResult Execute()
        {
            object _varRet       = null;
            int    CAMERA_NUMBER = this.GetIntegerVariable("Argument0", "Name0");
            int    WIDTH         = this.GetIntegerVariable("Argument1", "Name1");
            int    HEIGTH        = this.GetIntegerVariable("Argument2", "Name2");


            try
            {
                _varRet = QueryFrame(CAMERA_NUMBER, WIDTH, HEIGTH);
            }
            catch (Exception ex)
            {
                _varRet = ex.Message;
                this.FailTest(ex.Message);
                return(testResult);
            }

            ScriptVariable retVar0 = new ScriptVariable("ReturnValue0", VariableType.Object, _varRet);

            VariableSpace.setVariable(retVar0);
            testResult.Status = TestStatus.Pass;
            return(testResult);
        }
        public override bool FromScriptVariable(SequenceProcEnv environment, ScriptVariable variable, ref string errorMessage)
        {
            IList <ScriptVariable> list   = variable.ToList();
            SequenceData           parent = environment.SelectedSequence;

            if (this.Parent != null && this.Parent.Value != null)
            {
                parent = this.Parent.Value;
            }
            IList <string> borderNames = parent.Borders.GetLabelNames(true);
            List <string>  ret         = new List <string>();

            foreach (ScriptVariable v in list)
            {
                string name = v.ToString();
                if (!borderNames.Contains(name) && parent.Borders.DefaultName != name)
                {
                    errorMessage = MotionDataHandler.Properties.Settings.Default.Msg_LabelNameNotFound + ": " + name;
                    return(false);
                }
                ret.Add(name);
            }
            this.Value = ret;
            return(true);
        }
Exemple #7
0
        /// <summary>
        /// Returns the caller hierarchy
        /// </summary>
        /// <param name="scriptExpression">Script expression</param>
        /// <returns>Caller hierarchy</returns>
        public static List <string> GetCallerHierarchy(ScriptExpression scriptExpression)
        {
            List <string> hierarchy = new List <string>();

            ScriptMemberExpression memberExpression = scriptExpression as ScriptMemberExpression;

            while (memberExpression != null)
            {
                hierarchy.Add(memberExpression.Member.ToString());

                if (memberExpression.Target is ScriptMemberExpression)
                {
                    memberExpression = memberExpression.Target as ScriptMemberExpression;
                }
                else if (memberExpression.Target is ScriptVariable)
                {
                    ScriptVariable rootVariable = memberExpression.Target as ScriptVariable;
                    hierarchy.Add(rootVariable.Name);
                    break;
                }
                else
                {
                    break;
                }
            }

            hierarchy.Reverse();
            return(hierarchy);
        }
        public void Echo(ScriptVariable value = null)
        {
            if (value == null)
            {
                WriteHighlightLine($"# Echo is {(EchoEnabled ? "on":"off")}.");
                return;
            }
            var mode = value.Name;

            switch (mode)
            {
            case "true":
            case "on":
                EchoEnabled = true;
                WriteHighlightLine($"# Echo is on.");
                break;

            case "false":
            case "off":
                EchoEnabled = false;
                break;

            default:
                throw new ArgumentException($"Invalid parameter. Only on/true or off/false are valid for echo.", nameof(value));
            }
        }
        protected override RunControlType ExecuteInternal(ScriptExecutionEnvironment env, out ScriptVariable returnValue)
        {
            returnValue = null;
            if (!this.Do)
            {
                ScriptVariable condition = this.Condition.Calculate(env);
                if (condition == null || !condition.ToBoolean())
                {
                    return(RunControlType.None);
                }
            }
            while (true)
            {
                RunControlType ctrl = this.Statement.Execute(env, out returnValue);
                if (ctrl == RunControlType.Break)
                {
                    return(RunControlType.None);
                }
                if (ctrl == RunControlType.Return)
                {
                    return(RunControlType.Return);
                }

                ScriptVariable condition = this.Condition.Calculate(env);
                if (condition == null || !condition.ToBoolean())
                {
                    return(RunControlType.None);
                }
            }
        }
            private bool TryGetVariable(TemplateContext context, SourceSpan span, ScriptVariable variable, out object value)
            {
                try
                {
                    switch (variable.Name)
                    {
                    case "default":
                        value = new Default();
                        return(true);

                    case "translate":
                        value = new Translate(this.i18n, this.language);
                        return(true);

                    case "numberWithSeperator":
                        value = new NumberWithSeperator();
                        return(true);

                    default:
                        value = GetValue(this.data, variable.Name);
                        return(true);
                    }
                }
                catch
                {
                    value = null;
                    return(false);
                }
            }
        public override bool FromScriptVariable(MotionProcEnv environment, ScriptVariable variable, ref string errorMessage)
        {
            Sequence.SequenceData parent = this.Parent.Value;

            switch (variable.Type)
            {
            case ScriptVariableType.Number:
                int index = variable.ToInteger();
                if (index < 0 || index >= parent.Values.ColumnCount)
                {
                    errorMessage = MotionDataHandler.Properties.Settings.Default.Msg_IndexOutOfRange + ": " + index.ToString();
                    return(false);
                }
                this.Value = index;
                return(true);

            case ScriptVariableType.String:
                string name   = variable.ToString();
                int    index2 = Array.IndexOf(parent.Values.ColumnNames, name);
                if (index2 == -1)
                {
                    errorMessage = MotionDataHandler.Properties.Settings.Default.Msg_ColumnNameNotFound;
                    return(false);
                }
                this.Value = index2;
                return(true);

            default:
                errorMessage = MotionDataHandler.Properties.Settings.Default.Msg_SpecifyIndexOfColumnOrColumnName;
                return(false);
            }
        }
Exemple #12
0
 private void CheckVariableFound(ScriptVariable variable, bool found)
 {
     if (StrictVariables && !found)
     {
         throw new ScriptRuntimeException(variable.Span, $"The variable or function `{variable}` was not found");
     }
 }
Exemple #13
0
        public object GetValue(ScriptVariable variable)
        {
            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            var    stores = GetStoreForRead(variable);
            object value  = null;

            foreach (var store in stores)
            {
                if (store.TryGetValue(this, variable.Span, variable.Name, out value))
                {
                    return(value);
                }
            }

            bool found = false;

            if (TryGetVariable != null)
            {
                if (TryGetVariable(this, variable.Span, variable, out value))
                {
                    found = true;
                }
            }

            CheckVariableFound(variable, found);
            return(value);
        }
Exemple #14
0
        /// <summary>
        /// Gets the value for the specified variable from the current object context/scope.
        /// </summary>
        /// <param name="variable">The variable to retrieve the value</param>
        /// <returns>Value of the variable</returns>
        public object GetValue(ScriptVariable variable)
        {
            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }
            var    stores = GetStoreForSet(variable);
            object value  = null;

            foreach (var store in stores)
            {
                if (store.TryGetValue(this, variable.Span, variable.Name, out value))
                {
                    return(value);
                }
            }

            bool found = false;

            if (TryGetVariable != null)
            {
                if (TryGetVariable(this, variable.Span, variable, out value))
                {
                    found = true;
                }
            }

            if (StrictVariables && !found)
            {
                throw new ScriptRuntimeException(variable.Span, $"The variable `{variable}` was not found");
            }
            return(value);
        }
        /// <summary>
        /// Stores value of the object to a user-defined variable.
        /// </summary>
        /// <param name="sender">The script engine instance (frmScriptEngine) which contains session variables.</param>
        /// <param name="targetVariable">the name of the user-defined variable to override with new value</param>
        public static void StoreInUserVariable(this object variableValue, IEngine engine, string variableName)
        {
            if (variableName.StartsWith("{") && variableName.EndsWith("}"))
            {
                variableName = variableName.Replace("{", "").Replace("}", "");
            }
            else
            {
                throw new Exception("Variable markers '{}' missing. '" + variableName + "' is an invalid output variable name.");
            }

            if (engine.VariableList.Any(f => f.VariableName == variableName))
            {
                //update existing variable
                var existingVariable = engine.VariableList.FirstOrDefault(f => f.VariableName == variableName);
                existingVariable.VariableName  = variableName;
                existingVariable.VariableValue = variableValue;
            }
            else
            {
                //add new variable
                var newVariable = new ScriptVariable();
                newVariable.VariableName  = variableName;
                newVariable.VariableValue = variableValue;
                engine.VariableList.Add(newVariable);
            }
        }
Exemple #16
0
        public object CreateMatrix(ScriptVariable name, int row, int column, params object[] arguments)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (row <= 1)
            {
                throw new ArgumentOutOfRangeException(nameof(row), $"Invalid row count {row}. Expecting a value > 1.");
            }
            if (column <= 1)
            {
                throw new ArgumentOutOfRangeException(nameof(column), $"Invalid column count {column}. Expecting a value > 1.");
            }
            switch (name.Name)
            {
            case "int":
                return(new KalkMatrixConstructor <int>(row, column).Invoke(Engine, arguments));

            case "bool":
                return(new KalkMatrixConstructor <KalkBool>(row, column).Invoke(Engine, arguments));

            case "float":
                return(new KalkMatrixConstructor <float>(row, column).Invoke(Engine, arguments));

            case "half":
                return(new KalkMatrixConstructor <KalkHalf>(row, column).Invoke(Engine, arguments));

            case "double":
                return(new KalkMatrixConstructor <double>(row, column).Invoke(Engine, arguments));
            }

            throw new ArgumentException($"Unsupported matrix type {name.Name}. Only bool, int, float, half and double are supported", nameof(name));
        }
        private void NewFile()
        {
            ScriptFilePath = null;

            string  title      = $"New Tab {(uiScriptTabControl.TabCount + 1)} *";
            TabPage newTabPage = new TabPage(title);

            newTabPage.Name        = title;
            newTabPage.Tag         = new ScriptObject(new List <ScriptVariable>(), new List <ScriptElement>());
            newTabPage.ToolTipText = "";
            uiScriptTabControl.Controls.Add(newTabPage);
            newTabPage.Controls.Add(NewLstScriptActions(title));
            newTabPage.Controls.Add(pnlCommandHelper);

            uiScriptTabControl.SelectedTab = newTabPage;

            _selectedTabScriptActions = (UIListView)uiScriptTabControl.SelectedTab.Controls[0];
            _selectedTabScriptActions.Items.Clear();
            HideSearchInfo();

            _scriptVariables = new List <ScriptVariable>();
            //assign ProjectPath variable
            var projectPathVariable = new ScriptVariable
            {
                VariableName  = "ProjectPath",
                VariableValue = _scriptProjectPath
            };

            _scriptVariables.Add(projectPathVariable);
            GenerateRecentFiles();
            newTabPage.Controls[0].Hide();
            pnlCommandHelper.Show();
        }
Exemple #18
0
 public static void equateFields(object o, ScriptVariable v)
 {
     foreach (PropertyInfo p in v.Value.GetType().GetProperties())
     {
         o.GetType().GetField(p.Name).SetValue(o, getScriptValue(p.Name, v));
     }
 }
        public Expression CalculateScriptFunctionCall(ScriptFunctionCall scriptFunctionCall, ParameterFinder parameterFinder, List <Expression> arguments)
        {
            var args = scriptFunctionCall.Arguments.Select(arg => GetExpressionBody(arg, parameterFinder, null));

            //add first argument if it's being supplied (probably from ScriptPipeCall)
            if (arguments != null)
            {
                args = arguments.Union(args);
            }

            // we are attempting to pull the bottom target member up, so we know the method Name
            var toMember = scriptFunctionCall.Target as ScriptMemberExpression;

            if (toMember == null)
            {
                throw new NotSupportedException();
            }
            else
            {
                var            argumentTypes      = args.ToNullSafe().Select(e => e.Type);
                var            targetType         = GetExpressionBody(toMember.Target, parameterFinder, null);
                ScriptVariable functionNameScript = toMember.Member;
                var            methodInfo         = memberFinder.FindMember(targetType.Type, functionNameScript.Name, argumentTypes.ToArray());
                var            convertedArgs      = ConvertArgs(methodInfo as MethodInfo, args);
                return(ExpressionHelpers.CallMember(targetType, methodInfo, convertedArgs));
            }
        }
Exemple #20
0
        /// <summary>
        /// Gets the value for the specified variable from the current object context/scope.
        /// </summary>
        /// <param name="variable">The variable to retrieve the value</param>
        /// <returns>Value of the variable</returns>
        public object GetValue(ScriptVariable variable)
        {
            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            IEnumerable <IScriptObject> stores = GetStoreForSet(variable);
            object value = null;

            foreach (IScriptObject store in stores)
            {
                if (store.TryGetValue(this, variable.Span, variable.Name, out value))
                {
                    return(value);
                }
            }

            bool found = false;

            if (TryGetVariable != null)
            {
                if (TryGetVariable(this, variable.Span, variable, out value))
                {
                    found = true;
                }
            }

            if (StrictVariables && !found)
            {
                throw new ScriptRuntimeException(variable.Span, string.Format(RS.VariableNotFound, variable));
            }

            return(value);
        }
        public override TestResult Execute()
        {
            object SEARCH_IMAGE       = this.GetObjectVariable("Argument0", "Search Image");
            object TEMPLATE_IMAGE     = this.GetObjectVariable("Argument1", "Template Image");
            string MATCHING_ALGORITHM = this.GetStringVariable("Argument2", "Matching Algorithm").ToUpper();
            double MATCH_SCORE        = this.GetFloatVariable("Argument3", "Matching Score");
            bool   DEBUG = this.GetBooleanVariable("Argument4", "Debug Mode");

            try
            {
                _MatchImageViewer = new EmguCV_MatchTemplateViewer(SEARCH_IMAGE, TEMPLATE_IMAGE, MATCHING_ALGORITHM, MATCH_SCORE, DEBUG);
                DialogResult dr = new DialogResult();
                dr = _MatchImageViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                this.FailTest(ex.Message);
                return(testResult);
            }

            ScriptVariable retVar0 = new ScriptVariable("ReturnValue0", VariableType.Object, _MatchImageViewer._ImageEvidence);
            ScriptVariable retVar1 = new ScriptVariable("ReturnValue1", VariableType.Float, _MatchImageViewer._ConfidenceScore);

            VariableSpace.setVariable(retVar0);
            VariableSpace.setVariable(retVar1);
            testResult.Status = TestStatus.Pass;
            return(testResult);
        }
        public static async void RunScript()
        {
            var state = await CSharpScript.RunAsync("int x=0;int y=x+1; y");

            ScriptVariable y         = state.Variables.First(sv => sv.Name == "y");
            var            returnVal = state.ReturnValue;
        }
Exemple #23
0
 private void CheckVariableFound(ScriptVariable variable, bool found)
 {
     //ScriptVariable.Arguments is a special "magic" variable which is not always present so ignore this
     if (StrictVariables && !found && variable != ScriptVariable.Arguments)
     {
         throw new ScriptRuntimeException(variable.Span, $"The variable or function `{variable}` was not found");
     }
 }
Exemple #24
0
 void WriterScriptNodeVariable(JsonWriter writer, ScriptVariable val)
 {
     using (var s1 = new JsonScopeObjectWriter(writer)) {
         s1.WriteKeyValue("key", val.key);
         s1.WriteKeyValue("type", val.ShortFieldType);
         WriteObjectVariable(s1, val.value);
     }
 }
Exemple #25
0
 public VariableObject(ScriptVariable scriptVariable)
 {
     scriptVariable = scriptVariable ?? throw new ArgumentNullException(nameof(scriptVariable));
     IsReadOnly     = scriptVariable.IsReadOnly;
     Name           = scriptVariable.Name;
     Type           = scriptVariable.Type;
     Value          = scriptVariable.Value;
 }
 public KalkExpression DefineUserUnit(ScriptVariable name, string description = null, ScriptVariable symbol = null, KalkExpression value = null, string plural = null, string prefix = null)
 {
     if (name == null || string.IsNullOrEmpty(name.Name))
     {
         throw new ArgumentNullException(nameof(name));
     }
     return(RegisterUnit(new KalkUnit(name.Name), description, symbol?.Name, value, plural, prefix, isUser: true));
 }
Exemple #27
0
        private IScriptObject GetStoreForWrite(ScriptVariable variable)
        {
            var           scope      = variable.Scope;
            IScriptObject finalStore = null;

            switch (scope)
            {
            case ScriptVariableScope.Global:
                // In scientific we always resolve to local storage first
                IScriptObject storeWithVariable = null;

                var name           = variable.Name;
                int lastStoreIndex = _globalContexts.Count - 1;
                var items          = _globalContexts.Items;
                for (int i = lastStoreIndex; i >= 0; i--)
                {
                    var store = items[i].LocalObject;
                    if (storeWithVariable == null && store.Contains(name))
                    {
                        storeWithVariable = store;
                    }

                    // We check that for upper store, we actually can write a variable with this name
                    // otherwise we don't allow to create a variable with the same name as a readonly variable
                    if (!store.CanWrite(name))
                    {
                        var variableType = store == BuiltinObject ? "builtin " : string.Empty;
                        throw new ScriptRuntimeException(variable.Span, $"Cannot set the {variableType}readonly variable `{variable}`");
                    }
                }

                // If we have a store for this variable name use it, otherwise use the first store available.
                finalStore = storeWithVariable ?? items[lastStoreIndex].LocalObject;
                break;

            case ScriptVariableScope.Local:
                if (_currentLocalContext.LocalObject != null)
                {
                    finalStore = _currentLocalContext.LocalObject;
                }
                else if (_globalContexts.Count > 0)
                {
                    finalStore = _globalContexts.Peek().LocalObject;
                }
                else
                {
                    throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the local variable `{variable}` in the current context");
                }

                break;

            default:
                Debug.Assert(false, $"Variable scope `{scope}` is not implemented");
                break;
            }

            return(finalStore);
        }
        public static void CreateTestVariable(object variableValue, IAutomationEngineInstance engine, string variableName, Type variableType)
        {
            ScriptVariable newVar = new ScriptVariable();

            newVar.VariableName  = variableName;
            newVar.VariableValue = variableValue;
            newVar.VariableType  = variableType;
            engine.AutomationEngineContext.Variables.Add(newVar);
        }
 /// <summary>
 /// 実行時情報を設定しつつ,実行処理を呼び出します.
 /// </summary>
 /// <param name="env">変数環境</param>
 /// <param name="returnValue">式の戻り値</param>
 /// <returns>制御情報を返します</returns>
 public RunControlType Execute(ScriptExecutionEnvironment env, out ScriptVariable returnValue)
 {
     env.Console.PushSyntaxStack(this);
     try {
         return(this.ExecuteInternal(env, out returnValue));
     } finally {
         env.Console.PopSyntaxStack();
     }
 }
Exemple #30
0
        private IEnumerable <IScriptObject> GetStoreForRead(ScriptVariable variable)
        {
            var scope = variable.Scope;

            var loopItems = _currentLocalContext.Loops.Items;

            switch (scope)
            {
            case ScriptVariableScope.Global:
                for (int i = _currentLocalContext.Loops.Count - 1; i >= 0; i--)
                {
                    yield return(loopItems[i]);
                }

                for (int i = _globalStores.Count - 1; i >= 0; i--)
                {
                    yield return(_globalStores.Items[i]);
                }
                break;

            case ScriptVariableScope.Local:
                for (int i = _currentLocalContext.Loops.Count - 1; i >= 0; i--)
                {
                    yield return(loopItems[i]);
                }

                if (_currentLocalContext.LocalObject != null)
                {
                    yield return(_currentLocalContext.LocalObject);
                }
                else if (_globalStores.Count > 0)
                {
                    yield return(_globalStores.Peek());
                }
                else
                {
                    throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the local variable `{variable}` in the current context");
                }
                break;

            case ScriptVariableScope.Loop:
                if (_currentLocalContext.Loops.Count > 0)
                {
                    yield return(_currentLocalContext.Loops.Peek());
                }
                else
                {
                    // unit test: 215-for-special-var-error1.txt
                    throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the loop variable `{variable}` not inside a loop");
                }
                break;

            default:
                throw new NotImplementedException($"Variable scope `{scope}` is not implemented");
            }
        }
Exemple #31
0
 /// <summary>
 /// Sets the variable to read only.
 /// </summary>
 /// <param name="variable">The variable.</param>
 /// <param name="isReadOnly">if set to <c>true</c> the variable will be set to readonly.</param>
 /// <exception cref="System.ArgumentNullException">If variable is null</exception>
 /// <remarks>
 /// This will not throw an exception if a previous variable was readonly.
 /// </remarks>
 public void SetReadOnly(ScriptVariable variable, bool isReadOnly = true)
 {
     if (variable == null) throw new ArgumentNullException(nameof(variable));
     var store = GetStoreForSet(variable).First();
     store.SetReadOnly(variable.Name, isReadOnly);
 }
Exemple #32
0
 private IEnumerable<IScriptObject> GetStoreForSet(ScriptVariable variable)
 {
     var scope = variable.Scope; 
     if (scope == ScriptVariableScope.Global)
     {
         foreach (var store in globalStores)
         {
             yield return store;
         }
     }
     else if (scope == ScriptVariableScope.Local)
     {
         if (localStores.Count > 0)
         {
             yield return localStores.Peek();
         }
         else
         {
             throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the local variable [{variable}] in the current context");
         }
     }
     else if (scope == ScriptVariableScope.Loop)
     {
         if (loopStores.Count > 0)
         {
             yield return loopStores.Peek();
         }
         else
         {
             // unit test: 215-for-special-var-error1.txt
             throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the loop variable [{variable}] in the current context");
         }
     }
     else
     {
         throw new NotImplementedException($"Variable scope [{scope}] is not implemented");
     }
 }
        public void AddScriptVariable(string group, ScriptVariable val)
        {
            List<ScriptVariable> vars = null;
            if(!varGroupDict.TryGetValue(group, out vars)) {
                varGroupDict[group] = new List<ScriptVariable>();
                vars = varGroupDict[group];
            }

            vars.Add(val);
        }
 void WriterScriptNodeVariable(JsonWriter writer, ScriptVariable val)
 {
     using (var s1 = new JsonScopeObjectWriter(writer)) {
         s1.WriteKeyValue("key", val.key);
         s1.WriteKeyValue("type", val.ShortFieldType);
         WriteObjectVariable(s1, val.value);
     }
 }
Exemple #35
0
        /// <summary>
        /// Sets the variable with the specified value.
        /// </summary>
        /// <param name="variable">The variable.</param>
        /// <param name="value">The value.</param>
        /// <param name="asReadOnly">if set to <c>true</c> the variable set will be read-only.</param>
        /// <exception cref="System.ArgumentNullException">If variable is null</exception>
        /// <exception cref="ScriptRuntimeException">If an existing variable is already read-only</exception>
        public void SetValue(ScriptVariable variable, object value, bool asReadOnly)
        {
            if (variable == null) throw new ArgumentNullException(nameof(variable));

            var store = GetStoreForSet(variable).First();

            // Try to set the variable
            if (!store.TrySetValue(variable.Name, value, asReadOnly))
            {
                throw new ScriptRuntimeException(variable.Span, $"Cannot set value on the readonly variable [{variable}]"); // unit test: 105-assign-error2.txt
            }
        }
Exemple #36
0
 private object GetValueInternal(ScriptVariable variable)
 {
     if (variable == null) throw new ArgumentNullException(nameof(variable));
     var stores = GetStoreForSet(variable);
     object value = null;
     foreach (var store in stores)
     {
         if (store.TryGetValue(variable.Name, out value))
         {
             return value;
         }
     }
     return value;
 }
Exemple #37
0
        private ScriptExpression ParseVariableOrLiteral()
        {
            var currentToken = Current;
            var currentSpan = CurrentSpan;
            var endSpan = currentSpan;
            var text = GetAsText(currentToken);

            // Return ScriptLiteral for null, true, false
            // Return ScriptAnonymousFunction 
            switch (text)
            {
                case "null":
                    var nullValue = Open<ScriptLiteral>();
                    NextToken();
                    return Close(nullValue);
                case "true":
                    var trueValue = Open<ScriptLiteral>();
                    trueValue.Value = true;
                    NextToken();
                    return Close(trueValue);
                case "false":
                    var falseValue = Open<ScriptLiteral>();
                    falseValue.Value = false;
                    NextToken();
                    return Close(falseValue);
                case "do":
                    var functionExp = Open<ScriptAnonymousFunction>();
                    functionExp.Function = ParseFunctionStatement(true);
                    return Close(functionExp);
            }

            NextToken();

            var scope = ScriptVariableScope.Global;
            if (text.StartsWith("$"))
            {
                scope = ScriptVariableScope.Local;
                text = text.Substring(1);

                // Convert $0, $1... $n variable into $[0] $[1]...$[n] variables
                int index;
                if (int.TryParse(text, out index))
                {
                    var indexerExpression = new ScriptIndexerExpression
                    {
                        Span = currentSpan,

                        Target = new ScriptVariable(ScriptVariable.Arguments.Name, ScriptVariableScope.Local)
                        {
                            Span = currentSpan
                        },

                        Index = new ScriptLiteral() {Span = currentSpan, Value = index}
                    };
                    return indexerExpression;
                }
            }

            if (text == "for" || text == "while")
            {
                if (Current.Type == TokenType.Dot)
                {
                    NextToken();
                    if (Current.Type == TokenType.Identifier)
                    {
                        endSpan = CurrentSpan;
                        var loopVariableText = GetAsText(Current);
                        scope = ScriptVariableScope.Loop;
                        switch (loopVariableText)
                        {
                            case "first":
                                text = "for.first";
                                break;
                            case "last":
                                if (text == "while")
                                {
                                    // unit test: 108-variable-loop-error2.txt
                                    LogError(currentToken, "The loop variable <while.last> is invalid");
                                }
                                text = "for.last";
                                break;
                            case "even":
                                text = "for.even";
                                break;
                            case "odd":
                                text = "for.odd";
                                break;
                            case "index":
                                text = "for.index";
                                break;
                            default:
                                text = text + "." + loopVariableText;
                                // unit test: 108-variable-loop-error1.txt
                                LogError(currentToken, $"The loop variable <{text}> is not supported");
                                break;
                        }

                        // We no longer checks at parse time usage of loop variables, as they can be used in a wrap context
                        //if (!IsInLoop())
                        //{
                        //    LogError(currentToken, $"Unexpected variable <{text}> outside of a loop");
                        //}

                        NextToken();
                    }
                    else
                    {
                        LogError(currentToken, $"Invalid token [{Current.Type}]. The loop variable <{text}> dot must be followed by an identifier");
                    }
                }
                else
                {
                    LogError(currentToken, $"The reserved keyword <{text}> cannot be used as a variable");
                }
            }
            else if (IsKeyword(text))
            {
                // unit test: 108-variable-error1.txt
                LogError(currentToken, $"The reserved keyword <{text}> cannot be used as a variable");
            }

            var result = new ScriptVariable(text, scope)
            {
                Span = {FileName =currentSpan.FileName, Start = currentSpan.Start, End = endSpan.End}
            };
            return result;
        }
Exemple #38
0
        private static void AddVariableDeclaration(List<ScriptVariable> variables, ref FastString script, string thisWord, AutoCompleteParserState state)
        {
            if ((state.LastWord.Length > 0) && (state.WordBeforeLast.Length > 0))
            {
                if (!DoesCurrentLineHaveToken(script, AUTO_COMPLETE_IGNORE))
                {
                    bool isArray = false, isPointer = false;
                    bool isStatic = false, isStaticOnly = false;
                    bool isNoInherit = false, isProtected = false;
                    string type = state.WordBeforeLast;
                    string varName = state.LastWord;
                    if (thisWord == "[")
                    {
                        while ((script.Length > 0) && (GetNextWord(ref script) != "]")) ;
                        isArray = true;
                    }
                    else if (state.DynamicArrayDefinition)
                    {
                        varName = state.WordBeforeLast;
                        type = state.WordBeforeWordBeforeLast;
                        isArray = true;
                    }
                    if (type == "*")
                    {
                        isPointer = true;
                        if (state.DynamicArrayDefinition)
                        {
                            type = state.PreviousWords[3];
                        }
                        else
                        {
                            type = state.WordBeforeWordBeforeLast;
                        }
                    }
                    if (state.IsWordInPreviousList("static"))
                    {
                        isStatic = true;
                    }
                    if (state.IsWordInPreviousList("protected"))
                    {
                        isProtected = true;
                    }
                    if (DoesCurrentLineHaveToken(script, AUTO_COMPLETE_STATIC_ONLY))
                    {
                        isStaticOnly = true;
                    }
                    if (DoesCurrentLineHaveToken(script, AUTO_COMPLETE_NO_INHERIT))
                    {
                        isNoInherit = true;
                    }
                    // ignore "struct GUI;" prototypes
                    if (type != "struct")
                    {
                        //if (varName == "{") System.Diagnostics.Debugger.Break();
                        ScriptVariable newVar = new ScriptVariable(varName, type, isArray, isPointer, state.InsideIfDefBlock, state.InsideIfNDefBlock, isStatic, isStaticOnly, isNoInherit, isProtected, state.CurrentScriptCharacterIndex);

                        if (!string.IsNullOrEmpty(state.PreviousComment))
                        {
                            newVar.Description = state.PreviousComment;
                            state.PreviousComment = null;
                        }

                        variables.Add(newVar);
                    }
                }
                state.DynamicArrayDefinition = false;
            }
        }