AddAssemblyReferences() public méthode

public AddAssemblyReferences ( ) : IProjectContent
Résultat IProjectContent
        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 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();
        }
		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);
		}
		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 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;

        }
		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);
		}
        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);
        }
			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);
			}
        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)));
        }
        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)));
        }
		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);
		}
		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, ' ');
		}
Exemple #14
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);
			
		}
        // i'm not using this...
        public static CSharpCompletionEngine CreateEngine(string text, out int cursorPosition, params IUnresolvedAssembly[] references)
        {
            string parsedText;
            string editorText;
            cursorPosition = text.IndexOf('$');
            int endPos = text.IndexOf('$', cursorPosition + 1);
            if (endPos == -1)
            {
                if (cursorPosition < 0)
                {
                    parsedText = editorText = text;
                }
                else
                {
                    parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1);
                }
            }
            else
            {
                parsedText = text.Substring(0, cursorPosition) + new string(' ', endPos - cursorPosition) + text.Substring(endPos + 1);
                editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1);
                cursorPosition = endPos - 1;
            }
            var doc = new ReadOnlyDocument(editorText);

            IProjectContent projContent = new CSharpProjectContent();
            var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value, systemXmlLinq.Value };
            if (references != null)
                refs.AddRange(references);

            projContent = projContent.AddAssemblyReferences(refs);

            // Parse => SyntaxTree
            var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
            syntaxTree.Freeze();

            var unresolvedFile = syntaxTree.ToTypeSystem();
            // Add CSharpUnresolvedFile to CSharpProjectContent
            projContent = projContent.AddOrUpdateFiles(unresolvedFile);

            // Create a TypeSystem.ICompilation that allows resolving within the project.
            var compilation = projContent.CreateCompilation();
            var textCursorLocation = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation(1, 1);


            #region Create and Refine the type resolution context as much as possible 

            var typeResolveContext = new CSharpTypeResolveContext(compilation.MainAssembly);
            typeResolveContext = typeResolveContext.WithUsingScope(unresolvedFile.GetUsingScope(textCursorLocation).Resolve(compilation));

            var curDef = unresolvedFile.GetInnermostTypeDefinition(textCursorLocation);
            if (curDef != null)
            {
                var resolvedDef = curDef.Resolve(typeResolveContext).GetDefinition();
                typeResolveContext = typeResolveContext.WithCurrentTypeDefinition(resolvedDef);
                var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= textCursorLocation && textCursorLocation < m.BodyRegion.End);
                if (curMember != null)
                {
                    typeResolveContext = typeResolveContext.WithCurrentMember(curMember);
                }
            }

            #endregion
            
            // Cool!  Marry the concept of content & typed 
            var completionContext = new DefaultCompletionContextProvider(doc, unresolvedFile);
            #region Add Preprocessor Symbols
            completionContext.AddSymbol("TEST");
            foreach (var sym in syntaxTree.ConditionalSymbols)
            {
                completionContext.AddSymbol(sym);
            }
            #endregion
            var engine = new CSharpCompletionEngine(doc, completionContext, new TestCompletionDataFactory(new CSharpResolver(typeResolveContext)), projContent, typeResolveContext);

            engine.EolMarker = Environment.NewLine;
            engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
            return engine;
        }
