コード例 #1
0
ファイル: TikzParser.cs プロジェクト: wilsoc5/tikzedt
        //static public string TIKZEDT_CMD_COMMENT = "";

        public static Tikz_ParseTree ParseInputFile(string code)
        {
            //if code is empty to bother ANTLR (it will raise an exception)
            if (code.Trim() == "")
            {
                return(null);
            }

            simpletikzLexer   lex    = new simpletikzLexer(new ANTLRStringStream(code));
            CommonTokenStream tokens = new CommonTokenStream(lex);
            simpletikzParser  parser = new simpletikzParser(tokens);

            simpletikzParser.tikzdocument_wo_tikzpicture_return ret = parser.tikzdocument_wo_tikzpicture();
            CommonTree     t       = (CommonTree)ret.Tree;
            Tikz_ParseTree root    = new Tikz_ParseTree();
            bool           success = FillItem(root, t, tokens);

            if (success)
            {
                root.RegisterNodeAndStyleRefs(); // make a list with all node names for later reference
                return(root);
            }
            else
            {
                return(null);
            }
        }
コード例 #2
0
        public void ParseTest4()
        {
            string code =
                @"%some text
\begin{tikzpicture}[scale=2]
\draw (1,2) node (v) {bla} -- (3,3);
\end{tikzpicture}
";
            Tikz_ParseTree actual = TikzParser.Parse(code);

            Tikz_Picture tp = actual.GetTikzPicture();
            Tikz_Node    n  = tp.GetNodeByName("v");

            System.Windows.Point p;
            bool ret = n.GetAbsPos(out p);

            Assert.IsTrue(ret);
            Assert.AreEqual(2, p.X);
            Assert.AreEqual(4, p.Y);
            Assert.AreEqual("bla", n.label);
        }
コード例 #3
0
        public void ParseTestStyleDetection()
        {
            string code =
                @"
\tikzstyle{test 1}=[draw]
%!TE% \tikzset{ test   2 /.style={draw}}
\begin{tikzpicture}[test   3/.style={draw}]
\tikzstyle{test 4}=[draw]
\tikzset{   test   5/.style={draw}}

\end{tikzpicture}
";
            Tikz_ParseTree T = TikzParser.Parse(code);

            Assert.AreEqual <int>(5, T.styles.Count);

            // check whether style names are stored with whitespace removed
            for (int i = 1; i <= 5; i++)
            {
                Assert.IsTrue(T.styles.ContainsKey("test " + i));
            }
        }
コード例 #4
0
        public void ParseTest2()
        {
            string code =
                @"\begin{tikzpicture}
\draw (1,2) -- (3,3);
\end{tikzpicture}
";
            Tikz_ParseTree actual = TikzParser.Parse(code);

            Tikz_Picture tp = actual.GetTikzPicture();

            Assert.AreEqual(0, tp.StartPosition());
            Tikz_Path tpa = tp.Children.Find(tpi => tpi is Tikz_Path) as Tikz_Path;

            Assert.AreEqual(21, tpa.StartPosition());
            Tikz_Coord tc = tpa.Children.Find(tpi => tpi is Tikz_Coord) as Tikz_Coord;

            Assert.AreEqual(1, tc.uX.number);
            Assert.AreEqual(2, tc.uY.number);

            Assert.AreEqual(27, tc.StartPosition());
        }
