Пример #1
0
        static void Main(string[] args)
        {
            const string WELCOME = "Welcome to Calculator. Feel free to type any expression you want.";
            const string PROMPT  = ">> ";

            Console.Out.Write(WELCOME + Environment.NewLine);
            while (true)
            {
                Console.Out.Write(PROMPT);
                try
                {
                    var input = Console.In.ReadLine();
                    if (string.Compare(input, "exit", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        break;
                    }
                    var lexer      = new Lexer.Lexer(input);
                    var parser     = new Parser.Parser(lexer);
                    var expression = parser.Parse();
                    var result     = Evaluate.Evaluator.Eval(expression);
                    Console.Out.Write(result.Inspect());
                    Console.Out.Write(Environment.NewLine);
                }
                catch (Exception e)
                {
                    Console.Out.Write("Oops! Something seems to go wrong." + Environment.NewLine);
                    Console.Out.Write(e.Message);
                    Console.Out.Write(Environment.NewLine);
                }
            }
        }
Пример #2
0
        public Object3D(string path)//продумать на принятие готового объекта
        {
            Parser.Parser parser = new Parser.Parser();
            arrayModel = parser.Parse(path);
            mesh       = new MeshGeometry3D[arrayModel.Length];
            //model = new ModelUIElement3D[arrayModel.Length];
            model = new List <ModelUIElement3D>();
            double x     = 0;
            double y     = 0;
            double z     = 0;
            int    count = 0;

            for (int i = 0; i < arrayModel.Length; i++)
            {
                foreach (var a in arrayModel[i].Triangles)
                {
                    x     += a.GetPoint(0).X;
                    y     += a.GetPoint(0).Y;
                    z     += a.GetPoint(0).Z;
                    x     += a.GetPoint(1).X;
                    y     += a.GetPoint(1).Y;
                    z     += a.GetPoint(1).Z;
                    x     += a.GetPoint(2).X;
                    y     += a.GetPoint(2).Y;
                    z     += a.GetPoint(2).Z;
                    count += 3;
                }
            }
            Center = new Point3D(x / count, y / count, z / count);
        }//конструктор
Пример #3
0
 /// <summary>
 /// Можно ли редактировать открытую волновую диаграмму
 /// </summary>
 /// <param name="FilePath"></param>
 /// <param name="ArchitectureName"></param>
 /// <param name="EntityName"></param>
 /// <returns></returns>
 public bool AllowEditForEntity(string FilePath, string ArchitectureName, string EntityName)
 {
     try
     {
         Parser.Parser parser = new Parser.Parser(FilePath);
         parser.Parse();
         foreach (Parser.Entity entity in parser.EntityList)
         {
             //мы нашли необходимый Entity
             if (entity.name.EndsWith(EntityName))
             {
                 if (entity.Port_items.Count != 0)
                 {
                     return(true);
                 }
             }
         }
         return(false);
     }
     catch (Exception ex)
     {
         Schematix.Core.Logger.Log.Error("Parser Error.", ex);
         MessageBox.Show(ex.Message, "Parser Error", MessageBoxButton.OK, MessageBoxImage.Error);
         return(false);
     }
 }
Пример #4
0
 public ConditionElement(Parser.LexAnalyzer.Token left, Parser.LexAnalyzer.Token operation, Parser.LexAnalyzer.Token right)
     : base(TreeCode.Condition)
 {
     this.Left = left;
     this.Right = right;
     this.Operation = operation;
 }
Пример #5
0
 protected void ParseAndWalk(string source)
 {
     Console.WriteLine();
     Console.WriteLine(">> Tree for: " + source);
     var parser = new Parser(new Lexer(source));
     var ast = parser.Parse();
     ast.Accept(new PrintNodeWalker());
 }
Пример #6
0
        public static void Main(string[] args)
        {
            var kernel = new StandardKernel(new ConfigModule());

            Parser.Parser     parser       = new Parser.Parser(kernel.Get <ILogger>());
            IEnumerable <Uri> uriCollecton = parser.ParseFromStorage(kernel.Get <IStorage>());

            kernel.Get <ISerializer>().Serialize(uriCollecton);
        }
Пример #7
0
        //so what are we tsting
        //block name == blcok name
        //block followed by block
        //block followed by ; with block
        //attribute name/values
        //parameter name/values
        public static Document Parse(string text)
        {
            Parser parser = new Parser(new MemoryHost());
            Document document;

            parser.Parse(text, out document);

            return document;
        }
Пример #8
0
        public void Test_1_CheckParserAlreadyBusy()
        {
            // Create parser
            var newParser = new Parser.Parser();
            // Create list for the received events
            var receivedEventsCodes      = new List <DataTypes.ParserErrorCodes>();
            var receivedEventsWebContent = new List <string>();

            // WebSiteUrl for the parser
            Uri webSiteUrl = null;

            // Set website to Parser
            if (Uri.TryCreate(@"http://www.google.com", UriKind.Absolute, out var uriResult))
            {
                webSiteUrl = uriResult;
            }

            // Create RegexList
            var regexList = new RegExList(@"FirstRegex",
                                          new RegexElement(@"RegexString1", 1, true, new List <RegexOptions>()
            {
                RegexOptions.None
            }));

            regexList.Add(@"SecondRegex",
                          new RegexElement(@"RegexString2", 1, false,
                                           new List <RegexOptions>()
            {
                RegexOptions.Singleline, RegexOptions.IgnoreCase
            }));

            // Set parsing value to the parser
            newParser.ParsingValues = new ParsingValues(webSiteUrl, Encoding.UTF8.ToString(), regexList);

            // Create delegate function which adds the received events to the list
            newParser.OnParserUpdate += delegate(object sender, DataTypes.OnParserUpdateEventArgs e)
            {
                receivedEventsCodes.Add(e.ParserInfoState.LastErrorCode);
                receivedEventsWebContent.Add(e.ParserInfoState.WebSiteContentAsString);
            };

            // Start parsing
            newParser.StartParsing();
            Thread.Sleep(25);

            // Try to start parsing again
            var result = newParser.StartParsing();

            // Check if the start was not successful
            Assert.AreEqual(false, result);

            ShowParsingErrorCodes(receivedEventsCodes, receivedEventsWebContent);

            // Check if the BusyFailed event has been signaled
            Assert.GreaterOrEqual(receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.BusyFailed), 0);
        }
