Exemplo n.º 1
0
        void ResolveButtonClick(object sender, EventArgs e)
        {
            SimpleProjectContent     project        = new SimpleProjectContent();
            TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(project, "dummy.cs");

            compilationUnit.AcceptVisitor(convertVisitor, null);
            project.UpdateProjectContent(null, convertVisitor.ParsedFile.TopLevelTypeDefinitions, null, null);

            List <ITypeResolveContext> projects = new List <ITypeResolveContext>();

            projects.Add(project);
            projects.AddRange(builtInLibs.Value);

            using (var context = new CompositeTypeResolveContext(projects).Synchronize()) {
                CSharpResolver resolver = new CSharpResolver(context);

                IResolveVisitorNavigator navigator = null;
                if (csharpTreeView.SelectedNode != null)
                {
                    navigator = new NodeListResolveVisitorNavigator(new[] { (AstNode)csharpTreeView.SelectedNode.Tag });
                }
                ResolveVisitor visitor = new ResolveVisitor(resolver, convertVisitor.ParsedFile, navigator);
                visitor.Scan(compilationUnit);
                csharpTreeView.BeginUpdate();
                ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
                csharpTreeView.EndUpdate();
            }
        }
        protected void BuildSyntaxTree()
        {
            for (int i = 0; i < this.SourceFiles.Count; i++)
            {
                var fileName = this.SourceFiles[i];

                using (var reader = new StreamReader(fileName))
                {
                    var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser();
                    if (!string.IsNullOrEmpty(Defines))
                    {
                        string[] defs = Defines.Split(';');
                        foreach (string def in defs)
                        {
                            parser.CompilerSettings.ConditionalSymbols.Add(def);
                        }
                    }

                    if (this.DefineConstants != null && this.DefineConstants.Count > 0)
                    {
                        foreach (var defineConstant in this.DefineConstants)
                        {
                            parser.CompilerSettings.ConditionalSymbols.Add(defineConstant);
                        }
                    }

                    var syntaxTree = parser.Parse(reader, fileName);

                    if (parser.HasErrors)
                    {
                        foreach (var error in parser.Errors)
                        {
                            throw new EmitterException(syntaxTree, string.Format("Parsing error in a file {0} {2}: {1}", fileName, error.Message, error.Region.Begin.ToString()));
                        }
                    }

                    var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);
                    syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);

                    var emptyLambdaDetecter = new EmptyLambdaDetecter();
                    syntaxTree.AcceptVisitor(emptyLambdaDetecter);

                    if (emptyLambdaDetecter.Found)
                    {
                        var fixer   = new EmptyLambdaFixer();
                        var astNode = syntaxTree.AcceptVisitor(fixer);
                        syntaxTree = (astNode != null ? (SyntaxTree)astNode : syntaxTree);
                    }

                    var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile
                    {
                        FileName = fileName
                    });
                    this.ParsedSourceFiles.Add(f);

                    var tcv = new TypeSystemConvertVisitor(f.ParsedFile);
                    f.SyntaxTree.AcceptVisitor(tcv);
                }
            }
        }
Exemplo n.º 3
0
        protected ResolveResult Resolve(string code)
        {
            CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", "")));

            TextLocation[] dollars = FindDollarSigns(code).ToArray();
            Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node");

            SetUp();

            CSharpParsedFile         parsedFile     = new CSharpParsedFile("test.cs", resolver.CurrentUsingScope);
            TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile, resolver.CurrentUsingScope, null);

            cu.AcceptVisitor(convertVisitor, null);
            project.UpdateProjectContent(null, convertVisitor.ParsedFile);

            FindNodeVisitor fnv = new FindNodeVisitor(dollars[0], dollars[1]);

            cu.AcceptVisitor(fnv, null);
            Assert.IsNotNull(fnv.ResultNode, "Did not find DOM node at the specified location");

            Debug.WriteLine(new string('=', 70));
            Debug.WriteLine("Starting new resolver for " + fnv.ResultNode);

            var           navigator = new NodeListResolveVisitorNavigator(new[] { fnv.ResultNode });
            ResolveResult rr;

            using (var context = this.context.Synchronize()) {
                ResolveVisitor rv = new ResolveVisitor(new CSharpResolver(context), convertVisitor.ParsedFile, navigator);
                rv.Scan(cu);
                rr = rv.GetResolveResult(fnv.ResultNode);
            }
            Assert.IsNotNull(rr, "ResolveResult is null - did something go wrong while navigating to the target node?");
            Debug.WriteLine("ResolveResult is " + rr);
            return(rr);
        }
		public Tuple<CSharpParsedFile, AstNode, CompilationUnit> GetIndexerBeforeCursor ()
		{
			CompilationUnit baseUnit;
			if (currentMember == null && currentType == null) 
				return null;
			if (Unit == null)
				return null;
			baseUnit = ParseStub ("x] = a[1");
			
			var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
			var mref = baseUnit.GetNodeAt (location, n => n is IndexerExpression); 
			AstNode expr;
			if (mref is IndexerExpression) {
				expr = ((IndexerExpression)mref).Target;
			} else {
				return null;
			}
			
			var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
			var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
			if (member == null || member2 == null)
				return null;
			member2.Remove ();
			member.ReplaceWith (member2);
			var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
			Unit.AcceptVisitor (tsvisitor, null);
			return Tuple.Create (tsvisitor.ParsedFile, (AstNode)expr, Unit);
		}
