Inheritance: IProjectContent
		protected CSharpProjectContent(CSharpProjectContent pc)
		{
			this.assemblyName = pc.assemblyName;
			this.parsedFiles = new Dictionary<string, IParsedFile>(pc.parsedFiles, Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
			this.Location = pc.Location;
		}
        public CSharpCompletion()
        {
            ProjectContent = new CSharpProjectContent();
            var assemblies = new List<Assembly>
            {
                    typeof(object).Assembly, // mscorlib
                    typeof(Uri).Assembly, // System.dll
                    typeof(Enumerable).Assembly, // System.Core.dll
            //					typeof(System.Xml.XmlDocument).Assembly, // System.Xml.dll
            //					typeof(System.Drawing.Bitmap).Assembly, // System.Drawing.dll
            //					typeof(Form).Assembly, // System.Windows.Forms.dll
            //					typeof(ICSharpCode.NRefactory.TypeSystem.IProjectContent).Assembly,
                };

            var unresolvedAssemblies = new IUnresolvedAssembly[assemblies.Count];
            Stopwatch total = Stopwatch.StartNew();
            Parallel.For(
                0, assemblies.Count,
                delegate(int i)
                {
                    var loader = new CecilLoader();
                    var path = assemblies[i].Location;
                    loader.DocumentationProvider = GetXmlDocumentation(assemblies[i].Location);
                    unresolvedAssemblies[i] = loader.LoadAssemblyFile(assemblies[i].Location);
                });
            Debug.WriteLine("Init project content, loading base assemblies: " + total.Elapsed);
            ProjectContent = ProjectContent.AddAssemblyReferences((IEnumerable<IUnresolvedAssembly>)unresolvedAssemblies);
        }
        public IProjectContent AddAssemblyReferences(params IAssemblyReference[] references)
        {
            CSharpProjectContent pc = Clone();

            pc.assemblyReferences.AddRange(references);
            return(pc);
        }
		void Init(string program)
		{
			var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
			var cu = new CSharpParser().Parse(new StringReader(program), "program.cs");
			compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation();
			typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault();
		}
        public IProjectContent SetLocation(string newLocation)
        {
            CSharpProjectContent pc = Clone();

            pc.location = newLocation;
            return(pc);
        }
示例#6
0
 protected CSharpProjectContent(CSharpProjectContent pc)
 {
     this.assemblyName       = pc.assemblyName;
     this.parsedFiles        = new Dictionary <string, IParsedFile>(pc.parsedFiles, Platform.FileNameComparer);
     this.assemblyReferences = new List <IAssemblyReference>(pc.assemblyReferences);
     this.Location           = pc.Location;
 }
示例#7
0
        public Project(StructEx.Solution solution, string title, string fileName)
            : base(solution, title, fileName)
        {
            Files = new List<File>();
            ProjectContent = new CSharpProjectContent();
            ResolvedReferencedAssemblies = new List<IUnresolvedAssembly>();

            ProjectContent = ProjectContent.SetAssemblyName(AssemblyName);
            ProjectContent = ProjectContent.SetProjectFileName(fileName);

            ProjectContent = ProjectContent.SetCompilerSettings(Utils.Convert.ToCompilerSettings(CompilerSettings));

            foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile"))
            {
                Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude)));
            }

            var files =
                Files.Select(f => f.UnresolvedTypeSystemForFile);
            ProjectContent = ProjectContent.AddOrUpdateFiles(files);

            foreach (var projectReference in ReferencedProjects)
            {
                ProjectContent = ProjectContent.AddAssemblyReferences(new[] { new ProjectReference(projectReference) });
            }

            ResolveAssemblies();
        }
		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 MemberCollectorTests()
        {
            _memberCollector = new CollectAllMembers.MemberCollector();

            #region Initialize _compilation
            var referencedAssemblies = new Type[]
            {
                typeof (System.Exception),
                typeof (ICollection),
                typeof (IList<>)
            }
            .Select(t => t.Assembly.Location);

            IProjectContent dummyProject = new CSharpProjectContent();

            dummyProject =
                dummyProject.AddAssemblyReferences(
                    referencedAssemblies
                        .Distinct()
                        .Select(
                            a => new CecilLoader().LoadAssemblyFile(a)));

            _compilation =
                new DefaultSolutionSnapshot(new []{dummyProject})
                    .GetCompilation(dummyProject);
            #endregion
        }
        public IProjectContent SetAssemblyName(string newAssemblyName)
        {
            CSharpProjectContent pc = Clone();

            pc.assemblyName = newAssemblyName;
            return(pc);
        }