コード例 #5
0
ファイル: OverlayTool.cs プロジェクト: wilsoc5/tikzedt
        protected bool EnsureParseTreeExists()
        {
            // Try to create a new ParseTree
            if (overlay.ParseTree == null)
            {
                // TODO
                return(false);

                //TryCreateNew(this, out lret);
                if (overlay.AllowEditing)
                {
                    // create a new parsetree
                    Tikz_ParseTree t  = new Tikz_ParseTree();
                    Tikz_Picture   tp = new Tikz_Picture();
                    tp.starttag = "\\begin{tikzpicture}";
                    tp.AddChild(new Tikz_Something("\r\n"));
                    tp.endtag = "\\end{tikzpicture}";

                    overlay.BeginUpdate();

                    //      overlay.ParseTree = t;
                    t.AddChild(tp);
                    tp.UpdateText();

                    overlay.EndUpdate();
                    return(true);
                }
                else
                {
                    GlobalUI.ShowMessageBox("Parse tree could not be created. Please correct all parser errors in the code and try again.", "Function not available", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return(false);
                }
            }
            else
            {
                return(true);
            }
        }
コード例 #6
0
        /// <summary>
        /// Scans for duplicate node names in the parse tree and changes them to make them unique.
        /// Also updates references.
        /// </summary>
        /// <param name="tp"></param>
        public static void UniquefyNodeNames(Tikz_ParseTree tpt)
        {
            if (tpt == null)
            {
                return;
            }

            Dictionary <string, Tikz_Node> nodelist = new Dictionary <string, Tikz_Node>();

            Tikz_Picture tp = tpt.GetTikzPicture();

            if (tp == null)
            {
                return;
            }

            tpt.BeginModify();
            // clear current node refs
            tp.nodelist.Clear();
            // scan for nodes, rename and re-register noderefs
            ScanTree(tp, nodelist, tp);
            tpt.EndModify();
        }
コード例 #7
0
        void AsyncParser_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            AsyncParserResultType Result = e.Result as AsyncParserResultType;

            if (Result == null)
            {
                throw new Exception("AsyncParser_RunWorkerCompleted() can only handle e.Result  of type AsyncParserResultType!");
            }

            // in case of outdated parse -> ignore
            if (Result.DocumentID != DocumentID)
            {
                return;
            }

            //check if error occurred
            if (Result.Error != null && Result.Error is RecognitionException)
            {
                RecognitionException ex = Result.Error as RecognitionException;
                string errmsg           = ANTLRErrorMsg.ToString(ex, simpletikzParser.tokenNames);
                MainWindow.AddStatusLine("Couldn't parse code. " + errmsg, true);
                if (ex.Line == 0 && ex.CharPositionInLine == -1)
                {
                    addProblemMarker(errmsg, Document.LineCount, 0, Severity.ERROR, ShortFileName);
                }
                else
                {
                    addProblemMarker(errmsg, ex.Line, ex.CharPositionInLine, Severity.ERROR, ShortFileName);
                }
                ParseTree = null;
                TikzStyles.Clear();
            }
            else if (Result.Error != null)
            {
                string errmsg = Result.Error.GetType().ToString();
                if (Result.Error is Exception)
                {
                    errmsg += ":" + ((Exception)Result.Error).Message;
                }
                MainWindow.AddStatusLine("Couldn't parse code. " + errmsg, true);
                ParseTree = null;
                TikzStyles.Clear();
            }
            else
            {
                // parsing succesfull
                Tikz_ParseTree tp = Result.ParseTree as Tikz_ParseTree;
                ParseTree = tp;

                // if no other changes are pending, we can turn on editing again
                AllowEditing = true;

                // fill the style list
                UpdateStyleList();

                //now check if a warning occured. That would be a parser error in an included file.
                if (Result.Warning != null && Result.Warning is RecognitionException)
                {
                    RecognitionException ex = Result.Warning as RecognitionException;
                    string errmsg           = ANTLRErrorMsg.ToString(ex, simpletikzParser.tokenNames);
                    MainWindow.AddStatusLine("Couldn't parse included file. " + errmsg, true);
                    if (ex.Line == 0 && ex.CharPositionInLine == -1)
                    {
                        addProblemMarker(errmsg, Document.LineCount, 0, Severity.WARNING, Result.WarningSource);
                    }
                    else
                    {
                        addProblemMarker(errmsg, ex.Line, ex.CharPositionInLine, Severity.WARNING, Result.WarningSource);
                    }
                }
                else if (Result.Warning != null && Result.Warning is ParserException)
                {
                    ParserException pe = Result.Warning as ParserException;
                    addProblemMarker(this, pe.e);
                }
                else if (Result.Warning != null && Result.Warning is Exception)
                {
                    string errmsg = ((Exception)Result.Warning).Message;
                    MainWindow.AddStatusLine("Couldn't parse included file " + Result.WarningSource + ". " + errmsg, true);
                }
            }

            // Restart parser if necessary
            ParseNeeded = ParseNeeded;
        }