Exemplo n.º 5
0
        public static PreparedCompilation CreateCompilation(IEnumerable <ISourceFile> sourceFiles, IEnumerable <IAssemblyReference> references, IList <string> defineConstants)
        {
            IProjectContent project = new CSharpProjectContent();

            var files = sourceFiles.Select(f => {
                using (var rdr = f.Open()) {
                    var syntaxTree   = CreateParser(defineConstants).Parse(rdr, f.Filename);
                    var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);
                    syntaxTree       = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);
                    return(new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile {
                        FileName = f.Filename
                    }));
                }
            }).ToList();

            foreach (var f in files)
            {
                var tcv = new TypeSystemConvertVisitor(f.ParsedFile);
                f.SyntaxTree.AcceptVisitor(tcv);
                project = project.AddOrUpdateFiles(f.ParsedFile);
            }
            project = project.AddAssemblyReferences(references);

            return(new PreparedCompilation(project.CreateCompilation(), files));
        }
		public static PreparedCompilation CreateCompilation(string assemblyName, IEnumerable<ISourceFile> sourceFiles, IEnumerable<IAssemblyReference> references, IList<string> defineConstants, IEnumerable<IAssemblyResource> resources) {
			IProjectContent project = new CSharpProjectContent().SetAssemblyName(assemblyName);

			var files = sourceFiles.Select(f => { 
			                                        using (var rdr = f.Open()) {
			                                            var syntaxTree = CreateParser(defineConstants).Parse(rdr, f.Filename);
			                                            var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);
			                                            syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);
			                                            return new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile { FileName = f.Filename });
			                                        }
			                                    }).ToList();

			foreach (var f in files) {
				var tcv = new TypeSystemConvertVisitor(f.ParsedFile);
				f.SyntaxTree.AcceptVisitor(tcv);
				project = project.AddOrUpdateFiles(f.ParsedFile);
			}
			project = project.AddAssemblyReferences(references);
			if (resources != null) {
				var reslist = resources.ToList();
				if (reslist.Count > 0)
					project = project.AddResources(reslist);
			}

			return new PreparedCompilation(project.CreateCompilation(), files);
		}
        public Tuple <CSharpParsedFile, AstNode, CompilationUnit> GetIndexerBeforeCursor()
        {
            CompilationUnit baseUnit;

            if (currentMember == null && currentType == null)
            {
                return(null);
            }
            baseUnit = ParseStub("x] = a[1");

            var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
            var mref           = baseUnit.GetNodeAt(location, n => n is IndexerExpression);

            Print(baseUnit);
            AstNode expr;

            if (mref is IndexerExpression)
            {
                expr = ((IndexerExpression)mref).Target;
            }
            else
            {
                return(null);
            }

            var member  = Unit.GetNodeAt <AttributedNode> (memberLocation);
            var member2 = baseUnit.GetNodeAt <AttributedNode> (memberLocation);

            member2.Remove();
            member.ReplaceWith(member2);
            var tsvisitor = new TypeSystemConvertVisitor(CSharpParsedFile.FileName);

            Unit.AcceptVisitor(tsvisitor, null);
            return(Tuple.Create(tsvisitor.ParsedFile, (AstNode)expr, Unit));
        }
        public Tuple <CppParsedFile, AstNode, CompilationUnit> GetTypeBeforeCursor()
        {
            CompilationUnit baseUnit;

            if (currentMember == null && currentType == null)
            {
                return(null);
            }
            if (Unit == null)
            {
                return(null);
            }
            baseUnit = ParseStub("x> a");

            var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
            var expr           = baseUnit.GetNodeAt <AstType> (location.Line, location.Column + 1);  // '>' position
            var member         = Unit.GetNodeAt <AttributedNode> (memberLocation);
            var member2        = baseUnit.GetNodeAt <AttributedNode> (memberLocation);

            if (member == null || member2 == null)
            {
                return(null);
            }
            member2.Remove();
            member.ReplaceWith(member2);
            var tsvisitor = new TypeSystemConvertVisitor(CSharpParsedFile.FileName);

            Unit.AcceptVisitor(tsvisitor, null);
            return(Tuple.Create(tsvisitor.ParsedFile, (AstNode)expr, Unit));
        }
