public void UsingAliasDeclarationTest()
        {
            string program = "using TESTME=System;\n" +
                             "using myAlias=My.Name.Space;\n" +
                             "using StringCollection = System.Collections.Generic.List<string>;\n";
            CSharpParser    parser = new CSharpParser();
            CompilationUnit cu     = parser.Parse(new StringReader(program));

            Assert.IsFalse(parser.HasErrors);

            Assert.AreEqual(3, cu.Children.Count());

            Assert.IsTrue(cu.Children.ElementAt(0) is UsingAliasDeclaration);
            UsingAliasDeclaration ud = (UsingAliasDeclaration)cu.Children.ElementAt(0);

            Assert.AreEqual("TESTME", ud.Alias);
            Assert.AreEqual("System", ud.Import.ToString());

            Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration);
            ud = (UsingAliasDeclaration)cu.Children.ElementAt(1);
            Assert.AreEqual("myAlias", ud.Alias);
            Assert.AreEqual("My.Name.Space", ud.Import.ToString());

            Assert.IsTrue(cu.Children.ElementAt(2) is UsingAliasDeclaration);
            ud = (UsingAliasDeclaration)cu.Children.ElementAt(2);
            Assert.AreEqual("StringCollection", ud.Alias);
            Assert.AreEqual("System.Collections.Generic.List<string>", ud.Import.ToString());
        }
        public string GetHtmlForCsxContent(string csxContent, string baseReferencePath = null,
                                           bool failOnCompileWarning = false, bool failOnCompileError = true)
        {
            var parser           = new CSharpParser();
            var annotationResult = parser.Parse(csxContent, baseReferencePath);

            var errors = new List <string>();

            foreach (var r in annotationResult.DiagnosticResults)
            {
                if (failOnCompileError && r.Severity == Common.DiagnosticSeverity.Error)
                {
                    errors.Add(r.Message);
                }

                if (failOnCompileWarning && r.Severity == Common.DiagnosticSeverity.Warning)
                {
                    errors.Add(r.Message);
                }
            }
            if (errors.Any())
            {
                throw new CompilationErrorException(errors);
            }

            var exportedHtml = new HtmlExporter().ExportAnnotationResult(annotationResult.TextChunks.Cast <IChunk>());

            return(exportedHtml);
        }
Exemple #3
0
        public MethodResult ExtractPrototypeAndMethod(string code)
        {
            var @class     = "class A { " + code + " } ";
            var visitor    = new MethodVisitor();
            var parser     = new CSharpParser();
            var syntaxTree = parser.Parse(@class);

            syntaxTree.AcceptVisitor(visitor);
            syntaxTree.Freeze();

            var result = visitor.GetMethodDeclarations().FirstOrDefault();

            // find newlines in method signature to maintain linenumbers
            var newLines = code.Substring(0, code.IndexOf("{", StringComparison.Ordinal) - 1)
                           .Where(x => x.Equals('\n'))
                           .Aggregate(string.Empty, (a, c) => a + c);

            // use code methodblock to maintain linenumbers
            var codeBlock  = code.Substring(code.IndexOf("{", StringComparison.Ordinal), code.LastIndexOf("}", StringComparison.Ordinal) - code.IndexOf("{", StringComparison.Ordinal) + 1);
            var method     = result.MethodExpression.GetText();
            var blockStart = method.IndexOf("{", StringComparison.Ordinal);
            var blockEnd   = method.LastIndexOf("}", StringComparison.Ordinal);

            method = method.Remove(blockStart, blockEnd - blockStart + 1);
            method = method.Insert(blockStart, codeBlock);

            return(new MethodResult
            {
                ProtoType = result.MethodPrototype.GetText().Trim() + newLines,
                MethodExpression = newLines + method.Trim()
            });
        }