示例#11
0
		void Init(string program)
		{
			var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
			var syntaxTree = SyntaxTree.Parse(program, "program.cs");
			compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation();
			typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault();
		}
        public IProjectContent RemoveAssemblyReferences(IEnumerable <IAssemblyReference> references)
        {
            CSharpProjectContent pc = Clone();

            pc.assemblyReferences.RemoveAll(r => references.Contains(r));
            return(pc);
        }
        public IProjectContent AddAssemblyReferences(IEnumerable <IAssemblyReference> references)
        {
            CSharpProjectContent pc = Clone();

            pc.assemblyReferences.AddRange(references);
            return(pc);
        }
        public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
        {
            var doc = new ReadOnlyDocument(editorText);
            var location = doc.GetLocation(offset);

            string parsedText = editorText; // TODO: Why are there different values in test cases?


            var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
            syntaxTree.Freeze();
            var unresolvedFile = syntaxTree.ToTypeSystem();

            var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);

            IProjectContent pctx = new CSharpProjectContent();
            var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value };
            pctx = pctx.AddAssemblyReferences(refs);
            pctx = pctx.AddOrUpdateFiles(unresolvedFile);

            var cmp = pctx.CreateCompilation();

            var resolver3 = unresolvedFile.GetResolver(cmp, location);
            var engine = new CSharpCompletionEngine(doc, mb, new TestCompletionDataFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext);


            engine.EolMarker = Environment.NewLine;
            engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();

            var data = engine.GetCompletionData(offset, controlSpace: false);
            return data;

        }
        public IProjectContent UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile)
        {
            if (oldFile == null && newFile == null)
            {
                return(this);
            }
            if (oldFile != null && newFile != null)
            {
                if (!Platform.FileNameComparer.Equals(oldFile.FileName, newFile.FileName))
                {
                    throw new ArgumentException("When both oldFile and newFile are specified, they must use the same file name.");
                }
            }
            CSharpProjectContent pc = Clone();

            if (newFile == null)
            {
                pc.parsedFiles.Remove(oldFile.FileName);
            }
            else
            {
                pc.parsedFiles[newFile.FileName] = newFile;
            }
            return(pc);
        }
		void SetUpWithCode(string code, int offset)
		{
			textEditor.Document.Text = code;
			textEditor.Caret.Offset = offset;
			
			var parseInfo = textEditor.CreateParseInformation();
			IProject project = MockRepository.GenerateStrictMock<IProject>();
			var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile);
			pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml });
			var compilation = pc.CreateCompilation();
			SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>());
			SD.ParserService.Stub(p => p.GetCachedParseInformation(textEditor.FileName)).Return(parseInfo);
			SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation);
			SD.ParserService.Stub(p => p.GetCompilationForFile(textEditor.FileName)).Return(compilation);
			SD.ParserService.Stub(p => p.Parse(textEditor.FileName, textEditor.Document)).WhenCalled(
				i => {
					var p = new XamlParser();
					p.TaskListTokens = TaskListTokens;
					i.ReturnValue = p.Parse(textEditor.FileName, textEditor.Document, true, project, CancellationToken.None);
				}).Return(parseInfo); // fake Return to make it work
			SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock<IFileService>());
			IViewContent view = MockRepository.GenerateStrictMock<IViewContent>();
			view.Stub(v => v.GetService(typeof(ITextEditor))).Return(textEditor);
			SD.FileService.Stub(f => f.OpenFile(textEditor.FileName, false)).Return(view);
		}
		protected void Prepare(string source, bool minimizeNames = true, bool expectErrors = false) {
			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 });

			_errorReporter = new MockErrorReporter(!expectErrors);

			var compilation = project.CreateCompilation();
			var s = new AttributeStore(compilation, _errorReporter);
			RunAutomaticMetadataAttributeAppliers(s, compilation);
			s.RunAttributeCode();

			Metadata = new MetadataImporter(_errorReporter, compilation, s, new CompilerOptions { MinimizeScript = minimizeNames });

			Metadata.Prepare(compilation.GetAllTypeDefinitions());

			AllErrors = _errorReporter.AllMessages.ToList().AsReadOnly();
			AllErrorTexts = _errorReporter.AllMessages.Select(m => m.FormattedMessage).ToList().AsReadOnly();
			if (expectErrors) {
				Assert.That(AllErrorTexts, Is.Not.Empty, "Compile should have generated errors");
			}
			else {
				Assert.That(AllErrorTexts, Is.Empty, "Compile should not generate errors");
			}

			AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName);
		}
