Example #1
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));
        }
Example #2
0
        public void GenerateTypeSystem()
        {
            IProjectContent pc     = new CSharpProjectContent();
            CSharpParser    parser = new CSharpParser();

            parser.GenerateTypeSystemMode = true;
            foreach (string fileName in fileNames)
            {
                SyntaxTree syntaxTree;
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
                    syntaxTree = parser.Parse(fs, fileName);
                }
                var unresolvedFile = syntaxTree.ToTypeSystem();
                foreach (var td in unresolvedFile.GetAllTypeDefinitions())
                {
                    Assert.AreSame(unresolvedFile, td.UnresolvedFile);
                    foreach (var member in td.Members)
                    {
                        Assert.AreSame(unresolvedFile, member.UnresolvedFile);
                        Assert.AreSame(td, member.DeclaringTypeDefinition);
                    }
                }
                pc = pc.AddOrUpdateFiles(unresolvedFile);
            }
        }
Example #3
0
        static public ClassMapper analysecode(string sourceText, string file)
        {
            StringBuilder b = new StringBuilder();

            ClassMapper mapper = new ClassMapper();

            mapper.filename = file;

            string filename = file;

            //string sourceText = File.ReadAllText(filename);

            var        parser     = new CSharpParser();
            SyntaxTree syntaxTree = parser.Parse(sourceText, file);
            var        pc         = new CSharpProjectContent();

            pc = (CSharpProjectContent)pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem());
            ICompilation compilation = pc.CreateCompilation();
            var          resolver    = new CSharpAstResolver(compilation, syntaxTree, syntaxTree.ToTypeSystem());

            var classVisitor = new ClassVisitor(resolver);

            classVisitor.filename = filename;
            classVisitor.b        = b;
            classVisitor.wm       = new CacheManager();
            classVisitor.mapper   = mapper;

            classVisitor.syntax = syntaxTree;

            syntaxTree.AcceptVisitor(classVisitor);

            mapper.syntax = syntaxTree;

            return(mapper);
        }
        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();
        }
        private void Prepare(string source, Action preparer)
        {
            IProjectContent project = new CSharpProjectContent();
            var             parser  = new CSharpParser();

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

            var compilation = project.CreateCompilation();

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

            var er = new MockErrorReporter(true);
            var s  = new AttributeStore(compilation, er);

            Metadata = new MetadataImporter(er, compilation, s, new CompilerOptions());
            preparer();
            Metadata.Prepare(compilation.GetAllTypeDefinitions());
            Assert.That(er.AllMessages, Is.Empty, "Should not generate errrors");
        }
Example #6
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);
        }
Example #7
0
        public void ResetProject(Tuple <string, string>[] sourceFiles = null, params string[] assemblies)
        {
            Project = null;

            if (sourceFiles == null)
            {
                sourceFiles = new Tuple <string, string> [0]; //will happen only during the testing
            }
            var projectContents = new IUnresolvedAssembly[assemblies.Length];

            Parallel.For(0, assemblies.Length, i =>
            {
                projectContents[i] = new CecilLoader {
                    DocumentationProvider = GetXmlDocumentation(assemblies[i])
                }.LoadAssemblyFile(assemblies[i]);
            });

            var unresolvedAsms  = builtInLibs.Value.Concat(projectContents);
            var unresolvedFiles = new IUnresolvedFile[sourceFiles.Length];

            Parallel.For(0, unresolvedFiles.Length, i =>
            {
                var pair       = sourceFiles[i];
                var syntaxTree = new CSharpParser().Parse(pair.Item1, pair.Item2);
                syntaxTree.Freeze();
                unresolvedFiles[i] = syntaxTree.ToTypeSystem();
            });

            IProjectContent project = new CSharpProjectContent();

            project = project.AddAssemblyReferences(unresolvedAsms);
            project = project.AddOrUpdateFiles(unresolvedFiles);
            Project = project;
        }
        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("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();

            _errorReporter = new MockErrorReporter(!expectErrors);
            Metadata       = new MetadataImporter(_errorReporter, compilation, 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);
        }
