public bool TryParse(string sourceText, out MarkupExtension graph)
        {
            graph = null;

            try
            {
                ParseTree tree = _parser.Parse(sourceText);
            #if DEBUG
                // Save result tree for debugging purposes
                LastParseTree = tree;
                LastException = null;
            #endif
                if (tree.Status == ParseTreeStatus.Parsed)
                {
                    graph = MarkupExtension.Create(tree.Root);
                    return true;
                }
            }
            #if DEBUG
            catch (Exception ex)
            {
                LastParseTree = null;
                LastException = ex;
            }
            #else
            catch
            {
                // ignored
            }
            #endif
            return false;
        }
 public override void BuildAst(LanguageData language, ParseTree parseTree) {
   var opHandler = new OperatorHandler(language.Grammar.CaseSensitive);
   Util.Check(!parseTree.HasErrors(), "ParseTree has errors, cannot build AST.");
   var astContext = new InterpreterAstContext(language, opHandler);
   var astBuilder = new AstBuilder(astContext);
   astBuilder.BuildAst(parseTree);
 }
Example #3
0
 public virtual void BuildAst(LanguageData language, ParseTree parseTree)
 {
     if (!LanguageFlags.IsSet(LanguageFlags.CreateAst))
         return;
     var astContext = new AstContext(language);
     var astBuilder = new AstBuilder(astContext);
     astBuilder.BuildAst(parseTree);
 }
    public virtual string RunSample(RunSampleArgs args) {
      if (_app == null || args.ParsedSample != _prevSample)
        _app = new ScriptApp(args.Language); 
      _prevSample = args.ParsedSample;

      //for (int i = 0; i < 1000; i++)  //for perf measurements, to execute 1000 times
        _app.Evaluate(args.ParsedSample);
      return _app.OutputBuffer.ToString();
    }
Example #5
0
 private string NormalizeParseTree(ParseTree tree) {
     StringBuilder fullString = new StringBuilder();
     foreach (ParseTreeNode node in tree.Root.ChildNodes) {
         fullString.Append(node.Token.Value);
     }
     fullString = fullString.Replace("\r\n", "\\n");
     fullString = fullString.Replace("\n", "\\n");
     return fullString.ToString();
 }
Example #6
0
 public virtual void BuildAst(ParseTree parseTree) {
   if (parseTree.Root == null)
     return; 
   Context.Messages = parseTree.ParserMessages;
   if (!Context.Language.AstDataVerified)
     VerifyLanguageData();
   if (Context.Language.ErrorLevel == GrammarErrorLevel.Error)
     return; 
   BuildAst(parseTree.Root);
 }
Example #7
0
 //Note: we don't actually parse in current version, only scan. Will implement full parsing in the future,
 // to support all intellisense operations
 private  void ParseSource(string newText) {
   //Explicitly catch the case when new text is empty
   if (newText != string.Empty) {
     _parseTree = _parser.Parse(newText);// .ScanOnly(newText, "Source");
   }
   //notify views
   var views = GetViews();
   foreach (var view in views)
     view.UpdateParsedSource(_parseTree);
 }
Example #8
0
 public Block ParseString(string Chunk)
 {
     var parseTree = parser.Parse(Chunk);
     curParseTree = parseTree;
     var root = parseTree.Root;
     if (root == null)
     {
         var msg = parseTree.ParserMessages[0];
         throw new LuaException("", msg.Location.Line, msg.Location.Column, msg.Message);
     }
     return (ParseBlock(root));
 }
Example #9
0
        /// <summary>
        /// クエリを指定して初期化します。
        /// </summary>
        /// <param name="query">クエリ</param>
        public Kbtter3Query(string query)
        {
            Kbtter3QueryGrammar g = new Kbtter3QueryGrammar();
            Parser ps = new Parser(g);
            Variables = new Dictionary<string, Kbtter3QueryValue>();

            Tree = ps.Parse(query);
            if (Tree.Root == null)
            {
                throw new InvalidOperationException(Tree.ParserMessages[0].Message);
            }
        }
Example #10
0
 private string GetParserMessages(ParseTree parseTree)
 {
     var sb = new StringBuilder();
     foreach (var message in parseTree.ParserMessages)
     {
         sb.AppendFormat("{0} at line {1}, column {2}", message.Message, message.Location.Line, message.Location.Column);
     }
     sb.AppendLine();
     sb.AppendLine("Source Code:");
     sb.AppendLine();
     sb.Append(parseTree.SourceText);
     return sb.ToString();
 }