コード例 #8
0
        void AsyncParser_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            AsyncParserResultType Result = new AsyncParserResultType();

            //make sure that double typed numbers are converted with decimal point (not comma!) to string
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

            try
            {
                AsyncParserJob job = e.Argument as AsyncParserJob;
                Result.DocumentID = job.DocumentID;
                Tikz_ParseTree tp = TikzParser.Parse(job.code);
                Result.ParseTree = tp;

                //include any styles from include files via \input cmd
                string inputfile = "";
                try
                {
                    //find input files using Regex
                    MatchCollection files = InputsRegex.Matches(job.code);
                    foreach (Match file in files)
                    {
                        //open, read, parse, and close each included file.
                        inputfile = file.Groups["file"].ToString();
                        if (File.Exists(inputfile))
                        {
                            StreamReader sr        = new StreamReader(inputfile);
                            string       inputcode = sr.ReadToEnd();
                            sr.Close();
                            Tikz_ParseTree tp2 = TikzParser.ParseInputFile(inputcode);
                            //if tp2 == null there probably was nothing useful included.
                            if (tp2 != null)
                            {
                                //every style that was found in included file, add it to parse tree of main file.
                                foreach (KeyValuePair <string, Tikz_Option> style in tp2.styles)
                                {
                                    if (!Result.ParseTree.styles.ContainsKey(style.Key))
                                    {
                                        Result.ParseTree.styles.Add(style.Key, style.Value);
                                    }
                                    else
                                    {
                                        ParserException          pe = new ParserException("");
                                        TexOutputParser.TexError te = new TexOutputParser.TexError();
                                        te.Message  = "Style [" + style.Key + "] is defined multiple times. Check position " + style.Value.StartPosition() + " in " + inputfile + " and this definition.";
                                        te.pos      = Result.ParseTree.styles[style.Key].StartPosition();
                                        te.severity = Severity.WARNING;
                                        pe.e        = te;
                                        throw pe;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Result.Warning       = ex;
                    Result.WarningSource = inputfile;
                }
            }
            catch (Exception ex)
            {
                //never set e.Cancel = true;
                //if you do, you cannot access e.Result from AsyncParser_RunWorkerCompleted.
                Result.Error         = ex;
                Result.WarningSource = ShortFileName;
            }
            finally
            {
                e.Result = Result;
            }
        }
コード例 #9
0
ファイル: TikzParser.cs プロジェクト: wilsoc5/tikzedt
        public static Tikz_ParseTree Parse(string code)
        {
            code = PrepareCodeForParsing(code);

            //if code is empty to bother ANTLR (it will raise an exception)
            if (code.Trim() == "")
            {
                return(null);
            }

            simpletikzLexer   lex    = new simpletikzLexer(new ANTLRStringStream(code));
            CommonTokenStream tokens = new CommonTokenStream(lex);

            //for (int i = 0; i < tokens.Count; i++)
            //{
            //    string ds = tokens.Get(i).Text;
            //    ds = ds + "eee";
            //}

            simpletikzParser parser = new simpletikzParser(tokens);

            //tikzgrammarParser.expr_return r =
            simpletikzParser.tikzdocument_return ret = parser.tikzdocument();

            //CommonTreeAdaptor adaptor = new CommonTreeAdaptor();
            CommonTree t = (CommonTree)ret.Tree;
            //MessageBox.Show(printTree(t,0));



/*
 *      public string printTree(CommonTree t, int indent)
 *      {
 *          string s="";
 *          if ( t != null ) {
 *                      for ( int i = 0; i < indent; i++ )
 *                              s = s+"   ";
 *
 *              string r = "";// s + t.ToString() + "\r\n";
 *
 *              if (t.ChildCount >0)
 *                          foreach ( object o in t.Children ) {
 *                                  r=r+s+o.ToString()+"\r\n" + printTree((CommonTree)o, indent+1);
 *                  }
 *
 *              return r;
 *          }  else return "";
 *              }
 *  }*/


            Tikz_ParseTree root = new Tikz_ParseTree();

            bool success = FillItem(root, t, tokens);


            // mockup
            //t.Children.Add(new Tikz_Node(0, 0));
            //t.Children.Add(new Tikz_Node(5, 5));
            //t.Children.Add(new Tikz_Node(6, 8));
            //t.Children.Add(new Tikz_Node(8, 8));
            if (success)
            {
                root.RegisterNodeAndStyleRefs(); // make a list with all node names for later reference
                return(root);
            }
            else
            {
                return(null);
            }
        }