Exemple #16
0
        public CSharpProject(Solution solution, string title, string fileName)
        {
            // Normalize the file name
            fileName = Path.GetFullPath(fileName);

            _solution = solution;
            Title = title;
            FileName = fileName;

            // Use MSBuild to open the .csproj
            var msbuildProject = GetMSBuildProject(fileName);

            // Figure out some compiler settings
            AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
            CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
            CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
            string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");
            foreach (string symbol in defineConstants.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                CompilerSettings.ConditionalSymbols.Add(symbol.Trim());

            // Initialize the unresolved type system
            ProjectContent = new CSharpProjectContent();
            ProjectContent = ProjectContent.SetAssemblyName(AssemblyName);
            ProjectContent = ProjectContent.SetProjectFileName(fileName);
            ProjectContent = ProjectContent.SetCompilerSettings(CompilerSettings);
            // Parse the C# code files
            foreach (var item in msbuildProject.GetItems("Compile"))
            {
                AddCSharpFile(
                    new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude)));
            }

            var assemblyReferences =
                new AssemblyReferencesResolved
                {
                    References = ResolveAssemblyReferences(msbuildProject).ToList()
                };

            if (null != OnAssemblyReferencesResolved)
                OnAssemblyReferencesResolved(this, assemblyReferences);

            // Add referenced assemblies:
            foreach (string assemblyFile in assemblyReferences.References)
            {
                IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
                ProjectContent = ProjectContent.AddAssemblyReferences(new IAssemblyReference[] { assembly });
            }

            // Add project references:
            foreach (var item in msbuildProject.GetItems("ProjectReference"))
            {
                string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
                // Normalize the path; this is required to match the name with the referenced project's file name
                referencedFileName = Path.GetFullPath(referencedFileName);
                ProjectContent = ProjectContent.AddAssemblyReferences(new IAssemblyReference[] { new ProjectReference(referencedFileName) });
            }
        }
Exemple #17
0
		void ResolveButtonClick(object sender, EventArgs e)
		{
			IProjectContent project = new CSharpProjectContent();
			var parsedFile = compilationUnit.ToTypeSystem();
			project = project.UpdateProjectContent(null, parsedFile);
			project = project.AddAssemblyReferences(builtInLibs.Value);
			
			ICompilation compilation = project.CreateCompilation();
			
			StoreInDictionaryNavigator navigator;
			if (csharpTreeView.SelectedNode != null) {
				navigator = new StoreInDictionaryNavigator((AstNode)csharpTreeView.SelectedNode.Tag);
			} else {
				navigator = new StoreInDictionaryNavigator();
			}
			CSharpAstResolver resolver = new CSharpAstResolver(compilation, compilationUnit, parsedFile);
			resolver.ApplyNavigator(navigator);
			csharpTreeView.BeginUpdate();
			ShowResolveResultsInTree(csharpTreeView.Nodes, navigator);
			csharpTreeView.EndUpdate();
		}
        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 CSharpParsedFile("File.cs");
                var cu = parser.Parse(rdr, pf.FileName);
                cu.AcceptVisitor(new TypeSystemConvertVisitor(pf));
                project = project.UpdateProjectContent(null, pf);
            }
            project = project.AddAssemblyReferences(new[] { Common.Mscorlib });

            var compilation = project.CreateCompilation();

            errorReporter = new MockErrorReporter(!expectErrors);
            Metadata = new MetadataImporter.ScriptSharpMetadataImporter(minimizeNames);

            Metadata.Prepare(compilation.GetAllTypeDefinitions(), compilation.MainAssembly, errorReporter);

            AllErrors = errorReporter.AllMessages.ToList().AsReadOnly();
            AllErrorTexts = errorReporter.AllMessagesText.ToList().AsReadOnly();
            if (expectErrors) {
                AllErrorTexts.Should().NotBeEmpty("Compile should have generated errors");
            }
            else {
                AllErrorTexts.Should().BeEmpty("Compile should not generate errors");
            }

            AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName);
        }
Exemple #19
0
        public CSharpProject(Solution solution, string title, string fileName)
        {
            // Normalize the file name
            fileName = Path.GetFullPath(fileName);

            this.Solution = solution;
            this.Title = title;
            this.FileName = fileName;

            // Use MSBuild to open the .csproj
            var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
            // Figure out some compiler settings
            this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
            this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
            this.CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
            string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");
            foreach (string symbol in defineConstants.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
                this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());

            // Initialize the unresolved type system
            IProjectContent pc = new CSharpProjectContent();
            pc = pc.SetAssemblyName(this.AssemblyName);
            pc = pc.SetProjectFileName(fileName);
            pc = pc.SetCompilerSettings(this.CompilerSettings);
            // Parse the C# code files
            foreach (var item in msbuildProject.GetItems("Compile")) {
                var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
                Files.Add(file);
            }
            // Add parsed files to the type system
            pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile));

            // Add referenced assemblies:
            foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject)) {
                IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
                pc = pc.AddAssemblyReferences(new [] { assembly });
            }

            // Add project references:
            foreach (var item in msbuildProject.GetItems("ProjectReference")) {
                string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
                // Normalize the path; this is required to match the name with the referenced project's file name
                referencedFileName = Path.GetFullPath(referencedFileName);
                pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) });
            }
            this.ProjectContent = pc;
        }