Example #11
0
 public Block ParseFile(string Filename)
 {
     var source = File.ReadAllText(Filename);
     var parseTree = parser.Parse(source, Filename);
     curParseTree = parseTree;
     var root = parseTree.Root;
     if (root == null)
     {
         var msg = parseTree.ParserMessages[0];
         throw new LuaException(Filename, msg.Location.Line, msg.Location.Column, msg.Message);
     }
     return (ParseBlock(root));
 }
Example #12
0
        public void Refresh(ParseTree tree)
        {
            var root = tree.Root;
            if (root != null)
            {
                File = new LuaFile(FileManager.Instance.CurrentFile.File, tree.Tokens); ;

                RefreshTree(root);

                FileManager.Instance.CurrentFile = File;

                System.Diagnostics.Debug.Print("file refreshed.");
            }
        }
Example #13
0
        public sqlStmtParser(string tempstmt)
        {
            this.nowStmt = ReplaceQues(tempstmt);

            this.parser = new Parser(new SqlGrammar());
            this.wholeTree = parser.Parse(nowStmt);
            //Some non-typical sql couldn't be parsed right now
            if (wholeTree.Root != null)
            {
                this.isStmt = true;
                this.stmtType = wholeTree.Root.ChildNodes.First();
                this.stmtPoints = stmtType.ChildNodes;

            }
        }
        private Expression Analyze(ParseTree tree, CompilerState state)
        {
            if (tree == null)
            {
                throw new ArgumentNullException("tree");
            }

            if (tree.Status != ParseTreeStatus.Parsed)
            {
                throw new ArgumentException("Cannot build expression on incomplete tree");
            }

            var root = tree.Root;
            return Analyze(root, state);
        }
Example #15
0
        /// <summary>
        /// Reads a Dql query into an abstract syntax tree.
        /// </summary>
        /// <param name="query">Dql query.</param>
        /// <param name="node">The current abstract syntax tree to construct.</param>
        /// <returns>Time taken to build the abstract syntax tree in milliseconds.</returns>
        public long Read(string query, out ParseTree node)
        {
            var parser = new Parser(language);
            var tree = parser.Parse(query);

            if (tree.HasErrors())
            {
                // TODO: Throw LQL errors.
                throw new InvalidOperationException();
            }

#if DEBUG
            this.DisplayTree(tree.Root, 0);
#endif
            node = tree;
            return tree.ParseTimeMilliseconds;
        }
 public void ParseSample(string code)
 {
     if (parser == null || !parser.Language.CanParse()) return;
     ParseTree = null;
     GC.Collect(); //to avoid disruption of perf times with occasional collections
     parser.Context.TracingEnabled = false;//parsetrace not needed for us
     try {
         parser.Parse(code, "<source>");
     }
     catch (Exception ex) {
         Console.WriteLine(ex.Message);
         throw;
     }
     finally {
         ParseTree = parser.Context.CurrentParseTree;
     }
 }
Example #17
0
        public CodeCompileUnit GenerateCode(ParseTree tree)
        {
            var generator = new RuleCodeGenerator();
            var unit = new CodeCompileUnit();
            var ns = new CodeNamespace(GetType().Namespace);
            ns.Imports.Add(new CodeNamespaceImport(GetType().Namespace));

            var rules = tree.Root.ChildNodes[0].ChildNodes;
            var count = 1;
            foreach (var rule in rules)
            {
                ns.Types.Add(generator.GenerateRuleClass("Rule" + count, rule));
                count++;
            }

            unit.Namespaces.Add(ns);
            return unit;
        }
 public void SetUp()
 {
     // Given
     _grammar = new GherkinGrammar();
      _parser = new Parser(_grammar);
     _parseTree = _parser
                         .Parse("# language: en\n" +
                                "# some other remark\n" +
                                "Feature: bla bla\n" +
                                "    as a ...\n" +
                                "    i want to ...\n" +
                                "    so that I ...\n" +
                                " Scenario: first\n" +
                                "    Given a\n" +
                                "    When  b\n" +
                                "    Then  c\n" +
                                " Scenario: second\n" +
                                "    Given x\n" +
                                "    When  y\n" +
                                "    Then  z\n");
 }
Example #19
0
        public static LPModel ConvertParseTreeToModel(ParseTree tree)
        {
            string modelName = "";
            var lpGoal = new LPGoal();
            var lpConstraints = new List<LPConstraint>();

            if (tree.Root.ToString() == "lpApp")
            {
                foreach (ParseTreeNode node in tree.Root.ChildNodes)
                {
                    switch (node.ToString())
                    {
                        case "lpAppName":
                            modelName = ParseModelName(node);
                            break;
                        case "lpModel":
                            foreach (ParseTreeNode subNodes in node.ChildNodes)
                            {
                                switch (subNodes.ToString())
                                {
                                    case "lpGoal":
                                        lpGoal = ParseGoal(subNodes);
                                        break;
                                    case "lpConstraints":
                                        lpConstraints = ParseConstraints(subNodes);
                                        break;
                                }
                            }
                            break;
                    }
                }
            }
            else
            {
                throw new Exception("The Root element is not Correct");
            }

            return new LPModel(modelName.Replace("(appIdentifier)", "").Replace(" ", ""), lpGoal, lpConstraints);
        }
