예제 #1
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!(?:calc|eval) (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            if (output.Success)
            {
                String exp = output.Groups[1].Value;
                SemanticProcessor <MathToken> processor = new SemanticProcessor <MathToken>(new StringReader(exp), actions);
                ParseMessage parseMessage = processor.ParseAll();
                if (parseMessage == ParseMessage.Accept)
                {
                    message.Chat.SendMessage(
                        String.Format(
                            "{0} = {1}",
                            exp,
                            ((Computable)processor.CurrentToken).GetValue()));
                }
                else
                {
                    IToken token = processor.CurrentToken;
                    message.Chat.SendMessage(string.Format("{0} ({1} on line {2}, column {3})",
                                                           parseMessage, token.Symbol,
                                                           token.Position.Line, token.Position.Column));
                }
            }
        }
예제 #2
0
        public object Exec(string input, ExecutionContext ctx)
        {
            var          processor    = new SemanticProcessor <GCToken>(new StringReader(input), actions);
            ParseMessage parseMessage = processor.ParseAll();

            if (parseMessage == ParseMessage.Accept)
            {
                var statement = processor.CurrentToken as Expression;
                if (statement != null)
                {
                    try
                    {
                        return(statement.GetValue(ctx));
                    }
                    catch (FormulaSolverException ex)
                    {
                        return("??" + ex.Message);
                    }
                }
            }
            else
            {
                IToken token = processor.CurrentToken;
                return(String.Format("??Syntax error at: {0} [{1}]", token.Position.Index, parseMessage));
            }

            return(null);
        }