Exemple #20
0
        public static void Main(string[] args)
        {
            // Parse options.
            string jasminJar = null;
            string outputJar = null;
            bool noConfig;
            string target;
            string debugLevel;
            bool debug;
            bool optimize;
            string define;
            List<string> reference = new List<string>();
            string warnLevel;
            List<string> files;
            var options = new OptionSet()
            {
                { "jasmin=", "Path to Jasmin JAR", x => jasminJar = x },
                { "out=", "The resulting JAR to create", x => outputJar = x },
                { "noconfig", "", x => noConfig = true },
                { "target=", "", x => target = x },
                { "debug", "", x => debugLevel = x },
                { "debug+", "", x => debug = true },
                { "optimize+", "", x => optimize = true },
                { "debug-", "", x => debug = false },
                { "optimize-", "", x => optimize = false },
                { "define", "", x => define = x },
                { "reference:", "", reference.Add },
                { "warn", "", x => warnLevel = x },
            };
            try
            {
                files = options.Parse(args);
                if (files.Count == 1 && files[0][0] == '@')
                {
                    // Read command line from file.
                    using (var reader = new StreamReader(files[0].Substring(1)))
                    {
                        //Console.WriteLine(reader.ReadToEnd());
                        files = options.Parse(reader.ReadToEnd().Split(' '));
                    }
                }
            }
            catch (OptionException ex)
            {
                Console.Write("cscjvm: ");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Try `cscjvm --help' for more information.");
                return;
            }

            if (string.IsNullOrWhiteSpace(jasminJar))
            {
                Console.WriteLine("Defaulting Jasmin JAR path to JASMIN_JAR environment variable.");
                jasminJar = Environment.GetEnvironmentVariable("JASMIN_JAR");
                if (string.IsNullOrWhiteSpace(jasminJar))
                {
                    Console.WriteLine("Jasmin JAR path must be set.");
                    return;
                }
            }

            Console.WriteLine("C# to JVM Compiler");
            Console.WriteLine("Using Jasmin at: " + jasminJar);

            foreach (var arg in args)
            {
                Console.WriteLine("argument: " + arg);
            }

            IProjectContent project = new CSharpProjectContent();

            var trees = new List<SyntaxTree>();

            Console.WriteLine("Parsing C# files...");
            var parser = new CSharpParser();
            foreach (var filename in files)
            {
                using (var reader = new StreamReader(filename))
                {
                    trees.Add(parser.Parse(reader.ReadToEnd(), filename));
                }
            }

            Console.WriteLine("Creating references...");
            project = project.AddAssemblyReferences(GetProjectReferences(reference));
            foreach (var tree in trees)
            {
                project = project.AddOrUpdateFiles(tree.ToTypeSystem());
            }

            Console.WriteLine("Emitting Jasmin assembly...");
            var output = new DirectoryInfo(Environment.CurrentDirectory).CreateSubdirectory("obj");
            var sources = new List<string>();
            string entryPoint = null;
            foreach (var tree in trees)
            {
                var unresolvedFile = tree.ToTypeSystem();
                ICompilation compilation = project.CreateCompilation();
                CSharpAstResolver resolver = new CSharpAstResolver(compilation, tree, unresolvedFile);

                var typeVisitor = new JavaTypeVisitor(resolver, output);
                tree.AcceptVisitor(typeVisitor);
                sources.AddRange(typeVisitor.CreatedFiles);
                if (typeVisitor.EntryPoint != null)
                    entryPoint = typeVisitor.EntryPoint;
            }

            if (entryPoint == null)
            {
                Console.WriteLine("No class with [EntryPoint] attribute.  This JAR will be a library.");
            }

            Console.WriteLine("Compiling JAR...");
            var jasmin = new Jasmin(jasminJar);
            using (var writer = new StreamWriter(outputJar))
            {
                jasmin.CompileJar(output.FullName, sources, writer.BaseStream, entryPoint);
            }
            Console.WriteLine("Wrote JAR to " + outputJar);
        }
Exemple #21
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);
		}
		public static ICompilation CreateCompilation(params IUnresolvedFile[] unresolvedFiles)
		{
			var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles);
			pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
			return pc.CreateCompilation();
		}
        private void Prepare(string source, IRuntimeLibrary runtimeLibrary = null, bool expectErrors = false, bool MinimizeNames = 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, Files.Web, Files.Knockout });

            _compilation = project.CreateCompilation();

            var options = new CompilerOptions { MinimizeScript = MinimizeNames };
            _errorReporter = new MockErrorReporter(!expectErrors);
            var s = new AttributeStore(_compilation, _errorReporter);
            s.RunAttributeCode();
            _metadata = new MetadataImporter(_errorReporter, _compilation, s, options);

            _metadata.Prepare(_compilation.GetAllTypeDefinitions());

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

            var rtl = new RuntimeLibrary(_metadata, _errorReporter, _compilation, new Namer(), s);
        }
Exemple #24
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();
		}
		public static TestRefactoringContext Create (List<string> contents, int mainIndex, bool expectErrors = false, CSharpParser parser = null)
		{
			List<int> indexes = new List<int>();
			List<int> selectionStarts = new List<int>();
			List<int> selectionEnds = new List<int>();
			List<IDocument> documents = new List<IDocument>();
			List<CSharpUnresolvedFile> unresolvedFiles = new List<CSharpUnresolvedFile>();
			List<SyntaxTree> units = new List<SyntaxTree>();

			for (int i = 0; i < contents.Count; i++) {
				string content = contents[i];
				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;
				}
				indexes.Add(idx);
				selectionStarts.Add(selectionStart);
				selectionEnds.Add(selectionEnd);
				var doc = new StringBuilderDocument(content);
				if (parser == null)
					parser = new CSharpParser();
				var unit = parser.Parse(content, "program_" + i + ".cs");
				if (!expectErrors) {
					if (parser.HasErrors) {
						Console.WriteLine(content);
						Console.WriteLine("----");
					}
					foreach (var error in parser.ErrorsAndWarnings) {
						Console.WriteLine(error.Message);
					}
					Assert.IsFalse(parser.HasErrors, "The file " + i + " contains unexpected parsing errors.");
				}
				else {
					Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file " + i + "doesn't contain any.");
				}
				unit.Freeze();
				CSharpUnresolvedFile unresolvedFile = unit.ToTypeSystem();
				units.Add(unit);
				documents.Add(doc);
				unresolvedFiles.Add(unresolvedFile);
			}

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

			var compilation = pc.CreateCompilation ();
			List<TestRefactoringContext> contexts = new List<TestRefactoringContext>();

			for (int documentIndex = 0; documentIndex < documents.Count; ++documentIndex)
			{
				var doc = documents [documentIndex];
				var resolver = new CSharpAstResolver (compilation, units[documentIndex], unresolvedFiles[documentIndex]);
				TextLocation location = TextLocation.Empty;
				if (indexes[documentIndex] >= 0)
					location = doc.GetLocation (indexes[documentIndex]);
				var context = new TestRefactoringContext(doc, location, resolver) {
					selectionStart = selectionStarts[documentIndex],
					selectionEnd = selectionEnds[documentIndex],
					projectContexts = contexts,
					version = parser.CompilerSettings.LanguageVersion,
					defaultNamespace = "Test"
				};

				contexts.Add(context);
			}

			return contexts [mainIndex];
		}
        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);
        }
        public override void VisitCompilationUnit(CompilationUnit unit)
        {
            IProjectContent project = new CSharpProjectContent();
            _parsedFile = unit.ToTypeSystem();
            project = project.UpdateProjectContent(null, _parsedFile);
            project = project.AddAssemblyReferences(builtInLibs.Value);
            _compilation = project.CreateCompilation();
            _compilationUnit = unit;
            _resolver = new CSharpAstResolver(_compilation, _compilationUnit, _parsedFile);

            base.VisitCompilationUnit(unit);
        }