Example #20
0
        public void Generate(ParseTree parseTree) {
            if (parseTree == null) return;
            GeneratedOK = true;
            defaultClass = ag.Public.Class("Default");
            typeTable.Add("Default", defaultClass);
            mainMethod = defaultClass.Public.Static.Method(typeof(void), "Main");

            //generator stack
            typeStack.Push(defaultClass);
            funcStack.Push(mainMethod);

            //InitIO();
            InitRequiredType();
            PushScope();
            var ioOperand = mainMethod.Local(exp.New(typeTable["IO"]));

            ParseNode(parseTree.Root);
            
            if (GeneratedOK) {
                ag.Save();
                AppDomain.CurrentDomain.ExecuteAssembly(name + ".exe");
            }
        }
 private void CreateParser()
 {
     ParseTree = null;
     language = new LanguageData(grammar);
     parser = new Parser(language);
 }
Example #22
0
 public object Evaluate(ParseTree parsedScript)
 {
     var result = App.Evaluate(parsedScript);
       return result;
 }
Example #23
0
 public void Validate(ParseTree parseTree)
 {
     if (parseTree.HasErrors() && parseTree.ParserMessages.Count > 0)
     {
         var message = parseTree.ParserMessages[0];
         var error = message.Message + " at " + message.Location.ToUiString();
         throw new Exception(error);
     }
 }
Example #24
0
 public override string RunSample(ParseTree parsedSample)
 {
     var converter = new WikiHtmlConverter();
       var html = converter.Convert(this, parsedSample.Tokens);
       var path = Path.Combine(Path.GetTempPath(), "@wikiSample.html");
       File.WriteAllText(path, html);
       System.Diagnostics.Process.Start(path);
       return html;
 }
Example #25
0
 private void txtSource_TextChanged(object sender, FastColoredTextBoxNS.TextChangedEventArgs e) {
   _parseTree = null; //force it to recompile on run
 }
Example #26
0
 private void LoadSourceFile(string path) {
   _parseTree = null;
   StreamReader reader = null;
   try {
     reader = new StreamReader(path);
     txtSource.Text = null;  //to clear any old formatting
     txtSource.ClearUndo();
     txtSource.ClearStylesBuffer();
     txtSource.Text = reader.ReadToEnd();
     txtSource.SetVisibleState(0, FastColoredTextBoxNS.VisibleState.Visible);
     txtSource.Selection = txtSource.GetRange(0, 0);
   } catch (Exception e) {
     MessageBox.Show(e.Message);
   } finally {
     if (reader != null)
       reader.Close();
   }
 }
Example #27
0
 private void ParseSample() {
   ClearParserOutput();
   if (_parser == null || !_parser.Language.CanParse()) return;
   _parseTree = null;
   GC.Collect(); //to avoid disruption of perf times with occasional collections
   _parser.Context.TracingEnabled = chkParserTrace.Checked;
   try {
     _parser.Parse(txtSource.Text, "<source>");
   } catch (Exception ex) {
     gridCompileErrors.Rows.Add(null, ex.Message, null);
     tabBottom.SelectedTab = pageParserOutput;
     throw;
   } finally {
     _parseTree = _parser.Context.CurrentParseTree;
     ShowCompilerErrors();
     if (chkParserTrace.Checked) {
       ShowParseTrace();
     }
     ShowCompileStats();
     ShowParseTree();
     ShowAstTree();
   }
 }
Example #28
0
    private void CreateParser() {
      StopHighlighter();
      btnRun.Enabled = false;
      txtOutput.Text = string.Empty;
      _parseTree = null;

      btnRun.Enabled = _grammar is ICanRunSample;
      _language = new LanguageData(_grammar);
      _parser = new Parser (_language);
      ShowParserConstructionResults();
      StartHighlighter();
    }
Example #29
0
 public AstBuilder(PowerShellGrammar grammar, ParseTree parseTree)
 {
     _grammar = grammar;
     _parseTree = parseTree;
 }
Example #30
0
 public void EvaluateAsync(ParseTree parsedScript) {
   ParsedScript = parsedScript;
   EvaluateAsync(); 
 }
Example #31
0
 public ParseTree(Irony.Parsing.ParseTree parseTree)
 {
     this.parseTree = parseTree;
 }