Example #9
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();
        }
Example #10
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;
        }
Example #11
0
        internal static IParameterDataProvider CreateProvider(string text)
        {
            string parsedText;
            string editorText;
            int    cursorPosition = text.IndexOf('$');
            int    endPos         = text.IndexOf('$', cursorPosition + 1);

            if (endPos == -1)
            {
                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 pctx = new CSharpProjectContent();

            pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

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

            syntaxTree.Freeze();

            var unresolvedFile = syntaxTree.ToTypeSystem();

            pctx = pctx.AddOrUpdateFiles(unresolvedFile);
            var cmp = pctx.CreateCompilation();
            var loc = doc.GetLocation(cursorPosition);


            var rctx = new CSharpTypeResolveContext(cmp.MainAssembly);

            rctx = rctx.WithUsingScope(unresolvedFile.GetUsingScope(loc).Resolve(cmp));
            var curDef = unresolvedFile.GetInnermostTypeDefinition(loc);

            if (curDef != null)
            {
                rctx = rctx.WithCurrentTypeDefinition(curDef.Resolve(rctx).GetDefinition());
                var curMember = unresolvedFile.GetMember(loc);
                if (curMember != null)
                {
                    rctx = rctx.WithCurrentMember(curMember.CreateResolved(rctx));
                }
            }
            var mb     = new DefaultCompletionContextProvider(doc, unresolvedFile);
            var engine = new CSharpParameterCompletionEngine(doc, mb, new TestFactory(pctx), pctx, rctx);

            return(engine.GetParameterDataProvider(cursorPosition, doc.GetCharAt(cursorPosition - 1)));
        }
Example #12
0
        public void ResolveTypeWithUnknownAttributes()
        {
            const String source = "namespace ns\r\n" +
                                  "{\r\n" +
                                  "    public enum EE {v1 = 13, v2 = 666}\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple = true)]\r\n" +
                                  "    public class AttrA : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.Method)]\r\n" +
                                  "    public class AttrB : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "        public AttrB(int i, string s, EE e) {}\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "        [AttrA]\r\n" +
                                  "        [AttrB(666, \"iddqd\", EE.v1)]\r\n" +
                                  "        [AttrC]\r\n" +
                                  "        public void M()\r\n" +
                                  "        { }\r\n" +
                                  "    }\r\n" +
                                  "}";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(source);

            syntaxTree.FileName = "example.cs";
            CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem();
            IProjectContent      content = new CSharpProjectContent();

            content = content.AddOrUpdateFiles(unresolvedTypeSystem);
            CecilLoader         loader = new CecilLoader();
            AssemblyDefinition  mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location);
            IUnresolvedAssembly mscorlibAssembly           = loader.LoadAssembly(mscorlibAssemblyDefinition);

            content = content.AddAssemblyReferences(mscorlibAssembly);
            ICompilation        compilation  = content.CreateCompilation();
            CSharpAstResolver   resolver     = new CSharpAstResolver(compilation, syntaxTree);
            MethodDeclaration   method       = syntaxTree.Descendants.OfType <MethodDeclaration>().First(m => m.Name == "M");
            ResolveResult       result       = resolver.Resolve(method);
            MemberResolveResult memberResult = (MemberResolveResult)result;
            IMember             member       = memberResult.Member;

            foreach (IAttribute attribute in member.Attributes)
            {
                Console.WriteLine("attribute.AttributeType = {0}, attribute.AttributeType.Kind = {1}", attribute.AttributeType.FullName, attribute.AttributeType.Kind);
                Console.WriteLine("attribute.PositionalArguments.Count = {0}", attribute.PositionalArguments.Count);
                ProcessPositionalArgs(attribute.PositionalArguments);
                Console.WriteLine("attribute.NamedArguments.Count = {0}", attribute.NamedArguments.Count);
                Console.WriteLine();
            }
        }
Example #13
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));
            }