Пример #9
0
        public static void Main(string[] args)
        {
            var parser   = new Parser.Parser(args[0]);
            var formula  = parser.ParseCTLFormula();
            var automata = new Automata(args[1]);

            var mc = new ModelChecker.ModelChecker(automata, formula, parser.GetPropositionsFound());

            Console.WriteLine(mc.Check() ? "Yay" : "Nay");
        }
Пример #10
0
        public void Test_6_CheckParserSuccessful()
        {
            // Create parser
            var newParser = new Parser.Parser();
            // Create list for the received events
            var receivedEventsCodes      = new List <DataTypes.ParserErrorCodes>();
            var receivedEventsWebContent = new List <string>();

            // WebSiteUrl for the parser
            Uri webSiteUrl = null;

            // Set website to the Parser
            if (Uri.TryCreate(@"http://tbarth.eu/sunnyconnectoranalyzer", UriKind.Absolute, out var uriResult))
            {
                webSiteUrl = uriResult;
            }

            // Create regex list
            var regexList = new RegExList(@"Gesamt",
                                          new RegexElement(@">Gesamt-(.*?)<", -1, false, new List <RegexOptions>()
            {
                RegexOptions.None
            }));

            // Set parsing value to the parser
            newParser.ParsingValues = new ParsingValues(webSiteUrl, Encoding.UTF8.ToString(), regexList);

            // Create delegate function which adds the received events to the list
            newParser.OnParserUpdate += delegate(object sender, DataTypes.OnParserUpdateEventArgs e)
            {
                receivedEventsCodes.Add(e.ParserInfoState.LastErrorCode);
                receivedEventsWebContent.Add(e.ParserInfoState.WebSiteContentAsString);
            };

            // Start parsing
            var result = newParser.StartParsing();

            // Check if the start was not successful
            Assert.AreEqual(true, result);

            // Wait for the parsing result with a 5s timeout
            var counter = 0;

            while (counter < 500 &&
                   receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.Finished) < 0)
            {
                Thread.Sleep(10);
                counter++;
            }

            ShowParsingErrorCodes(receivedEventsCodes, receivedEventsWebContent);

            // Check if the Finished event has been signaled
            Assert.GreaterOrEqual(receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.Finished), 0);
        }