示例#18
0
		IEntity Lookup(string cref)
		{
			string program = @"using System;
using System.Collections.Generic;
/// <summary/>
class Test {
	int @int;
	void M(int a) {}
	
	void Overloaded(int a) {}
	void Overloaded(string a) {}
	void Overloaded(ref int a) {}
	
	public int this[int index] { get { return 0; } }
	
	public static int operator +(Test a, int b) { return 0; }
	public static implicit operator Test(int a) { return 0; }
	public static implicit operator int(Test a) { return 0; }
}
interface IGeneric<A, B> {
	void Test<T>(ref T[,] a);
}
class Impl<T> : IGeneric<List<string>[,], T> {
	void IGeneric<List<string>[,], T>.Test<X>(ref X[,] a) {}
}";
			
			var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
			var syntaxTree = SyntaxTree.Parse(program, "program.cs");
			var compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation();
			var typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.First();
			IEntity entity = typeDefinition.Documentation.ResolveCref(cref);
			Assert.IsNotNull(entity, "ResolveCref() returned null.");
			return entity;
		}
示例#19
0
        public IProjectContent SetProjectFileName(string newProjectFileName)
        {
            CSharpProjectContent pc = Clone();

            pc.projectFileName = newProjectFileName;
            return(pc);
        }
示例#20
0
 private IProjectContent CreateCSharpProjectContent(string fileName)
 {
     IProjectContent pc = new CSharpProjectContent();
     pc = pc.SetAssemblyName(AssemblyName);
     pc = pc.SetProjectFileName(fileName);
     pc = pc.SetCompilerSettings(CompilerSettings);
     return pc;
 }
示例#21
0
 public Project (IFileSystem fileSystem, Logger logger)
 {
     _fileSystem = fileSystem;
     _logger = logger;
     Files = new List<CSharpFile> ();
     References = new List<IAssemblyReference>();
     ProjectContent = new CSharpProjectContent();
 }
示例#22
0
 protected CSharpProjectContent(CSharpProjectContent pc)
 {
     this.assemblyName       = pc.assemblyName;
     this.projectFileName    = pc.projectFileName;
     this.location           = pc.location;
     this.unresolvedFiles    = new Dictionary <string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
     this.assemblyReferences = new List <IAssemblyReference>(pc.assemblyReferences);
     this.compilerSettings   = pc.compilerSettings;
 }
示例#23
0
		protected CSharpProjectContent(CSharpProjectContent pc)
		{
			this.assemblyName = pc.assemblyName;
			this.projectFileName = pc.projectFileName;
			this.location = pc.location;
			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
			this.compilerSettings = pc.compilerSettings;
		}
示例#24
0
        public IProjectContent RemoveAssemblyReferences(params IAssemblyReference[] references)
        {
            CSharpProjectContent pc = Clone();

            foreach (var r in references)
            {
                pc.assemblyReferences.Remove(r);
            }
            return(pc);
        }
示例#25
0
        /// <summary>
        /// Removes the files with the specified names.
        /// </summary>
        public IProjectContent RemoveFiles(IEnumerable <string> fileNames)
        {
            CSharpProjectContent pc = Clone();

            foreach (var fileName in fileNames)
            {
                pc.unresolvedFiles.Remove(fileName);
            }
            return(pc);
        }
示例#26
0
        /// <summary>
        /// Adds the specified files to the project content.
        /// If a file with the same name already exists, updated the existing file.
        /// </summary>
        public IProjectContent AddOrUpdateFiles(IEnumerable <IUnresolvedFile> newFiles)
        {
            CSharpProjectContent pc = Clone();

            foreach (var file in newFiles)
            {
                pc.unresolvedFiles[file.FileName] = file;
            }
            return(pc);
        }