예제 #3
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Language Scrappy Compiler 1.0");

            if (args.Length == 0)
            {
                Console.WriteLine("usage: Scrappy <file.sp>");
                return;
            }

            var grammar = CompiledGrammar.Load(typeof(Program), "Scrappy.egt");
            var actions = new SemanticTypeActions <BaseToken>(grammar);

            try
            {
                actions.Initialize(true);
            }
            catch (InvalidOperationException ex)
            {
                Console.Write("Error: " + ex.Message);
                return;
            }

            try
            {
                var path       = args[0];
                var outputName = Path.GetFileNameWithoutExtension(path) + ".xml";
                using (var reader = File.OpenText(path))
                {
                    var          processor    = new SemanticProcessor <BaseToken>(reader, actions);
                    ParseMessage parseMessage = processor.ParseAll();
                    if (parseMessage == ParseMessage.Accept)
                    {
                        Console.WriteLine("Parsing done.");
                        var compilationModel = new CompilationModel(File.ReadAllLines(path));
                        var start            = (Start)processor.CurrentToken;
                        start.Compile(compilationModel); // first classes, fields and methods needs to be compiled
                        compilationModel.Compile();      // after that compile method body
                        Console.WriteLine("Compiling done.");

                        using (var outfile = new StreamWriter(outputName))
                        {
                            outfile.Write(compilationModel.ToXml());
                        }

                        // PrintAst(start); // only for debugging
                    }
                    else
                    {
                        IToken token = processor.CurrentToken;
                        Console.WriteLine(token.Symbol);
                        Console.WriteLine("Error: Line: {0} Column: {1} Error: {2}", token.Position.Line, token.Position.Column, parseMessage);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error" + e.Message);
            }
        }
예제 #4
0
        public object Exec(string input, ExecutionContext ctx)
        {
            var processor = new SemanticProcessor<GCToken>(new StringReader(input), actions);
            ParseMessage parseMessage = processor.ParseAll();

            if (parseMessage == ParseMessage.Accept)
            {
                var statement = processor.CurrentToken as Expression;
                if (statement != null)
                {
                    try
                    {
                        return statement.GetValue(ctx);
                    }
                    catch (FormulaSolverException ex)
                    {
                        return "??" + ex.Message;
                    }
                }
            }
            else
            {
                IToken token = processor.CurrentToken;
                return String.Format("??Syntax error at: {0} [{1}]", token.Position.Index, parseMessage);
            }

            return null;
        }
예제 #5
0
        static void Main(string[] args)
        {
            CompiledGrammar grammar = CompiledGrammar.Load(typeof(Token), "minim0.2.cgt");
            SemanticTypeActions<Token> actions = new SemanticTypeActions<Token>(grammar);
            CodeGenerator.Init("test.exe");
            TypeChecker.Init();

            try
            {
                actions.Initialize(true);
            }
            catch (InvalidOperationException ex)
            {
                Console.Write(ex.Message);
                Console.ReadKey(true);
                return;
            }

            SemanticProcessor<Token> processor = new SemanticProcessor<Token>(new StreamReader(args[0]), actions);
            ParseMessage parseMessage = processor.ParseAll();
            if (parseMessage == ParseMessage.Accept)
            {
                Console.WriteLine("Parsed successfully.");
                Program p = (Program)processor.CurrentToken;
                CodeGenerator.Complete();
            }
            else
            {
                IToken token = processor.CurrentToken;
                Console.WriteLine("Error on line " + token.Position.Line + ".\n" + token.Position.ToString());
                Console.WriteLine(string.Format("{0} {1}", "^".PadLeft((int)(token.Position.Index + 1)), parseMessage));
            }
        }
		public void ParseEmpty() {
			using (TestStringReader reader = new TestStringReader("")) {
				SemanticProcessor<TestToken> processor = new SemanticProcessor<TestToken>(reader, actions);
				Assert.Equal(ParseMessage.Accept, processor.ParseAll());
				Assert.IsType<TestEmpty>(processor.CurrentToken);
			}
		}
예제 #7
0
		public void GenericParse() {
			SemanticTypeActions<MockGenericTokenBase> actions = new SemanticTypeActions<MockGenericTokenBase>(grammar);
			actions.Initialize();
			SemanticProcessor<MockGenericTokenBase> processor = new SemanticProcessor<MockGenericTokenBase>(new StringReader("-1+2+3*4-8"), actions);
			Assert.Equal(ParseMessage.Accept, processor.ParseAll());
			Assert.IsAssignableFrom<MockGenericTokenBase>(processor.CurrentToken);
		}
예제 #8
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Language Scrappy Compiler 1.0");

            if (args.Length == 0)
            {
                Console.WriteLine("usage: Scrappy <file.sp>");
                return;
            }

            var grammar = CompiledGrammar.Load(typeof(Program), "Scrappy.egt");
            var actions = new SemanticTypeActions<BaseToken>(grammar);
            try
            {
                actions.Initialize(true);
            }
            catch (InvalidOperationException ex)
            {
                Console.Write("Error: " + ex.Message);
                return;
            }

            try
            {
                var path = args[0];
                var outputName = Path.GetFileNameWithoutExtension(path) + ".xml";
                using (var reader = File.OpenText(path))
                {
                    var processor = new SemanticProcessor<BaseToken>(reader, actions);
                    ParseMessage parseMessage = processor.ParseAll();
                    if (parseMessage == ParseMessage.Accept)
                    {
                        Console.WriteLine("Parsing done.");
                        var compilationModel = new CompilationModel(File.ReadAllLines(path));
                        var start = (Start)processor.CurrentToken;
                        start.Compile(compilationModel); // first classes, fields and methods needs to be compiled
                        compilationModel.Compile(); // after that compile method body
                        Console.WriteLine("Compiling done.");

                        using (var outfile = new StreamWriter(outputName))
                        {
                            outfile.Write(compilationModel.ToXml());
                        }

                        // PrintAst(start); // only for debugging
                    }
                    else
                    {
                        IToken token = processor.CurrentToken;
                        Console.WriteLine(token.Symbol);
                        Console.WriteLine("Error: Line: {0} Column: {1} Error: {2}", token.Position.Line, token.Position.Column, parseMessage);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error" + e.Message);
            }
        }
		public void ParseNull() {
			using (TestStringReader reader = new TestStringReader("NULL")) {
				SemanticProcessor<TestToken> processor = new SemanticProcessor<TestToken>(reader, actions);
				Assert.Equal(ParseMessage.Accept, processor.ParseAll());
				Assert.IsType<TestEmpty>(processor.CurrentToken);
				Assert.False((processor.CurrentToken is TestSpecial) && ((TestSpecial)processor.CurrentToken).IsString);
			}
		}
		public void ParseSimpleExpression() {
			using (TestStringReader reader = new TestStringReader("100")) {
				SemanticProcessor<TestToken> processor = new SemanticProcessor<TestToken>(reader, actions);
				Assert.Equal(ParseMessage.Accept, processor.ParseAll());
				Assert.IsAssignableFrom<TestValue>(processor.CurrentToken);
				TestValue value = (TestValue)processor.CurrentToken;
				Assert.Equal(100, value.Compute());
			}
		}
		public void ParseComplexExpression() {
			using (TestStringReader reader = new TestStringReader("((100+5.0)/\r\n(4.5+.5))-\r\n12345.4e+1")) {
				SemanticProcessor<TestToken> processor = new SemanticProcessor<TestToken>(reader, actions);
				Assert.Equal(ParseMessage.Accept, processor.ParseAll());
				Assert.IsAssignableFrom<TestValue>(processor.CurrentToken);
				TestValue value = (TestValue)processor.CurrentToken;
				Assert.Equal(-123433.0, value.Compute());
			}
		}
예제 #12
0
			public static bool Parse(Stream stream) {
				CompiledGrammar grammar = CompiledGrammar.Load(typeof(TestUnicode), "TestUnicode.egt"); // embedded resource
				SemanticTypeActions<TestToken> actions = new SemanticTypeActions<TestToken>(grammar);
				actions.Initialize(true);
				using (StreamReader reader = new StreamReader(stream)) // defaults to UTF-8
				{
					SemanticProcessor<TestToken> processor = new SemanticProcessor<TestToken>(reader, actions);
					ParseMessage parseMessage = processor.ParseAll();
					return (parseMessage == ParseMessage.Accept);
				}
			}
예제 #13
0
		public static ParsedLine Parse(string line) {
			if (line == null) {
				throw new ArgumentNullException("line");
			}
			using (StringReader reader = new StringReader(line)) {
				SemanticProcessor<CliToken> processor = new SemanticProcessor<CliToken>(reader, GetSemanticActions());
				ParseMessage result = processor.ParseAll();
				if (result != ParseMessage.Accept) {
					throw new FormatException(string.Format("The given string could not be parsed: {0} at position {1}", result, ((IToken)processor.CurrentToken).Position.Index+1));
				}
				return (ParsedLine)processor.CurrentToken;
			}
		}
예제 #14
0
        public static void Execute(string filePath)
        {
            if (grammarActions == null)
            {
                init();
            }

            ExecutionContext.Reset();

            //create default base context
            ExecutionContext.EnterLevel();
            (ExecutionContext.Current.DefaultBroker as FileBlockBroker).SetLibFolder(DefaultBlocksPath);

            ScriptReader reader = new ScriptReader(filePath);
            SemanticProcessor<Token> processor = new SemanticProcessor<Token>(reader, grammarActions);
            ParseMessage parseMessage = processor.ParseAll();

            reader.Close();

            if (parseMessage != ParseMessage.Accept)
            {
                string newLine = "\n";
                string errorMessage = parseMessage.ToString()+".";
                string location = string.Format("Expecting one of following tokens at Line {0}, Column {1}:", processor.CurrentToken.Line, processor.CurrentToken.Column);
                string symbols = "";
                foreach (Symbol s in processor.GetExpectedTokens())
                {
                    string txt = "\t'" + s.Name + "' of type " + s.Kind.ToString()+newLine;
                    symbols += txt;
                }

                throw new Exception(errorMessage+newLine+location+newLine+symbols);
            }

            Optional<TokenList<CommandHandler>> optCommands = processor.CurrentToken as Optional<TokenList<CommandHandler>>;

            if (optCommands.HasValue)
            {
                TokenList<CommandHandler> commands = optCommands.Value;

                foreach (CommandHandler command in commands)
                {
                    command.Execute();
                }
            }
        }
예제 #15
0
 public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
     Match output = Regex.Match(message.Body, @"^!(?:calc|eval) (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
     if (output.Success) {
         String exp = output.Groups[1].Value;
         SemanticProcessor<MathToken> processor = new SemanticProcessor<MathToken>(new StringReader(exp), actions);
         ParseMessage parseMessage = processor.ParseAll();
         if (parseMessage == ParseMessage.Accept) {
             message.Chat.SendMessage(
                 String.Format(
                     "{0} = {1}",
                     exp,
                     ((Computable)processor.CurrentToken).GetValue()));
         } else {
             IToken token = processor.CurrentToken;
             message.Chat.SendMessage(string.Format("{0} ({1} on line {2}, column {3})",
                                                    parseMessage, token.Symbol,
                                                    token.Position.Line, token.Position.Column));
         }
     }
 }
예제 #16
0
		private static void Main(string[] args) {
			Console.WriteLine("*** CALCULATOR SAMPLE *** (input formula, empty line terminates)");
			CompiledGrammar grammar = CompiledGrammar.Load(typeof(CalculatorToken), "Calculator.cgt");
			SemanticTypeActions<CalculatorToken> actions = new SemanticTypeActions<CalculatorToken>(grammar);
			try {
				actions.Initialize(true);
			} catch (InvalidOperationException ex) {
				Console.Write(ex.Message);
				Console.ReadKey(true);
				return;
			}
			for (string formula = Console.ReadLine(); !string.IsNullOrEmpty(formula); formula = Console.ReadLine()) {
				SemanticProcessor<CalculatorToken> processor = new SemanticProcessor<CalculatorToken>(new StringReader(formula), actions);
				ParseMessage parseMessage = processor.ParseAll();
				if (parseMessage == ParseMessage.Accept) {
					Console.WriteLine(string.Format(NumberFormatInfo.InvariantInfo, "Result: {0}", ((Computable)processor.CurrentToken).GetValue()));
				} else {
					IToken token = processor.CurrentToken;
					Console.WriteLine(string.Format("{0} {1}", "^".PadLeft(token.Position.Column), parseMessage));
				}
			}
		}