Exemplo n.º 9
0
        public static ILSpyUnresolvedFile Create(DecompiledTypeReference name, AstBuilder builder)
        {
            var writer = new StringWriter();
            var target = new TextWriterTokenWriter(writer)
            {
                IndentationString = "\t"
            };
            var output = new DebugInfoTokenWriterDecorator(TokenWriter.WrapInWriterThatSetsLocationsInAST(target));

            builder.RunTransformations();
            var syntaxTree = builder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });
            syntaxTree.AcceptVisitor(new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop()));
            ILSpyUnresolvedFile file = new ILSpyUnresolvedFile(name);
            var v = new TypeSystemConvertVisitor(file);

            syntaxTree.AcceptVisitor(v);

            file.MemberLocations = output.MemberLocations;
            file.DebugSymbols    = output.DebugSymbols;
            file.output          = writer.ToString();

            return(file);
        }
Exemplo n.º 10
0
		void Init(string program)
		{
			pc = new IDStringTestProjectContent();
			
			var cu = new CSharpParser().Parse(new StringReader(program));
			var parsedFile = new TypeSystemConvertVisitor(pc, "program.cs").Convert(cu);
			pc.UpdateProjectContent(null, parsedFile);
		}
Exemplo n.º 11
0
        void FindReferencesButtonClick(object sender, EventArgs e)
        {
            if (csharpTreeView.SelectedNode == null)
            {
                return;
            }

            SimpleProjectContent project = new SimpleProjectContent();
            var parsedFile = new TypeSystemConvertVisitor(project, "dummy.cs").Convert(compilationUnit);

            project.UpdateProjectContent(null, parsedFile);

            List <ITypeResolveContext> projects = new List <ITypeResolveContext>();

            projects.Add(project);
            projects.AddRange(builtInLibs.Value);

            using (var context = new CompositeTypeResolveContext(projects).Synchronize()) {
                CSharpResolver resolver = new CSharpResolver(context);

                AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag;
                IResolveVisitorNavigator navigator = new NodeListResolveVisitorNavigator(new[] { node });
                ResolveVisitor           visitor   = new ResolveVisitor(resolver, parsedFile, navigator);
                visitor.Scan(compilationUnit);
                IEntity             entity;
                MemberResolveResult mrr = visitor.GetResolveResult(node) as MemberResolveResult;
                TypeResolveResult   trr = visitor.GetResolveResult(node) as TypeResolveResult;
                if (mrr != null)
                {
                    entity = mrr.Member;
                }
                else if (trr != null)
                {
                    entity = trr.Type.GetDefinition();
                }
                else
                {
                    return;
                }

                FindReferences         fr             = new FindReferences();
                int                    referenceCount = 0;
                FoundReferenceCallback callback       = delegate(AstNode matchNode, ResolveResult result) {
                    referenceCount++;
                };

                var searchScopes = fr.GetSearchScopes(entity);
                navigator = new CompositeResolveVisitorNavigator(searchScopes.Select(s => s.GetNavigator(callback)).ToArray());
                visitor   = new ResolveVisitor(resolver, parsedFile, navigator);
                visitor.Scan(compilationUnit);

                csharpTreeView.BeginUpdate();
                ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
                csharpTreeView.EndUpdate();

                MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName);
            }
        }
Exemplo n.º 12
0
        void Init(string program)
        {
            pc = new IDStringTestProjectContent();

            var cu         = new CSharpParser().Parse(new StringReader(program));
            var parsedFile = new TypeSystemConvertVisitor(pc, "program.cs").Convert(cu);

            pc.UpdateProjectContent(null, parsedFile);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Converts this syntax tree into a parsed file that can be stored in the type system.
        /// </summary>
        public AlUnresolvedFile ToTypeSystem()
        {
            if (string.IsNullOrEmpty(this.FileName))
            {
                throw new InvalidOperationException("Cannot use ToTypeSystem() on a syntax tree without file name.");
            }
            var v = new TypeSystemConvertVisitor(this.FileName);

            v.VisitSyntaxTree(this);
            return(v.UnresolvedFile);
        }
Exemplo n.º 14
0
        protected Tuple <CSharpParsedFile, AstNode, CompilationUnit> GetInvocationBeforeCursor(bool afterBracket)
        {
            CompilationUnit baseUnit;

            if (currentMember == null)
            {
                baseUnit = ParseStub("", false);
                var section = baseUnit.GetNodeAt <AttributeSection> (location.Line, location.Column - 2);
                var attr    = section != null?section.Attributes.LastOrDefault() : null;

                if (attr != null)
                {
                    // insert target type into compilation unit, to respect the
                    attr.Remove();
                    var node = Unit.GetNodeAt(location) ?? Unit;
                    node.AddChild(attr, AttributeSection.AttributeRole);
                    return(Tuple.Create(CSharpParsedFile, (AstNode)attr, Unit));
                }
            }

            if (currentMember == null && currentType == null)
            {
                return(null);
            }
            baseUnit = ParseStub(afterBracket ? "" : "x");

            var     memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
            var     mref           = baseUnit.GetNodeAt(location.Line, location.Column - 1, n => n is InvocationExpression || n is ObjectCreateExpression);
            AstNode expr;

            if (mref is InvocationExpression)
            {
                expr = ((InvocationExpression)mref).Target;
            }
            else if (mref is ObjectCreateExpression)
            {
                expr = mref;
            }
            else
            {
                return(null);
            }
            var member  = Unit.GetNodeAt <AttributedNode> (memberLocation);
            var member2 = baseUnit.GetNodeAt <AttributedNode> (memberLocation);

            member2.Remove();
            member.ReplaceWith(member2);
            var tsvisitor = new TypeSystemConvertVisitor(CSharpParsedFile.FileName);

            Unit.AcceptVisitor(tsvisitor, null);
            return(Tuple.Create(tsvisitor.ParsedFile, (AstNode)expr, Unit));
        }
Exemplo n.º 15
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));
			}
		}
