public void DifferentLanguageTest() { generator.GenerateSrcMLFromFile("srcmltest\\CSHARP.cs", "srcml_xml\\differentlanguage_java.xml", Language.Java); var doc = new SrcMLFile("srcml_xml\\differentlanguage_java.xml"); Assert.IsNotNull(doc); }
public void MultipleFilesTest_Language() { generator.GenerateSrcMLFromFiles(new string[] { "srcmltest\\foo.c", "srcmltest\\bar.c" }, "srcml_xml\\multiplefile.xml", Language.CPlusPlus); var doc = new SrcMLFile("srcml_xml\\multiplefile.xml"); Assert.IsNotNull(doc); var files = doc.FileUnits.ToList(); Assert.AreEqual(2, files.Count()); string file = "srcmltest\\foo.c"; var f1 = (from ele in files where ele.Attribute("filename").Value == file select ele); Assert.AreEqual("srcmltest\\foo.c", f1.FirstOrDefault().Attribute("filename").Value); Assert.AreEqual("C++", f1.FirstOrDefault().Attribute("language").Value); string file2 = "srcmltest\\bar.c"; var f2 = (from ele in files where ele.Attribute("filename").Value == file2 select ele); Assert.AreEqual("srcmltest\\bar.c", f2.FirstOrDefault().Attribute("filename").Value); Assert.AreEqual("C++", f2.FirstOrDefault().Attribute("language").Value); }
public void BasicTest() { if (!File.Exists(Helper.NppXmlPath)) { Assert.Ignore(String.Format("SrcML for Notepad++ is not available at {0}", Helper.NppXmlPath)); } var document = new SrcMLFile(Helper.NppXmlPath); var newUses = from unit in document.FileUnits from use in QueryForNew(unit) select use; SyntaticCategoryDataModel model = new SyntaticCategoryDataModel(); foreach (var element in newUses) { var occurrence = new SyntaticOccurance(model, element); } //Console.WriteLine("{0} uses of the \"new\" operator in {1} categories", newUses.Count(), model.SyntaticCategories.Keys.Count); foreach (var category in model.SyntaticCategories.Keys) { var xpath = model.SyntaticCategories[category].First().CategoryAsXPath;//.Substring(1); var results = from use in newUses let occurrence = new SyntaticOccurance(model, use) where occurrence.CategoryAsXPath == xpath select use; //Console.WriteLine("{0,3} uses of the new operator in {1}", results.Count(), xpath); Assert.AreEqual(model.SyntaticCategories[category].Count, results.Count(), category); } }
private void srcmlGenWorker_DoWork(object sender, DoWorkEventArgs e) { Object[] array = new Object[2]; DirectoryInfo source = e.Argument as DirectoryInfo; var docPath = getPathFor(source); if (null == docPath) { docPath = Path.GetTempFileName(); } array[0] = source as Object; try { var so = new SrcML(); SrcMLFile doc = so.GenerateSrcMLFromDirectory(source.FullName, docPath); array[1] = (doc == null ? null : doc.FileName as Object); } catch (TargetInvocationException ex) { MessageBox.Show(String.Format("Could not load {0}: {1}", source.FullName, ex.Message)); } catch (SrcMLException ex) { MessageBox.Show(String.Format("Could not load {0}: {1}", source.FullName, ex.Message)); } e.Result = array; }
private void exportSourceWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Object[] results = e.Result as Object[]; DirectoryInfo outputDir = results[0] as DirectoryInfo; SrcMLFile outputDoc = results[1] as SrcMLFile; Dictionary <String, Exception> errors = results[2] as Dictionary <String, Exception>; addNewSourceFolder(outputDir); generatingSource = false; runTransformButton.Text = Resources.ExecuteButton; progressBar.Value = 0; if (0 == errors.Count) { messageLabel.Text = "Wrote source to " + outputDir; } else if (errors.Count < outputDoc.FileUnits.Count()) { messageLabel.Text = String.Format("Wrote Source to {0}. Could not write {1} / {2} files", outputDir, errors.Count, outputDoc.FileUnits.Count()); } else { messageLabel.Text = "Could not write any files to " + outputDir; } progressLabel.Text = ""; OnSrcMLFileCreatedEvent(new SrcMLFileCreatedEventArgs(outputDoc.FileName)); setButtons(); }
public void TestApplyXsltToSrcMLFile() { LibSrcMLRunner run = new LibSrcMLRunner(); Assert.IsTrue(File.Exists("function_def.xml")); Assert.IsTrue(File.Exists("Test.xsl")); run.ApplyXsltToSrcMLFile("function_def.xml", "Test.xsl", "o.cpp.xml"); SrcMLFile srcFile = new SrcMLFile("o.cpp.xml.xslout"); Assert.IsNotNull(srcFile); var files = srcFile.FileUnits.ToList(); Assert.AreEqual(1, files.Count()); XmlReader read = srcFile.GetXDocument().CreateReader(); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(read.NameTable); namespaceManager.AddNamespace("src", "http://www.srcML.org/srcML/src"); var persist = srcFile.GetXDocument().XPathSelectElement("//src:test", namespaceManager); Assert.IsNotNull(persist); Assert.AreEqual(persist.Value, "TestPassed"); }
public void TestGenerateSrcMLFromFile() { LibSrcMLRunner run = new LibSrcMLRunner(); try { run.GenerateSrcMLFromFile(Path.Combine(TestInputPath, "input.cpp"), "output", Language.CPlusPlus, new List <UInt32>() { LibSrcMLRunner.SrcMLOptions.SRCML_OPTION_MODIFIER }, new Dictionary <string, Language>() { }); Assert.True(File.Exists("output0.cpp.xml")); SrcMLFile srcFile = new SrcMLFile("output0.cpp.xml"); Assert.IsNotNull(srcFile); var files = srcFile.FileUnits.ToList(); Assert.AreEqual(1, files.Count()); string file = Path.Combine(TestInputPath, "input.cpp"); var f1 = (from ele in files where ele.Attribute("filename").Value == file select ele); Assert.AreEqual(file, f1.FirstOrDefault().Attribute("filename").Value); } catch (SrcMLException e) { throw new SrcMLException(e.Message, e); } }
public void TestGenerateSrcMLFromFile_NonDefaultExtension() { generator.GenerateSrcMLFromFile(@"srcmltest\CSHARP.cs", @"srcml_xml\CSHARP.xml"); var doc = new SrcMLFile(@"srcml_xml\CSHARP.xml"); Assert.IsNotNull(doc); Assert.AreEqual(1, doc.FileUnits.Count()); }
public void InputWithSpacesTest() { generator.GenerateSrcMLFromFile("srcmltest\\File with spaces.cpp", "srcml_xml\\input_with_spaces.xml"); var doc = new SrcMLFile("srcml_xml\\input_with_spaces.xml"); Assert.IsNotNull(doc); Assert.AreEqual(1, doc.FileUnits.Count()); }
public void TestStrangeEncodings([Values(@"badPathTest\BadPath™\badPathTest.c", @"srcmltest\fooBody.c")] string sourceFileName) { var xmlFileName = Path.Combine("srcml_xml", Path.GetFileName(Path.ChangeExtension(sourceFileName, ".xml"))); generator.GenerateSrcMLFromFile(sourceFileName, xmlFileName, Language.C); var doc = new SrcMLFile(xmlFileName); Assert.IsNotNull(doc); }
public Archive(SrcMLFile document) : this() { if (null == document) throw new ArgumentNullException("document"); this.Path = document.FileName; this.LastUpdated = System.IO.File.GetLastWriteTime(this.Path); }
public void TestCreateSrcMLArchiveMtF() { using (Archive srcmlArchive = new Archive()) { List <String> bufferList = new List <String>(); List <String> fileList = new List <String>(); String str = "int main(){int c; c = 0; ++c;}"; String str2 = "int foo(){int c; c = 0; ++c;}"; fileList.Add("input.cpp"); fileList.Add("input2.cpp"); bufferList.Add(str); bufferList.Add(str2); var buffandfile = bufferList.Zip(fileList, (b, f) => new { buf = b, file = f }); foreach (var pair in buffandfile) { using (Unit srcmlUnit = new Unit()) { srcmlUnit.SetUnitBuffer(pair.buf); srcmlUnit.SetUnitFilename(pair.file); srcmlArchive.SetArchiveLanguage(LibSrcMLRunner.SrcMLLanguages.SRCML_LANGUAGE_CXX); srcmlArchive.AddUnit(srcmlUnit); } } srcmlArchive.SetOutputFile("output"); srcmlArchive.ArchivePack(); IntPtr structPtr = srcmlArchive.GetPtrToStruct(); List <IntPtr> structArrayPtr = new List <IntPtr>(); structArrayPtr.Add(structPtr); Assert.True(LibSrcMLRunner.SrcmlCreateArchiveMtF(structArrayPtr.ToArray(), structArrayPtr.Count()) == IntPtr.Zero); Assert.True(File.Exists("output0.cpp.xml")); SrcMLFile srcFile = new SrcMLFile("output0.cpp.xml"); Assert.IsNotNull(srcFile); var files = srcFile.FileUnits.ToList(); Assert.AreEqual(2, files.Count()); string file = "input.cpp"; var f1 = (from ele in files where ele.Attribute("filename").Value == file select ele); Assert.AreEqual("input.cpp", f1.FirstOrDefault().Attribute("filename").Value); string file2 = "input2.cpp"; var f2 = (from ele in files where ele.Attribute("filename").Value == file2 select ele); Assert.AreEqual(file2, f2.FirstOrDefault().Attribute("filename").Value); } }
public void SingleFileTest() { File.WriteAllText("test.xml", String.Format(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <unit xmlns=""{0}"" xmlns:cpp=""{1}"" xmlns:op=""{2}"" xmlns:type=""{3}"" languageFilter=""C++"" dir="""" filename=""bar.c""> </unit>", SRC.NS, CPP.NS, SRC.NS, TYPE.NS)); var doc = new SrcMLFile("test.xml"); Assert.IsNotNull(doc); Assert.AreEqual(1, doc.FileUnits.Count(), "A non-compound file should have only a single file unit"); }
public void SingleFileTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <unit xmlns=""http://www.sdml.info/srcML/src"" xmlns:cpp=""http://www.sdml.info/srcML/cpp"" xmlns:op=""http://www.sdml.info/srcML/operator"" xmlns:type=""http://www.sdml.info/srcML/modifier"" languageFilter=""C++"" dir="""" filename=""bar.c""> </unit>"); var doc = new SrcMLFile("test.xml"); Assert.IsNotNull(doc); Assert.AreEqual(1, doc.FileUnits.Count(), "A non-compound file should have only a single file unit"); }
public void EmptyOutputFileTest() { File.WriteAllText("srcml_xml\\emptyFile.xml", ""); Assert.IsTrue(File.Exists("srcml_xml\\emptyFile.xml")); generator.GenerateSrcMLFromFile("srcmltest\\foo.c", "srcml_xml\\emptyFile.xml"); var doc = new SrcMLFile("srcml_xml\\emptyFile.xml"); Assert.IsNotNull(doc); Assert.AreEqual(1, doc.FileUnits.Count()); }
public void DisjunctMergedFileTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""utf-8""?><unit xmlns=""http://www.sdml.info/srcML/src""> <unit languageFilter=""C"" filename=""c:\Test\foo.c""></unit> <unit languageFilter=""C"" filename=""z:\Release\bar.c""></unit> </unit>"); var doc = new SrcMLFile("test.xml"); Assert.IsNotNull(doc); Assert.IsNull(doc.ProjectDirectory, String.Format("The ProjectDirectory property should be null when there is no common path. ({0})", doc.ProjectDirectory)); }
public void CompoundFileTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""utf-8""?><unit xmlns=""http://www.sdml.info/srcML/src""> <unit languageFilter=""C"" dir="""" filename=""foo.c""></unit> <unit languageFilter=""C"" dir="""" filename=""bar.c""></unit> </unit>"); var doc = new SrcMLFile("test.xml"); Assert.IsNotNull(doc); Assert.AreEqual(2, doc.FileUnits.Count(), "This compound file should have 2 units."); }
public static void SrcML2Src([Required(Description = "SrcML folder containing the source code")] string fileName, [Optional(null, Description = "Folder to write the source code to. Default: original folder")] string outputFolder) { string workingFileName = (null == outputFolder ? fileName : Path.GetTempFileName()); if (null != outputFolder) { File.Copy(fileName, workingFileName, true); } try { SrcMLFile doc = new SrcMLFile(workingFileName); if (null != outputFolder) { doc.ProjectDirectory = outputFolder; } try { doc.ExportSource(); } catch (IOException e) { Console.Error.WriteLine("IO Exception {0}", e.Message); } //if (1 == errors.Count) // Console.Error.WriteLine("Could not write {0}", errors[0]); //else if (1 < errors.Count) //{ // Console.Error.WriteLine("Could not write the following {0} files:", errors.Count); // foreach (var error in errors) // Console.Error.WriteLine("\t{0}", error); //} if (null != outputFolder) { File.Delete(workingFileName); } } catch (SrcMLException ex) { Console.Error.WriteLine("Could not read {0}: {1}", fileName, ex.Message); } catch (IOException ex) { Console.WriteLine(ex.Message); } }
private void queryWorker_DoWork(object sender, DoWorkEventArgs e) { Object[] args = e.Argument as Object[]; SrcMLFile doc = new SrcMLFile(args[0] as string); ITransform transform = args[1] as ITransform; SyntaticCategoryDataModel categories = new SyntaticCategoryDataModel(); List <DataCell> data = executeTransform(doc, transform, ref categories, sender as BackgroundWorker); Object[] results = { doc, data, categories }; e.Result = results; }
public void MultipleFilesTest_Language() { generator.GenerateSrcMLFromFiles(new string[] { "srcmltest\\foo.c", "srcmltest\\bar.c" }, "srcml_xml\\multiplefile.xml", Language.CPlusPlus); var doc = new SrcMLFile("srcml_xml\\multiplefile.xml"); Assert.IsNotNull(doc); var files = doc.FileUnits.ToList(); Assert.AreEqual(2, files.Count()); Assert.AreEqual("srcmltest\\foo.c", files[0].Attribute("filename").Value); Assert.AreEqual("C++", files[0].Attribute("language").Value); Assert.AreEqual("srcmltest\\bar.c", files[1].Attribute("filename").Value); Assert.AreEqual("C++", files[1].Attribute("language").Value); }
public void EmptyElementTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""utf-8""?> <unit xmlns=""http://www.sdml.info/srcML/src""> <unit languageFilter=""C"" dir=""c:\Test"" filename=""beforeBlank.c""><expr_stmt /></unit> <unit languageFilter=""C"" dir=""c:\Test"" filename=""foo.c"" /> <unit languageFilter=""C"" dir=""c:\Test"" filename=""bar.c""><comment type=""line"">//line1</comment> <comment type=""line"">//line2</comment> </unit> </unit>"); var doc = new SrcMLFile("test.xml"); Assert.AreEqual(3, doc.FileUnits.Count()); }
public void TestGetDefinitionForMethodCall_function() { SrcMLFile src = new SrcMLFile(@"..\..\TestInputs\function_def.xml"); SrcMLDataContext srcDb = SrcMLDataContext.CreateDatabaseConnection("SrcMLDataContextTests", true); srcDb.Load(src.FileName); var file = src.FileUnits.First(); var calls = file.Descendants(SRC.Call).ToList(); Assert.AreEqual(1, calls.Count); MethodDefinition md = srcDb.GetDefinitionForMethodCall(calls[0]); Console.WriteLine("Method call: {0}", calls[0].Value); Console.WriteLine("Matched defintion on line {0}: {1}", md.LineNumber, md.MethodSignature); Assert.AreEqual(3, md.LineNumber); }
/// <summary> /// Initializes a new instance of the <see cref="CallGraph"/> class. /// </summary> /// <param name="xmlFileName">Name of the XML file.</param> /// <param name="db">The db.</param> public CallGraph(string xmlFileName, SrcMLDataContext db) { this._xmlFileName = xmlFileName; this._document = new SrcMLFile(xmlFileName); var methods = FetchMethods(db, xmlFileName); this.methodMap = new Dictionary<int, MethodDefinition>(); this.signatureMap = new Dictionary<string, int>(); foreach (var method in methods) { methodMap[method.Id] = method; signatureMap[method.MethodSignature] = method.Id; } this.edgeSet = new HashSet<Tuple<int, int>>(FetchEdgeSet(db, xmlFileName)); FetchCalleeLists(db); FetchCallerLists(db); }
public void WhitespaceInSingleDocumentTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""utf-8""?> <unit xmlns=""http://www.sdml.info/srcML/src"" languageFilter=""C"" dir=""c:\Test"" filename=""foo.c""><comment type=""line"">//line1</comment> <comment type=""line"">//line2</comment> </unit>"); var doc = new SrcMLFile("test.xml"); var firstUnit = doc.FileUnits.First(); var firstComment = firstUnit.Elements(SRC.Comment).First(); var lastComment = firstUnit.Elements(SRC.Comment).Last(); var nextNode = firstComment.NextNode; Assert.AreNotEqual(lastComment, nextNode); }
public void InvalidLanguageTest() { generator.GenerateSrcMLFromFile("srcmltest\\foo.c", "srcml_xml\\invalidlanguage_java.xml", Language.Java); var doc = new SrcMLFile("srcml_xml\\invalidlanguage_java.xml"); Assert.IsNotNull(doc); doc = null; generator.GenerateSrcMLFromFile("srcmltest\\foo.c", "srcml_xml\\invalidlanguage_cpp.xml", Language.CPlusPlus); doc = new SrcMLFile("srcml_xml\\invalidlanguage_cpp.xml"); Assert.IsNotNull(doc); doc = null; generator.GenerateSrcMLFromFile("srcmltest\\foo.c", "srcml_xml\\invalidlanguage_c.xml", Language.C); doc = new SrcMLFile("srcml_xml\\invalidlanguage_c.xml"); Assert.IsNotNull(doc); }
public void GetXPathExtensionTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""utf-8""?> <unit xmlns=""http://www.srcML.org/srcML/src"" xmlns:cpp=""http://www.srcML.org/srcML/cpp""> <unit languageFilter=""C"" filename=""c:\Test\myapp.c""> <cpp:include>#<cpp:directive>include</cpp:directive> <cpp:file><stdio.h></cpp:file></cpp:include> <function_decl><type><name>void</name></type> <name>foo</name><parameter_list>(<param><decl><type><name>int</name></type> <name>a</name></decl></param>, <param><decl><type><name>int</name></type> <name>b</name></decl></param>)</parameter_list>;</function_decl> <method><type><name>int</name></type> <name>main</name><parameter_list>(<param><decl><type><name>int</name></type> <name>argc</name></decl></param>, <param><decl><type><name>char</name> **</type><name>argv</name></decl></param>)</parameter_list> <block>{ <expr_stmt><expr><call><name>foo</name><argument_list>(<argument><expr><call><name>atoi</name><argument_list>(<argument><expr><name><name>argv</name><index>[<expr>1</expr>]</index></name></expr></argument>)</argument_list></call></expr></argument>, <argument><expr><call><name>atoi</name><argument_list>(<argument><expr><name><name>argv</name><index>[<expr>2</expr>]</index></name></expr></argument>)</argument_list></call></expr></argument>)</argument_list></call></expr>;</expr_stmt> <expr_stmt><expr><call><name>printf</name><argument_list>(<argument><expr>""Finished with %s and %s""</expr></argument>, <argument><expr><name><name>argv</name><index>[<expr>1</expr>]</index></name></expr></argument>, <argument><expr><name><name>argv</name><index>[<expr>2</expr>]</index></name></expr></argument>)</argument_list></call></expr>;</expr_stmt> <return>return <expr>0</expr>;</return> }</block></method> <method><type><name>void</name></type> <name>foo</name><parameter_list>(<param><decl><type><name>int</name></type> <name>a</name></decl></param>, <param><decl><type><name>int</name></type> <name>b</name></decl></param>)</parameter_list> <block>{ <for>for(<init><decl><type><name>int</name></type> <name>i</name> =<init> <expr><name>a</name></expr></init></decl>;</init> <condition><expr><name>i</name> < <name>b</name></expr>;</condition> <incr><expr><name>i</name>++</expr></incr>) <block>{ <expr_stmt><expr><call><name>printf</name><argument_list>(<argument><expr><name>i</name></expr></argument>)</argument_list></call></expr>;</expr_stmt> }</block></for> }</block></method> </unit> <unit languageFilter=""C"" filename=""c:\Test\bar.c""><comment type=""line"">//line1</comment> <comment type=""line"">//line2</comment> </unit> </unit>"); SrcMLFile doc = new SrcMLFile("test.xml"); foreach (var unit in doc.FileUnits) { foreach (var element in unit.Descendants()) { var xpath = element.GetXPath(); // Console.WriteLine("{0}: {1}\n", element.ToSource(), xpath); var elementsFromXPath = unit.XPathSelectElements(xpath, SrcML.NamespaceManager); Assert.AreEqual(1, elementsFromXPath.Count()); Assert.AreEqual(element, elementsFromXPath.First()); } } }
public override void Execute() { Console.WriteLine("Using srcML file {0}", this.File); UnigramSwumBuilder builder = new UnigramSwumBuilder(); if (CountFile != null) { Console.WriteLine("Initializing SamuraiIdSplitter using word count file {0}", this.CountFile); builder.Splitter = new SamuraiIdSplitter(CountFile); } Console.WriteLine("SwumBuilder initialized"); if (this.SamplePercent <= 0) { this.SamplePercent = 100; } Random rand = new Random(); SrcMLFile testFile = new SrcMLFile(this.File); int methodCount = 0; var functionTypes = new XName[] { SRC.Function, SRC.Constructor, SRC.Destructor }; foreach (XElement file in testFile.FileUnits) { Console.WriteLine("File {0}:", file.Attribute("filename").Value); //print all the function names foreach (var func in (from func in file.Descendants() where functionTypes.Any(c => c == func.Name) && !func.Ancestors(SRC.Declaration).Any() && (rand.Next(100) < this.SamplePercent) select func)) { string funcName = SrcMLElement.GetNameForMethod(func).Value; Console.WriteLine("<{0}> {1}", func.Name.LocalName, GetMethodSignature(func)); MethodDeclarationNode mdn = new MethodDeclarationNode(funcName, ContextBuilder.BuildMethodContext(func)); builder.ApplyRules(mdn); Console.WriteLine(mdn.ToString() + Environment.NewLine); methodCount++; } } Console.WriteLine("{0} functions analyzed", methodCount); }
public void GetXPathExtensionTest() { File.WriteAllText("test.xml", @"<?xml version=""1.0"" encoding=""utf-8""?> <unit xmlns=""http://www.sdml.info/srcML/src"" xmlns:cpp=""http://www.sdml.info/srcML/cpp""> <unit languageFilter=""C"" filename=""c:\Test\myapp.c""> <cpp:include>#<cpp:directive>include</cpp:directive> <cpp:file><stdio.h></cpp:file></cpp:include> <function_decl><type><name>void</name></type> <name>foo</name><parameter_list>(<param><decl><type><name>int</name></type> <name>a</name></decl></param>, <param><decl><type><name>int</name></type> <name>b</name></decl></param>)</parameter_list>;</function_decl> <method><type><name>int</name></type> <name>main</name><parameter_list>(<param><decl><type><name>int</name></type> <name>argc</name></decl></param>, <param><decl><type><name>char</name> **</type><name>argv</name></decl></param>)</parameter_list> <block>{ <expr_stmt><expr><call><name>foo</name><argument_list>(<argument><expr><call><name>atoi</name><argument_list>(<argument><expr><name><name>argv</name><index>[<expr>1</expr>]</index></name></expr></argument>)</argument_list></call></expr></argument>, <argument><expr><call><name>atoi</name><argument_list>(<argument><expr><name><name>argv</name><index>[<expr>2</expr>]</index></name></expr></argument>)</argument_list></call></expr></argument>)</argument_list></call></expr>;</expr_stmt> <expr_stmt><expr><call><name>printf</name><argument_list>(<argument><expr>""Finished with %s and %s""</expr></argument>, <argument><expr><name><name>argv</name><index>[<expr>1</expr>]</index></name></expr></argument>, <argument><expr><name><name>argv</name><index>[<expr>2</expr>]</index></name></expr></argument>)</argument_list></call></expr>;</expr_stmt> <return>return <expr>0</expr>;</return> }</block></method> <method><type><name>void</name></type> <name>foo</name><parameter_list>(<param><decl><type><name>int</name></type> <name>a</name></decl></param>, <param><decl><type><name>int</name></type> <name>b</name></decl></param>)</parameter_list> <block>{ <for>for(<init><decl><type><name>int</name></type> <name>i</name> =<init> <expr><name>a</name></expr></init></decl>;</init> <condition><expr><name>i</name> < <name>b</name></expr>;</condition> <incr><expr><name>i</name>++</expr></incr>) <block>{ <expr_stmt><expr><call><name>printf</name><argument_list>(<argument><expr><name>i</name></expr></argument>)</argument_list></call></expr>;</expr_stmt> }</block></for> }</block></method> </unit> <unit languageFilter=""C"" filename=""c:\Test\bar.c""><comment type=""line"">//line1</comment> <comment type=""line"">//line2</comment> </unit> </unit>"); SrcMLFile doc = new SrcMLFile("test.xml"); foreach (var unit in doc.FileUnits) { foreach (var element in unit.Descendants()) { var xpath = element.GetXPath(); // Console.WriteLine("{0}: {1}\n", element.ToSource(), xpath); var elementsFromXPath = unit.XPathSelectElements(xpath, SrcML.NamespaceManager); Assert.AreEqual(1, elementsFromXPath.Count()); Assert.AreEqual(element, elementsFromXPath.First()); } } }
public void WhitespaceInCompoundDocumentTest() { File.WriteAllText("test.xml", String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?><unit xmlns=""{0}""> <unit languageFilter=""C"" filename=""c:\Test\foo.c""> <comment type=""line"">//line1</comment> <comment type=""line"">//line2</comment> </unit> <unit languageFilter=""C"" filename=""z:\Test\bar.c""></unit> </unit>", SRC.NS)); var doc = new SrcMLFile("test.xml"); var firstUnit = doc.FileUnits.First(); var firstComment = firstUnit.Elements(SRC.Comment).First(); var lastComment = firstUnit.Elements(SRC.Comment).Last(); var nextNode = firstComment.NextNode; Assert.AreNotEqual(lastComment, nextNode); }
public void TestGetDeclarationForVariableName() { SrcMLFile src = new SrcMLFile(@"..\..\TestInputs\foo.xml"); SrcMLDataContext srcDb = SrcMLDataContext.CreateDatabaseConnection("SrcMLDataContextTests", true); srcDb.Load(src.FileName); var file = src.FileUnits.First(); var varNames = (from name in file.Descendants(SRC.Name) where name.Parent.Name == SRC.Expression select name).ToList(); Assert.AreEqual(3, varNames.Count, "Wrong number of variable usages found"); var varDecl = srcDb.GetDeclarationForVariableName(varNames[0]); Assert.AreEqual(1, varDecl.LineNumber); varDecl = srcDb.GetDeclarationForVariableName(varNames[1]); Assert.AreEqual(5, varDecl.LineNumber); varDecl = srcDb.GetDeclarationForVariableName(varNames[2]); Assert.AreEqual(5, varDecl.LineNumber); }
private void queryWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Object[] results = e.Result as Object[]; this.selectedDoc = results[0] as SrcMLFile; this.data = results[1] as List <DataCell>; this.categories = results[2] as SyntaticCategoryDataModel; int count = 0; if (null != this.data) { dataGridView1.DataSource = this.data; count = this.data.Count; } if (null != this.categories) { CategoryTreeNode root = new CategoryTreeNode("All"); categoryTreeView.BeginUpdate(); categoryTreeView.Nodes.Clear(); categoryTreeView.Nodes.Add(root); foreach (var category in categories.SyntaticCategories.Keys) { var xpath = categories.SyntaticCategories[category].First().CategoryAsXPath; var categoryCount = categories.SyntaticCategories[category].Count; root.AddCategory(xpath, categoryCount); } categoryTreeView.SelectedNode = root; categoryTreeView.EndUpdate(); } queryingXML = false; runQueryButton.Text = Resources.TestButton; progressBar.Value = 0; progressLabel.Text = ""; messageLabel.Text = String.Format("Found {0} items.", count); setButtons(); }
private void srcmlLoadWorker_DoWork(object sender, DoWorkEventArgs e) { List <FileInfo> srcmldocs = e.Argument as List <FileInfo>; Dictionary <DirectoryInfo, string> results = new Dictionary <DirectoryInfo, string>(); int i = 0; float count = (float)srcmldocs.Count; foreach (var fi in srcmldocs) { var path = fi.FullName; if (File.Exists(path)) { try { var srcml = new SrcMLFile(path); if (null != srcml.ProjectDirectory) { var sourceFolder = new DirectoryInfo(srcml.ProjectDirectory); results[sourceFolder] = path; } } catch (XmlException ex) { MessageBox.Show(String.Format("Error Loading {0}: {1}", path, ex.Message)); } catch (OutOfMemoryException ex) { MessageBox.Show(String.Format("Error Loading {0}: {1}", path, ex.Message)); } catch (SrcMLException ex) { MessageBox.Show(String.Format("Error Loading {0}: {1}", path, ex.Message)); } } srcmlLoadWorker.ReportProgress((int)(100 * (float)++i / count)); } e.Result = results as Object; }
public void TestGetDeclarationForVariableName_NestedScopes() { SrcMLFile src = new SrcMLFile(@"..\..\TestInputs\nested_scopes.xml"); SrcMLDataContext srcDb = SrcMLDataContext.CreateDatabaseConnection("SrcMLDataContextTests", true); srcDb.Load(src.FileName); var file = src.FileUnits.First(); var varNames = (from name in file.Descendants(SRC.Name) where name.Parent.Name == SRC.Expression select name).ToList(); int[] declLineNumbers = new int[] { 1, 6, 5, 6, 9, 4 }; Assert.AreEqual(declLineNumbers.Length, varNames.Count, "Wrong number of variable usages found"); for(int i = 0; i < varNames.Count; i++) { var decl = srcDb.GetDeclarationForVariableName(varNames[i]); Assert.IsNotNull(decl, string.Format("No declaration found for {0}", varNames[i])); Assert.AreEqual(declLineNumbers[i], decl.LineNumber); } }
public DataCell(SrcMLFile doc, XElement xe, ITransform transform, SyntaticOccurance occurrence) { this.doc = doc; this.node = xe; this.transform = transform; this.occurrence = occurrence; this.Xml.AddAnnotation(new DataEnabledAnnotation()); this.location = doc.RelativePath(node); this.lineNumber = xe.GetSrcLineNumber(); if (xe.Descendants().Any()) { this.endLineNumber = xe.Descendants().Last().GetSrcLineNumber(); } else { this.endLineNumber = this.lineNumber; } if (null != this.Xml && null != this.Transform) { try { this.text = Xml.ToSource(4); var nodeCopy = new XElement(this.node); var transformedNode = this.transform.Transform(nodeCopy); this.Xml.AddAnnotation(new DataTransformAnnotation(transformedNode)); transformedText = transformedNode.ToSource(4); } catch (Exception e) { error = String.Format("{0}: {1} ({2})", e.Source, e.Message, e.GetType().ToString()); this.Enabled = false; } } }
private static List <DataCell> executeTransform(SrcMLFile doc, ITransform transform, ref SyntaticCategoryDataModel categories, BackgroundWorker worker) { IEnumerable <XElement> elements; List <DataCell> data = null; if (null != transform) { try { elements = doc.QueryEachUnit(transform); if (null != elements) { float numElements = (float)elements.Count(); int i = 0, percentComplete = 0; data = new List <DataCell>(); foreach (var node in elements) { var occurrence = new SyntaticOccurance(categories, node); categories.AddOccurance(occurrence); data.Add(new DataCell(doc, node, transform, occurrence)); percentComplete = (int)((float)++i / numElements * 100); worker.ReportProgress(percentComplete); } foreach (var d in data) { d.Enabled = true; } } } catch (Exception e) { MessageBox.Show(String.Format("{0}: {1}\n{2}", e.Source, e.Message, e.StackTrace)); } } return(data); }
public static void Stats([Required(Description = "Path to srcML file")] string fileName, [Optional(null, Description = "Path to write output to (standard out by default)")] string outputPath) { SrcMLFile doc = new SrcMLFile(fileName); int numFileUnits = doc.FileUnits.Count(); var dict = GenerateUnitChildDictionary(doc); using (var output = (null == outputPath ? Console.Out : new StreamWriter(outputPath))) { output.WriteLine("{0} has {1} files containing", Path.GetFileName(doc.FileName), numFileUnits); var numChildren = (from list in dict.Values select list.Count).Sum(); var sortedKeys = from key in dict.Keys orderby dict[key].Count descending select key; foreach (var key in sortedKeys) { int count = dict[key].Count; var percentage = ((float)count / numChildren) * 100; output.WriteLine("\t{0,10} ({1,5:f2}%) {2} elements", count, percentage, key.LocalName); } } }
private static List<DataCell> executeTransform(SrcMLFile doc, ITransform transform, ref SyntaticCategoryDataModel categories, BackgroundWorker worker) { IEnumerable<XElement> elements; List<DataCell> data = null; if (null != transform) { try { elements = doc.QueryEachUnit(transform); if (null != elements) { float numElements = (float)elements.Count(); int i = 0, percentComplete = 0; data = new List<DataCell>(); foreach (var node in elements) { var occurrence = new SyntaticOccurance(categories, node); categories.AddOccurance(occurrence); data.Add(new DataCell(doc, node, transform, occurrence)); percentComplete = (int)((float)++i / numElements * 100); worker.ReportProgress(percentComplete); } foreach (var d in data) d.Enabled = true; } } catch (Exception e) { MessageBox.Show(String.Format("{0}: {1}\n{2}", e.Source, e.Message, e.StackTrace)); } } return data; }
public void TestGetDefinitionForMethodCall_methods() { SrcMLFile src = new SrcMLFile(@"..\..\TestInputs\method_def.xml"); SrcMLDataContext srcDb = SrcMLDataContext.CreateDatabaseConnection("SrcMLDataContextTests", true); srcDb.Load(src.FileName); var file = src.FileUnits.First(); var calls = file.Descendants(SRC.Call).ToList(); Assert.AreEqual(4, calls.Count); int[] declLineNumbers = new int[] { 10, 21, 17, 21 }; for(int i = 0; i < declLineNumbers.Length; i++) { MethodDefinition md = srcDb.GetDefinitionForMethodCall(calls[i]); Console.WriteLine("Method call on line {0}: {1}", calls[i].GetSrcLineNumber(), calls[i].Value); Console.WriteLine("Matched defintion on line {0}: {1}", md.LineNumber, md.MethodSignature); Assert.AreEqual(declLineNumbers[i], md.LineNumber); } }
private void exportSourceWorker_DoWork(object sender, DoWorkEventArgs e) { Object[] args = e.Argument as Object[]; Object[] results = new Object[3]; List<DataCell> queryResults = args[0] as List<DataCell>; SrcMLFile doc = args[1] as SrcMLFile; DirectoryInfo target = args[2] as DirectoryInfo; SrcMLFile output; Dictionary<String, Exception> errors = new Dictionary<string, Exception>(); var outputDoc = getPathFor(target); if (null != queryResults) { // get the files that contain the changes the user wants to make // put the files in a list -- this takes more memory, but will be stable //var units = (from node in queryResults // select (node.Enabled ? node.TransformedXml : node.Xml).Ancestors(SRC.Unit).First()).Distinct().ToList(); var units = (from node in queryResults where node.Enabled where node.TransformedXml != null where node.TransformedXml.Ancestors(SRC.Unit).Any() select node.TransformedXml.Ancestors(SRC.Unit).First()).Distinct().ToList(); doc.Save(outputDoc, units); output = new SrcMLFile(outputDoc); output.ProjectDirectory = target.FullName; float numUnits = output.FileUnits.Count(); int unitsProcessed = 0; int percentComplete = 0; foreach (var unit in output.FileUnits) { var filename = unit.Attribute("filename").Value; FileInfo fileInfo = new FileInfo(filename); try { Directory.CreateDirectory(fileInfo.DirectoryName); File.WriteAllText(filename, unit.ToSource(), Encoding.UTF8); percentComplete = (++unitsProcessed / (int)numUnits); exportSourceWorker.ReportProgress(percentComplete); } catch (UnauthorizedAccessException uae) { errors[filename] = uae; } } results[0] = target as Object; results[1] = output as Object; results[2] = errors as Object; } e.Result = results as Object; }
private void queryWorker_DoWork(object sender, DoWorkEventArgs e) { Object[] args = e.Argument as Object[]; SrcMLFile doc = new SrcMLFile(args[0] as string); ITransform transform = args[1] as ITransform; SyntaticCategoryDataModel categories = new SyntaticCategoryDataModel(); List<DataCell> data = executeTransform(doc, transform, ref categories, sender as BackgroundWorker); Object[] results = { doc, data, categories }; e.Result = results; }
private void queryWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Object[] results = e.Result as Object[]; this.selectedDoc = results[0] as SrcMLFile; this.data = results[1] as List<DataCell>; this.categories = results[2] as SyntaticCategoryDataModel; int count = 0; if (null != this.data) { dataGridView1.DataSource = this.data; count = this.data.Count; } if (null != this.categories) { CategoryTreeNode root = new CategoryTreeNode("All"); categoryTreeView.BeginUpdate(); categoryTreeView.Nodes.Clear(); categoryTreeView.Nodes.Add(root); foreach (var category in categories.SyntaticCategories.Keys) { var xpath = categories.SyntaticCategories[category].First().CategoryAsXPath; var categoryCount = categories.SyntaticCategories[category].Count; root.AddCategory(xpath, categoryCount); } categoryTreeView.SelectedNode = root; categoryTreeView.EndUpdate(); } queryingXML = false; runQueryButton.Text = Resources.TestButton; progressBar.Value = 0; progressLabel.Text = ""; messageLabel.Text = String.Format("Found {0} items.", count); setButtons(); }
private void srcmlLoadWorker_DoWork(object sender, DoWorkEventArgs e) { List<FileInfo> srcmldocs = e.Argument as List<FileInfo>; Dictionary<DirectoryInfo, string> results = new Dictionary<DirectoryInfo, string>(); int i = 0; float count = (float) srcmldocs.Count; foreach (var fi in srcmldocs) { var path = fi.FullName; if (File.Exists(path)) { try { var srcml = new SrcMLFile(path); if (null != srcml.ProjectDirectory) { var sourceFolder = new DirectoryInfo(srcml.ProjectDirectory); results[sourceFolder] = path; } } catch (XmlException ex) { MessageBox.Show(String.Format("Error Loading {0}: {1}", path, ex.Message)); } catch (OutOfMemoryException ex) { MessageBox.Show(String.Format("Error Loading {0}: {1}", path, ex.Message)); } catch (SrcMLException ex) { MessageBox.Show(String.Format("Error Loading {0}: {1}", path, ex.Message)); } } srcmlLoadWorker.ReportProgress((int)(100 * (float)++i / count)); } e.Result = results as Object; }
public DataCell(SrcMLFile doc, XElement xe, ITransform transform, SyntaticOccurance occurrence) { this.doc = doc; this.node = xe; this.transform = transform; this.occurrence = occurrence; this.Xml.AddAnnotation(new DataEnabledAnnotation()); this.location = doc.RelativePath(node); this.lineNumber = xe.GetSrcLineNumber(); if (xe.Descendants().Any()) { this.endLineNumber = xe.Descendants().Last().GetSrcLineNumber(); } else { this.endLineNumber = this.lineNumber; } if (null != this.Xml && null != this.Transform) { try { this.text = Xml.ToSource(4); var nodeCopy = new XElement(this.node); var transformedNode = this.transform.Transform(nodeCopy); this.Xml.AddAnnotation(new DataTransformAnnotation(transformedNode)); transformedText = transformedNode.ToSource(4); } catch (Exception e) { error = String.Format("{0}: {1} ({2})", e.Source, e.Message, e.GetType().ToString()); this.Enabled = false; } } }