Exemple #4
0
        public CSharpFile(CSharpProject project, string fileName)
        {
            this.Project  = project;
            this.FileName = fileName;

            CSharpParser p = new CSharpParser(project.CompilerSettings);

//			using (var stream = File.OpenRead(fileName)) {
//				this.CompilationUnit = p.Parse(stream, fileName);
//			}

            // Keep the original text around; we might use it for a refactoring later
            this.OriginalText = File.ReadAllText(fileName);
            this.SyntaxTree   = p.Parse(this.OriginalText, fileName);

            if (p.HasErrors)
            {
                Console.WriteLine("Error parsing " + fileName + ":");
                foreach (var error in p.ErrorsAndWarnings)
                {
                    Console.WriteLine("  " + error.Region + " " + error.Message);
                }
            }
            this.UnresolvedTypeSystemForFile = this.SyntaxTree.ToTypeSystem();
        }
        public void TestIfForcementWithComment()
        {
            TextEditorData data = new TextEditorData();

            data.Document.FileName = "a.cs";
            data.Document.Text     = @"class Test
{
	void TestMethod ()
	{
		if (true) // TestComment
			Call ();
	}
}";

            CSharpFormattingPolicy policy = new CSharpFormattingPolicy();

            policy.StatementBraceStyle  = BraceStyle.EndOfLine;
            policy.IfElseBraceForcement = BraceForcement.AddBraces;
            CSharpParser parser          = new CSharpParser();
            var          compilationUnit = parser.Parse(data);

            TestErrors(parser);
            compilationUnit.AcceptVisitor(new AstIndentationVisitor(policy, data), null);
            System.Console.WriteLine(data.Document.Text);
            Assert.AreEqual(@"class Test
{
	void TestMethod ()
	{
		if (true) {
			// TestComment
			Call ();
		}
	}
}", data.Document.Text);
        }
Exemple #6
0
        protected override void Run()
        {
            MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
            CSharpParser parser = new CSharpParser();
            var          unit   = parser.Parse(doc.Editor);

            if (unit == null)
            {
                return;
            }
            var node = unit.GetNodeAt(doc.Editor.Caret.Line, doc.Editor.Caret.Column);

            if (node == null)
            {
                return;
            }

            if (doc.Editor.IsSomethingSelected)
            {
                while (node != null && doc.Editor.MainSelection.IsSelected(node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column))
                {
                    node = node.Parent;
                }
            }

            if (node != null)
            {
                doc.Editor.SetSelection(node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column);
            }
        }
Exemple #7
0
        public IEnumerable <ContentType> Parse(TextReader reader)
        {
            var tree = parser.Parse(reader);

            ValidateTree(tree);
            return(FindTypes(tree).Select(Generate));
        }
        public static SyntaxTree CreateSyntaxTree(IDocument document)
        {
            var parser     = new CSharpParser();
            var syntaxTree = parser.Parse(document, document.FileName);

            return(syntaxTree);
        }
        private void CreateUserFile(TargetClassComparisonResult targetClass, string userFilePath)
        {
            string typeName;
            string typeNamespace;

            DotNetParserHelper.SplitType(targetClass.TargetClassFullName, out typeName, out typeNamespace);
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Linq;");
            sb.AppendLine("using System.Text;");
            sb.AppendLine("using MMDB.UITest.Core;");
            sb.AppendLine("using WatiN.Core;");
            sb.AppendLine();
            sb.AppendLine(string.Format("namespace {0}", typeNamespace));
            sb.AppendLine("{");
            sb.AppendLine(string.Format("\tpublic partial class {0}", typeName));
            sb.AppendLine("\t{");
            sb.AppendLine();
            sb.AppendLine("\t}");
            sb.AppendLine("}");
            CSharpParser parser          = new CSharpParser();
            var          compilationUnit = parser.Parse(sb.ToString(), Path.GetFileName(userFilePath));

            if (!Directory.Exists(Path.GetDirectoryName(userFilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(userFilePath));
            }
            using (StreamWriter writer = new StreamWriter(userFilePath))
            {
                CSharpOutputVisitor outputVistor = new CSharpOutputVisitor(writer, new CSharpFormattingOptions());
                compilationUnit.AcceptVisitor(outputVistor, null);
            }
        }
Exemple #10
0
        public CSharpFile(CSharpProject project, string filePath)
        {
            _project  = project;
            _filePath = filePath;

            var parser = new CSharpParser(project.CompilerSettings);

            if (!(_exists = File.Exists(filePath)))
            {
                return;
            }
            using (FileStream stream = File.OpenRead(filePath))
            {
                _syntaxTree           = parser.Parse(stream, filePath);
                _unresolvedTypeSystem = _syntaxTree.ToTypeSystem();
            }
            if (parser.HasErrors)
            {
                _project.AddToErrorCount(parser.Errors.Count());
            }

            if (parser.HasWarnings)
            {
                _project.AddToWarningCount(parser.Warnings.Count());
            }
        }
        public void UsingWithAliasing()
        {
            string program = "using global::System;\n" +
                             "using myAlias=global::My.Name.Space;\n" +
                             "using a::b.c;\n";
            CSharpParser    parser = new CSharpParser();
            CompilationUnit cu     = parser.Parse(new StringReader(program));

            Assert.IsFalse(parser.HasErrors);

            Assert.AreEqual(3, cu.Children.Count());

            Assert.IsTrue(cu.Children.ElementAt(0) is UsingDeclaration);
            Assert.IsFalse(cu.Children.ElementAt(0) is UsingAliasDeclaration);
            UsingDeclaration ud = (UsingDeclaration)cu.Children.ElementAt(0);

            Assert.AreEqual("global::System", ud.Namespace);

            Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration);
            UsingAliasDeclaration uad = (UsingAliasDeclaration)cu.Children.ElementAt(1);

            Assert.AreEqual("myAlias", uad.Alias);
            Assert.AreEqual("global::My.Name.Space", uad.Import.ToString());

            Assert.IsTrue(cu.Children.ElementAt(2) is UsingDeclaration);
            Assert.IsFalse(cu.Children.ElementAt(2) is UsingAliasDeclaration);
            ud = (UsingDeclaration)cu.Children.ElementAt(2);
            Assert.AreEqual("a::b.c", ud.Namespace);
        }
		public void UsingWithAliasing()
		{
			string program = "using global::System;\n" +
				"using myAlias=global::My.Name.Space;\n" +
				"using a::b.c;\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.IsFalse(parser.HasErrors);
			
			Assert.AreEqual(3, cu.Children.Count());
			
			Assert.IsTrue(cu.Children.ElementAt(0) is UsingDeclaration);
			Assert.IsFalse(cu.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingDeclaration ud = (UsingDeclaration)cu.Children.ElementAt(0);
			Assert.AreEqual("global::System", ud.Namespace);
			
			Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration);
			UsingAliasDeclaration uad = (UsingAliasDeclaration)cu.Children.ElementAt(1);
			Assert.AreEqual("myAlias", uad.Alias);
			Assert.AreEqual("global::My.Name.Space", uad.Import.ToString());
			
			Assert.IsTrue(cu.Children.ElementAt(2) is UsingDeclaration);
			Assert.IsFalse(cu.Children.ElementAt(2) is UsingAliasDeclaration);
			ud = (UsingDeclaration)cu.Children.ElementAt(2);
			Assert.AreEqual("a::b.c", ud.Namespace);
		}
Exemple #13
0
        public void UsingAliasDeclarationTest()
        {
            string program = "using TESTME=System;\n" +
                             "using myAlias=My.Name.Space;\n" +
                             "using StringCollection = System.Collections.Generic.List<string>;\n";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(program);

            Assert.IsFalse(parser.HasErrors);

            Assert.IsTrue(3 <= syntaxTree.Children.Count());

            Assert.IsTrue(syntaxTree.Children.ElementAt(0) is UsingAliasDeclaration);
            UsingAliasDeclaration ud = (UsingAliasDeclaration)syntaxTree.Children.ElementAt(0);

            Assert.AreEqual("TESTME", ud.Alias);
            Assert.AreEqual("System", ud.Import.ToString());

            Assert.IsTrue(syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(1) is UsingAliasDeclaration);
            ud = (UsingAliasDeclaration)syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(1);
            Assert.AreEqual("myAlias", ud.Alias);
            Assert.AreEqual("My.Name.Space", ud.Import.ToString());

            Assert.IsTrue(syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(2) is UsingAliasDeclaration);
            ud = (UsingAliasDeclaration)syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(2);
            Assert.AreEqual("StringCollection", ud.Alias);
            Assert.AreEqual("System.Collections.Generic.List<string>", ud.Import.ToString());
        }
        private void Prepare(string source, Action preparer)
        {
            IProjectContent project = new CSharpProjectContent();
            var             parser  = new CSharpParser();

            using (var rdr = new StringReader(source)) {
                var pf = new CSharpUnresolvedFile {
                    FileName = "File.cs"
                };
                var syntaxTree = parser.Parse(rdr, pf.FileName);
                syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf));
                project = project.AddOrUpdateFiles(pf);
            }
            project = project.AddAssemblyReferences(new[] { Files.Mscorlib });

            var compilation = project.CreateCompilation();

            AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName);

            var er = new MockErrorReporter(true);

            Metadata = new MetadataImporter(er, compilation, new CompilerOptions());
            preparer();
            Metadata.Prepare(compilation.GetAllTypeDefinitions());
            Assert.That(er.AllMessages, Is.Empty, "Should not generate errrors");
        }
Exemple #15
0
        public void GenerateTypeSystem()
        {
            IProjectContent pc     = new CSharpProjectContent();
            CSharpParser    parser = new CSharpParser();

            parser.GenerateTypeSystemMode = true;
            foreach (string fileName in fileNames)
            {
                SyntaxTree syntaxTree;
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
                    syntaxTree = parser.Parse(fs, fileName);
                }
                var unresolvedFile = syntaxTree.ToTypeSystem();
                foreach (var td in unresolvedFile.GetAllTypeDefinitions())
                {
                    Assert.AreSame(unresolvedFile, td.UnresolvedFile);
                    foreach (var member in td.Members)
                    {
                        Assert.AreSame(unresolvedFile, member.UnresolvedFile);
                        Assert.AreSame(td, member.DeclaringTypeDefinition);
                    }
                }
                pc = pc.AddOrUpdateFiles(unresolvedFile);
            }
        }
