Beispiel #1
0
        public object Evaluate(string formula)
        {
            if (string.IsNullOrEmpty(formula))
            {
                return(0);
            }

            var parsedFormula = new VariableParser(formula, Variables);

            formula = parsedFormula.Parse();

            var inputStream = new AntlrInputStream(formula);
            var lexer       = new FormulaLexer(inputStream);
            var tokens      = new CommonTokenStream(lexer);
            var parser      = new FormulaParser(tokens);

            var errorListener = new FormulaErrorListener();

            parser.RemoveErrorListeners();
            parser.AddErrorListener(errorListener);
            var parseTree = parser.main();

            if (!errorListener.IsValid)
            {
                throw new FormulaException(
                          errorListener.ErrorLocation,
                          errorListener.ErrorMessage);
            }

            return(new EvaluationVisitor(Functions).VisitMain(parseTree));
        }
        public void should_return_correct_value_for_range_variable()
        {
            const string formula        = "=SUM([ID5:ID6])";
            var          variableParser = new VariableParser(formula, Values);

            variableParser.Parse();
        }
Beispiel #3
0
 public void ParseMethod_WhiteSpaceString_ThrowNullArgumentException()
 {
     Should.Throw <ArgumentNullException>(() =>
     {
         var parseResult = VariableParser.Parse("    ");
     });
 }
        public void ErrorHandler(object sender, ErrorInformation errorInformation)
        {
            var cmdlet = _cmdlet;

            if (cmdlet == null)
            {
                return;
            }

            var exceptionName = errorInformation.Exception.InnerException?.GetType().Name ?? errorInformation.Exception.GetType().Name;

            var errorMessage = $"Perry ({exceptionName}): {errorInformation.ErrorMessage}";

            if (_options?.IncludeVariable == true)
            {
                var variables = VariableParser.GetVariables(errorInformation.ErrorMessage);
                foreach (var variable in variables)
                {
                    var variableValue = cmdlet.GetVariableValue(variable).ToString();
                    errorMessage += $"{Environment.NewLine}   Variable: ${variable} = {variableValue}";
                }
            }

            if (_options?.IncludeException == true)
            {
                errorMessage += $"{Environment.NewLine}{errorInformation.Exception}";
            }

            cmdlet.WriteWarning(errorMessage);
        }
Beispiel #5
0
 public void ParseMethod_NotValidVariablestring_FormatException(string variableString)
 {
     Should.Throw <FormatException>(() =>
     {
         var parseResult = VariableParser.Parse(variableString);
     });
 }
Beispiel #6
0
        public void WhenVariableHasWhiteSpace_ThenReplaceWithUnderline()
        {
            var input  = " a,b c";
            var output = VariableParser.Parse(input);

            Approvals.Verify(output.ToPrettyString());
        }
Beispiel #7
0
        public void Parse_ValidParameters_CorrectParsing(string input, string expectedName, int expectedExponent)
        {
            var variable = VariableParser.Parse(input);

            Assert.AreEqual(expectedName, variable.Name);
            Assert.AreEqual(expectedExponent, variable.Exponent);
        }
Beispiel #8
0
        public void VerifyStringWithOneVariable()
        {
            var input  = "a";
            var output = VariableParser.Parse(input);

            Approvals.Verify(output.ToPrettyString());
        }
Beispiel #9
0
        public void VerifyStringWithUntrimmedVariables()
        {
            var input  = " a,b ";
            var output = VariableParser.Parse(input);

            Approvals.Verify(output.ToPrettyString());
        }
 public VariableInfo(string name, string help, VariableParser parser, VariablePrinter printer)
 {
     Name    = name;
     Help    = help;
     Printer = printer;
     Parser  = parser;
 }
        public void should_return_correct_value_for_variable(string formula, string variableName, int expectedVariableValue)
        {
            var variableParser = new VariableParser(formula, Values);

            variableParser.Parse();

            Assert.Equal(variableParser.Variables[variableName], expectedVariableValue);
        }
        public void should_return_expected_formula_with_replaced_values(string formula, string expectedResult)
        {
            var variableParser = new VariableParser(formula, Values);

            var result = variableParser.Parse();

            Assert.Equal(result, expectedResult);
        }
            public void GetNoVariable()
            {
                var inputData = "Cause-Error -Input 'Oops'";

                var result = VariableParser.GetVariables(inputData);

                Assert.Empty(result);
            }
            public void GetVariableWithoutNamespace()
            {
                var inputData = "10 / $myvariable";

                var result = VariableParser.GetVariables(inputData).Single();

                Assert.Equal("myvariable", result);
            }