Пример #11
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage; {0} [-t | <filename>]", Process.GetCurrentProcess().ProcessName);
                return;
            }

            try
            {
                StreamReader input;

                if (args[0] == "-t")
                {
                    input = new StreamReader(Console.OpenStandardInput());
                }
                else
                {
                    input = new StreamReader(args[0]);
                }
                var program = input.ReadToEnd();

                byte[]        data   = Encoding.ASCII.GetBytes(program);
                MemoryStream  stream = new MemoryStream(data, 0, data.Length);
                Scanner       l      = new Scanner(stream);
                Parser.Parser p      = new Parser.Parser(l);

                if (!p.Parse())
                {
                    Console.WriteLine("Parse error");
                    Console.WriteLine(program);
                    return;
                }

                try
                {
                    var progTC  = new ProgramTypeChecker(p);
                    var progGen = new ProgramCodeGenerator();
                    var t42prog = progGen.Start(p.program);

                    Console.Out.WriteLine(t42prog.ToString());
                }
                catch (TypeCheckerException e)
                {
                    Console.WriteLine("Type error {0}", e.Message);
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Пример #12
0
        public void Test_ASTHelper_Constructor(string content)
        {
            StreamReader FakeReader = CreateFakeReader(content, Encoding.UTF8);
            Tokeniser    tokeniser  = new Tokeniser(FakeReader);

            tokeniser.GenerateTokens();
            List <ScannerToken> tokens = tokeniser.Tokens.ToList();

            Parser.Parser parser = new Parser.Parser(tokens);
            parser.Parse(out nowhere);
            Assert.IsFalse(Parser.Parser.HasError, "The parser encountered an error");
        }
Пример #13
0
        public void TestMethod2()
        {
            Parser.Parser pars     = new Parser.Parser();
            IProcessing   preproc  = pars.PreProcessing;
            IProcessing   postproc = pars.PostProcessing;
            List <ICurve> curves   = new List <ICurve>();
            List <IPoint> points   = new List <IPoint>();

            pars.load("C:/Users/Ани/Desktop/xml_test.xml");
            preproc.convert(ref curves, ref points, ref pars.Gmesh.Poligons[0].Curves, ref pars.Gmesh.Poligons[0].Points);
            postproc.convert(ref curves, ref points, ref pars.Gmesh.Poligons[0].Curves, ref pars.Gmesh.Poligons[0].Points);
            pars.save("C:/Users/Ани/Desktop/xml_new_test.xml");
        }
Пример #14
0
        public TestBenchModel(string fileName, string entityName, string archName)
        {
            this.fileName   = fileName;
            this.entityName = entityName;
            this.archName   = archName;
            currentPorts    = new List <PortGenerator>();
            currentSignals  = new List <SignalGenerator>();
            selectedPorts   = new List <PortGenerator>();
            selectedSignals = new List <SignalGenerator>();

            parser = new Parser.Parser(fileName);
            parser.Parse();
        }
Пример #15
0
        public void CheckAllTagsTest()
        {
            string textGood1 = "<html><head><title> Some title </title></head><body><p> some <b> Paragraf </b> </p> <ul> <li> <p> listItem1 </p> </li> <li> listItem2 </li> </ul> < /body>  <  /html>";
            string textGood2 = "<html><head><title> Some title </title></head><body> < /body>  <  /html>";
            string textBad1  = "<html>   <title> Some title </title></head><body> < /body>  <  /html>";
            string textBad2  = "<html><head><title> Some title </title></head><body> some <p> paragraf < /body>  <  /html>";

            Parser.Parser p = new Parser.Parser();

            Assert.AreEqual(true, p.CheckAllTags(textGood1));
            Assert.AreEqual(true, p.CheckAllTags(textGood2));
            Assert.AreEqual(false, p.CheckAllTags(textBad1));
            Assert.AreEqual(false, p.CheckAllTags(textBad2));
        }
Пример #16
0
        public void Test_8_CheckOnVistaApiRequestHistoryWebContentNotLoaded()
        {
            // Create parser
            var newParser = new Parser.Parser();
            // Create list for the received events
            var receivedEventsCodes      = new List <DataTypes.ParserErrorCodes>();
            var receivedEventsWebContent = new List <string>();

            // WebSiteUrl for the parser
            Uri webSiteUrl = null;

            // Set website to the Parser
            if (Uri.TryCreate(
                    @"https://api.onvista.de/api/v1/instruments/FUND/114917893/eod_history?idNotation=3951732&startDate=2021-02-28&range=M1",
                    UriKind.Absolute, out var uriResult))
            {
                webSiteUrl = uriResult;
            }

            // Set parsing value to the parser
            newParser.ParsingValues = new ParsingValues(webSiteUrl, null, Encoding.UTF8.ToString(), DataTypes.ParsingType.OnVistaHistoryData);

            // Create delegate function which adds the received events to the list
            newParser.OnParserUpdate += delegate(object sender, DataTypes.OnParserUpdateEventArgs e)
            {
                receivedEventsCodes.Add(e.ParserInfoState.LastErrorCode);
                receivedEventsWebContent.Add(e.ParserInfoState.WebSiteContentAsString);
            };

            // Start parsing
            var result = newParser.StartParsing();

            // Check if the start was not successful
            Assert.AreEqual(true, result);

            // Wait for the parsing result with a 5s timeout
            var counter = 0;

            while (counter < 500 &&
                   receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.NoWebContentLoaded) < 0)
            {
                Thread.Sleep(10);
                counter++;
            }

            ShowParsingErrorCodes(receivedEventsCodes, receivedEventsWebContent);

            // Check if the Finished event has been signaled
            Assert.GreaterOrEqual(receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.NoWebContentLoaded), 0);
        }
Пример #17
0
        public void Test_12_CheckYahooApiRequestHistoryData()
        {
            // Create parser
            var newParser = new Parser.Parser(true);
            // Create list for the received events
            var receivedEventsCodes      = new List <DataTypes.ParserErrorCodes>();
            var receivedEventsWebContent = new List <string>();

            // WebSiteUrl for the parser
            Uri webSiteUrl = null;

            // Set website to the Parser
            if (Uri.TryCreate(
                    @"https://yfapi.net/v8/finance/chart/APC.F?range=1mo&region=DE&interval=1d&lang=de",
                    UriKind.Absolute, out var uriResult))
            {
                webSiteUrl = uriResult;
            }

            // Set parsing value to the parser
            newParser.ParsingValues = new ParsingValues(webSiteUrl, "T7Dcb5soihfwQpPoQAXtMashju0rQj8VCfztXC90", Encoding.UTF8.ToString(), DataTypes.ParsingType.YahooHistoryData);

            // Create delegate function which adds the received events to the list
            newParser.OnParserUpdate += delegate(object sender, DataTypes.OnParserUpdateEventArgs e)
            {
                receivedEventsCodes.Add(e.ParserInfoState.LastErrorCode);
                receivedEventsWebContent.Add(e.ParserInfoState.WebSiteContentAsString);
            };

            // Start parsing
            var result = newParser.StartParsing();

            // Check if the start was not successful
            Assert.AreEqual(true, result);

            // Wait for the parsing result with a 5s timeout
            var counter = 0;

            while (counter < 500 &&
                   receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.Finished) < 0)
            {
                Thread.Sleep(10);
                counter++;
            }

            ShowParsingErrorCodes(receivedEventsCodes, receivedEventsWebContent);

            // Check if the Finished event has been signaled
            Assert.GreaterOrEqual(receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.Finished), 0);
        }