Exemple #16
0
        public static SyntaxTree Parse(ITextSource textSource, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            var parser = new CSharpParser(settings);

            return(parser.Parse(textSource, fileName));
        }
        protected SyntaxTree ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
        {
            var mt = GetMemberTextToCaret();

            if (mt == null)
            {
                return(null);
            }

            string memberText      = mt.Item1;
            var    memberLocation  = mt.Item2;
            int    closingBrackets = 1;
            int    generatedLines  = 0;
            var    wrapper         = CreateWrapper(continuation, appendSemicolon, afterContinuation, memberText, memberLocation, ref closingBrackets, ref generatedLines);
            var    parser          = new CSharpParser();

            foreach (var sym in CompletionContextProvider.ConditionalSymbols)
            {
                parser.CompilerSettings.ConditionalSymbols.Add(sym);
            }
            parser.InitialLocation = new TextLocation(memberLocation.Line - generatedLines, 1);
            var result = parser.Parse(wrapper.ToString());

            return(result);
        }
		public void UsingAliasDeclarationTest()
		{
			string program = "using TESTME=System;\n" +
				"using myAlias=My.Name.Space;\n" +
				"using StringCollection = System.Collections.Generic.List<string>;\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.IsFalse(parser.HasErrors);
			
			Assert.AreEqual(3, cu.Children.Count());
			
			Assert.IsTrue(cu.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingAliasDeclaration ud = (UsingAliasDeclaration)cu.Children.ElementAt(0);
			Assert.AreEqual("TESTME", ud.Alias);
			Assert.AreEqual("System", ud.Import.ToString());
			
			Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)cu.Children.ElementAt(1);
			Assert.AreEqual("myAlias", ud.Alias);
			Assert.AreEqual("My.Name.Space", ud.Import.ToString());
			
			Assert.IsTrue(cu.Children.ElementAt(2) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)cu.Children.ElementAt(2);
			Assert.AreEqual("StringCollection", ud.Alias);
			Assert.AreEqual("System.Collections.Generic.List<string>", ud.Import.ToString());
		}
Exemple #19
0
        public void UsingWithAliasing()
        {
            string program = "using global::System;\n" +
                             "using myAlias=global::My.Name.Space;\n" +
                             "using a::b.c;\n";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(program);

            Assert.IsFalse(parser.HasErrors);

            Assert.IsTrue(3 <= syntaxTree.Children.Count());

            Assert.IsTrue(syntaxTree.Children.ElementAt(0) is UsingDeclaration);
            Assert.IsFalse(syntaxTree.Children.ElementAt(0) is UsingAliasDeclaration);
            UsingDeclaration ud = (UsingDeclaration)syntaxTree.Children.ElementAt(0);

            Assert.AreEqual("global::System", ud.Namespace);

            Assert.IsTrue(syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(1) is UsingAliasDeclaration);
            UsingAliasDeclaration uad = (UsingAliasDeclaration)syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(1);

            Assert.AreEqual("myAlias", uad.Alias);
            Assert.AreEqual("global::My.Name.Space", uad.Import.ToString());

            Assert.IsTrue(syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(2) is UsingDeclaration);
            Assert.IsFalse(syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(2) is UsingAliasDeclaration);
            ud = (UsingDeclaration)syntaxTree.Children.Where(c => c.Role != Roles.NewLine).ElementAt(2);
            Assert.AreEqual("a::b.c", ud.Namespace);
        }
Exemple #20
0
        public void GenerateTypeSystem()
        {
            IProjectContent pc     = new CSharpProjectContent();
            CSharpParser    parser = new CSharpParser();

            parser.GenerateTypeSystemMode = true;
            foreach (string fileName in fileNames)
            {
                CompilationUnit cu;
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
                    cu = parser.Parse(fs, fileName);
                }
                var parsedFile = cu.ToTypeSystem();
                foreach (var td in parsedFile.GetAllTypeDefinitions())
                {
                    Assert.AreSame(parsedFile, td.ParsedFile);
                    foreach (var member in td.Members)
                    {
                        Assert.AreSame(parsedFile, member.ParsedFile);
                        Assert.AreSame(td, member.DeclaringTypeDefinition);
                    }
                }
                pc = pc.UpdateProjectContent(null, parsedFile);
            }
        }