Exemplo n.º 16
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));
            }
        }
        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);
        }
Exemplo n.º 18
0
		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;
		}
Exemplo n.º 19
0
        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 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);
        }
Exemplo n.º 21
0
        protected ResolveResult ResolveAtLocation(string code)
        {
            CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", "")));

            TextLocation[] dollars = FindDollarSigns(code).ToArray();
            Assert.AreEqual(1, dollars.Length, "Expected 1 dollar signs marking the location");

            SetUp();

            CSharpParsedFile         parsedFile     = new CSharpParsedFile("test.cs", resolver.CurrentUsingScope);
            TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile, resolver.CurrentUsingScope, null);

            cu.AcceptVisitor(convertVisitor, null);
            project.UpdateProjectContent(null, convertVisitor.ParsedFile);

            ResolveResult rr = Resolver.ResolveAtLocation.Resolve(this.context, parsedFile, cu, dollars[0]);

            return(rr);
        }
Exemplo n.º 22
0
		public static ILSpyUnresolvedFile Create(DecompiledTypeReference name, AstBuilder builder)
		{
			var writer = new StringWriter();
			var target = new TextWriterTokenWriter(writer) { IndentationString = "\t" };
			var output = new DebugInfoTokenWriterDecorator(TokenWriter.WrapInWriterThatSetsLocationsInAST(target));
			builder.RunTransformations();
			var syntaxTree = builder.SyntaxTree;
			
			syntaxTree.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true });
			syntaxTree.AcceptVisitor(new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop()));
			ILSpyUnresolvedFile file = new ILSpyUnresolvedFile(name);
			var v = new TypeSystemConvertVisitor(file);
			syntaxTree.AcceptVisitor(v);
	
			file.MemberLocations = output.MemberLocations;
			file.DebugSymbols = output.DebugSymbols;
			file.output = writer.ToString();
			
			return file;
		}