Example #14
0
        public virtual void Parse()
        {
            if (References.Where(t => t.IndexOf("mscorlib.dll", StringComparison.InvariantCultureIgnoreCase) >= 0).FirstOrDefault() == null) //Don't add mscorlib twice
            {
                string mscorlib = null;
                if (!String.IsNullOrEmpty(TargetFrameworkVersion))
                {
                    if (TargetFrameworkVersion == "v2.0" ||
                        TargetFrameworkVersion == "v3.0" ||
                        TargetFrameworkVersion == "v3.5")
                    {
                        mscorlib = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll");
                    }
                }
                if (mscorlib == null)
                {
                    mscorlib = typeof(string).Assembly.Location;
                }
                References.Add(mscorlib);
            }

            NFiles       = new List <NFile>();
            CSharpParser = new CSharpParser();
            if (Defines != null)
            {
                Defines.ForEach(t => CSharpParser.CompilerSettings.ConditionalSymbols.Add(t));
            }
            NFiles = SourceFiles.Select(t => new NFile {
                Filename = t, Project = this
            }).ToList();
            AssemblyReferences = References.Select(t => new NAssembly {
                Filename = t
            }).ToList();
            //danel: parser.ErrorPrinter

            ParseCsFiles();
            LoadAssemblies();
            var ms = StopwatchHelper.TimeInMs(LoadAssemblies);

            FormatLine("{0} References End: {1}ms", AssemblyReferences.Count, ms);
            ProjectContent     = new CSharpProjectContent();
            ProjectContent     = (CSharpProjectContent)ProjectContent.SetAssemblyName(AssemblyName);
            ProjectContent     = (CSharpProjectContent)ProjectContent.AddAssemblyReferences(AssemblyReferences.Select(t => t.UnresolvedAssembly).Where(t => t != null));
            ProjectContent     = (CSharpProjectContent)ProjectContent.AddOrUpdateFiles(NFiles.Select(t => t.UnresolvedFile));
            ProjectContent.Tag = this;
            ms = StopwatchHelper.TimeInMs(() => Compilation = ProjectContent.CreateCompilation());
            Compilation.CacheManager.SetShared(typeof(NProject), this);
            FormatLine("CreateCompilation {0}ms", ms);
            //Navigator = CreateNavigator(null);
            //ApplyNavigator will happen BeforeExport only on needed files, in parallel
        }
Example #15
0
        ICompilation createCompilation(string mainPath, SyntaxTree tree)
        {
            List <IUnresolvedAssembly> assemblies = new List <IUnresolvedAssembly>();
            var             unresolved            = tree.ToTypeSystem();
            IProjectContent project = new CSharpProjectContent();

            string[]       paths = { /* mainPath, */ typeof(String).Assembly.Location, typeof(INotifyPropertyChanged).Assembly.Location,
                                                     typeof(Enumerable).Assembly.Location,   typeof(System.Drawing.Bitmap).Assembly.Location };
            AssemblyLoader loader = AssemblyLoader.Create();

            return(project.AddOrUpdateFiles(unresolved)
                   .AddAssemblyReferences(paths.Select(path => loader.LoadAssemblyFile(path)))
                   .CreateCompilation());
        }
Example #16
0
        private 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);
        }
Example #17
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);
        }
Example #18
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
            Project msbuildProject = new Project(fileName, null, "14.0");

            // 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
            IProjectContent pc = new CSharpProjectContent();

            pc = pc.SetAssemblyName(AssemblyName);
            pc = pc.SetProjectFileName(fileName);
            pc = pc.SetCompilerSettings(CompilerSettings);
            // Parse the C# code files
            foreach (CSharpFile file in msbuildProject.GetItems("Compile").Select(item => 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:
            pc = ResolveAssemblyReferences(msbuildProject).Select(solution.LoadAssembly).Aggregate(pc, (current, assembly) => current.AddAssemblyReferences(assembly));

            // Add project references:
            pc             = msbuildProject.GetItems("ProjectReference").Select(item => Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude)).Select(Path.GetFullPath).Aggregate(pc, (current, referencedFileName) => current.AddAssemblyReferences(new ProjectReference(referencedFileName)));
            ProjectContent = pc;
        }
        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);
        }
		public void GenerateTypeSystem()
		{
			IProjectContent pc = new CSharpProjectContent();
			CSharpParser parser = new CSharpParser();
			parser.GenerateTypeSystemMode = true;
			foreach (string fileName in fileNames) {
				SyntaxTree syntaxTree;
				using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
					syntaxTree = parser.Parse(fs, fileName);
				}
				var unresolvedFile = syntaxTree.ToTypeSystem();
				foreach (var td in unresolvedFile.GetAllTypeDefinitions()) {
					Assert.AreSame(unresolvedFile, td.UnresolvedFile);
					foreach (var member in td.Members) {
						Assert.AreSame(unresolvedFile, member.UnresolvedFile);
						Assert.AreSame(td, member.DeclaringTypeDefinition);
					}
				}
				pc = pc.AddOrUpdateFiles(unresolvedFile);
			}
		}