Exemple #21
0
        public virtual List <CSClass> ParseString(string data, string filePath, string projectDirectory, IEnumerable <CSClass> existingClassList)
        {
            string relativeFilePath = filePath.Replace(projectDirectory, "");

            if (relativeFilePath.StartsWith("\\"))
            {
                relativeFilePath = relativeFilePath.Substring(1);
            }
            List <CSClass> returnValue       = new List <CSClass>(existingClassList ?? new CSClass[] {});
            var            parser            = new CSharpParser();
            var            compilationUnit   = parser.Parse(data, filePath);
            var            namespaceNodeList = compilationUnit.Children.Where(i => i is NamespaceDeclaration);

            foreach (NamespaceDeclaration namespaceNode in namespaceNodeList)
            {
                var typeDeclarationNodeList = namespaceNode.Children.Where(i => i is TypeDeclaration);
                foreach (TypeDeclaration typeDeclarationNode in typeDeclarationNodeList)
                {
                    var classObject = returnValue.SingleOrDefault(i => i.ClassName == typeDeclarationNode.Name && i.NamespaceName == namespaceNode.FullName);
                    if (classObject == null)
                    {
                        classObject = new CSClass
                        {
                            NamespaceName = namespaceNode.FullName,
                            ClassName     = typeDeclarationNode.Name
                        };
                        returnValue.Add(classObject);
                    }
                    ClassParser.BuildClass(classObject, typeDeclarationNode, relativeFilePath);
                }
            }
            return(returnValue);
        }
		public void UsingAliasDeclarationTest()
		{
			string program = "using TESTME=System;\n" +
				"using myAlias=My.Name.Space;\n" +
				"using StringCollection = System.Collections.Generic.List<string>;\n";
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree = parser.Parse(program);
			Assert.IsFalse(parser.HasErrors);
			
			Assert.IsTrue(3 <= syntaxTree.Children.Count());
			
			Assert.IsTrue(syntaxTree.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingAliasDeclaration ud = (UsingAliasDeclaration)syntaxTree.Children.ElementAt(0);
			Assert.AreEqual("TESTME", ud.Alias);
			Assert.AreEqual("System", ud.Import.ToString());
			
			Assert.IsTrue(syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1);
			Assert.AreEqual("myAlias", ud.Alias);
			Assert.AreEqual("My.Name.Space", ud.Import.ToString());
			
			Assert.IsTrue(syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(2) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(2);
			Assert.AreEqual("StringCollection", ud.Alias);
			Assert.AreEqual("System.Collections.Generic.List<string>", ud.Import.ToString());
		}
        public bool Analyze(RefactoringOptions options)
        {
            var data = options.GetTextEditorData();

            if (data.Document.MimeType != CSharpFormatter.MimeType)
            {
                return(false);
            }
            var parser = new CSharpParser();
            var unit   = parser.Parse(data);

            if (unit == null)
            {
                return(false);
            }
            resolvePosition = new DomLocation(data.Caret.Line, data.Caret.Column);

            if (!AnalyzeTargetExpression(options, unit))
            {
                return(false);
            }

            invocation = GetInvocation(unit, data);
            if (invocation != null)
            {
                return(AnalyzeInvocation(options));
            }
            delegateType = GetDelegateType(options, unit);
            return(delegateType != null);
        }
        IUnresolvedFile Parse(string fileName, string code)
        {
            var parser     = new CSharpParser();
            var syntaxTree = parser.Parse(code, fileName);

            Assert.IsFalse(parser.HasErrors);
            return(syntaxTree.ToTypeSystem());
        }
		public void WrongUsingTest()
		{
			string program = "using\n";
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree = parser.Parse (program);
			Assert.AreEqual(0, syntaxTree.Children.Count());
			Assert.IsTrue(parser.HasErrors);
		}
 private static IEnumerable <AstNode> ParseAsMethodBody(CSharpParser parser, ref string sourceCode)
 {
     sourceCode = ExtraCode.Add(
         before: "unsafe partial class MyClass { void M() { ",
         code: sourceCode,
         after: "}}");
     return(parser.Parse(new StringReader(sourceCode), "").Children);
 }
		public void WrongUsingTest()
		{
			string program = "using\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.AreEqual(0, cu.Children.Count());
			Assert.IsTrue(parser.HasErrors);
		}
        string ConvertTypeDeclaration(string code)
        {
            CSharpParser parser     = new CSharpParser();
            var          syntaxTree = parser.Parse(code, "program.cs");

            Assert.IsFalse(parser.HasErrors);
            return(ConvertTypeDeclaration((EntityDeclaration)syntaxTree.Children.Single()));
        }
        static int Main(string[] args)
        {
            try {
                File.Delete("conversion.log");

                List <string> map = new List <string>()
                {
                    "..\\Controller\\Profiler",
                    "..\\Controller\\Data\\UnmanagedCallTreeNode",
                    "..\\Controller\\structs"
                };

                foreach (string path in map)
                {
                    CSharpParser parser = new CSharpParser();
                                        #if DEBUG
                    parser.CompilerSettings.ConditionalSymbols.Add("DEBUG");
                                        #endif
                    string filePath = path + ".cs";

                    if (File.Exists(filePath))
                    {
                        using (StreamReader reader = new StreamReader(filePath)) {
                            SyntaxTree syntaxTree = parser.Parse(reader, filePath);

                            if (parser.HasErrors)
                            {
                                string message = "Parser errors in file " + filePath + ":\n";
                                foreach (Error error in parser.Errors)
                                {
                                    message += error.Message + "\n";
                                }
                                Console.WriteLine(message);
                                File.WriteAllText(path + "64.cs", message);
                                return(2);
                            }

                            syntaxTree.AcceptVisitor(new Converter());

                            using (StreamWriter writer = new StreamWriter(path + "64.cs")) {
                                CSharpOutputVisitor output = new CSharpOutputVisitor(writer, FormattingOptionsFactory.CreateSharpDevelop());
                                syntaxTree.AcceptVisitor(output);
                            }
                        }
                    }
                }

                return(0);
            } catch (Exception e) {
                try {
                    File.WriteAllText("conversion.log", e.ToString());
                } catch (Exception) {
                    return(-2);
                }
                return(-1);
            }
        }
        public void WrongUsingTest()
        {
            string       program    = "using\n";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(program);

            Assert.AreEqual(0, syntaxTree.Children.Count());
            Assert.IsTrue(parser.HasErrors);
        }
        public void WrongUsingTest()
        {
            string          program = "using\n";
            CSharpParser    parser  = new CSharpParser();
            CompilationUnit cu      = parser.Parse(new StringReader(program));

            Assert.AreEqual(0, cu.Children.Count());
            Assert.IsTrue(parser.HasErrors);
        }
        public void ParseFile(FileRef file, Func <string> getContent)
        {
            var parser = new CSharpParser();
            var ast    = parser.Parse(getContent());

            _file = file;
            _writer.WriteFile(file);
            scanNode(ast);
        }
Exemple #33
0
        public void NewLinesAfterPreprocessorDirectives()
        {
            string       program    = @"#define FOO
#undef FOO
#define FOO
#region Blah
#if FOO
class Test {}
#elif FOO
class Test {}
#else
class Test {}
#endif
#endregion";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(program);

            Assert.IsFalse(parser.HasErrors, string.Join(Environment.NewLine, parser.Errors.Select(e => string.Format("{0}: {1}", e.Region.BeginLine, e.Message))));
            var roles = syntaxTree.Children.Select(c => c.Role).ToArray();

            Assert.AreEqual(new Role[] {
                // #define FOO
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // #undef FOO
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // #define FOO
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // #region Blah
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // #if FOO
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // class Test {}
                NamespaceDeclaration.MemberRole,
                Roles.NewLine,
                // #elif FOO
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // class Test {}
                Roles.Comment,
                // #else
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // class Test {}
                Roles.Comment,
                // #endif
                Roles.PreProcessorDirective,
                Roles.NewLine,
                // #endregion
                Roles.PreProcessorDirective
            }, roles);
        }
Exemple #34
0
        public override bool Index(IndexWriter writer, FileInfo file)
        {
            if (CanIndex(file))
            {
                if (writer == null)
                {
                    return(false);
                }
                string path   = Path.Combine(file.DirectoryName ?? string.Empty, file.Name);
                var    parser = new CSharpParser();
                var    syntax = parser.Parse(file.FullName);

                // Build a key based on the file syntax
                // TODO: Need semantic model in order to get full class name, i.e. namespace.className.
                // The original reason for having key field was to use DuplicateFilter. It however cannot be used
                // if index has multiple segments, not at least in version 3.0.1. Once this bug is fixed, key field
                // can be added to other indexers to be used by DuplicateFilter, which requires all documents to have it.
                string key;
                if (syntax.Classes.Any())
                {
                    var firstClassNameInTheFile = syntax.Classes.First().ClassName;
                    key = !string.IsNullOrEmpty(syntax.Namespace)
                        ? string.Format("{0}.{1}", syntax.Namespace, firstClassNameInTheFile)
                        : firstClassNameInTheFile;          // Classes in global (default) namespace
                    using (var reader = writer.GetReader()) // We want to get a new reader once per document
                    {
                        var term = new Term(Fields.Key, key);
                        var docs = reader.TermDocs(term);
                        if (docs.Next())
                        {
                            return(false); // We have already indexed this file.
                        }
                    }
                }
                else
                {
                    key = path;
                }
                var doc = new Document();
                doc.Add(new Field(Fields.Key, key, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
                doc.Add(new Field(Fields.Content, file.OpenText(), Field.TermVector.WITH_OFFSETS));

                AddComments(doc, syntax);
                AddUsings(doc, syntax);
                AddClasses(doc, syntax);

                doc.Add(new Field(Fields.Path, path, Field.Store.YES, Field.Index.NO));
                doc.Add(new Field(Fields.Language, Languages.CSharp, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                writer.AddDocument(doc); // here we can specify an analyzer
                return(true);
            }
            else
            {
                return(base.Index(writer, file));
            }
        }
Exemple #35
0
        public IEnumerable <IMethod> Extract(string fileCode)
        {
            var        parser     = new CSharpParser();
            SyntaxTree syntaxTree = parser.Parse(new StringReader(fileCode));

            IMethodsVisitor methodsVisitor = visitorsFactory.CreateMethodsVisitor();

            syntaxTree.AcceptVisitor(methodsVisitor);
            return(methodsVisitor.Methods);
        }
Exemple #36
0
		public void ParseAndCheckPositions()
		{
			CSharpParser parser = new CSharpParser();
			foreach (string fileName in fileNames) {
				var currentDocument = new ReadOnlyDocument(File.ReadAllText(fileName));
				SyntaxTree syntaxTree = parser.Parse(currentDocument, fileName);
				if (parser.HasErrors)
					continue;
				ConsistencyChecker.CheckPositionConsistency(syntaxTree, fileName, currentDocument);
				ConsistencyChecker.CheckMissingTokens(syntaxTree, fileName, currentDocument);
			}
		}
		internal static IProjectContent ParseTestCase()
		{
			const string fileName = "TypeSystemTests.TestCase.cs";
			
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree;
			using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
				syntaxTree = parser.Parse(s, fileName);
			}
			
			return CreateContent(syntaxTree.ToTypeSystem());
		}
Exemple #38
0
		public void ParseAndCheckPositions()
		{
			CSharpParser parser = new CSharpParser();
			foreach (string fileName in fileNames) {
				this.currentDocument = new ReadOnlyDocument(File.ReadAllText(fileName));
				CompilationUnit cu = parser.Parse(currentDocument.CreateReader(), fileName);
				if (parser.HasErrors)
					continue;
				this.currentFileName = fileName;
				CheckPositionConsistency(cu);
				CheckMissingTokens(cu);
			}
		}
        public void AssemblyAndModuleAttributesDoNotAppearOnTypes()
        {
            var parser = new CSharpParser();
            var cu = parser.Parse("[assembly: My1][module: My2][My3]class C {} public class My1Attribute : System.Attribute {} public class My2Attribute : System.Attribute {} public class My3Attribute : System.Attribute {}", "File.cs");

            var ts = cu.ToTypeSystem();
            var compilation = new CSharpProjectContent()
                .UpdateProjectContent(null, ts)
                .AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib })
                .CreateCompilation();
            var type = ReflectionHelper.ParseReflectionName("C").Resolve(compilation).GetDefinition();
            Assert.That(type.Attributes.Select(a => a.AttributeType.FullName).ToList(), Is.EqualTo(new[] { "My3Attribute" }));
        }
Exemple #40
0
		public void GenerateTypeSystem()
		{
			SimpleProjectContent pc = new SimpleProjectContent();
			CSharpParser parser = new CSharpParser();
			parser.GenerateTypeSystemMode = true;
			foreach (string fileName in fileNames) {
				CompilationUnit cu;
				using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
					cu = parser.Parse(fs);
				}
				TypeSystemConvertVisitor cv = new TypeSystemConvertVisitor(pc, fileName);
				pc.UpdateProjectContent(null, cv.Convert(cu));
			}
		}
		internal static IProjectContent ParseTestCase()
		{
			const string fileName = "TypeSystemTests.TestCase.cs";
			
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu;
			using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
				cu = parser.Parse(s);
			}
			
			var testCasePC = new SimpleProjectContent();
			CSharpParsedFile parsedFile = new TypeSystemConvertVisitor(testCasePC, fileName).Convert(cu);
			parsedFile.Freeze();
			testCasePC.UpdateProjectContent(null, parsedFile);
			return testCasePC;
		}
 public void ConditionalSymbolTest()
 {
     const string program = @"// Test
     #if AAA
     #undef AAA
     #define CCC
     #else
     #define DDD
     #endif
     class C {}";
     CSharpParser parser = new CSharpParser();
     parser.CompilerSettings.ConditionalSymbols.Add("AAA");
     parser.CompilerSettings.ConditionalSymbols.Add("BBB");
     var syntaxTree = parser.Parse(program, "elif.cs");
     Assert.AreEqual(new[] { "BBB", "CCC" }, syntaxTree.ConditionalSymbols);
 }
        public void FixtureSetUp()
        {
            const string fileName = "TypeSystemTests.TestCase.cs";

            CSharpParser parser = new CSharpParser();
            CompilationUnit cu;
            using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
                cu = parser.Parse(s);
            }

            testCasePC = new SimpleProjectContent();
            TypeSystemConvertVisitor visitor = new TypeSystemConvertVisitor(testCasePC, fileName);
            cu.AcceptVisitor(visitor, null);
            ParsedFile parsedFile = visitor.ParsedFile;
            ((SimpleProjectContent)testCasePC).UpdateProjectContent(null, parsedFile.TopLevelTypeDefinitions, null, null);
        }
		internal static IProjectContent ParseTestCase()
		{
			const string fileName = "TypeSystemTests.TestCase.cs";
			
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree;
			using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
				syntaxTree = parser.Parse(s, fileName);
			}
			
			var unresolvedFile = syntaxTree.ToTypeSystem();
			return new CSharpProjectContent()
				.AddOrUpdateFiles(unresolvedFile)
				.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib })
				.SetAssemblyName(typeof(TypeSystemTests).Assembly.GetName().Name);
		}
		internal static IProjectContent ParseTestCase()
		{
			const string fileName = "TypeSystemTests.TestCase.cs";
			
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu;
			using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
				cu = parser.Parse(s, fileName);
			}
			
			var parsedFile = cu.ToTypeSystem();
			return new CSharpProjectContent()
				.UpdateProjectContent(null, parsedFile)
				.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib })
				.SetAssemblyName(typeof(TypeSystemTests).Assembly.GetName().Name);
		}
		public void PropertyRegionTest()
		{
			const string code = "class T {\n\tint Prop {\n\t\tget { return f; }\n\t\tset { f = value; }\n\t}\n}\n";
			int line2Pos = code.IndexOf("\tint Prop");
			int line3Pos = code.IndexOf("\t\tget");
			int line4Pos = code.IndexOf("\t\tset");
			
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree = parser.Parse(code);
			PropertyDeclaration pd = (PropertyDeclaration)syntaxTree.Children.Single().GetChildByRole(Roles.TypeMemberRole);
			Assert.AreEqual(new TextLocation(2, code.IndexOf("{\n\t\tget") - line2Pos + 1), pd.GetChildByRole(Roles.LBrace).StartLocation);
			Assert.AreEqual(new TextLocation(5, 3), pd.EndLocation);
			Assert.AreEqual(new TextLocation(3, code.IndexOf("{ return") - line3Pos + 1), pd.Getter.Body.StartLocation);
			Assert.AreEqual(new TextLocation(3, code.IndexOf("}\n\t\tset") + 1 - line3Pos + 1), pd.Getter.Body.EndLocation);
			Assert.AreEqual(new TextLocation(4, code.IndexOf("{ f =") - line4Pos + 1), pd.Setter.Body.StartLocation);
			Assert.AreEqual(new TextLocation(4, code.IndexOf("}\n\t}") + 1 - line4Pos + 1), pd.Setter.Body.EndLocation);
		}
		public void PropertyRegionTest()
		{
			const string code = "class T {\n\tint Prop {\n\t\tget { return f; }\n\t\tset { f = value; }\n\t}\n}\n";
			int line2Pos = code.IndexOf("\tint Prop");
			int line3Pos = code.IndexOf("\t\tget");
			int line4Pos = code.IndexOf("\t\tset");
			
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(code));
			PropertyDeclaration pd = (PropertyDeclaration)cu.Children.Single().GetChildByRole(TypeDeclaration.MemberRole);
			Assert.AreEqual(new AstLocation(2, code.IndexOf("{\n\t\tget") - line2Pos + 1), pd.GetChildByRole(AstNode.Roles.LBrace).StartLocation);
			Assert.AreEqual(new AstLocation(5, 3), pd.EndLocation);
			Assert.AreEqual(new AstLocation(3, code.IndexOf("{ return") - line3Pos + 1), pd.Getter.Body.StartLocation);
			Assert.AreEqual(new AstLocation(3, code.IndexOf("}\n\t\tset") + 1 - line3Pos + 1), pd.Getter.Body.EndLocation);
			Assert.AreEqual(new AstLocation(4, code.IndexOf("{ f =") - line4Pos + 1), pd.Setter.Body.StartLocation);
			Assert.AreEqual(new AstLocation(4, code.IndexOf("}\n\t}") + 1 - line4Pos + 1), pd.Setter.Body.EndLocation);
		}
		public void DeclarationTest()
		{
			string program = "using System;\n" +
				"using My.Name.Space;\n";
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree = parser.Parse(program);
			Assert.IsFalse(parser.HasErrors);
			
			Assert.IsTrue(2 <= syntaxTree.Children.Count());
			Assert.IsTrue(syntaxTree.Children.ElementAt(0) is UsingDeclaration);
			Assert.IsFalse(syntaxTree.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingDeclaration ud = (UsingDeclaration)syntaxTree.Children.ElementAt(0);
			Assert.AreEqual("System", ud.Namespace);
			
			Assert.IsTrue(syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1) is UsingDeclaration);
			Assert.IsFalse(syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1) is UsingAliasDeclaration);
			ud = (UsingDeclaration)syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1);
			Assert.AreEqual("My.Name.Space", ud.Namespace);
		}
		public void DeclarationTest()
		{
			string program = "using System;\n" +
				"using My.Name.Space;\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.IsFalse(parser.HasErrors);
			
			Assert.AreEqual(2, cu.Children.Count());
			Assert.IsTrue(cu.Children.ElementAt(0) is UsingDeclaration);
			Assert.IsFalse(cu.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingDeclaration ud = (UsingDeclaration)cu.Children.ElementAt(0);
			Assert.AreEqual("System", ud.Namespace);
			
			Assert.IsTrue(cu.Children.ElementAt(1) is UsingDeclaration);
			Assert.IsFalse(cu.Children.ElementAt(1) is UsingAliasDeclaration);
			ud = (UsingDeclaration)cu.Children.ElementAt(1);
			Assert.AreEqual("My.Name.Space", ud.Namespace);
		}
		public void GenerateTypeSystem()
		{
			IProjectContent pc = new CSharpProjectContent();
			CSharpParser parser = new CSharpParser();
			parser.GenerateTypeSystemMode = true;
			foreach (string fileName in fileNames) {
				SyntaxTree syntaxTree;
				using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
					syntaxTree = parser.Parse(fs, fileName);
				}
				var unresolvedFile = syntaxTree.ToTypeSystem();
				foreach (var td in unresolvedFile.GetAllTypeDefinitions()) {
					Assert.AreSame(unresolvedFile, td.UnresolvedFile);
					foreach (var member in td.Members) {
						Assert.AreSame(unresolvedFile, member.UnresolvedFile);
						Assert.AreSame(td, member.DeclaringTypeDefinition);
					}
				}
				pc = pc.AddOrUpdateFiles(unresolvedFile);
			}
		}