Beispiel #15
0
        public ArrayParserTest()
        {
            var dictionary = new Dictionary <string, ParameterExpression>();
            var stack      = new Stack <string>();

            ArrayParser    = new ArrayParser(dictionary, stack);
            VariableParser = new VariableParser(dictionary, stack);
        }
            public void GetMultipleVariables()
            {
                var inputData = "$var1 / $var2";

                var result = VariableParser.GetVariables(inputData);

                Assert.Equal(new[] { "var1", "var2" }, result);
            }
        public void Yakima11146_QC()
        {
            string expression = "BUM_AF-BUM_AF[t-1]+RIM_AF-RIM_AF[t-1]+CLE_AF-CLE_AF[t-1]+KAC_AF-KAC_AF[t-1]+KEE_AF-KEE_AF[t-1]+SNCW_QC+ROZW_QC+RSDW_QC+RSCW_QC+KTCW_QC+'1146_QC'+TIEW_QC+WOPW_QC+NACW_QM";
            var    vp         = new VariableParser();
            var    vars       = vp.GetAllVariables(expression);

            Console.WriteLine(string.Join("\n", vars));
            Assert.AreEqual(19, vars.Length);
            Assert.AreEqual("1146_QC", vars[15]);
        }
Beispiel #18
0
        public void Issue138Variable()
        {
            var x = Math.FileLookupInterpolate2D(new Series(), new Series(), "");

            string equation = "FileLookupInterpolate2D(rir_fb, rir_ra, \"rir_q_2da.txt\") +FileLookupInterpolate2D(rir_fb, rir_rb, \"rir_q_2d.txt\")";
            var    vars     = VariableParser.Default().GetAllVariables(equation);

            Assert.IsTrue(Array.IndexOf(vars, "rir_fb") >= 0, "rir_fb");
            Assert.IsTrue(Array.IndexOf(vars, "rir_ra") >= 0, "rir_ra");
            Assert.IsTrue(Array.IndexOf(vars, "rir_rb") >= 0, "rir_rb");
        }