Пример #18
0
 /// <summary>
 /// Проанализировать VHDL файл и добавить все имеющиеся сигналы
 /// </summary>
 /// <param name="FilePath"></param>
 /// <param name="ArchitectureName"></param>
 /// <param name="EntityName"></param>
 public void AnalyseVHDLFile(string FilePath, string ArchitectureName, string EntityName)
 {
     Parser.Parser parser = new Parser.Parser(FilePath);
     parser.Parse();
     foreach (Parser.Entity entity in parser.EntityList)
     {
         //мы нашли необходимый Entity
         if (entity.name.EndsWith(EntityName, StringComparison.InvariantCultureIgnoreCase))
         {
             this.entity = entity;
             break;
         }
     }
 }
Пример #19
0
        public void Test_AssignmentNode_NodeHasNoOperator()
        {
            StreamReader reader    = CreateFakeReader(program2);
            Tokeniser    tokeniser = new Tokeniser(reader);

            tokeniser.GenerateTokens();
            Parser.Parser parser = new Parser.Parser(tokeniser.Tokens.ToList());
            parser.Parse(out nowhere);
            Assert.IsFalse(Parser.Parser.HasError, "Parser encountered an error state:\n\n" + nowhere);
            parser.Root.Accept(new TypeChecker(new List <string>()
            {
                "3", "5", "6", "9", "10", "11"
            }));
            Assert.IsNull(((AssignmentNode)parser.Root.Statements[0]).Operator, "Operator was not null for assignment node");
        }
Пример #20
0
        public void Test_TypeChecker_CheckHasNoErrors(string program)
        {
            StreamReader reader    = CreateFakeReader(program);
            Tokeniser    tokeniser = new Tokeniser(reader);

            tokeniser.GenerateTokens();
            Parser.Parser parser = new Parser.Parser(tokeniser.Tokens.ToList());
            parser.Parse(out nowhere);
            Assert.IsFalse(Parser.Parser.HasError, "Parser encountered an error state:\n\n" + nowhere);
            parser.Root.Accept(new TypeChecker(new List <string>()
            {
                "3", "5", "6", "9", "10", "11"
            }));
            Assert.IsFalse(TypeChecker.HasError, "Typechecker encountered an error.");
        }
Пример #21
0
        public void Test_ASTHelper_Assign_2(string test)
        {
            StreamReader FakeReader = CreateFakeReader(test, Encoding.UTF8);
            Tokeniser    tokeniser  = new Tokeniser(FakeReader);

            tokeniser.GenerateTokens();
            List <ScannerToken> tokens = tokeniser.Tokens.ToList();

            Parser.Parser parser = new Parser.Parser(tokens);
            parser.Parse(out nowhere);
            if (Parser.Parser.HasError)
            {
                Assert.Fail();
            }
            parser.Root.Accept(new PrettyPrinter());
        }
Пример #22
0
        public OptionsManager(string path, Parser.Parser parser, IValidator validator)
        {
            defaultOptions = new T();
            string options;

            try
            {
                using (StreamReader sr = new StreamReader($"{path}appsettings.json"))
                {
                    options = sr.ReadToEnd();
                }

                jsonOptions = parser.DeserializeJson <T>(options);
                validator.Validate(jsonOptions);
                isJsonConfigured = true;
                LogString       += "appsettings.json is loaded.\n";
            }
            catch (Exception ex)
            {
                isJsonConfigured = false;
                LogString       += ex.Message;
            }

            try
            {
                using (StreamReader sr = new StreamReader($"{path}config.xml"))
                {
                    options = sr.ReadToEnd();
                }

                xmlOptions = parser.DeserializeXML <T>(options);
                validator.Validate(xmlOptions);
                isXmlConfigured = true;
                LogString      += "config.xml is loaded.\n";
            }
            catch (Exception ex)
            {
                isXmlConfigured = false;
                LogString      += ex.Message;
            }

            if (!isJsonConfigured && !isXmlConfigured)
            {
                LogString += "default configuration.\n";
            }
        }