示例#27
0
        /// <summary>
        /// Sets both the short and the full assembly names.
        /// </summary>
        /// <param name="newAssemblyName">New full assembly name.</param>
        public IProjectContent SetAssemblyName(string newAssemblyName)
        {
            CSharpProjectContent pc = Clone();

            pc.fullAssemblyName = newAssemblyName;
            int pos = newAssemblyName != null?newAssemblyName.IndexOf(',') : -1;

            pc.assemblyName = pos < 0 ? newAssemblyName : newAssemblyName.Substring(0, pos);
            return(pc);
        }
        public IProjectContent RemoveResources(IEnumerable <IAssemblyResource> resources)
        {
            CSharpProjectContent pc = Clone();

            foreach (var r in resources)
            {
                pc.resources.Remove(r);
            }
            return(pc);
        }
示例#29
0
        public IProjectContent SetCompilerSettings(object compilerSettings)
        {
            if (!(compilerSettings is CompilerSettings))
            {
                throw new ArgumentException("Settings must be an instance of " + typeof(CompilerSettings).FullName, "compilerSettings");
            }
            CSharpProjectContent pc = Clone();

            pc.compilerSettings = (CompilerSettings)compilerSettings;
            pc.compilerSettings.Freeze();
            return(pc);
        }
示例#30
0
			internal static StubbedRefactoringContext Create(SyntaxTree tree, bool supportsVersion5 = true)
			{
				IProjectContent pc = new CSharpProjectContent();
				pc = pc.AddAssemblyReferences(CecilLoaderTests.Mscorlib);
				pc = pc.AddOrUpdateFiles(new[] {
					tree.ToTypeSystem()
				});
				var compilation = pc.CreateCompilation();
				var resolver = new CSharpAstResolver(compilation, tree);

				return new StubbedRefactoringContext(resolver, supportsVersion5);
			}
示例#31
0
        public OrphanProject(ISolution solution)
        {
            Title = "Orphan Project";
            _file = new CSharpFile(this, "dummy_file", "");
            Files = new List<CSharpFile>();
            Files.Add(_file);

            string mscorlib = CSharpProject.FindAssembly(CSharpProject.AssemblySearchPaths, "mscorlib");
            ProjectContent = new CSharpProjectContent()
                .SetAssemblyName("OrphanProject")
                .AddAssemblyReferences(CSharpProject.LoadAssembly(mscorlib));
        }
        protected string Process(IEnumerable<JsType> types, IScriptSharpMetadataImporter metadataImporter = null)
        {
            metadataImporter = metadataImporter ?? new MockScriptSharpMetadataImporter();

            IProjectContent proj = new CSharpProjectContent();
            proj = proj.AddAssemblyReferences(new[] { Common.Mscorlib });
            var comp = proj.CreateCompilation();
            var er = new MockErrorReporter(true);
            var obj = new OOPEmulator.ScriptSharpOOPEmulator(metadataImporter, er);
            Assert.That(er.AllMessages, Is.Empty, "Should not have errors");
            var rewritten = obj.Rewrite(types, comp);
            return string.Join("", rewritten.Select(s => OutputFormatter.Format(s, allowIntermediates: true)));
        }
示例#33
0
        public OrphanProject(IFileSystem fileSystem, Logger logger) : base(fileSystem, logger)
        {
            Title = "Orphan Project";
            Files = new List<CSharpFile>();

            ProjectId = Guid.NewGuid();

            References = new List<IAssemblyReference>();
            FileName = ProjectFileName;
            string mscorlib = FindAssembly("mscorlib");
            Console.WriteLine(mscorlib);
            ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(ProjectFileName)
                .AddAssemblyReferences(LoadAssembly(mscorlib));
        }