Exemple #51
0
		public void GenerateTypeSystem()
		{
			IProjectContent pc = new CSharpProjectContent();
			CSharpParser parser = new CSharpParser();
			parser.GenerateTypeSystemMode = true;
			foreach (string fileName in fileNames) {
				CompilationUnit cu;
				using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
					cu = parser.Parse(fs, fileName);
				}
				var parsedFile = cu.ToTypeSystem();
				foreach (var td in parsedFile.GetAllTypeDefinitions()) {
					Assert.AreSame(parsedFile, td.ParsedFile);
					foreach (var member in td.Members) {
						Assert.AreSame(parsedFile, member.ParsedFile);
						Assert.AreSame(td, member.DeclaringTypeDefinition);
					}
				}
				pc = pc.UpdateProjectContent(null, parsedFile);
			}
		}
        public TestRefactoringContext(string content)
        {
            int idx = content.IndexOf ("$");
            if (idx >= 0)
                content = content.Substring (0, idx) + content.Substring (idx + 1);
            doc = new ReadOnlyDocument (content);
            var parser = new CSharpParser ();
            Unit = parser.Parse (content, "program.cs");
            if (parser.HasErrors)
                parser.ErrorPrinter.Errors.ForEach (e => Console.WriteLine (e.Message));
            Assert.IsFalse (parser.HasErrors, "File contains parsing errors.");
            parsedFile = Unit.ToTypeSystem();

            IProjectContent pc = new CSharpProjectContent();
            pc = pc.UpdateProjectContent(null, parsedFile);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            compilation = pc.CreateCompilation();
            resolver = new CSharpAstResolver(compilation, Unit, parsedFile);
            if (idx >= 0)
                Location = doc.GetLocation (idx);
        }
		ExpressionResult GetNewExpressionAt(int offset)
		{
			var parser = new CSharpParser();
			var text = GetMemberTextToCaret();
			int closingBrackets = 0, generatedLines = 0;
			var sb = CreateWrapper("a ();", false, "", text.Item1, text.Item2, ref closingBrackets, ref generatedLines);

			var completionUnit = parser.Parse(sb.ToString());
			var offsetLocation = document.GetLocation(offset);
			var loc = new TextLocation(offsetLocation.Line - text.Item2.Line + generatedLines + 1, offsetLocation.Column);

			var expr = completionUnit.GetNodeAt(loc, n => n is Expression);
			if (expr == null) {
				// try without ";"
				sb = CreateWrapper("a ()", false, "", text.Item1, text.Item2, ref closingBrackets, ref generatedLines);
				completionUnit = parser.Parse(sb.ToString());

				expr = completionUnit.GetNodeAt(loc, n => n is Expression);
				if (expr == null) {
					return null;
				}
			}
			return new ExpressionResult(expr, completionUnit);
		}
		ExpressionResult GetNewExpressionAt(int offset)
		{
			var parser = new CSharpParser();
			string text = this.document.GetText(0, this.offset); 
			var sb = new StringBuilder(text);
			sb.Append("a ();");
			AppendMissingClosingBrackets(sb, text, false);
			
			var stream = new System.IO.StringReader(sb.ToString());
			var completionUnit = parser.Parse(stream, CSharpParsedFile.FileName, 0);
			stream.Close();
			var loc = document.GetLocation(offset);
			
			var expr = completionUnit.GetNodeAt(loc, n => n is Expression);
			if (expr == null) {
				// try without ";"
				sb = new StringBuilder(text);
				sb.Append("a ()");
				AppendMissingClosingBrackets(sb, text, false);
				stream = new System.IO.StringReader(sb.ToString());
				completionUnit = parser.Parse(stream, CSharpParsedFile.FileName, 0);
				stream.Close();
				loc = document.GetLocation(offset);
				
				expr = completionUnit.GetNodeAt(loc, n => n is Expression);
				if (expr == null) {
					return null;
				}
			}
			return new ExpressionResult(expr, completionUnit);
		}
		protected SyntaxTree ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
		{
			var mt = GetMemberTextToCaret();
			if (mt == null) {
				return null;
			}

			string memberText = mt.Item1;
			var memberLocation = mt.Item2;
			int closingBrackets = 1;
			int generatedLines = 0;
			var wrapper = new StringBuilder();
			bool wrapInClass = memberLocation != new TextLocation(1, 1);
			if (wrapInClass) {
				wrapper.Append("class Stub {");
				wrapper.AppendLine();
				closingBrackets++;
				generatedLines++;
			}
			wrapper.Append(memberText);
			wrapper.Append(continuation);
			AppendMissingClosingBrackets(wrapper, memberText, appendSemicolon);
			wrapper.Append(afterContinuation);
			if (closingBrackets > 0) { 
				wrapper.Append(new string('}', closingBrackets));
			}
			var parser = new CSharpParser ();
			foreach (var sym in CompletionContextProvider.ConditionalSymbols)
				parser.CompilerSettings.ConditionalSymbols.Add (sym);
			parser.InitialLocation = new TextLocation(memberLocation.Line - generatedLines, 1);
			var result = parser.Parse(wrapper.ToString ());
			return result;
		}
        ExpressionResult GetExpressionAt(int offset)
        {
            var parser = new CSharpParser();
            string text = this.document.GetText(0, this.offset);
            var sb = new StringBuilder(text);
            sb.Append("a;");
            AppendMissingClosingBrackets(sb, text, false);
            var completionUnit = parser.Parse(sb.ToString());
            var loc = document.GetLocation(offset);

            var expr = completionUnit.GetNodeAt(
                loc,
                n => n is Expression || n is VariableDeclarationStatement
                );
            if (expr == null) {
                return null;
            }
            return new ExpressionResult(expr, completionUnit);
        }