Пример #23
0
        public void Test_TypeChecker_CanThrowExceptions(string program)
        {
            StreamReader reader    = CreateFakeReader(program);
            Tokeniser    tokeniser = new Tokeniser(reader);

            tokeniser.GenerateTokens();
            Parser.Parser parser = new Parser.Parser(tokeniser.Tokens.ToList());
            parser.Parse(out nowhere);
            Assert.IsFalse(Parser.Parser.HasError, "Parser encountered an error state:\n\n" + nowhere);
            try {
                parser.Root.Accept(new TypeChecker(new List <string>()
                {
                    "3", "5", "6", "9", "10", "11"
                }));
            } catch {
            }
            Assert.IsTrue(TypeChecker.HasError, "The error was not caught");
        }
Пример #24
0
        public void TestMethod1()
        {
            Parser.Parser pars     = new Parser.Parser();
            IProcessing   preproc  = pars.PreProcessing;
            IProcessing   postproc = pars.PostProcessing;
            List <ICurve> curves   = new List <ICurve>();
            List <IPoint> points   = new List <IPoint>();

            points.Add(new Geometry.Point(0, 1));
            points.Add(new Geometry.Point(5, 8));
            points.Add(new Geometry.Point(2, 4));
            for (int i = 0; i < 2; i++)
            {
                curves.Add(new Line(points[i], points[i + 1]));
            }
            postproc.convert(ref curves, ref points, ref pars.Gmesh.Poligons[0].Curves, ref pars.Gmesh.Poligons[0].Points);
            pars.save("C:/Users/Ани/Desktop/xml_test.xml");
        }
Пример #25
0
        public void CheckHtmlStartTagsUntilTitleTest()
        {
            string textGood1 = "<html><head><title>";
            string textGood2 = "  < html> <  head    >       <    title    >  something blb lbaba ";
            string textBad1  = "";
            string textBad2  = "   <html>  <head><bla> something";
            string textBad3  = "   <head><html><title>";
            string textBad4  = "something <html><head><title>";

            Parser.Parser p = new Parser.Parser();

            Assert.AreEqual(true, p.CheckHtmlStartTagsUntilTitle(textGood1));
            Assert.AreEqual(true, p.CheckHtmlStartTagsUntilTitle(textGood2));
            Assert.AreEqual(false, p.CheckHtmlStartTagsUntilTitle(textBad1));
            Assert.AreEqual(false, p.CheckHtmlStartTagsUntilTitle(textBad2));
            Assert.AreEqual(false, p.CheckHtmlStartTagsUntilTitle(textBad3));
            Assert.AreEqual(false, p.CheckHtmlStartTagsUntilTitle(textBad4));
        }
Пример #26
0
 public BeeMethod(int Bs, double a, double T0, double T1, int n, int maxIt, double[] rMin, double[] rMax, double w, double e, double myEta, double myBeta, double myGamma, double myRange, int orient, Parser.PostfixNotationExpression myFunc)
 {
     B = Bs; // must be > 0
     alpha = a;
     T = T0;
     TFinal = T1;
     argCnt = n; // must be > 0
     iterMax = maxIt; // must be > 0
     rangeMin = new Point(argCnt, rMin); //
     rangeMax = new Point(argCnt, rMax); //
     wMax = w;
     eMax = e;
     eta = myEta;
     beta = myBeta;
     gamma = myGamma;
     range = myRange;
     optOrient = orient; // must be +-1
     func = myFunc;
     rand = new Random();
 }
Пример #27
0
        public void CheckHtmlTagsInsideBodyTest()
        {
            string textGood1 = "";
            string textGood2 = "<p> some <b> Paragraf </b> </p>";
            string textGood3 = "<p> some <b> Paragraf </b> </p> <ul> <li> <p> listItem1 </p> </li> <li> listItem2 </li> </ul>";
            string textBad1  = "<p> some Paragraf </p> </p>";
            string textBad2  = "<p> some paragraf </p> </p> <p>";
            string textBad3  = "</p> some paragraf <p> <p> </p>";
            string textBad4  = "<p> some paragraf </p> </p> <p>";

            Parser.Parser p = new Parser.Parser();

            Assert.AreEqual(true, p.CheckHtmlTagsInsideBody(textGood1));
            Assert.AreEqual(true, p.CheckHtmlTagsInsideBody(textGood2));
            Assert.AreEqual(true, p.CheckHtmlTagsInsideBody(textGood3));
            Assert.AreEqual(false, p.CheckHtmlTagsInsideBody(textBad1));
            Assert.AreEqual(false, p.CheckHtmlTagsInsideBody(textBad2));
            Assert.AreEqual(false, p.CheckHtmlTagsInsideBody(textBad3));
            Assert.AreEqual(false, p.CheckHtmlTagsInsideBody(textBad4));
        }
Пример #28
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string inputText = textBox1.Text;
                Parser.Parser parser = new Parser.Parser(inputText);

                AbstractSyntaxTree tree = parser.Parse();

                parseTree.Nodes.Clear();
                TreeNode root = new TreeNode("Program");
                parseTree.Nodes.Add(root);

                tree.syntaxTreeRoot.PrintParseTree(root);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #29