示例#34
0
        public OrphanProject()
        {
            Title = "Orphan Project";
            Files = new List<CSharpFile>();

            ProjectId = Guid.NewGuid();

            References = new List<IAssemblyReference>();
            FileName = "OrphanProject";
            string mscorlib = CSharpProject.FindAssembly("mscorlib");
            Console.WriteLine(mscorlib);
            ProjectContent = new CSharpProjectContent()
                .SetAssemblyName("OrphanProject")
                .AddAssemblyReferences(CSharpProject.LoadAssembly(mscorlib));
        }
        protected string Process(IEnumerable<JsType> types, IScriptSharpMetadataImporter metadataImporter = null, IErrorReporter errorReporter = null, IMethod entryPoint = null)
        {
            metadataImporter = metadataImporter ?? new MockScriptSharpMetadataImporter();

            IProjectContent proj = new CSharpProjectContent();
            proj = proj.AddAssemblyReferences(new[] { Common.Mscorlib });
            var comp = proj.CreateCompilation();
            bool verifyNoErrors = errorReporter == null;
            errorReporter = errorReporter ?? new MockErrorReporter();
            var obj = new OOPEmulator.ScriptSharpOOPEmulator(comp, metadataImporter, new MockRuntimeLibrary(), new MockNamer(), errorReporter);
            if (verifyNoErrors)
                Assert.That(((MockErrorReporter)errorReporter).AllMessages, Is.Empty, "Should not have errors");

            var rewritten = obj.Process(types, comp, entryPoint);
            return string.Join("", rewritten.Select(s => OutputFormatter.Format(s, allowIntermediates: true)));
        }
        public IProjectContent UpdateProjectContent(IEnumerable <IParsedFile> oldFiles, IEnumerable <IParsedFile> newFiles)
        {
            CSharpProjectContent pc = Clone();

            if (oldFiles != null)
            {
                foreach (var oldFile in oldFiles)
                {
                    pc.parsedFiles.Remove(oldFile.FileName);
                }
            }
            if (newFiles != null)
            {
                foreach (var newFile in newFiles)
                {
                    pc.parsedFiles.Add(newFile.FileName, newFile);
                }
            }
            return(pc);
        }
		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("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");
		}
		public void SetUp()
		{
			SD.InitializeForUnitTests();
			textEditor = new MockTextEditor();
			textEditor.Document.Text = programStart + "override " + programEnd;
			textEditor.Caret.Offset = programStart.Length + "override ".Length;
			var parseInfo = textEditor.CreateParseInformation();
			var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile);
			pc = pc.AddAssemblyReferences(new[] { Corlib });
			var compilation = pc.CreateCompilation();
			SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>());
			SD.ParserService.Stub(p => p.GetCachedParseInformation(textEditor.FileName)).Return(parseInfo);
			SD.ParserService.Stub(p => p.GetCompilationForFile(textEditor.FileName)).Return(compilation);
			SD.ParserService.Stub(p => p.Parse(textEditor.FileName, textEditor.Document)).WhenCalled(
				i => {
					var syntaxTree = new CSharpParser().Parse(textEditor.Document, textEditor.FileName);
					i.ReturnValue = new CSharpFullParseInformation(syntaxTree.ToTypeSystem(), null, syntaxTree);
				});
			CSharpCompletionBinding completion = new CSharpCompletionBinding();
			keyPressResult = completion.HandleKeyPressed(textEditor, ' ');
		}
示例#39
0
		void SetUpWithCode(FileName fileName, ITextSource textSource)
		{
			IProject project = MockRepository.GenerateStrictMock<IProject>();
			var parseInfo = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None);
			
			var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile);
			pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml });
			var compilation = pc.CreateCompilation();
			SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>());
			
			SD.ParserService.Stub(p => p.GetCachedParseInformation(fileName)).Return(parseInfo);
			SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation);
			SD.ParserService.Stub(p => p.GetCompilationForFile(fileName)).Return(compilation);
			SD.ParserService.Stub(p => p.Parse(fileName, textSource)).WhenCalled(
				i => {
					i.ReturnValue = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None);
				}).Return(parseInfo); // fake Return to make it work
			SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock<IFileService>());
			IViewContent view = MockRepository.GenerateStrictMock<IViewContent>();
			SD.FileService.Stub(f => f.OpenFile(fileName, false)).Return(view);
		}
        public void DynamicAndObjectShouldBeConsideredTheSameTypeWhenMatchingSignatures()
        {
            string program = @"using System.Collections.Generic;
            public class Base {
              public virtual void M1(object p) {}
              public virtual void M2(List<object> p) {}
              public virtual object M3() { return null; }
              public virtual List<object> M4() { return null; }
              public virtual void M5(dynamic p) {}
              public virtual void M6(List<dynamic> p) {}
              public virtual dynamic M7() { return null; }
              public virtual List<dynamic> M8() { return null; }
            }

            public class Derived : Base {
              public override void M1(dynamic p) {}
              public override void M2(List<dynamic> p) {}
              public override dynamic M3() { return null; }
              public override List<dynamic> M4() { return null; }
              public override void M5(object p) {}
              public override void M6(List<object> p) {}
              public override object M7() { return null; }
              public override List<object> M8() { return null; }
            }";

            var unresolvedFile = new CSharpParser().Parse(program, "program.cs").ToTypeSystem();
            var compilation = new CSharpProjectContent().AddAssemblyReferences(CecilLoaderTests.Mscorlib).AddOrUpdateFiles(unresolvedFile).CreateCompilation();

            var dtype = (ITypeDefinition)ReflectionHelper.ParseReflectionName("Derived").Resolve(compilation);
            var btype = (ITypeDefinition)ReflectionHelper.ParseReflectionName("Base").Resolve(compilation);

            foreach (var name in new[] { "M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8" }) {
                Assert.That(InheritanceHelper.GetBaseMember(dtype.Methods.Single(m => m.Name == name)), Is.EqualTo(btype.Methods.Single(m => m.Name == name)), name + " does not match");
            }

            foreach (var name in new[] { "M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8" }) {
                Assert.That(InheritanceHelper.GetDerivedMember(btype.Methods.Single(m => m.Name == name), dtype), Is.EqualTo(dtype.Methods.Single(m => m.Name == name)), name + " does not match");
            }
        }