Exemple #57
0
        Tuple<CSharpParsedFile, AstNode, CompilationUnit> GetExpressionAt(int offset)
        {
            var parser = new CSharpParser ();
            string text = this.document.GetText (0, this.offset);
            var sb = new StringBuilder (text);
            sb.Append ("a;");
            AppendMissingClosingBrackets (sb, text, false);
            var stream = new System.IO.StringReader (sb.ToString ());
            var completionUnit = parser.Parse (stream, CSharpParsedFile.FileName, 0);
            stream.Close ();
            var loc = document.GetLocation (offset);

            var expr = completionUnit.GetNodeAt (loc, n => n is Expression || n is VariableDeclarationStatement);
            if (expr == null)
                return null;
            var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
            completionUnit.AcceptVisitor (tsvisitor, null);

            return Tuple.Create (tsvisitor.ParsedFile, expr, completionUnit);
        }
        public static TestRefactoringContext Create(string content, bool expectErrors = false)
        {
            int idx = content.IndexOf ("$");
            if (idx >= 0)
                content = content.Substring (0, idx) + content.Substring (idx + 1);
            int idx1 = content.IndexOf ("<-");
            int idx2 = content.IndexOf ("->");

            int selectionStart = 0;
            int selectionEnd = 0;
            if (0 <= idx1 && idx1 < idx2) {
                content = content.Substring (0, idx2) + content.Substring (idx2 + 2);
                content = content.Substring (0, idx1) + content.Substring (idx1 + 2);
                selectionStart = idx1;
                selectionEnd = idx2 - 2;
                idx = selectionEnd;
            }

            var doc = new StringBuilderDocument(content);
            var parser = new CSharpParser();
            var unit = parser.Parse(content, "program.cs");
            if (!expectErrors) {
                if (parser.HasErrors) {
                    Console.WriteLine (content);
                    Console.WriteLine ("----");
                }
                foreach (var error in parser.Errors) {
                    Console.WriteLine(error.Message);
                }
                Assert.IsFalse(parser.HasErrors, "The file contains unexpected parsing errors.");
            } else {
                Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file doesn't contain any.");
            }

            unit.Freeze ();
            var unresolvedFile = unit.ToTypeSystem ();

            IProjectContent pc = new CSharpProjectContent ();
            pc = pc.AddOrUpdateFiles (unresolvedFile);
            pc = pc.AddAssemblyReferences (new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var compilation = pc.CreateCompilation ();
            var resolver = new CSharpAstResolver (compilation, unit, unresolvedFile);
            TextLocation location = TextLocation.Empty;
            if (idx >= 0)
                location = doc.GetLocation (idx);
            return new TestRefactoringContext(doc, location, resolver) {
                selectionStart = selectionStart,
                selectionEnd = selectionEnd
            };
        }
		protected CompilationUnit ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
		{
			var mt = GetMemberTextToCaret();
			if (mt == null) {
				return null;
			}

			string memberText = mt.Item1;
			var memberLocation = mt.Item2;
			int closingBrackets = 1;
			int generatedLines = 0;
			var wrapper = new StringBuilder();
			bool wrapInClass = memberLocation != new TextLocation(1, 1);
			if (wrapInClass) {
				wrapper.Append("class Stub {");
				wrapper.AppendLine();
				closingBrackets++;
				generatedLines++;
			}
			wrapper.Append(memberText);
			wrapper.Append(continuation);
			AppendMissingClosingBrackets(wrapper, memberText, appendSemicolon);
			wrapper.Append(afterContinuation);
			if (closingBrackets > 0) { 
				wrapper.Append(new string('}', closingBrackets));
			}
			using (var stream = new System.IO.StringReader (wrapper.ToString ())) {
				try {
					var parser = new CSharpParser ();
					var result = parser.Parse(stream, "stub.cs", memberLocation.Line - 1 - generatedLines);
					return result;
				} catch (Exception) {
					Console.WriteLine("------");
					Console.WriteLine(wrapper);
					throw;
				}
			}
		}
		bool Analyze (RefactoringOptions options, ExtractMethodParameters param, bool fillParameter)
		{
			var data = options.GetTextEditorData ();
			var parser = new CSharpParser ();
			var unit = parser.Parse (data);
			var resolver = options.GetResolver ();
			if (unit == null)
				return false;
			var selectionRange = data.SelectionRange;
			var startOffset = selectionRange.Offset;
			while (startOffset + 1 < data.Length && char.IsWhiteSpace (data.GetCharAt (startOffset + 1)))
				startOffset++;
			var endOffset = selectionRange.EndOffset;
			while (startOffset < endOffset && endOffset - 1 > 0 && char.IsWhiteSpace (data.GetCharAt (endOffset - 1)))
				endOffset--;
			if (startOffset >= endOffset)
				return false;
			
			var endLocation = data.OffsetToLocation (endOffset);
			var startLocation = data.OffsetToLocation (startOffset);
			param.StartOffset = startOffset;
			param.EndOffset = endOffset;
			param.Nodes = new List<AstNode> (unit.GetNodesBetween (startLocation.Line, startLocation.Column, endLocation.Line, endLocation.Column));
			string text = options.Document.Editor.GetTextBetween (startLocation, endLocation);
			
			param.Text = RemoveIndent (text, GetIndent (data.GetTextBetween (data.GetLine (startLocation.Line).Offset, data.GetLine (endLocation.Line).EndOffset))).TrimEnd ('\n', '\r');
			VariableLookupVisitor visitor = new VariableLookupVisitor (resolver, param.Location);
			visitor.MemberLocation = param.DeclaringMember.Location;
			visitor.CutRegion = new DomRegion (startLocation.Line, startLocation.Column, endLocation.Line, endLocation.Column);
			if (fillParameter) {
				unit.AcceptVisitor (visitor, null);
				if (param.Nodes != null && (param.Nodes.Count == 1 && param.Nodes [0].NodeType == NodeType.Expression)) {
					ResolveResult resolveResult = resolver.Resolve (new ExpressionResult ("(" + text + ")"), param.Location);
					if (resolveResult != null && resolveResult.ResolvedType != null)
						param.ExpressionType = resolveResult.ResolvedType;
				}
				
				foreach (VariableDescriptor varDescr in visitor.VariableList.Where (v => !v.IsDefinedInsideCutRegion && (v.UsedInCutRegion || v.IsChangedInsideCutRegion || v.UsedAfterCutRegion && v.IsDefinedInsideCutRegion))) {
					param.Parameters.Add (varDescr);
				}
			
				param.Variables = new List<VariableDescriptor> (visitor.Variables.Values);
				param.ReferencesMember = visitor.ReferencesMember;
				
				param.OneChangedVariable = param.Variables.Count (p => p.IsDefinedInsideCutRegion && p.UsedAfterCutRegion) == 1;
				if (param.OneChangedVariable)
					param.ExpressionType = param.Variables.First (p => p.IsDefinedInsideCutRegion && p.UsedAfterCutRegion).ReturnType;
				/*
					foreach (VariableDescriptor varDescr in visitor.VariableList.Where (v => !v.IsDefined && param.Variables.Contains (v))) {
					if (param.Parameters.Contains (varDescr))
						continue;
					if (startLocation <= varDescr.Location && varDescr.Location < endLocation)
						continue;
					param.Parameters.Add (varDescr);
				}
				
				
				param.ChangedVariables = new HashSet<string> (visitor.Variables.Values.Where (v => v.GetsChanged).Select (v => v.Name));
				*/
				// analyze the variables outside of the selected text
				IMember member = param.DeclaringMember;
			
				int bodyStartOffset = data.Document.LocationToOffset (member.BodyRegion.Start.Line, member.BodyRegion.Start.Column);
				int bodyEndOffset = data.Document.LocationToOffset (member.BodyRegion.End.Line, member.BodyRegion.End.Column);
				if (startOffset < bodyStartOffset || bodyEndOffset < endOffset)
					return false;
				text = data.Document.GetTextBetween (bodyStartOffset, startOffset) + data.Document.GetTextBetween (endOffset, bodyEndOffset);
				//				ICSharpCode.OldNRefactory.Ast.INode parsedNode = provider.ParseText (text);
				//				visitor = new VariableLookupVisitor (resolver, param.Location);
				//				visitor.CutRegion = new DomRegion (data.MainSelection.MinLine, data.MainSelection.MaxLine);
				//				visitor.MemberLocation = new Location (param.DeclaringMember.Location.Column, param.DeclaringMember.Location.Line);
				//				if (parsedNode != null)
				//					parsedNode.AcceptVisitor (visitor, null);
				
				
				/*	
				param.VariablesOutside = new Dictionary<string, VariableDescriptor> ();
				foreach (var pair in visitor.Variables) {
					if (startLocation < pair.Value.Location || endLocation >= pair.Value.Location) {
						param.VariablesOutside.Add (pair.Key, pair.Value);
					}
				}
				param.OutsideVariableList = new List<VariableDescriptor> ();
				foreach (var v in visitor.VariableList) {
					if (startLocation < v.Location || endLocation >= v.Location)
						param.OutsideVariableList.Add (v);
				}
				
				param.ChangedVariablesUsedOutside = new List<VariableDescriptor> (param.Variables.Where (v => v.GetsChanged && param.VariablesOutside.ContainsKey (v.Name)));
				param.OneChangedVariable = param.Nodes.Count == 1 && param.Nodes[0] is BlockStatement;
				if (param.OneChangedVariable) 
					param.OneChangedVariable = param.ChangedVariablesUsedOutside.Count == 1;
				
				param.VariablesToGenerate = new List<VariableDescriptor> (param.ChangedVariablesUsedOutside.Where (v => v.IsDefined));
				foreach (VariableDescriptor var in param.VariablesToGenerate) {
					param.Parameters.Add (var);
				}
				if (param.OneChangedVariable) {
					param.VariablesToDefine = new List<VariableDescriptor> (param.Parameters.Where (var => !var.InitialValueUsed));
					param.VariablesToDefine.ForEach (var => param.Parameters.Remove (var));
				} else {
					param.VariablesToDefine = new List<VariableDescriptor> ();
				}*/
			}
			
			return true;
		}