0
        public void CheckHtmlTagsAfterTitleUntilBodyTest()
        {
            string textGood1 = "<html><head><title> Some title </title></head><body>";
            string textGood2 = "<html><head><title></title></head><body>";
            string textGood3 = "<  html  >   <head>  <  title> Some title <  /title>  <  /head  ><  body   > something";
            string textBad1  = "";
            string textBad2  = "<html><head><title";
            string textBad3  = "<html><head><title> something ";
            string textBad4  = "<html><head><title> something <";
            string textBad5  = "<html><head><title> Some title </title></head>";

            Parser.Parser p = new Parser.Parser();

            Assert.AreEqual(true, p.CheckHtmlTagsAfterTitleUntilBody(textGood1));
            Assert.AreEqual(true, p.CheckHtmlTagsAfterTitleUntilBody(textGood2));
            Assert.AreEqual(true, p.CheckHtmlTagsAfterTitleUntilBody(textGood3));
            Assert.AreEqual(false, p.CheckHtmlTagsAfterTitleUntilBody(textBad1));
            Assert.AreEqual(false, p.CheckHtmlTagsAfterTitleUntilBody(textBad2));
            Assert.AreEqual(false, p.CheckHtmlTagsAfterTitleUntilBody(textBad3));
            Assert.AreEqual(false, p.CheckHtmlTagsAfterTitleUntilBody(textBad4));
            Assert.AreEqual(false, p.CheckHtmlTagsAfterTitleUntilBody(textBad5));
        }
Пример #30
0
        public void CheckHtmlTagsNotInsideBodyTest()
        {
            string textGood1 = "<html><head><title> Some title </title></head><body> Some body < /body>  <  /html>";
            string textGood2 = "<html><head><title></title></head><body></body></html>";
            string textBad1  = "";
            string textBad2  = "<html><head><title";
            string textBad3  = "<html>head><title> Some title ";
            string textBad4  = "<html><head><title> Some title </title></head><body";
            string textBad5  = "<html><head><title> Some title </title></head><body> Some body ";
            string textBad6  = "<html><head><title> Some title </title></head><body> Some body </body>";

            Parser.Parser p = new Parser.Parser();

            Assert.AreEqual(true, p.CheckHtmlTagsNotInsideBody(textGood1));
            Assert.AreEqual(true, p.CheckHtmlTagsNotInsideBody(textGood2));
            Assert.AreEqual(false, p.CheckHtmlTagsNotInsideBody(textBad1));
            Assert.AreEqual(false, p.CheckHtmlTagsNotInsideBody(textBad2));
            Assert.AreEqual(false, p.CheckHtmlTagsNotInsideBody(textBad3));
            Assert.AreEqual(false, p.CheckHtmlTagsNotInsideBody(textBad4));
            Assert.AreEqual(false, p.CheckHtmlTagsNotInsideBody(textBad5));
            Assert.AreEqual(false, p.CheckHtmlTagsNotInsideBody(textBad6));
        }
Пример #31
0
        public void Test_2_CheckEmptyWebSiteGiven()
        {
            // Create parser
            var newParser = new Parser.Parser();
            // Create list for the received events
            var receivedEventsCodes      = new List <DataTypes.ParserErrorCodes>();
            var receivedEventsWebContent = new List <string>();

            // WebSiteUrl for the parser
            Uri webSiteUrl = null;

            // Set website to a empty string;
            if (!Uri.TryCreate(@"", UriKind.Absolute, out var uriResult))
            {
                webSiteUrl = uriResult;
            }

            // Set parsing value to the parser
            newParser.ParsingValues = new ParsingValues(webSiteUrl, Encoding.UTF8.ToString(), new RegExList());

            // Create delegate function which adds the received events to the list
            newParser.OnParserUpdate += delegate(object sender, DataTypes.OnParserUpdateEventArgs e)
            {
                receivedEventsCodes.Add(e.ParserInfoState.LastErrorCode);
                receivedEventsWebContent.Add(e.ParserInfoState.WebSiteContentAsString);
            };

            // Start parsing
            var result = newParser.StartParsing();

            // Check if the start was not successful
            Assert.AreEqual(false, result);

            ShowParsingErrorCodes(receivedEventsCodes, receivedEventsWebContent);

            // Check if the InvalidWebSiteGiven event has been signaled
            Assert.GreaterOrEqual(
                receivedEventsCodes.FindIndex(x => x == DataTypes.ParserErrorCodes.InvalidWebSiteGiven), 0);
        }
Пример #32
0
        public void Test_Program(string program)
        {
            StreamReader FakeReader = CreateFakeReader(program, Encoding.UTF8);
            Tokeniser    tokeniser  = new Tokeniser(FakeReader);

            tokeniser.GenerateTokens();
            List <ScannerToken> tokens = tokeniser.Tokens.ToList();

            Parser.Parser parser = new Parser.Parser(tokens);
            parser.Parse(out nowhere);
            if (Parser.Parser.HasError)
            {
                Assert.Fail();
            }
            parser.Root.Accept(new TypeChecker(new List <string>()
            {
                "3", "5", "6", "9", "10", "11"
            }));
            CodeGenerationVisitor codeGenerationVisitor = new CodeGenerationVisitor("Codegen_output.cpp", new List <string>());

            parser.Root.Accept(codeGenerationVisitor);
        }