示例#41
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);
        }
示例#42
0
		void FindReferencesButtonClick(object sender, EventArgs e)
		{
			if (csharpTreeView.SelectedNode == null)
				return;
			
			IProjectContent project = new CSharpProjectContent();
			var unresolvedFile = syntaxTree.ToTypeSystem();
			project = project.AddOrUpdateFiles(unresolvedFile);
			project = project.AddAssemblyReferences(builtInLibs.Value);
			
			ICompilation compilation = project.CreateCompilation();
			CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
			
			AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag;
			IEntity entity;
			MemberResolveResult mrr = resolver.Resolve(node) as MemberResolveResult;
			TypeResolveResult trr = resolver.Resolve(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) {
				Debug.WriteLine(matchNode.StartLocation + " - " + matchNode + " - " + result);
				referenceCount++;
			};
			
			var searchScopes = fr.GetSearchScopes(entity);
			Debug.WriteLine("Find references to " + entity.ReflectionName);
			fr.FindReferencesInFile(searchScopes, unresolvedFile, syntaxTree, compilation, callback, CancellationToken.None);
			
			MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName);
		}
示例#43
0
		void ResolveButtonClick(object sender, EventArgs e)
		{
			IProjectContent project = new CSharpProjectContent();
			var unresolvedFile = syntaxTree.ToTypeSystem();
			project = project.AddOrUpdateFiles(unresolvedFile);
			project = project.AddAssemblyReferences(builtInLibs.Value);
			
			ICompilation compilation = project.CreateCompilation();
			
			ResolveResult result;
			if (csharpTreeView.SelectedNode != null) {
				var selectedNode = (AstNode)csharpTreeView.SelectedNode.Tag;
				CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
				result = resolver.Resolve(selectedNode);
				// CSharpAstResolver.Resolve() never returns null
			} else {
				TextLocation location = GetTextLocation(csharpCodeTextBox, csharpCodeTextBox.SelectionStart);
				result = ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, location);
				if (result == null) {
					MessageBox.Show("Could not find a resolvable node at the caret location.");
					return;
				}
			}
			using (var dlg = new SemanticTreeDialog(result))
				dlg.ShowDialog();
		}
示例#44
0
		public static ICompilation CreateCompilationWithoutCorlib(params IUnresolvedFile[] unresolvedFiles)
		{
			var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles);
			return pc.CreateCompilation();
		}
示例#45
0
		public static ICompilation CreateCompilation(params IUnresolvedFile[] unresolvedFiles)
		{
			var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles);
			pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
			return pc.CreateCompilation();
		}
示例#46
0
		void HandleClicked (object sender, EventArgs e)
		{
			var parser = new CSharpParser ();
			var unit = parser.Parse (textview1.Buffer.Text, "dummy.cs");
			
			var unresolvedFile = unit.ToTypeSystem();
			
			IProjectContent project = new CSharpProjectContent ();
			project = project.AddOrUpdateFiles (unresolvedFile);
			project = project.AddAssemblyReferences (builtInLibs.Value);
			
			
			CSharpAstResolver resolver = new CSharpAstResolver(project.CreateCompilation (), unit, unresolvedFile);
			ShowUnit (unit, resolver);
			
		}
示例#47
0
 protected CSharpProjectContent(CSharpProjectContent pc)
 {
     this.assemblyName       = pc.assemblyName;
     this.parsedFiles        = new Dictionary <string, IParsedFile>(pc.parsedFiles);
     this.assemblyReferences = new List <IAssemblyReference>(pc.assemblyReferences);
 }