Exemplo n.º 23
0
        IMember GetMemberFromLocation(AstNode node)
        {
            ITypeDefinition typeDef = resolver.CurrentTypeDefinition;

            if (typeDef == null)
            {
                return(null);
            }
            TextLocation location = TypeSystemConvertVisitor.GetStartLocationAfterAttributes(node);

            return(typeDef.GetMembers(
                       delegate(IUnresolvedMember m) {
                if (m.UnresolvedFile.FileName != unresolvedFile.FileName)
                {
                    return false;
                }
                DomRegion region = m.Region;
                return !region.IsEmpty && region.Begin <= location && region.End > location;
            },
                       GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions
                       ).FirstOrDefault());
        }
        protected void BuildSyntaxTree()
        {
            this.Log.Info("Building syntax tree...");

            var rewriter = new SharpSixRewriter(this);

            for (int i = 0; i < this.SourceFiles.Count; i++)
            {
                var fileName = this.SourceFiles[i];

                this.Log.Trace("Source file " + (fileName ?? string.Empty) + " ...");

                var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser();

                if (this.DefineConstants != null && this.DefineConstants.Count > 0)
                {
                    foreach (var defineConstant in this.DefineConstants)
                    {
                        parser.CompilerSettings.ConditionalSymbols.Add(defineConstant);
                    }
                }

                var syntaxTree = parser.Parse(rewriter.Rewrite(i), fileName);
                syntaxTree.FileName = fileName;
                //var syntaxTree = parser.Parse(reader, fileName);
                this.Log.Trace("\tParsing syntax tree done");

                if (parser.HasErrors)
                {
                    foreach (var error in parser.Errors)
                    {
                        throw new EmitterException(syntaxTree, string.Format("Parsing error in a file {0} {2}: {1}", fileName, error.Message, error.Region.Begin.ToString()));
                    }
                }

                var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);
                this.Log.Trace("\tExpanding query expressions done");

                syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);

                var emptyLambdaDetecter = new EmptyLambdaDetecter();
                syntaxTree.AcceptVisitor(emptyLambdaDetecter);
                this.Log.Trace("\tAccepting lambda detector visitor done");

                if (emptyLambdaDetecter.Found)
                {
                    var fixer   = new EmptyLambdaFixer();
                    var astNode = syntaxTree.AcceptVisitor(fixer);
                    this.Log.Trace("\tAccepting lambda fixer visitor done");
                    syntaxTree          = (astNode != null ? (SyntaxTree)astNode : syntaxTree);
                    syntaxTree.FileName = fileName;
                }

                var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile
                {
                    FileName = fileName
                });
                this.ParsedSourceFiles.Add(f);

                var tcv = new TypeSystemConvertVisitor(f.ParsedFile);
                f.SyntaxTree.AcceptVisitor(tcv);
                this.Log.Trace("\tAccepting type system convert visitor done");

                this.Log.Trace("Source file " + (fileName ?? string.Empty) + " done");
            }

            this.Log.Info("Building syntax tree done");
        }
		public Tuple<CSharpParsedFile, AstNode, CompilationUnit> GetTypeBeforeCursor ()
		{
			CompilationUnit baseUnit;
			if (currentMember == null && currentType == null) 
				return null;
			if (Unit == null)
				return null;
			baseUnit = ParseStub ("x> a");
			
			var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
			var expr = baseUnit.GetNodeAt<AstType> (location.Line, location.Column + 1); // '>' position
			var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
			var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
			if (member == null || member2 == null)
				return null;
			member2.Remove ();
			member.ReplaceWith (member2);
			var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
			Unit.AcceptVisitor (tsvisitor, null);
			return Tuple.Create (tsvisitor.ParsedFile, (AstNode)expr, Unit);
		}
Exemplo n.º 26
0
        public PreparedCompilation CreateCompilation(IEnumerable<ISourceFile> sourceFiles, IEnumerable<IAssemblyReference> references, IList<string> defineConstants)
        {
            IProjectContent project = new CSharpProjectContent();

            var files = sourceFiles.Select(f => {
                                                    using (var rdr = f.Open()) {
                                                        var syntaxTree = CreateParser(defineConstants).Parse(rdr, f.Filename);
                                                        var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);
                                                        syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);
                                                        var definedSymbols = DefinedSymbolsGatherer.Gather(syntaxTree, defineConstants);
                                                        return new PreparedCompilation.ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile(f.Filename, new UsingScope()), definedSymbols);
                                                    }
                                                }).ToList();

            foreach (var f in files) {
                var tcv = new TypeSystemConvertVisitor(f.ParsedFile);
                f.SyntaxTree.AcceptVisitor(tcv);
                project = project.AddOrUpdateFiles(f.ParsedFile);
            }
            project = project.AddAssemblyReferences(references);

            return new PreparedCompilation(project.CreateCompilation(), files);
        }
Exemplo n.º 27
0
		void ResolveButtonClick(object sender, EventArgs e)
		{
			SimpleProjectContent project = new SimpleProjectContent();
			TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(project, "dummy.cs");
			compilationUnit.AcceptVisitor(convertVisitor, null);
			project.UpdateProjectContent(null, convertVisitor.ParsedFile.TopLevelTypeDefinitions, null, null);
			
			List<ITypeResolveContext> projects = new List<ITypeResolveContext>();
			projects.Add(project);
			projects.AddRange(builtInLibs.Value);
			
			using (var context = new CompositeTypeResolveContext(projects).Synchronize()) {
				CSharpResolver resolver = new CSharpResolver(context);
				
				IResolveVisitorNavigator navigator = null;
				if (csharpTreeView.SelectedNode != null) {
					navigator = new NodeListResolveVisitorNavigator(new[] { (AstNode)csharpTreeView.SelectedNode.Tag });
				}
				ResolveVisitor visitor = new ResolveVisitor(resolver, convertVisitor.ParsedFile, navigator);
				visitor.Scan(compilationUnit);
				csharpTreeView.BeginUpdate();
				ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
				csharpTreeView.EndUpdate();
			}
		}