Example #21
0
        static TestSemanticHighlightingVisitor CreateHighighting(string text)
        {
            var syntaxTree = SyntaxTree.Parse(text, "a.cs");

            if (syntaxTree.Errors.Count > 0)
            {
                Console.WriteLine(text);
                Console.WriteLine("---");
                syntaxTree.Errors.ForEach(err => Console.WriteLine(err.Message));
                Assert.Fail("parse error.");
            }
            var project = new CSharpProjectContent().AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
            var file    = syntaxTree.ToTypeSystem();

            project = project.AddOrUpdateFiles(file);

            var resolver = new CSharpAstResolver(project.CreateCompilation(), syntaxTree, file);
            var result   = new TestSemanticHighlightingVisitor(resolver);

            syntaxTree.AcceptVisitor(result);
            return(result);
        }
Example #22
0
        private void TestCommonBody(String source)
        {
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(source);

            syntaxTree.FileName = "example.cs";
            BaseReferenceExpression baseRef = syntaxTree.Descendants.OfType <BaseReferenceExpression>().First();
            ExpressionStatement     expr    = MoveToParent <ExpressionStatement>(baseRef);
            CSharpUnresolvedFile    unresolvedTypeSystem = syntaxTree.ToTypeSystem();
            IProjectContent         content = new CSharpProjectContent();

            content = content.AddOrUpdateFiles(unresolvedTypeSystem);
            CecilLoader         loader = new CecilLoader();
            AssemblyDefinition  mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location);
            IUnresolvedAssembly mscorlibAssembly           = loader.LoadAssembly(mscorlibAssemblyDefinition);

            content = content.AddAssemblyReferences(mscorlibAssembly);
            ICompilation      compilation = content.CreateCompilation();
            CSharpAstResolver resolver    = new CSharpAstResolver(compilation, syntaxTree);

            ShowSubtree(expr, 0, resolver);
        }
Example #23
0
        public void AnalyzeCSharpFile(string path)
        {
            mapper = new ClassMapper();

            if (mappers == null)
            {
                mappers = new ArrayList();
            }

            mappers.Add(mapper);

            mapper.filename = path;

            string filename = path;

            string sourceText = File.ReadAllText(filename);

            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(sourceText, Path.GetFileNameWithoutExtension(filename));
            var          pc         = new CSharpProjectContent();

            pc = (CSharpProjectContent)pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem());
            ICompilation compilation = pc.CreateCompilation();
            var          resolver    = new CSharpAstResolver(compilation, syntaxTree, syntaxTree.ToTypeSystem());

            var classVisitor = new ClassVisitor(resolver);

            classVisitor.filename = path;
            classVisitor.b        = b;
            classVisitor.wm       = wm;
            classVisitor.mapper   = mapper;

            classVisitor.syntax = syntaxTree;

            syntaxTree.AcceptVisitor(classVisitor);

            syntax = syntaxTree;
        }