Пример #33
0
        private static void DoNamedTest([CallerMemberName] string name = "")
        {
            if (!name.StartsWith("Test"))
            {
                Assert.Fail("Named test should only be called from test framework with Test[Name] pattern");
            }

            name = name.Remove(0, 4);
            const string resourcesParser  = @"..\..\Resources\Parser";
            const string goldExtension    = ".gold";
            const string tempExtension    = ".temp";
            const string parserExtension  = ".txt";
            var          currentInputFile = Path.Combine(resourcesParser, name, name + parserExtension);
            var          currentTempFile  = Path.Combine(resourcesParser, name, name + tempExtension);
            var          currentGoldFile  = Path.Combine(resourcesParser, name, name + goldExtension);

            Assert.True(File.Exists(currentInputFile), $"Input file does not exists: {currentInputFile}");
            var    fileInfo = new FileInfo(currentInputFile);
            string text;

            using (var streamReader = fileInfo.OpenText())
            {
                var exp = new Parser.Parser(new Lexer(streamReader)).Parse();
                text = exp + "\n" + exp.GetInternalRepresentation();
            }

            using (var tempStream = File.CreateText(currentTempFile))
            {
                tempStream.Write(text);
            }

            Assert.True(File.Exists(currentGoldFile), "No gold found");
            var gold = File.ReadAllText(currentGoldFile);

            Assert.AreEqual(gold, text, "Temp not equals gold");
            File.Delete(currentTempFile);
        }
Пример #34
0
        public void Test_CodeGenVisitor_pin_fail()
        {
            StreamReader FakeReader = CreateFakeReader(pin_fail, Encoding.UTF8);
            Tokeniser    tokeniser  = new Tokeniser(FakeReader);

            tokeniser.GenerateTokens();
            List <ScannerToken> tokens = tokeniser.Tokens.ToList();

            Parser.Parser parser = new Parser.Parser(tokens);
            parser.Parse(out dbg);
            if (Parser.Parser.HasError)
            {
                Assert.Fail("The parser encountered an error\n\n" + dbg);
            }
            parser.Root.Accept(new TypeChecker(new List <string>()
            {
                "3", "5", "6", "9", "10", "11"
            }));
            Assert.IsFalse(TypeChecker.HasError, "Typechecker visitor encountered an error");
            CodeGenerationVisitor codeGenerationVisitor = new CodeGenerationVisitor("Codegen_output.cpp", new List <string>());

            parser.Root.Accept(codeGenerationVisitor);
            Assert.IsTrue(CodeGenerationVisitor.HasError, "Code gen visitor encountered an error");
        }
Пример #35
0
        internal object Execute(string source, string filePath = null)
        {
            var oldCurentExecFolder = Context.CurrentExecFolder;
            var currentExecFolder = filePath == null
                ? Directory.GetCurrentDirectory()
                : Path.GetDirectoryName(filePath);
            Context.CurrentExecFolder = currentExecFolder;
            if (currentExecFolder != null)
                Directory.SetCurrentDirectory(currentExecFolder);

            try
            {
                var lexer = new Lexer(source, filePath);
                var parser = new Parser(lexer);
                var ast = parser.Parse();
                return ast.Accept(this);
            }
            finally
            {
                Context.CurrentExecFolder = oldCurentExecFolder;
                if (oldCurentExecFolder != null)
                    Directory.SetCurrentDirectory(oldCurentExecFolder);
            }
        }
 public void newFunc(ref Parser.Rec Rec)
 {
 }
