/// <summary>
        /// Initializes a new instance of the <see cref="CSharpCompletionContext"/> class.
        /// </summary>
        /// <param name="document">The document, make sure the FileName property is set on the document.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="projectContent">Content of the project.</param>
        /// <param name="usings">The usings.</param>
        /// <param name="variables">The variables</param>
        /// <param name="namespace">The namespace.</param>
        public CSharpCompletionContext(IDocument document, int offset, IProjectContent projectContent, string usings = null, string variables = null, string @namespace = null)
        {
            OriginalDocument  = document;
            OriginalOffset    = offset;
            OriginalUsings    = usings;
            OriginalVariables = variables;
            OriginalNamespace = @namespace;

            //if the document is a c# script we have to soround the document with some code.
            Document = PrepareCompletionDocument(document, ref offset, usings, variables, @namespace);
            Offset   = offset;

            var syntaxTree = new CSharpParser().Parse(Document, Document.FileName);

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

            ProjectContent = projectContent.AddOrUpdateFiles(unresolvedFile);
            //note: it's important that the project content is used that is returned after adding the unresolved file
            Compilation = ProjectContent.CreateCompilation();

            var location = Document.GetLocation(Offset);

            Resolver = unresolvedFile.GetResolver(Compilation, location);
            TypeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(Compilation, location);
            CompletionContextProvider = new DefaultCompletionContextProvider(Document, unresolvedFile);
        }
示例#2
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;
        }
示例#3
0
        public Common.DomRegion ResolveTypeByName(string typeName, string typeMemberName)
        {
            if (Project == null)
            {
                return(Common.DomRegion.Empty);
            }

            var code     = $"class dummy11111 {{ System.Type t = typeof({typeName}); }}";
            var location = new ReadOnlyDocument(code).GetLocation(code.Length - 6);

            var syntaxTree = new CSharpParser().Parse(code, "dummy11111.cs");

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

            Project = Project.AddOrUpdateFiles(unresolvedFile);

            var compilation = Project.CreateCompilation();

            var result = ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, location);

            var type = (result as TypeResolveResult).Type as DefaultResolvedTypeDefinition;

            if (type != null)
            {
                var asm = type.ParentAssembly;
                if (asm.UnresolvedAssembly is IUnresolvedAssembly) //referenced assembly
                {
                    FileLocation document = new Reflector().ReconstructToFile(asm, type, memberName: typeMemberName);
                    return(document.ToDomRegion().ToCommon());
                }
            }

            return(Common.DomRegion.Empty);
        }
示例#4
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)));
        }
示例#5
0
        public IEnumerable <Common.TypeInfo> GetPossibleNamespaces(string editorText, string nameToResolve, string fileName) // not the best way to put in the whole string every time
        {
            try
            {
                if (Project == null && string.IsNullOrEmpty(nameToResolve))
                {
                    return(new Common.TypeInfo[0]);
                }

                var syntaxTree = new CSharpParser().Parse(editorText, fileName);
                syntaxTree.Freeze();
                var unresolvedFile = syntaxTree.ToTypeSystem();

                Project = Project.AddOrUpdateFiles(unresolvedFile);

                var srcNamespaces = Project.Files
                                    .SelectMany(x => x.TopLevelTypeDefinitions)
                                    .Union(Project.Files
                                           .SelectMany(x => x.TopLevelTypeDefinitions)
                                           .SelectMany(x => x.NestedTypes))
                                    .Where(x => x.Name == nameToResolve)
                                    .Distinct()
                                    .Select(x => new Common.TypeInfo {
                    Namespace = x.Namespace, FullName = x.FullName
                });

                var asmNamespaces = Project.AssemblyReferences
                                    .SelectMany(x => ((DefaultUnresolvedAssembly)x).TopLevelTypeDefinitions)
                                    .Union(Project.AssemblyReferences
                                           .SelectMany(x => ((DefaultUnresolvedAssembly)x).TopLevelTypeDefinitions)
                                           .SelectMany(x => x.NestedTypes))
                                    .Where(x => x.Name == nameToResolve)
                                    .Distinct()
                                    .Select(x => new Common.TypeInfo {
                    Namespace = x.Namespace, FullName = x.FullName
                });

                return(srcNamespaces.Union(asmNamespaces)
                       .OrderBy(x => x.Namespace)
                       .DistinctBy(x => x.FullName)
                       .ToArray());
            }
            catch
            {
                return(new Common.TypeInfo[0]); //the exception can happens even for the internal NRefactor-related reasons
            }
        }