Example #24
0
        public void MethodParamsReturnAttributes()
        {
            const String source = "namespace ns\r\n" +
                                  "{\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.Parameter)]\r\n" +
                                  "    public class AttrA : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.ReturnValue)]\r\n" +
                                  "    public class AttrB : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "        [return: AttrB]\r\n" +
                                  "        public string SomeMethod(int p1, [AttrA]string p2) { return \"iddqd\"; }\r\n" +
                                  "    }\r\n" +
                                  "}";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(source);

            syntaxTree.FileName = "example.cs";
            CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem();
            IProjectContent      content = new CSharpProjectContent();

            content = content.AddOrUpdateFiles(unresolvedTypeSystem);
            CecilLoader         loader = new CecilLoader();
            AssemblyDefinition  mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location);
            IUnresolvedAssembly mscorlibAssembly           = loader.LoadAssembly(mscorlibAssemblyDefinition);

            content = content.AddAssemblyReferences(mscorlibAssembly);
            ICompilation        compilation  = content.CreateCompilation();
            CSharpAstResolver   resolver     = new CSharpAstResolver(compilation, syntaxTree);
            MethodDeclaration   method       = syntaxTree.Descendants.OfType <MethodDeclaration>().First(m => m.Name == "SomeMethod");
            ResolveResult       result       = resolver.Resolve(method);
            MemberResolveResult memberResult = (MemberResolveResult)result;
            IMember             member       = memberResult.Member;
        }
        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);
        }
		internal static IParameterDataProvider CreateProvider(string text)
		{
			string parsedText;
			string editorText;
			int cursorPosition = text.IndexOf('$');
			int endPos = text.IndexOf('$', cursorPosition + 1);
			if (endPos == -1) {
				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 pctx = new CSharpProjectContent();
			pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
			
			var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
			syntaxTree.Freeze();
			
			var unresolvedFile = syntaxTree.ToTypeSystem();
			pctx = pctx.AddOrUpdateFiles(unresolvedFile);
			var cmp = pctx.CreateCompilation();
			var loc = doc.GetLocation(cursorPosition);
			
			
			var rctx = new CSharpTypeResolveContext(cmp.MainAssembly);
			rctx = rctx.WithUsingScope(unresolvedFile.GetUsingScope(loc).Resolve(cmp));
			var curDef = unresolvedFile.GetInnermostTypeDefinition(loc);
			if (curDef != null) {
				rctx = rctx.WithCurrentTypeDefinition(curDef.Resolve(rctx).GetDefinition());
				var curMember = unresolvedFile.GetMember(loc);
				if (curMember != null) {
					rctx = rctx.WithCurrentMember(curMember.CreateResolved(rctx));
				}
			}
			var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
			var engine = new CSharpParameterCompletionEngine (doc, mb, new TestFactory (pctx), pctx, rctx);
			return engine.GetParameterDataProvider (cursorPosition, doc.GetCharAt (cursorPosition - 1));
		}
        public static TestRefactoringContext Create(string content, bool expectErrors = false)
        {
            int idx = content.IndexOf("$");

            if (idx >= 0)
            {
                content = content.Substring(0, idx) + content.Substring(idx + 1);
            }
            int idx1 = content.IndexOf("<-");
            int idx2 = content.IndexOf("->");

            int selectionStart = 0;
            int selectionEnd   = 0;

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

            var doc    = new StringBuilderDocument(content);
            var parser = new CSharpParser();
            var unit   = parser.Parse(content, "program.cs");

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

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

            IProjectContent pc = new CSharpProjectContent();

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

            var          compilation = pc.CreateCompilation();
            var          resolver    = new CSharpAstResolver(compilation, unit, unresolvedFile);
            TextLocation location    = TextLocation.Empty;

            if (idx >= 0)
            {
                location = doc.GetLocation(idx);
            }
            return(new TestRefactoringContext(doc, location, resolver)
            {
                selectionStart = selectionStart,
                selectionEnd = selectionEnd
            });
        }
Example #28
0
        public static TestRefactoringContext Create(List <string> contents, int mainIndex, bool expectErrors = false)
        {
            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);
                var 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.Errors)
                    {
                        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
                };

                contexts.Add(context);
            }

            return(contexts [mainIndex]);
        }
        public static TestRefactoringContext Create(string content, bool expectErrors = false)
        {
            int idx = content.IndexOf ("$");
            if (idx >= 0)
                content = content.Substring (0, idx) + content.Substring (idx + 1);
            int idx1 = content.IndexOf ("<-");
            int idx2 = content.IndexOf ("->");

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

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

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

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

            var compilation = pc.CreateCompilation ();
            var resolver = new CSharpAstResolver (compilation, unit, unresolvedFile);
            TextLocation location = TextLocation.Empty;
            if (idx >= 0)
                location = doc.GetLocation (idx);
            return new TestRefactoringContext(doc, location, resolver) {
                selectionStart = selectionStart,
                selectionEnd = selectionEnd
            };
        }
		public static void CreateCompilation (string parsedText, out IProjectContent pctx, out SyntaxTree syntaxTree, out CSharpUnresolvedFile unresolvedFile, bool expectErrors, params IUnresolvedAssembly[] references)
		{
			pctx = new CSharpProjectContent();
			var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value, systemXmlLinq.Value };
			if (references != null)
				refs.AddRange (references);
			
			pctx = pctx.AddAssemblyReferences(refs);
			
			syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
			syntaxTree.Freeze();
			if (!expectErrors && syntaxTree.Errors.Count > 0) {
				Console.WriteLine ("----");
				Console.WriteLine (parsedText);
				Console.WriteLine ("----");
				foreach (var error in syntaxTree.Errors)
					Console.WriteLine (error.Message);
				Assert.Fail ("Parse error.");
			}

			unresolvedFile = syntaxTree.ToTypeSystem();
			pctx = pctx.AddOrUpdateFiles(unresolvedFile);
		}
        // 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);
        }
		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 pctx = new CSharpProjectContent();
			var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value, systemXmlLinq.Value };
			if (references != null)
				refs.AddRange (references);

			pctx = pctx.AddAssemblyReferences(refs);

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

			var unresolvedFile = syntaxTree.ToTypeSystem();
			pctx = pctx.AddOrUpdateFiles(unresolvedFile);

			var cmp = pctx.CreateCompilation();
			var loc = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation (1, 1);

			var rctx = new CSharpTypeResolveContext(cmp.MainAssembly);
			rctx = rctx.WithUsingScope(unresolvedFile.GetUsingScope(loc).Resolve(cmp));

			var curDef = unresolvedFile.GetInnermostTypeDefinition(loc);
			if (curDef != null) {
					var resolvedDef = curDef.Resolve(rctx).GetDefinition();
					rctx = rctx.WithCurrentTypeDefinition(resolvedDef);
					var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= loc && loc < m.BodyRegion.End);
					if (curMember != null) {
							rctx = rctx.WithCurrentMember(curMember);
					}
			}
			var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
			mb.AddSymbol ("TEST");
			var engine = new CSharpCompletionEngine(doc, mb, new TestFactory(new CSharpResolver (rctx)), pctx, rctx);

			engine.EolMarker = Environment.NewLine;
			engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
			return engine;
		}
Example #33
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);
        }
		static Tuple<ReadOnlyDocument, CSharpCompletionEngine> GetContent(string text, SyntaxTree syntaxTree)
		{
			var doc = new ReadOnlyDocument(text);
			IProjectContent pctx = new CSharpProjectContent();
			pctx = pctx.AddAssemblyReferences(new [] { mscorlib.Value, systemAssembly.Value, systemCore.Value, systemXmlLinq.Value });
			var unresolvedFile = syntaxTree.ToTypeSystem();
			
			pctx = pctx.AddOrUpdateFiles(unresolvedFile);
			var cmp = pctx.CreateCompilation();
			
			var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
			var engine = new CSharpCompletionEngine (doc, mb, new TestFactory (new CSharpResolver (new CSharpTypeResolveContext (cmp.MainAssembly))), pctx, new CSharpTypeResolveContext (cmp.MainAssembly));
			engine.EolMarker = Environment.NewLine;
			engine.FormattingPolicy = FormattingOptionsFactory.CreateMono ();
			return Tuple.Create (doc, engine);
		}