Exemplo n.º 28
0
		protected Tuple<CppParsedFile, AstNode, CompilationUnit> GetInvocationBeforeCursor (bool afterBracket)
		{
			CompilationUnit baseUnit;
			if (currentMember == null) {
				baseUnit = ParseStub ("", false);
				var section = baseUnit.GetNodeAt<AttributeSection> (location.Line, location.Column - 2);
				var attr = section != null ? section.Attributes.LastOrDefault () : null;
				if (attr != null) {
					// insert target type into compilation unit, to respect the 
					attr.Remove ();
					var node = Unit.GetNodeAt (location) ?? Unit;
					node.AddChild (attr, AttributeSection.AttributeRole);
					return Tuple.Create (CSharpParsedFile, (AstNode)attr, Unit);
				}
			}
			if (currentMember == null && currentType == null) {
				return null;
			}
			baseUnit = ParseStub (afterBracket ? "" : "x");
			
			var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
			var mref = baseUnit.GetNodeAt (location.Line, location.Column - 1, n => n is InvocationExpression || n is ObjectCreateExpression); 
			AstNode expr = null;
			if (mref is InvocationExpression) {
				expr = ((InvocationExpression)mref).Target;
			} else if (mref is ObjectCreateExpression) {
				expr = mref;
			} else {
				baseUnit = ParseStub (")};", false);
				mref = baseUnit.GetNodeAt (location.Line, location.Column - 1, n => n is InvocationExpression || n is ObjectCreateExpression); 
				if (mref is InvocationExpression) {
					expr = ((InvocationExpression)mref).Target;
				} else if (mref is ObjectCreateExpression) {
					expr = mref;
				}
				if (expr == null)
					return null;
			}
			var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
			var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
			member2.Remove ();
			member.ReplaceWith (member2);
			var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
			Unit.AcceptVisitor (tsvisitor, null);
			return Tuple.Create (tsvisitor.ParsedFile, (AstNode)expr, Unit);
		}
Exemplo n.º 29
0
		void FindReferencesButtonClick(object sender, EventArgs e)
		{
			if (csharpTreeView.SelectedNode == null)
				return;
			
			SimpleProjectContent project = new SimpleProjectContent();
			var parsedFile = new TypeSystemConvertVisitor(project, "dummy.cs").Convert(compilationUnit);
			project.UpdateProjectContent(null, parsedFile);
			
			List<ITypeResolveContext> projects = new List<ITypeResolveContext>();
			projects.Add(project);
			projects.AddRange(builtInLibs.Value);
			
			using (var context = new CompositeTypeResolveContext(projects).Synchronize()) {
				CSharpResolver resolver = new CSharpResolver(context);
				
				AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag;
				IResolveVisitorNavigator navigator = new NodeListResolveVisitorNavigator(new[] { node });
				ResolveVisitor visitor = new ResolveVisitor(resolver, parsedFile, navigator);
				visitor.Scan(compilationUnit);
				IEntity entity;
				MemberResolveResult mrr = visitor.GetResolveResult(node) as MemberResolveResult;
				TypeResolveResult trr = visitor.GetResolveResult(node) as TypeResolveResult;
				if (mrr != null) {
					entity = mrr.Member;
				} else if (trr != null) {
					entity = trr.Type.GetDefinition();
				} else {
					return;
				}
				
				FindReferences fr = new FindReferences();
				int referenceCount = 0;
				FoundReferenceCallback callback = delegate(AstNode matchNode, ResolveResult result) {
					referenceCount++;
				};
				
				var searchScopes = fr.GetSearchScopes(entity);
				navigator = new CompositeResolveVisitorNavigator(searchScopes.Select(s => s.GetNavigator(callback)).ToArray());
				visitor = new ResolveVisitor(resolver, parsedFile, navigator);
				visitor.Scan(compilationUnit);
				
				csharpTreeView.BeginUpdate();
				ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
				csharpTreeView.EndUpdate();
				
				MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName);
			}
		}
