Пример #1
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 cu = new CSharpParser().Parse(new StringReader(program), "program.cs");
			var compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation();
			var typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.Single();
			IEntity entity = typeDefinition.Documentation.ResolveCref(cref);
			Assert.IsNotNull(entity, "ResolveCref() returned null.");
			return entity;
		}
        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;

        }
Пример #3
0
		void Init(string program)
		{
			var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
			var cu = new CSharpParser().Parse(new StringReader(program), "program.cs");
			compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation();
			typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault();
		}
Пример #4
0
		void Init(string program)
		{
			pc = new IDStringTestProjectContent();
			
			var cu = new CSharpParser().Parse(new StringReader(program), "program.cs");
			foreach (var type in cu.ToTypeSystem().TopLevelTypeDefinitions) {
				pc.AddTypeDefinition(type);
			}
			compilation = new SimpleCompilation(pc, CecilLoaderTests.Mscorlib);
		}
		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, ' ');
		}
        /// <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>
        public CSharpCompletionContext(IDocument document, int offset, IProjectContent projectContent, string usings = null)
        {
            OriginalDocument = document;
            OriginalOffset = offset;

            //if the document is a c# script we have to soround the document with some code.
            Document = PrepareCompletionDocument(document, ref offset, usings);
            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);
        }
Пример #7
0
		public override IEnumerable<MemberReference> FindReferences (Project project, IProjectContent content, IEnumerable<FilePath> possibleFiles, IEnumerable<object> members)
		{
			if (project == null)
				throw new ArgumentNullException ("project", "Project not set.");
			if (content == null)
				throw new ArgumentNullException ("content", "Project content not set.");
			SetPossibleFiles (possibleFiles);
			SetSearchedMembers (members);
			
			var scopes = searchedMembers.Select (e => refFinder.GetSearchScopes (e as IEntity));
			var compilation = TypeSystemService.GetCompilation (project);
			List<MemberReference> refs = new List<MemberReference> ();
			foreach (var opendoc in openDocuments) {
				foreach (var newRef in FindInDocument (opendoc.Item2)) {
					if (newRef == null || refs.Any (r => r.FileName == newRef.FileName && r.Region == newRef.Region))
						continue;
					refs.Add (newRef);
				}
			}
			
			foreach (var file in files) {
				string text = Mono.TextEditor.Utils.TextFileUtility.ReadAllText (file);
				if (memberName != null && text.IndexOf (memberName, StringComparison.Ordinal) < 0 &&
					(keywordName == null || text.IndexOf (keywordName, StringComparison.Ordinal) < 0))
					continue;
				using (var editor = TextEditorData.CreateImmutable (text)) {
					editor.Document.FileName = file;
					var unit = new CSharpParser ().Parse (editor);
					if (unit == null)
						continue;
					
					var storedFile = content.GetFile (file);
					var parsedFile = storedFile as CSharpParsedFile;
					
					if (parsedFile == null && storedFile is ParsedDocumentDecorator) {
						parsedFile = ((ParsedDocumentDecorator)storedFile).ParsedFile as CSharpParsedFile;
					}
					
					if (parsedFile == null) {
						// for fallback purposes - should never happen.
						parsedFile = unit.ToTypeSystem ();
						content = content.UpdateProjectContent (content.GetFile (file), parsedFile);
						compilation = content.CreateCompilation ();
					}
					foreach (var scope in scopes) {
						refFinder.FindReferencesInFile (
							scope,
							parsedFile,
							unit,
							compilation,
							(astNode, result) => {
								var newRef = GetReference (result, astNode, file, editor);
								if (newRef == null || refs.Any (r => r.FileName == newRef.FileName && r.Region == newRef.Region))
									return;
								refs.Add (newRef);
							},
							CancellationToken.None
						);
					}
				}
			}
			return refs;
		}
 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);
     }
 }
        // 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;
        }