Пример #37
0
        public Tokenizer(string FileName, MainForm form)
        {
            string letters = LexerGenerationHelper.getBigOr(new List<char>{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'});
            string digits = LexerGenerationHelper.getBigOr(new List<char>{'1','2','3','4','5','6','7','8','9','0'});
            string anybutquote = LexerGenerationHelper.getRegExpExcept(34);
            string anybutapostrophe = LexerGenerationHelper.getRegExpExcept(39);
            string any = LexerGenerationHelper.getAny();
            theTokensDefinition.Add(new TokenDefinition(TokenType.POINTPOINT, ".."));
            theTokensDefinition.Add(new TokenDefinition(TokenType.OR, "|"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.DOT, "."));
            theTokensDefinition.Add(new TokenDefinition(TokenType.LEFTPAR, "("));
            theTokensDefinition.Add(new TokenDefinition(TokenType.RIGHTPAR, ")"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.LEFTSQUARE, "["));
            theTokensDefinition.Add(new TokenDefinition(TokenType.RIGHTSQUARE, "]"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.LEFTCURLY, "{"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.RIGHTCURLY, "}"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.PLUS, "+"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.MINUS, "-"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.CHR, "CHR"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.END, "END"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.EQUALS, "="));
            theTokensDefinition.Add(new TokenDefinition(TokenType.TOKENS, "TOKENS"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.EXCEPT, "EXCEPT"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.IGNORE, "IGNORE"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.KEYWORDS, "KEYWORDS"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.COMPILER, "COMPILER"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.CHARACTERS,"CHARACTERS"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.PRODUCTIONS,"PRODUCTIONS"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.Attributes, "<." + any + LexerGenerationHelper.getEquivalent('*') + ".>"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.SemAction, "(." + any + ".)"));
            theTokensDefinition.Add(new TokenDefinition(TokenType.Ident, letters + LexerGenerationHelper.getEquivalent('(') + letters + LexerGenerationHelper.getEquivalent('|') + digits + LexerGenerationHelper.getEquivalent(')') + LexerGenerationHelper.getEquivalent('*')));
            theTokensDefinition.Add(new TokenDefinition(TokenType.Number, digits + digits + LexerGenerationHelper.getEquivalent('*')));
            theTokensDefinition.Add(new TokenDefinition(TokenType.String, "\"" + anybutquote + LexerGenerationHelper.getEquivalent('*') + "\""));
            theTokensDefinition.Add(new TokenDefinition(TokenType.Char,"'"+anybutapostrophe+"'"));

            try
            {
                using (StreamReader myStream = new StreamReader(FileName))
                {
                    String file;
                    file = myStream.ReadToEnd();
                    theTokenList = getTokens(file, form);
                    foreach (Token t in theTokenList)
                    {
                        form.appendText(t.getValue() + " = " + t.getTokenType()+"\n");
                    }
                }
                Parser ps = new Parser(theTokenList);
                ps.Parse(form);
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error reading the file: " + ex.Message);
            }
        }
Пример #38
0
 /// <summary> Call the wrapped pool.</summary>
 /// <param name="parser">
 /// </param>
 public virtual void Put(Parser.Parser parser)
 {
     parser.ReInit((ICharStream)null);
     pool.Put(parser);
 }
Пример #39
0
 protected void ShowTraces(Parser parser)
 {
     var oldTraces = scroller.Child as Widget;
     if (oldTraces != null)
     {
         scroller.Remove(oldTraces);
         oldTraces.Destroy();
     }
     var tb = new TraceBox(parser.RootTrace) { Trace = parser.RootTrace, ProfileInfoVisible = profileButton.State == StateType.Active };
     scroller.AddWithViewport(tb);
     tb.Show();
 }
        void MainForm_OnSSCParsed (Parser.SSC ssc) {

            tree.Nodes.Clear();
            {
                TreeNode raw_node = new TreeNode("Raw Data");
                tree.Nodes.Add(raw_node);
                foreach (var kvp in ssc.raw_data) {
                    TreeNode key_node = new TreeNode(kvp.Key);
                    TreeNode val_node = new TreeNode(kvp.Value);
                    raw_node.Nodes.Add(key_node);
                    key_node.Nodes.Add(val_node);
                }
            }
            {
                TreeNode chart_node = new TreeNode("Charts");
                tree.Nodes.Add(chart_node);
                foreach (Chart c in ssc.charts) {
                    TreeNode c_node = new TreeNode(string.Format("{0} {1}", c.raw_data[Chart.KEY_STEPSTYPE], c.raw_data[Chart.KEY_METER]));
                    c_node.Tag = c;
                    chart_node.Nodes.Add(c_node);
                    c_node.Nodes.Add(new TreeNode(string.Format("Total Second = {0}", c.total_second)));
                    {
                        foreach (var kvp in c.raw_data) {
                            TreeNode key_node = new TreeNode(kvp.Key);
                            TreeNode val_node = new TreeNode(kvp.Value);
                            c_node.Nodes.Add(key_node);
                            key_node.Nodes.Add(val_node);
                        }
                    }
                    {
                        TreeNode measure_node = new TreeNode("Measures");
                        c_node.Nodes.Add(measure_node);
                        foreach (Measure m in c.measures) {
                            TreeNode m_node = new TreeNode(string.Format("Measure {0}: Size {1}", measure_node.Nodes.Count, m.beats.Count));
                            measure_node.Nodes.Add(m_node);
                            foreach (Beat b in m.beats) {
                                TreeNode b_node = new TreeNode(string.Format("Beat {0}", m_node.Nodes.Count));
                                m_node.Nodes.Add(b_node);
                                b_node.Nodes.Add(new TreeNode(b.beat.ToString()));
                                b_node.Nodes.Add(new TreeNode(b.second.ToString()));

                                foreach (Note n in b.notes) {
                                    TreeNode n_node = new TreeNode(n.name);
                                    b_node.Nodes.Add(n_node);
                                }
                            }
                        }
                    }
                    {
                        TreeNode bpm_node = new TreeNode("BPMS");
                        c_node.Nodes.Add(bpm_node);
                        foreach (BPMS.Data data in c.bpms.data) {
                            TreeNode d_node = new TreeNode(string.Format("{0}={1}BPM", data.beat, data.bpm));
                            bpm_node.Nodes.Add(d_node);
                        }
                    }
                    {
                        TreeNode delay_node = new TreeNode("DELAYS");
                        c_node.Nodes.Add(delay_node);
                        foreach (DELAYS.Data data in c.delays.data) {
                            TreeNode d_node = new TreeNode(string.Format("{0}={1}", data.beat, data.duration_second));
                            delay_node.Nodes.Add(d_node);
                        }
                    }
                }
            }
        }