Exemplo n.º 30
0
        private void BuildSyntaxTreeForFile(int index, ref string[] rewriten)
        {
            var fileName = this.SourceFiles[index];

            this.Log.Trace("Source file " + (fileName ?? string.Empty) + " ...");

            var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser();

            if (this.DefineConstants != null && this.DefineConstants.Count > 0)
            {
                foreach (var defineConstant in this.DefineConstants)
                {
                    parser.CompilerSettings.ConditionalSymbols.Add(defineConstant);
                }
            }

            var syntaxTree = parser.Parse(rewriten[index], fileName);

            syntaxTree.FileName = fileName;
            this.Log.Trace("\tParsing syntax tree done");

            if (parser.HasErrors)
            {
                var errors = new List <string>();
                foreach (var error in parser.Errors)
                {
                    errors.Add(fileName + ":" + error.Region.BeginLine + "," + error.Region.BeginColumn + ": " + error.Message);
                }

                throw new EmitterException(syntaxTree, "Error parsing code." + Environment.NewLine + String.Join(Environment.NewLine, errors));
            }

            var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);

            this.Log.Trace("\tExpanding query expressions done");

            syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);

            var emptyLambdaDetecter = new EmptyLambdaDetecter();

            syntaxTree.AcceptVisitor(emptyLambdaDetecter);
            this.Log.Trace("\tAccepting lambda detector visitor done");

            if (emptyLambdaDetecter.Found)
            {
                var fixer   = new EmptyLambdaFixer();
                var astNode = syntaxTree.AcceptVisitor(fixer);
                this.Log.Trace("\tAccepting lambda fixer visitor done");
                syntaxTree          = (astNode != null ? (SyntaxTree)astNode : syntaxTree);
                syntaxTree.FileName = fileName;
            }

            var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile
            {
                FileName = fileName
            });

            this.ParsedSourceFiles[index] = f;

            var tcv = new TypeSystemConvertVisitor(f.ParsedFile);

            f.SyntaxTree.AcceptVisitor(tcv);
            this.Log.Trace("\tAccepting type system convert visitor done");

            this.Log.Trace("Source file " + (fileName ?? string.Empty) + " done");
        }
Exemplo n.º 31
0
        protected void BuildSyntaxTree()
        {
            for (int i = 0; i < this.SourceFiles.Count; i++)
            {
                var fileName = this.SourceFiles[i];

                using (var reader = new StreamReader(fileName))
                {
                    var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser();

                    if (this.DefineConstants != null && this.DefineConstants.Count > 0)
                    {
                        foreach (var defineConstant in this.DefineConstants)
                        {
                            parser.CompilerSettings.ConditionalSymbols.Add(defineConstant);
                        }
                    }

                    var syntaxTree = parser.Parse(reader, fileName);

                    if (parser.HasErrors)
                    {
                        foreach (var error in parser.Errors)
                        {
                            throw new EmitterException(syntaxTree, string.Format("Parsing error in a file {0} {2}: {1}", fileName, error.Message, error.Region.Begin.ToString()));
                        }
                    }

                    var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree);
                    syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree);

                    var emptyLambdaDetecter = new EmptyLambdaDetecter();
                    syntaxTree.AcceptVisitor(emptyLambdaDetecter);

                    if (emptyLambdaDetecter.Found)
                    {
                        var fixer = new EmptyLambdaFixer();
                        var astNode = syntaxTree.AcceptVisitor(fixer);
                        syntaxTree = (astNode != null ? (SyntaxTree)astNode : syntaxTree);
                    }

                    var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile { FileName = fileName });
                    this.ParsedSourceFiles.Add(f);

                    var tcv = new TypeSystemConvertVisitor(f.ParsedFile);
                    f.SyntaxTree.AcceptVisitor(tcv);
                }
            }
        }
Exemplo n.º 32
0
        Tuple<CSharpParsedFile, AstNode, CompilationUnit> GetExpressionBeforeCursor()
        {
            CompilationUnit baseUnit;
            if (currentMember == null) {
                baseUnit = ParseStub ("st {}", false);
                var type = baseUnit.GetNodeAt<MemberType> (location);
                if (type == null) {
                    baseUnit = ParseStub ("a;", false);
                    type = baseUnit.GetNodeAt<MemberType> (location);
                }
                if (type != null) {
                    // insert target type into compilation unit, to respect the
                    var target = type.Target;
                    target.Remove ();
                    var node = Unit.GetNodeAt (location) ?? Unit;
                    node.AddChild (target, AstNode.Roles.Type);
                    return Tuple.Create (CSharpParsedFile, (AstNode)target, Unit);
                }
            }

            if (currentMember == null && currentType == null) {
                return null;
            }
            baseUnit = ParseStub ("a()");

            // Hack for handle object initializer continuation expressions
            if (baseUnit.GetNodeAt (location) is AttributedNode || baseUnit.GetNodeAt<Expression> (location) == null) {
                baseUnit = ParseStub ("a()};");
            }

            var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
            var mref = baseUnit.GetNodeAt<MemberReferenceExpression> (location);
            Print (baseUnit);
            if (mref == null) {
                var invoke = baseUnit.GetNodeAt<InvocationExpression> (location);
                if (invoke != null)
                    mref = invoke.Target as MemberReferenceExpression;
            }
            Expression expr = null;
            if (mref != null) {
                expr = mref.Target.Clone ();
                mref.Parent.ReplaceWith (expr);
            } else {
                Expression tref = baseUnit.GetNodeAt<TypeReferenceExpression> (location);
                var memberType = tref != null ? ((TypeReferenceExpression)tref).Type as MemberType : null;
                if (memberType == null) {
                    memberType = baseUnit.GetNodeAt<MemberType> (location);
                    if (memberType != null) {
                        tref = baseUnit.GetNodeAt<Expression> (location);
                        if (tref == null)
                            return null;
                    }
                    if (tref is ObjectCreateExpression) {
                        expr = new TypeReferenceExpression (memberType.Target.Clone ());
                        expr.AddAnnotation (new ObjectCreateExpression ());
                    }
                }

                if (memberType == null)
                    return null;
                if (expr == null)
                    expr = new TypeReferenceExpression (memberType.Target.Clone ());
                tref.ReplaceWith (expr);
            }

            var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
            var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
            member2.Remove ();
            member.ReplaceWith (member2);
            var tsvisitor = new TypeSystemConvertVisitor (this.CSharpParsedFile.FileName);
            Unit.AcceptVisitor (tsvisitor, null);
            return Tuple.Create (tsvisitor.ParsedFile, (AstNode)expr, Unit);
        }