示例#6
0
        IEnumerable <Common.ICompletionData> GetCSharpCompletionData(ReadOnlyDocument doc, string editorText, int offset, string fileName, bool isControlSpace = true) // not the best way to put in the whole string every time
        {
            if (editorText[offset] != '.')                                                                                                                             //we may be at the partially complete word
            {
                for (int i = offset - 1; i >= 0; i--)
                {
                    if (SimpleCodeCompletion.Delimiters.Contains(editorText[i]))
                    {
                        offset = i + 1;
                        break;
                    }
                }
            }

            //test for C# completion
            var location = doc.GetLocation(offset);

            var syntaxTree = new CSharpParser().Parse(editorText, fileName);

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

            Project = Project.AddOrUpdateFiles(unresolvedFile);

            //note project should be reassigned/recreated every time we add asms or file

            //IProjectContent project = new CSharpProjectContent();
            //project = project.AddAssemblyReferences(builtInLibs.Value);
            //project = project.AddOrUpdateFiles(unresolvedFile);

            //IProjectContent project = new CSharpProjectContent().AddAssemblyReferences(builtInLibs.Value).AddOrUpdateFiles(unresolvedFile);

            var completionContextProvider = new DefaultCompletionContextProvider(doc, unresolvedFile);

            var compilation = Project.CreateCompilation();
            var resolver    = unresolvedFile.GetResolver(compilation, location);

            var engine = new CSharpCompletionEngine(doc,
                                                    completionContextProvider,
                                                    new SimpleCompletionDataFactory(resolver),
                                                    Project,
                                                    resolver.CurrentTypeResolveContext);

            var data = engine.GetCompletionData(offset, isControlSpace);

            return(data.PrepareForDisplay().ToCommon());
        }
示例#7
0
 public void ProcessInput(string input, string sourceFile)
 {
     if (string.IsNullOrEmpty(sourceFile))
     {
         return;
     }
     //see if it contains the word class, enum or struct
     //todo: this is buggy because if two classes are evaluated seperately, the original file will overwrite it
     // if the file is a script we should try to extract the class name and use it as the file name. sciptname + class
     // we can probably use the AST for that.
     if (input.Contains("class ") || input.Contains("enum ") || input.Contains("struct "))
     {
         var syntaxTree = new CSharpParser().Parse(input, sourceFile);
         syntaxTree.Freeze();
         var unresolvedFile = syntaxTree.ToTypeSystem();
         projectContent = projectContent.AddOrUpdateFiles(unresolvedFile);
     }
 }
示例#8
0
        ResolveResult ResolveFromPosition(string editorText, int offset, string fileName)
        {
            if (Project == null)
            {
                return(null);
            }

            var location = new ReadOnlyDocument(editorText).GetLocation(offset);

            var syntaxTree = new CSharpParser().Parse(editorText, fileName);

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

            Project = Project.AddOrUpdateFiles(unresolvedFile);

            var compilation = Project.CreateCompilation();

            return(ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, location));
        }
        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);
        }
示例#10
0
		static CompletionDataList CreateProvider (string text, bool isCtrlSpace)
		{
			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 compilationUnit = new CSharpParser ().Parse (parsedText, "program.cs");
			compilationUnit.Freeze ();
			
			var parsedFile = compilationUnit.ToTypeSystem ();
			pctx = pctx.UpdateProjectContent (null, parsedFile);
			
			var cmp = pctx.CreateCompilation ();
			var loc = doc.GetLocation (cursorPosition);
			
			var rctx = new CSharpTypeResolveContext (cmp.MainAssembly);
			rctx = rctx.WithUsingScope (parsedFile.GetUsingScope (loc).Resolve (cmp));
			

			var curDef = parsedFile.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 engine = new CSharpCompletionEngine (doc, new TestFactory (), pctx, rctx, compilationUnit, parsedFile);
				
			engine.EolMarker = Environment.NewLine;
			engine.FormattingPolicy = FormattingOptionsFactory.CreateMono ();
			
			var data = engine.GetCompletionData (cursorPosition, isCtrlSpace);
			
			return new CompletionDataList () {
				Data = data,
				AutoCompleteEmptyMatch = engine.AutoCompleteEmptyMatch,
				AutoSelect = engine.AutoSelect,
				DefaultCompletionString = engine.DefaultCompletionString
			};
		}
        // 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 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);
		}
		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 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;
		}