Beispiel #19
0
        public void Test_000_Should_create_instance()
        {
            // Arrange
            VariableParser instance = default;

            // Act
            Action action = () => instance = CreateInstance();

            // Assert
            Should.NotThrow(action);
            instance.ShouldNotBe(default);
Beispiel #20
0
        public void ParseMethod_ValidResult_ReturnProperties(string variableString, char name, int power)
        {
            Variable parsedVariable = null;

            Should.NotThrow(() =>
            {
                parsedVariable = VariableParser.Parse(variableString);
            });

            parsedVariable?.Name.ShouldBe(name);
            parsedVariable?.Power.ShouldBe(power);
        }
        public void Initialize()
        {
            _parser = new VariableParser(new[]
            {
                _handler1.Object,
                _handler2.Object
            });

            _handler1
            .Setup(m => m.Name)
            .Returns("handler1");
            _handler2
            .Setup(m => m.Name)
            .Returns("handler2");
        }
Beispiel #22
0
        public void WhenInputIsEmpty_ThenThrowException()
        {
            var input = "";
            var exc   = "";

            try
            {
                VariableParser.Parse(input);
            }
            catch (ArgumentException ex)
            {
                exc = ex.Message;
            }
            Approvals.Verify("Exception message: " + exc);
        }
        public void SetVariableTest()
        {
            var variables = new Dictionary <string, string>()
            {
                { "$var", "never" },
                { "$v", "gonna" },
                { "$variable", "give" }
            };

            string command = "echo $var $v $variable you up";

            VariableParser.SetVariable(ref command, variables);
            Assert.AreEqual(command, "echo never gonna give you up ");

            Assert.Pass();
        }
        public static Parser Create()
        {
            // Create the object tree without DI Framework
            var expressionParser = new ExpressionParser();
            var variableParser   = new VariableParser();
            var functionParser   = new FunctionParser(expressionParser);
            var factorParser     = new FactorParser(expressionParser, variableParser, functionParser);
            var powerTermParser  = new PowerTermParser(factorParser);
            var termParser       = new TermParser(powerTermParser);

            expressionParser.TermParser = termParser;
            var lexerRules  = new LexerRules();
            var tokenizer   = new Tokenizer(lexerRules, s => new LexerReader(s), lexems => new LinePositionCalculator(lexems));
            var tokenWalker = new TokenWalker(tokenizer, () => new EpsilonToken(), lexems => new LinePositionCalculator(lexems));

            return(new Parser(tokenWalker, expressionParser));
        }
        public void VariableNames()
        {
            string equation = "Merge()"; // not a variable

            Assert.AreEqual(0, VariableParser.Default().GetAllVariables(equation).Length);

            equation = "Merge(series1,'series 2')+'Series 5'";
            var vars = VariableParser.Default().GetAllVariables(equation);

            Assert.AreEqual("series1", vars[0]);
            Assert.AreEqual("series 2", vars[1]);
            Assert.AreEqual("Series 5", vars[2]);


            equation = "'jck af'+two";
            vars     = VariableParser.Default().GetAllVariables(equation);
            Assert.AreEqual(2, vars.Length);
        }
Beispiel #26
0
        public void ErrorHandler(object sender, ErrorInformation errorInformation)
        {
            var cmdlet = _cmdlet;

            if (cmdlet == null || _options == null)
            {
                return;
            }

            var exceptionName = errorInformation.Exception.InnerException?.GetType().Name ?? errorInformation.Exception.GetType().FullName;

            var errorMessage = $"{DateTime.UtcNow:u} {exceptionName}{Environment.NewLine}{errorInformation.ErrorMessage}";

            if (_options?.IncludeVariable == true)
            {
                var variables = VariableParser.GetVariables(errorInformation.ErrorMessage);
                foreach (var variable in variables)
                {
                    var variableValue = cmdlet.GetVariableValue(variable).ToString();
                    errorMessage += $"{Environment.NewLine}   Variable: ${variable} = {variableValue}";
                }
            }

            if (_options?.IncludeException == true)
            {
                errorMessage += $"{Environment.NewLine}{errorInformation.Exception}";
            }

            var outputFile = Path.Combine(_options.LogPath, "perry.log");

            lock (_syncLogs)
            {
                try
                {
                    RollLogFiles(outputFile);
                    File.AppendAllText(outputFile, $"{errorMessage}{Environment.NewLine}", Encoding.UTF8);
                }
                catch (Exception e)
                {
                    Trace.TraceError(e.ToString());
                }
            }
        }
        public void SetVariableExceptionTest()
        {
            var variables = new Dictionary <string, string>()
            {
                { "$var", "never" },
            };

            string command = "echo $v";

            try
            {
                VariableParser.SetVariable(ref command, variables);
            }
            catch (Exception ex)
            {
                Assert.AreEqual("Variable $v does not exist.", ex.Message);
            }

            Assert.Pass();
        }
Beispiel #28
0
        internal List <string> GetDependentVariables()
        {
            List <string> rval     = new List <string>();
            string        equation = ExpressionPreProcessor();

            foreach (var n in VariableParser.Default().GetAllVariables(equation))
            {
                if (this.Table.TableName == n)
                {
                    Logger.WriteLine("warning: possible recursive dependency: " + n);
                    continue;
                }

                if (rval.Contains(n))
                {
                    continue;
                }

                rval.Add(n);
            }

            return(rval);
        }
Beispiel #29
0
        /// <summary>
        /// 識別子一つを解決
        /// </summary>
        /// <param name="wc"></param>
        /// <param name="idStr">識別子文字列</param>
        /// <param name="varCode">変数の引数の場合はその変数のCode。連想配列的につかう</param>
        /// <returns></returns>
        private static IOperandTerm reduceIdentifier(WordCollection wc, string idStr, VariableCode varCode)
        {
            wc.ShiftNext();
            SymbolWord symbol = wc.Current as SymbolWord;

            if (symbol != null && symbol.Type == '.')
            {            //名前空間
                throw new NotImplCodeEE();
            }
            else if (symbol != null && (symbol.Type == '(' || symbol.Type == '['))
            {                           //関数
                wc.ShiftNext();
                if (symbol.Type == '[') //1810 多分永久に実装されない
                {
                    throw new CodeEE("[]を使った機能はまだ実装されていません");
                }
                //引数を処理
                IOperandTerm[] args   = ReduceArguments(wc, ArgsEndWith.RightParenthesis, false);
                IOperandTerm   mToken = GlobalStatic.IdentifierDictionary.GetFunctionMethod(GlobalStatic.LabelDictionary, idStr, args, false);
                if (mToken == null)
                {
                    if (!Program.AnalysisMode)
                    {
                        GlobalStatic.IdentifierDictionary.ThrowException(idStr, true);
                    }
                    else
                    {
                        if (GlobalStatic.tempDic.ContainsKey(idStr))
                        {
                            GlobalStatic.tempDic[idStr]++;
                        }
                        else
                        {
                            GlobalStatic.tempDic.Add(idStr, 1);
                        }
                        return(new NullTerm(0));
                    }
                }
                return(mToken);
            }
            else
            {                                             //変数 or キーワード
                VariableToken id = ReduceVariableIdentifier(wc, idStr);
                if (id != null)                           //idStrが変数名の場合、
                {
                    if (varCode != VariableCode.__NULL__) //変数の引数が引数を持つことはない
                    {
                        return(VariableParser.ReduceVariable(id, null, null, null));
                    }
                    else
                    {
                        return(VariableParser.ReduceVariable(id, wc));
                    }
                }
                //idStrが変数名でない場合、
                IOperandTerm refToken = GlobalStatic.IdentifierDictionary.GetFunctionMethod(GlobalStatic.LabelDictionary, idStr, null, false);
                if (refToken != null)                //関数参照と名前が一致したらそれを返す。実際に使うとエラー
                {
                    return(refToken);
                }
                if (varCode != VariableCode.__NULL__ && GlobalStatic.ConstantData.isDefined(varCode, idStr))                //連想配列的な可能性アリ
                {
                    return(new SingleTerm(idStr));
                }
                GlobalStatic.IdentifierDictionary.ThrowException(idStr, false);
            }
            throw new ExeEE("エラー投げ損ねた");            //ここまででthrowかreturnのどちらかをするはず。
        }
        private void ReadVariables(BinaryReader reader, IReadSavegameProgress progress)
        {
            var parser = new VariableParser(VariableNames);

            // TODO: Use while loops in each of the recursive parsers
            var parsers = new List<VariableParserBase>
            {
                new ManuVariableParser(),
                new OpVariableParser(),
                new VlVariableParser(),
                new AvalVariableParser(),
                new PorpVariableParser(),
                new SxapVariableParser(),
                new SsVariableParser(parser),
                new BsVariableParser(parser),
                new BlckVariableParser(parser)
            };
            parser.RegisterParsers(parsers);

            Variable[] variables = new Variable[VariableTableEntries.Length];
            for (int i = 0; i < VariableTableEntries.Length; i++)
            {
                // Calculate the size of the next token
                var size = VariableTableEntries[i].Size;
                int tokenSize;

                // There is a hidden variable before the last one
                if (i < VariableTableEntries.Length - 2)
                {
                    tokenSize = VariableTableEntries[i + 1].Offset - VariableTableEntries[i].Offset;
                }
                else
                {
                    tokenSize = VariableTableEntries[i].Size;
                }

                reader.BaseStream.Position = VariableTableEntries[i].Offset;
                try
                {
                    // Tokenizing
                    var readTokenSize = tokenSize;
                    var variable = parser.Parse(reader, ref readTokenSize);
                    variable.Size = size;
                    variable.TokenSize = tokenSize;
                    variables[i] = variable;
                }
                catch (ParseVariableException e)
                {
                    Debug.WriteLine(e.Message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }

                if (i % 250 == 0 && progress != null) progress.Report(true, false, i, VariableTableEntries.Length);
            }

            // Parsing
            var valueParser = new VariableValueParser();
            var stack = new Stack<Variable>(variables.Reverse());
            var root = valueParser.Parse<SavegameRoot>(stack);
            Variables = variables;
        }
Beispiel #31
0
        public bool Initialize()
        {
            LexicalAnalyzer.UseMacro = false;
            state         = new ProcessState(console);
            originalState = state;
            initialiing   = true;
            try
            {
                ParserMediator.Initialize(console);
                if (ParserMediator.HasWarning)
                {
                    ParserMediator.FlushWarningList();
                    if (MessageBox.Show("コンフィグファイルに異常があります\nEmueraを終了しますか", "コンフィグエラー", MessageBoxButtons.YesNo)
                        == DialogResult.Yes)
                    {
                        console.PrintSystemLine("コンフィグファイルに異常があり、終了が選択されたため処理を終了しました");
                        return(false);
                    }
                }
                Content.AppContents.LoadContents();

                if (Config.UseKeyMacro && !Program.AnalysisMode)
                {
                    if (File.Exists(Program.ExeDir + "macro.txt"))
                    {
                        if (Config.DisplayReport)
                        {
                            console.PrintSystemLine("macro.txt読み込み中・・・");
                        }
                        KeyMacro.LoadMacroFile(Program.ExeDir + "macro.txt");
                    }
                }
                if (Config.UseReplaceFile && !Program.AnalysisMode)
                {
                    if (File.Exists(Program.CsvDir + "_Replace.csv"))
                    {
                        if (Config.DisplayReport)
                        {
                            console.PrintSystemLine("_Replace.csv読み込み中・・・");
                        }
                        ConfigData.Instance.LoadReplaceFile(Program.CsvDir + "_Replace.csv");
                        if (ParserMediator.HasWarning)
                        {
                            ParserMediator.FlushWarningList();
                            if (MessageBox.Show("_Replace.csvに異常があります\nEmueraを終了しますか", "_Replace.csvエラー", MessageBoxButtons.YesNo)
                                == DialogResult.Yes)
                            {
                                console.PrintSystemLine("_Replace.csvに異常があり、終了が選択されたため処理を終了しました");
                                return(false);
                            }
                        }
                    }
                }
                Config.SetReplace(ConfigData.Instance);
                //ここでBARを設定すれば、いいことに気づいた予感
                console.setStBar(Config.DrawLineString);

                if (Config.UseRenameFile)
                {
                    if (File.Exists(Program.CsvDir + "_Rename.csv"))
                    {
                        if (Config.DisplayReport || Program.AnalysisMode)
                        {
                            console.PrintSystemLine("_Rename.csv読み込み中・・・");
                        }
                        ParserMediator.LoadEraExRenameFile(Program.CsvDir + "_Rename.csv");
                    }
                    else
                    {
                        console.PrintError("csv\\_Rename.csvが見つかりません");
                    }
                }
                if (!Config.DisplayReport)
                {
                    console.PrintSingleLine(Config.LoadLabel);
                    console.RefreshStrings(true);
                }
                gamebase = new GameBase();
                if (!gamebase.LoadGameBaseCsv(Program.CsvDir + "GAMEBASE.CSV"))
                {
                    console.PrintSystemLine("GAMEBASE.CSVの読み込み中に問題が発生したため処理を終了しました");
                    return(false);
                }
                console.SetWindowTitle(gamebase.ScriptWindowTitle);
                GlobalStatic.GameBaseData = gamebase;

                ConstantData constant = new ConstantData(gamebase);
                constant.LoadData(Program.CsvDir, console, Config.DisplayReport);
                GlobalStatic.ConstantData = constant;
                TrainName = constant.GetCsvNameList(VariableCode.TRAINNAME);

                vEvaluator = new VariableEvaluator(gamebase, constant);
                GlobalStatic.VEvaluator = vEvaluator;

                idDic = new IdentifierDictionary(vEvaluator.VariableData);
                GlobalStatic.IdentifierDictionary = idDic;

                StrForm.Initialize();
                VariableParser.Initialize();

                exm = new ExpressionMediator(this, vEvaluator, console);
                GlobalStatic.EMediator = exm;

                labelDic = new LabelDictionary();
                GlobalStatic.LabelDictionary = labelDic;
                HeaderFileLoader hLoader = new HeaderFileLoader(console, idDic, this);

                LexicalAnalyzer.UseMacro = false;
                if (!hLoader.LoadHeaderFiles(Program.ErbDir, Config.DisplayReport))
                {
                    console.PrintSystemLine("ERHの読み込み中にエラーが発生したため処理を終了しました");
                    return(false);
                }
                LexicalAnalyzer.UseMacro = idDic.UseMacro();

                ErbLoader loader = new ErbLoader(console, exm, this);
                if (Program.AnalysisMode)
                {
                    noError = loader.loadErbs(Program.AnalysisFiles, labelDic);
                }
                else
                {
                    noError = loader.LoadErbFiles(Program.ErbDir, Config.DisplayReport, labelDic);
                }
                initSystemProcess();
                initialiing = false;
            }
            catch (Exception e)
            {
                handleException(e, null, true);
                console.PrintSystemLine("初期化中に致命的なエラーが発生したため処理を終了しました");
                return(false);
            }
            if (labelDic == null)
            {
                return(false);
            }
            state.Begin(BeginType.TITLE);
            GC.Collect();
            return(true);
        }