Exemplo n.º 33
0
        Tuple<CSharpParsedFile, AstNode, CompilationUnit> GetExpressionAtCursor()
        {
            //			if (currentMember == null && currentType == null)
            //				return null;

            TextLocation memberLocation;
            if (currentMember != null) {
                memberLocation = currentMember.Region.Begin;
            } else if (currentType != null) {
                memberLocation = currentType.Region.Begin;
            } else {
                memberLocation = location;
            }

            var baseUnit = ParseStub ("");

            var tmpUnit = baseUnit;
            AstNode expr = baseUnit.GetNodeAt<IdentifierExpression> (location.Line, location.Column - 1);
            if (expr == null)
                expr = baseUnit.GetNodeAt<Attribute> (location.Line, location.Column - 1);

            // try insertStatement
            if (expr == null && baseUnit.GetNodeAt<EmptyStatement> (location.Line, location.Column) != null) {
                tmpUnit = baseUnit = ParseStub ("a();", false);
                expr = baseUnit.GetNodeAt<InvocationExpression> (location.Line, location.Column + 1);
            }

            if (expr == null) {
                baseUnit = ParseStub ("()");
                expr = baseUnit.GetNodeAt<IdentifierExpression> (location.Line, location.Column - 1);
            }

            // try initializer expression
            if (expr == null) {
                baseUnit = ParseStub ("a = b};", false);
                expr = baseUnit.GetNodeAt<ArrayInitializerExpression> (location.Line, location.Column - 1);
            }

            // try statement
            if (expr == null) {
                expr = tmpUnit.GetNodeAt<SwitchStatement> (location.Line, location.Column - 1);
                baseUnit = tmpUnit;
            }

            if (expr == null) {
                var forStmt = tmpUnit.GetNodeAt<ForStatement> (location.Line, location.Column - 3);
                if (forStmt != null && forStmt.EmbeddedStatement.IsNull) {
                    expr = forStmt;
                    var id = new IdentifierExpression ("stub");
                    forStmt.EmbeddedStatement = new BlockStatement () { Statements = { new ExpressionStatement (id) }};
                    expr = id;
                    baseUnit = tmpUnit;
                }
            }

            if (expr == null) {
                var forStmt = tmpUnit.GetNodeAt<ForeachStatement> (location.Line, location.Column - 3);
                if (forStmt != null && forStmt.EmbeddedStatement.IsNull) {
                    forStmt.VariableNameToken = Identifier.Create ("stub");
                    expr = forStmt.VariableNameToken;
                    baseUnit = tmpUnit;
                }
            }

            if (expr == null) {
                expr = tmpUnit.GetNodeAt<VariableInitializer> (location.Line, location.Column - 1);
                baseUnit = tmpUnit;
            }

            // try parameter declaration type
            if (expr == null) {
                baseUnit = ParseStub (">", false, "{}");
                expr = baseUnit.GetNodeAt<TypeParameterDeclaration> (location.Line, location.Column - 1);
            }

            // try parameter declaration method
            if (expr == null) {
                baseUnit = ParseStub ("> ()", false, "{}");
                expr = baseUnit.GetNodeAt<TypeParameterDeclaration> (location.Line, location.Column - 1);
            }

            if (expr == null)
                return null;
            var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
            var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
            if (member != null && member2 != null) {
                member2.Remove ();

                if (member is TypeDeclaration) {
                    member.AddChild (member2, TypeDeclaration.MemberRole);
                } else {
                    member.ReplaceWith (member2);
                }
            } else {
                var tsvisitor2 = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
                Unit.AcceptVisitor (tsvisitor2, null);
                return Tuple.Create (tsvisitor2.ParsedFile, expr, baseUnit);
            }
            var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
            Unit.AcceptVisitor (tsvisitor, null);
            return Tuple.Create (tsvisitor.ParsedFile, expr, Unit);
        }
Exemplo n.º 34
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);
        }