Пример #1
0
//			CompletionDataList result = new ProjectDomCompletionDataList ();
//			// "var o = new " needs special treatment.
//			if (returnType == null && returnTypeUnresolved != null && returnTypeUnresolved.FullName == "var")
//				returnType = returnTypeUnresolved = DomReturnType.Object;
//
//			//	ExpressionContext.TypeExpressionContext tce = context as ExpressionContext.TypeExpressionContext;
//
//			CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, callingType, location);
//			IType type = null;
//			if (returnType != null)
//				type = dom.GetType (returnType);
//			if (type == null)
//				type = dom.SearchType (Document.CompilationUnit, callingType, location, returnTypeUnresolved);
//
//			// special handling for nullable types: Bug 674516 - new completion for nullables should not include "Nullable"
//			if (type is InstantiatedType && ((InstantiatedType)type).UninstantiatedType.FullName == "System.Nullable" && ((InstantiatedType)type).GenericParameters.Count == 1) {
//				var genericParameter = ((InstantiatedType)type).GenericParameters [0];
//				returnType = returnTypeUnresolved = Document.CompilationUnit.ShortenTypeName (genericParameter, location);
//				type = dom.SearchType (Document.CompilationUnit, callingType, location, genericParameter);
//			}
//
//			if (type == null || !(type.IsAbstract || type.ClassType == ClassType.Interface)) {
//				if (type == null || type.ConstructorCount == 0 || type.Methods.Any (c => c.IsConstructor && c.IsAccessibleFrom (dom, callingType, type, callingType != null && dom.GetInheritanceTree (callingType).Any (x => x.FullName == type.FullName)))) {
//					if (returnTypeUnresolved != null) {
//						col.FullyQualify = true;
//						CompletionData unresovedCompletionData = col.Add (returnTypeUnresolved);
//						col.FullyQualify = false;
//						// don't set default completion string for arrays, since it interferes with:
//						// string[] arr = new string[] vs new { "a"}
//						if (returnTypeUnresolved.ArrayDimensions == 0)
//							result.DefaultCompletionString = StripGenerics (unresovedCompletionData.CompletionText);
//					} else {
//						CompletionData unresovedCompletionData = col.Add (returnType);
//						if (returnType.ArrayDimensions == 0)
//							result.DefaultCompletionString = StripGenerics (unresovedCompletionData.CompletionText);
//					}
//				}
//			}
//
//			//				if (tce != null && tce.Type != null) {
//			//					result.DefaultCompletionString = StripGenerics (col.AddCompletionData (result, tce.Type).CompletionString);
//			//				}
//			//			else {
//			//			}
//			if (type == null)
//				return result;
//			HashSet<string > usedNamespaces = new HashSet<string> (GetUsedNamespaces ());
//			if (type.FullName == DomReturnType.Object.FullName)
//				AddPrimitiveTypes (col);
//
//			foreach (IType curType in dom.GetSubclasses (type)) {
//				if (context != null && context.FilterEntry (curType))
//					continue;
//				if ((curType.TypeModifier & TypeModifier.HasOnlyHiddenConstructors) == TypeModifier.HasOnlyHiddenConstructors)
//					continue;
//				if (usedNamespaces.Contains (curType.Namespace)) {
//					if (curType.ConstructorCount > 0) {
//						if (!(curType.Methods.Any (c => c.IsConstructor && c.IsAccessibleFrom (dom, curType, callingType, callingType != null && dom.GetInheritanceTree (callingType).Any (x => x.FullName == curType.FullName)))))
//							continue;
//					}
//					col.Add (curType);
//				} else {
//					string nsName = curType.Namespace;
//					int idx = nsName.IndexOf ('.');
//					if (idx >= 0)
//						nsName = nsName.Substring (0, idx);
//					col.Add (new Namespace (nsName));
//				}
//			}
//
//			// add aliases
//			if (returnType != null) {
//				foreach (IUsing u in Document.CompilationUnit.Usings) {
//					foreach (KeyValuePair<string, IReturnType> alias in u.Aliases) {
//						if (alias.Value.ToInvariantString () == returnType.ToInvariantString ())
//							result.Add (alias.Key, "md-class");
//					}
//				}
//			}
//
//			return result;
//		}

//		IEnumerable<ICompletionData> GetDefineCompletionData ()
//		{
//			if (Document.Project == null)
//				yield break;
//
//			var symbols = new Dictionary<string, string> ();
//			var cp = new ProjectDomCompletionDataList ();
//			foreach (DotNetProjectConfiguration conf in Document.Project.Configurations) {
//				var cparams = conf.CompilationParameters as CSharpCompilerParameters;
//				if (cparams != null) {
//					string[] syms = cparams.DefineSymbols.Split (';');
//					foreach (string s in syms) {
//						string ss = s.Trim ();
//						if (ss.Length > 0 && !symbols.ContainsKey (ss)) {
//							symbols [ss] = ss;
//							yield return factory.CreateLiteralCompletionData (ss);
//						}
//					}
//				}
//			}
//		}

        public override ParameterDataProvider HandleParameterCompletion(CodeCompletionContext completionContext, char completionChar)
        {
            if (!EnableCodeCompletion)
            {
                return(null);
            }
            if (Unit == null || CSharpUnresolvedFile == null)
            {
                return(null);
            }
            try {
                var engine = new CSharpParameterCompletionEngine(
                    TextEditorData.Document,
                    typeSystemSegmentTree,
                    this,
                    Document.GetProjectContext(),
                    CSharpUnresolvedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext
                    );
                return(engine.GetParameterDataProvider(completionContext.TriggerOffset, completionChar) as ParameterDataProvider);
            } catch (Exception e) {
                LoggingService.LogError("Unexpected parameter completion exception." + Environment.NewLine +
                                        "FileName: " + Document.FileName + Environment.NewLine +
                                        "Position: line=" + completionContext.TriggerLine + " col=" + completionContext.TriggerLineOffset + Environment.NewLine +
                                        "Line text: " + Document.Editor.GetLineText(completionContext.TriggerLine),
                                        e);
                return(null);
            } finally {
                //			if (timer != null)
                //				timer.Dispose ();
            }
        }
Пример #2
0
        public CSharpFile(CSharpProject project, string fileName)
        {
            this.Project  = project;
            this.FileName = fileName;

            CSharpParser p = new CSharpParser(project.CompilerSettings);

//			using (var stream = File.OpenRead(fileName)) {
//				this.CompilationUnit = p.Parse(stream, fileName);
//			}

            // Keep the original text around; we might use it for a refactoring later
            this.OriginalText = File.ReadAllText(fileName);
            this.SyntaxTree   = p.Parse(this.OriginalText, fileName);
            this.SyntaxTree.Freeze();             // the various tests shouldn't modify the AST shared by all tests

            if (p.HasErrors)
            {
                Console.WriteLine("Error parsing " + fileName + ":");
                foreach (var error in p.ErrorsAndWarnings)
                {
                    Console.WriteLine("  " + error.Region + " " + error.Message);
                }
            }
            this.UnresolvedTypeSystemForFile = this.SyntaxTree.ToTypeSystem();
        }
Пример #3
0
        public static ResolveResult Resolve(Lazy <ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location,
                                            CancellationToken cancellationToken = default(CancellationToken))
        {
            AstNode node;

            return(Resolve(compilation, unresolvedFile, syntaxTree, location, out node, cancellationToken));
        }
        // Token: 0x06000012 RID: 18 RVA: 0x0000243C File Offset: 0x0000063C
        private ResolveResult GetLanguageItem(ProjectDocument doc, string expression, Client.SourceLocation location)
        {
            ParsedDocument parsedDocument = doc.ParsedDocument;

            if (parsedDocument == null)
            {
                return(null);
            }
            SyntaxTree           ast = parsedDocument.GetAst <SyntaxTree>();
            CSharpUnresolvedFile csharpUnresolvedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile;

            if (ast == null || csharpUnresolvedFile == null)
            {
                return(null);
            }
            AstNode nodeAt = ast.GetNodeAt(location.Line, location.Column, null);

            if (nodeAt == null)
            {
                return(null);
            }
            CSharpTypeResolveContext typeResolveContext = csharpUnresolvedFile.GetTypeResolveContext(doc.Compilation, new TextLocation(location.Line, location.Column));
            CSharpResolver           resolver           = new CSharpResolver(typeResolveContext);
            CSharpAstResolver        csharpAstResolver  = new CSharpAstResolver(resolver, ast, csharpUnresolvedFile);

            csharpAstResolver.ApplyNavigator(new NodeListResolveVisitorNavigator(new AstNode[]
            {
                nodeAt
            }), CancellationToken.None);
            CSharpResolver resolverStateBefore = csharpAstResolver.GetResolverStateBefore(nodeAt, CancellationToken.None);

            return(resolverStateBefore.LookupSimpleNameOrTypeName(expression, new List <IType>(), NameLookupMode.Expression));
        }
Пример #5
0
		public static ICompilation CreateCompilationWithoutCorlib(params IUnresolvedTypeDefinition[] unresolvedTypeDefinitions)
		{
			var unresolvedFile = new CSharpUnresolvedFile();
			foreach (var typeDef in unresolvedTypeDefinitions)
				unresolvedFile.TopLevelTypeDefinitions.Add(typeDef);
			return CreateCompilation(unresolvedFile);
		}
Пример #6
0
        public MethodParameterDataProvider(int startOffset, CSharpCompletionTextEditorExtension ext, IEnumerable <IMethod> m) : base(ext, startOffset)
        {
            compilation = ext.UnresolvedFileCompilation;
            file        = ext.CSharpUnresolvedFile;

            HashSet <string> alreadyAdded = new HashSet <string> ();

            foreach (var method in m)
            {
                if (method.IsConstructor)
                {
                    continue;
                }
                if (!method.IsBrowsable())
                {
                    continue;
                }
                string str = ambience.GetString(method, OutputFlags.IncludeParameters | OutputFlags.GeneralizeGenerics | OutputFlags.IncludeGenerics);
                if (alreadyAdded.Contains(str))
                {
                    continue;
                }
                alreadyAdded.Add(str);
                methods.Add(method);
            }

            methods.Sort(MethodComparer);
        }
Пример #7
0
 private void CompileAndResolve()
 {
     _unresolvedFile = SyntaxTree.ToTypeSystem();
     _projectContent = _projectContent.AddOrUpdateFiles(_unresolvedFile);
     _compilation    = _projectContent.CreateCompilation();
     _resolver       = new CSharpAstResolver(_compilation, SyntaxTree, _unresolvedFile);
 }
		public IndexerParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType type, IEnumerable<IProperty> indexers, AstNode resolvedExpression) : base (ext, startOffset)
		{
			compilation = ext.UnresolvedFileCompilation;
			file = ext.CSharpUnresolvedFile;
			//			this.resolvedExpression = resolvedExpression;
			this.indexers = new List<IProperty> (indexers);
		}
Пример #9
0
 void Init(string code)
 {
     syntaxTree     = SyntaxTree.Parse(code, "test.cs");
     unresolvedFile = syntaxTree.ToTypeSystem();
     compilation    = TypeSystemHelper.CreateCompilation(unresolvedFile);
     findReferences = new FindReferences();
 }
Пример #10
0
        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");
        }
Пример #11
0
		public DelegateDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType delegateType) : base (ext, startOffset)
		{
			compilation = ext.UnresolvedFileCompilation;
			file = ext.CSharpUnresolvedFile;
			//			this.delegateType = delegateType;
			this.delegateMethod = delegateType.GetDelegateInvokeMethod ();
		}
Пример #12
0
        public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
		                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            node = syntaxTree.GetNodeAt(location);
            if (node == null || node is ArrayInitializerExpression)
                return null;
            if (node.Parent is UsingAliasDeclaration && node.Role == UsingAliasDeclaration.AliasRole) {
                var r = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
                return r.Resolve(((UsingAliasDeclaration)node.Parent).Import, cancellationToken);
            }
            if (CSharpAstResolver.IsUnresolvableNode(node)) {
                if (node is Identifier) {
                    node = node.Parent;
                } else if (node.NodeType == NodeType.Token) {
                    if (node.Parent is IndexerExpression || node.Parent is ConstructorInitializer) {
                        // There's no other place where one could hover to see the indexer's tooltip,
                        // so we need to resolve it when hovering over the '[' or ']'.
                        // For constructor initializer, the same applies to the 'base'/'this' token.
                        node = node.Parent;
                    } else {
                        return null;
                    }
                } else {
                    // don't resolve arbitrary nodes - we don't want to show tooltips for everything
                    return null;
                }
            } else {
                // It's a resolvable node.
                // However, we usually don't want to show the tooltip everywhere
                // For example, hovering with the mouse over an empty line between two methods causes
                // node==TypeDeclaration, but we don't want to show any tooltip.

                if (!node.GetChildByRole(Roles.Identifier).IsNull) {
                    // We'll suppress the tooltip for resolvable nodes if there is an identifier that
                    // could be hovered over instead:
                    return null;
                }
            }

            if (node == null)
                return null;

            if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) {
                node = node.Parent;
            }

            InvocationExpression parentInvocation = null;
            if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) {
                // we also need to resolve the invocation
                parentInvocation = node.Parent as InvocationExpression;
            }

            // TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused
            CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
            ResolveResult rr = resolver.Resolve(node, cancellationToken);
            if (rr is MethodGroupResolveResult && parentInvocation != null)
                return resolver.Resolve(parentInvocation);
            else
                return rr;
        }
Пример #13
0
 public TypeCompletionData(IType type, CSharpCompletionTextEditorExtension ext, Lazy <string> displayText, string icon) : base(null, displayText, icon)
 {
     this.type        = type;
     this.ext         = ext;
     this.file        = ext.CSharpUnresolvedFile;
     this.compilation = ext.UnresolvedFileCompilation;
 }
Пример #14
0
		void Init(string code)
		{
			syntaxTree = SyntaxTree.Parse(code, "test.cs");
			unresolvedFile = syntaxTree.ToTypeSystem();
			compilation = TypeSystemHelper.CreateCompilation(unresolvedFile);
			findReferences = new FindReferences();
		}
        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);
        }
Пример #16
0
        ICompletionDataList InternalHandleCodeCompletion(CodeCompletionContext completionContext, char completionChar, bool ctrlSpace, ref int triggerWordLength)
        {
            var data = TextEditorData;

            if (data.CurrentMode is TextLinkEditMode)
            {
                if (((TextLinkEditMode)data.CurrentMode).TextLinkMode == TextLinkMode.EditIdentifier)
                {
                    return(null);
                }
            }
            if (Unit == null || CSharpUnresolvedFile == null)
            {
                return(null);
            }
            if (typeSystemSegmentTree == null)
            {
                return(null);
            }

            var list = new CSharpCompletionDataList();

            list.Resolver = CSharpUnresolvedFile != null?CSharpUnresolvedFile.GetResolver(UnresolvedFileCompilation, Document.Editor.Caret.Location) : new CSharpResolver(Compilation);

            var ctx = CSharpUnresolvedFile.GetTypeResolveContext(UnresolvedFileCompilation, data.Caret.Location) as CSharpTypeResolveContext;

            var engine = new CSharpCompletionEngine(
                data.Document,
                typeSystemSegmentTree,
                new CompletionDataFactory(this, new CSharpResolver(ctx)),
                Document.GetProjectContext(),
                ctx
                );

            engine.FormattingPolicy = FormattingPolicy.CreateOptions();
            engine.EolMarker        = data.EolMarker;
            engine.IndentString     = data.Options.IndentationString;
            try {
                foreach (var cd in engine.GetCompletionData(completionContext.TriggerOffset, ctrlSpace))
                {
                    list.Add(cd);
                    if (cd is IListData)
                    {
                        ((IListData)cd).List = list;
                    }
                }
            } catch (Exception e) {
                LoggingService.LogError("Error while getting completion data.", e);
            }
            list.AutoCompleteEmptyMatch             = engine.AutoCompleteEmptyMatch;
            list.AutoCompleteEmptyMatchOnCurlyBrace = engine.AutoCompleteEmptyMatchOnCurlyBracket;
            list.AutoSelect = engine.AutoSelect;
            list.DefaultCompletionString = engine.DefaultCompletionString;
            list.CloseOnSquareBrackets   = engine.CloseOnSquareBrackets;
            if (ctrlSpace)
            {
                list.AutoCompleteUniqueMatch = true;
            }
            return(list.Count > 0 ? list : null);
        }
Пример #17
0
 public DelegateDataProvider(int startOffset, CSharpCompletionTextEditorExtension ext, IType delegateType) : base(ext, startOffset)
 {
     compilation = ext.UnresolvedFileCompilation;
     file        = ext.CSharpUnresolvedFile;
     //			this.delegateType = delegateType;
     this.delegateMethod = delegateType.GetDelegateInvokeMethod();
 }
		protected void Prepare(string source, bool minimizeNames = true, bool expectErrors = false) {
			IProjectContent project = new CSharpProjectContent();
			var parser = new CSharpParser();

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

			_errorReporter = new MockErrorReporter(!expectErrors);

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

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

			Metadata.Prepare(compilation.GetAllTypeDefinitions());

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

			AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName);
		}
Пример #19
0
        public ICodeContext ResolveContext(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken)
        {
            var csParseInfo = parseInfo as CSharpFullParseInformation;

            if (csParseInfo == null)
            {
                throw new ArgumentException("Parse info does not have SyntaxTree");
            }

            CSharpUnresolvedFile unresolvedFile = csParseInfo.UnresolvedFile;
            var projectContents = compilation.Assemblies.Select(asm => asm.UnresolvedAssembly).OfType <IProjectContent>().ToList();

            if (projectContents.All(pc => pc.GetFile(unresolvedFile.FileName) != unresolvedFile))
            {
                unresolvedFile = null;
            }
            var syntaxTree = csParseInfo.SyntaxTree;
            var node       = syntaxTree.GetNodeAt(location);

            if (node == null)
            {
                return(null);                // null result is allowed; the parser service will substitute a dummy context
            }
            var resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);

            return(resolver.GetResolverStateBefore(node));
        }
Пример #20
0
 public IndexerParameterDataProvider(int startOffset, CSharpCompletionTextEditorExtension ext, IType type, IEnumerable <IProperty> indexers, AstNode resolvedExpression) : base(ext, startOffset)
 {
     compilation = ext.UnresolvedFileCompilation;
     file        = ext.CSharpUnresolvedFile;
     //			this.resolvedExpression = resolvedExpression;
     this.indexers = new List <IProperty> (indexers);
 }
Пример #21
0
        public CSharpFile(CSharpProject project, string filePath)
        {
            _project  = project;
            _filePath = filePath;

            var parser = new CSharpParser(project.CompilerSettings);

            if (!(_exists = File.Exists(filePath)))
            {
                return;
            }
            using (FileStream stream = File.OpenRead(filePath))
            {
                _syntaxTree           = parser.Parse(stream, filePath);
                _unresolvedTypeSystem = _syntaxTree.ToTypeSystem();
            }
            if (parser.HasErrors)
            {
                _project.AddToErrorCount(parser.Errors.Count());
            }

            if (parser.HasWarnings)
            {
                _project.AddToWarningCount(parser.Warnings.Count());
            }
        }
Пример #22
0
        public CSharpFile(CSharpProject project, string fileName)
        {
            Project  = project;
            FileName = fileName;

            CSharpParser p = new CSharpParser(project.CompilerSettings);

//			using (var stream = File.OpenRead(fileName)) {
//				this.CompilationUnit = p.Parse(stream, fileName);
//			}

            // Keep the original text around; we might use it for a refactoring later
            OriginalText = File.ReadAllText(fileName);
            SyntaxTree   = p.Parse(OriginalText, fileName);

            if (p.HasErrors)
            {
                Console.WriteLine("Error parsing " + fileName + ":");
                foreach (Error error in p.ErrorsAndWarnings)
                {
                    Console.WriteLine("  " + error.Region + " " + error.Message);
                }
            }
            UnresolvedTypeSystemForFile = SyntaxTree.ToTypeSystem();
        }
Пример #23
0
        public AstType CreateShortType(ICompilation compilation, CSharpUnresolvedFile parsedFile, TextLocation loc, IType fullType)
        {
            var csResolver = parsedFile.GetResolver(compilation, loc);
            var builder    = new ICSharpCode.NRefactory.CSharp.Refactoring.TypeSystemAstBuilder(csResolver);

            return(builder.ConvertType(fullType));
        }
Пример #24
0
        CSharpUnresolvedFile Parse(string program)
        {
            SyntaxTree           syntaxTree     = SyntaxTree.Parse(program, "test.cs");
            CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();

            project     = project.AddOrUpdateFiles(unresolvedFile);
            compilation = project.CreateCompilation();
            return(unresolvedFile);
        }
		public CSharpFullParseInformation(CSharpUnresolvedFile unresolvedFile, ITextSourceVersion parsedVersion, SyntaxTree compilationUnit)
			: base(unresolvedFile, parsedVersion, isFullParseInformation: true)
		{
			if (unresolvedFile == null)
				throw new ArgumentNullException("unresolvedFile");
			if (compilationUnit == null)
				throw new ArgumentNullException("compilationUnit");
			this.syntaxTree = compilationUnit;
		}
		public DefaultCompletionContextProvider (IDocument document, CSharpUnresolvedFile unresolvedFile)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (unresolvedFile == null)
				throw new ArgumentNullException("unresolvedFile");
			this.document = document;
			this.unresolvedFile = unresolvedFile;
		}
        public static ICompilation CreateCompilation(params IUnresolvedTypeDefinition[] unresolvedTypeDefinitions)
        {
            var unresolvedFile = new CSharpUnresolvedFile("dummy.cs");

            foreach (var typeDef in unresolvedTypeDefinitions)
            {
                unresolvedFile.TopLevelTypeDefinitions.Add(typeDef);
            }
            return(CreateCompilation(unresolvedFile));
        }
        void Init(string program)
        {
            pc             = new CSharpProjectContent();
            pc             = pc.SetAssemblyName("MyAssembly");
            unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem();
            pc             = pc.AddOrUpdateFiles(unresolvedFile);
            pc             = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });

            compilation = pc.CreateCompilation();
        }
Пример #29
0
		void Init(string program)
		{
			pc = new CSharpProjectContent();
			pc = pc.SetAssemblyName("MyAssembly");
			unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem();
			pc = pc.AddOrUpdateFiles(unresolvedFile);
			pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });
			
			compilation = pc.CreateCompilation();
		}
Пример #30
0
        CSharpUnresolvedFile Parse(string program)
        {
            SyntaxTree           syntaxTree     = SyntaxTree.Parse(program, "test.cs");
            CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();

            project     = project.AddOrUpdateFiles(unresolvedFile);
            compilation = project.CreateCompilation();
            lookup      = new MemberLookup(null, compilation.MainAssembly);
            return(unresolvedFile);
        }
Пример #31
0
        // Token: 0x0600001A RID: 26 RVA: 0x00002560 File Offset: 0x00000760
        private ParsedDocument Parse(TextReader content, string fileName, ProjectVisualStudio project)
        {
            CSharpParser csharpParser = new CSharpParser(this.GetCompilerArguments(project));
            SyntaxTree   syntaxTree   = csharpParser.Parse(content, fileName);

            syntaxTree.Freeze();
            CSharpUnresolvedFile parsedFile = syntaxTree.ToTypeSystem();

            return(new ParsedDocument(syntaxTree, parsedFile));
        }
Пример #32
0
 public CSharpFile(CSharpProject project, FileName fileName)
 {
     this.Project = project;
     this.FileName = fileName;
     this.OriginalText = File.ReadAllText(fileName);
     CSharpParser p = new CSharpParser(project.CompilerSettings);
     this.SyntaxTree = p.Parse(this.OriginalText, fileName);
     this.UnresolvedTypeSystemForFile = SD.ParserService.GetExistingUnresolvedFile(fileName, null, project.IProject) as CSharpUnresolvedFile;
     if (this.UnresolvedTypeSystemForFile == null)
         throw new InvalidOperationException("LoadSolutionProjectsThread not yet finished?");
 }
Пример #33
0
		/// <summary>
		/// Creates a new C# AST resolver.
		/// Use this overload if you are resolving within a complete C# file.
		/// </summary>
		/// <param name="compilation">The current compilation.</param>
		/// <param name="syntaxTree">The syntax tree to be resolved.</param>
		/// <param name="unresolvedFile">
		/// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
		/// <para>
		/// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
		/// </para>
		/// <para>
		/// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
		/// member declarations in the AST with members in the type system.
		/// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
		/// member's signature in the AST with the signature in the type system.
		/// </para>
		/// </param>
		public CSharpAstResolver(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile = null)
		{
			if (compilation == null)
				throw new ArgumentNullException("compilation");
			if (syntaxTree == null)
				throw new ArgumentNullException("syntaxTree");
			this.initialResolverState = new CSharpResolver(compilation);
			this.rootNode = syntaxTree;
			this.unresolvedFile = unresolvedFile;
			this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
		}
Пример #34
0
        public override int GetCurrentParameterIndex(int startOffset)
        {
            var engine = new CSharpParameterCompletionEngine(
                TextEditorData.Document,
                typeSystemSegmentTree,
                this,
                Document.GetProjectContext(),
                CSharpUnresolvedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext
                );

            return(engine.GetCurrentParameterIndex(startOffset, document.Editor.Caret.Offset));
        }
        public override void SetUp()
        {
            base.SetUp();
            unresolvedFile = new CSharpUnresolvedFile("test.cs");
            unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System"));
            unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System.Collections.Generic"));
            unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System.Linq"));

            convertVisitor = new CodeDomConvertVisitor();
            convertVisitor.AllowSnippetNodes          = false;
            convertVisitor.UseFullyQualifiedTypeNames = true;
        }
		public override void SetUp()
		{
			base.SetUp();
			unresolvedFile = new CSharpUnresolvedFile();
			unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System"));
			unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System.Collections.Generic"));
			unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System.Linq"));
			
			convertVisitor = new CodeDomConvertVisitor();
			convertVisitor.AllowSnippetNodes = false;
			convertVisitor.UseFullyQualifiedTypeNames = true;
		}
Пример #37
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();
            }
        }
Пример #38
0
        public override bool GetParameterCompletionCommandOffset(out int cpos)
        {
            var engine = new CSharpParameterCompletionEngine(
                TextEditorData.Document,
                typeSystemSegmentTree,
                this,
                Document.GetProjectContext(),
                CSharpUnresolvedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext
                );

            engine.SetOffset(document.Editor.Caret.Offset);
            return(engine.GetParameterCompletionCommandOffset(out cpos));
        }
Пример #39
0
 public CSharpFullParseInformation(CSharpUnresolvedFile unresolvedFile, ITextSourceVersion parsedVersion, SyntaxTree compilationUnit)
     : base(unresolvedFile, parsedVersion, isFullParseInformation: true)
 {
     if (unresolvedFile == null)
     {
         throw new ArgumentNullException("unresolvedFile");
     }
     if (compilationUnit == null)
     {
         throw new ArgumentNullException("compilationUnit");
     }
     this.syntaxTree = compilationUnit;
 }
 public DefaultCompletionContextProvider(IDocument document, CSharpUnresolvedFile unresolvedFile)
 {
     if (document == null)
     {
         throw new ArgumentNullException("document");
     }
     if (unresolvedFile == null)
     {
         throw new ArgumentNullException("unresolvedFile");
     }
     this.document       = document;
     this.unresolvedFile = unresolvedFile;
 }
Пример #41
0
        public CSharpFile(CSharpProject project, FileName fileName)
        {
            this.Project      = project;
            this.FileName     = fileName;
            this.OriginalText = File.ReadAllText(fileName);
            CSharpParser p = new CSharpParser(project.CompilerSettings);

            this.SyntaxTree = p.Parse(this.OriginalText, fileName);
            this.UnresolvedTypeSystemForFile = SD.ParserService.GetExistingUnresolvedFile(fileName, null, project.IProject) as CSharpUnresolvedFile;
            if (this.UnresolvedTypeSystemForFile == null)
            {
                throw new InvalidOperationException("LoadSolutionProjectsThread not yet finished?");
            }
        }
Пример #42
0
		public void SetUp()
		{
			pc = new CSharpProjectContent();
			pc = pc.SetAssemblyName("MyAssembly");
			unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem();
			pc = pc.AddOrUpdateFiles(unresolvedFile);
			pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });
			
			compilation = pc.CreateCompilation();
			
			baseClass = compilation.RootNamespace.GetTypeDefinition("Base", 1);
			nestedClass = baseClass.NestedTypes.Single();
			derivedClass = compilation.RootNamespace.GetTypeDefinition("Derived", 2);
			systemClass = compilation.RootNamespace.GetChildNamespace("NS").GetTypeDefinition("System", 0);
		}
Пример #43
0
        public void SetUp()
        {
            pc             = new CSharpProjectContent();
            pc             = pc.SetAssemblyName("MyAssembly");
            unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem();
            pc             = pc.AddOrUpdateFiles(unresolvedFile);
            pc             = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });

            compilation = pc.CreateCompilation();

            baseClass    = compilation.RootNamespace.GetTypeDefinition("Base", 1);
            nestedClass  = baseClass.NestedTypes.Single();
            derivedClass = compilation.RootNamespace.GetTypeDefinition("Derived", 2);
            systemClass  = compilation.RootNamespace.GetChildNamespace("NS").GetTypeDefinition("System", 0);
        }
		private CSharpCompletionContext(ITextEditor editor, IList<string> conditionalSymbols, ICompilation compilation, IProjectContent projectContent, IDocument document, CSharpUnresolvedFile unresolvedFile, TextLocation caretLocation)
		{
			Debug.Assert(editor != null);
			Debug.Assert(unresolvedFile != null);
			Debug.Assert(compilation != null);
			Debug.Assert(projectContent != null);
			Debug.Assert(document != null);
			this.Editor = editor;
			this.Document = document;
			this.ConditionalSymbols = conditionalSymbols;
			this.Compilation = compilation;
			this.ProjectContent = projectContent;
			this.TypeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(compilation, caretLocation);
			this.CompletionContextProvider = new DefaultCompletionContextProvider(document, unresolvedFile);
			this.CompletionContextProvider.ConditionalSymbols.AddRange(conditionalSymbols);
		}
Пример #45
0
        public CSharpFile(NRefactory.CSharpProject project, string fileName, string sourceCode)
        {
            _project = project;
            FileName = fileName;

            var parser = new CSharpParser(project.CompilerSettings);

            // Keep the original text around; we might use it for a refactoring later
            OriginalText = sourceCode;
            SyntaxTree = parser.Parse(OriginalText, fileName);

            _errors = parser.HasErrors
                ? parser.ErrorsAndWarnings
                : new List<Error>(0);

            UnresolvedTypeSystemForFile = SyntaxTree.ToTypeSystem();
        }
Пример #46
0
        public CSharpFile(CSharpProject project, FilePath fileName, string sourceCode)
        {
            Ensure.ArgumentNotNull(project, "project");

            Project = project;
            FileName = fileName;
            OriginalText = sourceCode;

            var parser = new CSharpParser(Project.CompilerSettings);

            SyntaxTree = parser.Parse(sourceCode, fileName.FullPath);

            Errors = parser.HasErrors
                ? parser.ErrorsAndWarnings
                : new List<Error>(0);

            UnresolvedTypeSystemForFile = SyntaxTree.ToTypeSystem();
        }
		public MethodParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IEnumerable<IMethod> m) : base (ext, startOffset)
		{
			compilation = ext.UnresolvedFileCompilation;
			file = ext.CSharpUnresolvedFile;

			HashSet<string> alreadyAdded = new HashSet<string> ();
			foreach (var method in m) {
				if (method.IsConstructor)
					continue;
				if (!method.IsBrowsable ())
					continue;
				string str = ambience.GetString (method, OutputFlags.IncludeParameters | OutputFlags.GeneralizeGenerics | OutputFlags.IncludeGenerics);
				if (alreadyAdded.Contains (str))
					continue;
				alreadyAdded.Add (str);
				methods.Add (method);
			}
			
			methods.Sort (MethodComparer);
		}
Пример #48
0
		private void Prepare(string source, Action preparer) {
			IProjectContent project = new CSharpProjectContent();
			var parser = new CSharpParser();

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

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

			var er = new MockErrorReporter(true);
			Metadata = new MetadataImporter(er, compilation, new CompilerOptions());
			preparer();
			Metadata.Prepare(compilation.GetAllTypeDefinitions());
			Assert.That(er.AllMessages, Is.Empty, "Should not generate errrors");
		}
Пример #49
0
		public CSharpFile(CSharpProject project, string fileName)
		{
			this.Project = project;
			this.FileName = fileName;
			
			CSharpParser p = new CSharpParser(project.CompilerSettings);
//			using (var stream = File.OpenRead(fileName)) {
//				this.CompilationUnit = p.Parse(stream, fileName);
//			}
			
			// Keep the original text around; we might use it for a refactoring later
			this.OriginalText = File.ReadAllText(fileName);
			this.SyntaxTree = p.Parse(this.OriginalText, fileName);
			
			if (p.HasErrors) {
				Console.WriteLine("Error parsing " + fileName + ":");
				foreach (var error in p.ErrorsAndWarnings) {
					Console.WriteLine("  " + error.Region + " " + error.Message);
				}
			}
			this.UnresolvedTypeSystemForFile = this.SyntaxTree.ToTypeSystem();
		}
Пример #50
0
		/// <summary>
		/// Creates a new C# AST resolver.
		/// Use this overload if you are resolving code snippets (not necessarily complete files).
		/// </summary>
		/// <param name="resolver">The resolver state at the root node (to be more precise: just outside the root node).</param>
		/// <param name="rootNode">The root node of the tree to be resolved.</param>
		/// <param name="unresolvedFile">
		/// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
		/// <para>
		/// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
		/// </para>
		/// <para>
		/// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
		/// member declarations in the AST with members in the type system.
		/// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
		/// member's signature in the AST with the signature in the type system.
		/// </para>
		/// </param>
		public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpUnresolvedFile unresolvedFile = null)
		{
			if (resolver == null)
				throw new ArgumentNullException("resolver");
			if (rootNode == null)
				throw new ArgumentNullException("rootNode");
			this.initialResolverState = resolver;
			this.rootNode = rootNode;
			this.unresolvedFile = unresolvedFile;
			this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
		}
		public AstType CreateShortType (ICompilation compilation, CSharpUnresolvedFile parsedFile, TextLocation loc, IType fullType)
		{
			var csResolver = parsedFile.GetResolver (compilation, loc);
			var builder = new ICSharpCode.NRefactory.CSharp.Refactoring.TypeSystemAstBuilder (csResolver);
			return builder.ConvertType (fullType);			
		}
Пример #52
0
        /// <summary>
        /// Finds all references of a given type parameter.
        /// </summary>
        /// <param name="typeParameter">The type parameter for which to look.</param>
        /// <param name="unresolvedFile">The type system representation of the file being searched.</param>
        /// <param name="syntaxTree">The syntax tree of the file being searched.</param>
        /// <param name="compilation">The compilation.</param>
        /// <param name="callback">Callback used to report the references that were found.</param>
        /// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
        public void FindTypeParameterReferences(IType typeParameter, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
		                                ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
        {
            if (typeParameter == null)
                throw new ArgumentNullException("typeParameter");
            if (typeParameter.Kind != TypeKind.TypeParameter)
                throw new ArgumentOutOfRangeException("typeParameter", "Only type parameters are allowed");
            var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator((ITypeParameter)typeParameter));
            searchScope.declarationCompilation = compilation;
            searchScope.accessibility = Accessibility.Private;
            FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
        }
Пример #53
0
        /// <summary>
        /// Finds all references in the given file.
        /// </summary>
        /// <param name="searchScopes">The search scopes for which to look.</param>
        /// <param name="unresolvedFile">The type system representation of the file being searched.</param>
        /// <param name="syntaxTree">The syntax tree of the file being searched.</param>
        /// <param name="compilation">The compilation for the project that contains the file.</param>
        /// <param name="callback">Callback used to report the references that were found.</param>
        /// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
        public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
		                                 ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
        {
            if (searchScopes == null)
                throw new ArgumentNullException("searchScopes");
            if (syntaxTree == null)
                throw new ArgumentNullException("syntaxTree");
            if (compilation == null)
                throw new ArgumentNullException("compilation");
            if (callback == null)
                throw new ArgumentNullException("callback");

            if (searchScopes.Count == 0)
                return;
            var navigators = new IResolveVisitorNavigator[searchScopes.Count];
            for (int i = 0; i < navigators.Length; i++) {
                navigators[i] = searchScopes[i].GetNavigator(compilation, callback);
            }
            IResolveVisitorNavigator combinedNavigator;
            if (searchScopes.Count == 1) {
                combinedNavigator = navigators[0];
            } else {
                combinedNavigator = new CompositeResolveVisitorNavigator(navigators);
            }

            cancellationToken.ThrowIfCancellationRequested();
            combinedNavigator = new DetectSkippableNodesNavigator(combinedNavigator, syntaxTree);
            cancellationToken.ThrowIfCancellationRequested();
            CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
            resolver.ApplyNavigator(combinedNavigator, cancellationToken);
            foreach (var n in navigators) {
                var frn = n as FindReferenceNavigator;
                if (frn != null)
                    frn.NavigatorDone(resolver, cancellationToken);
            }
        }
Пример #54
0
        /// <summary>
        /// Finds all references in the given file.
        /// </summary>
        /// <param name="searchScope">The search scope for which to look.</param>
        /// <param name="unresolvedFile">The type system representation of the file being searched.</param>
        /// <param name="syntaxTree">The syntax tree of the file being searched.</param>
        /// <param name="compilation">The compilation for the project that contains the file.</param>
        /// <param name="callback">Callback used to report the references that were found.</param>
        /// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
        public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
		                                 ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
        {
            if (searchScope == null)
                throw new ArgumentNullException("searchScope");
            FindReferencesInFile(new[] { searchScope }, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
        }
Пример #55
0
        /// <summary>
        /// Finds all references of a given variable.
        /// </summary>
        /// <param name="variable">The variable for which to look.</param>
        /// <param name="unresolvedFile">The type system representation of the file being searched.</param>
        /// <param name="syntaxTree">The syntax tree of the file being searched.</param>
        /// <param name="compilation">The compilation.</param>
        /// <param name="callback">Callback used to report the references that were found.</param>
        /// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
        public void FindLocalReferences(IVariable variable, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
		                                ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
        {
            if (variable == null)
                throw new ArgumentNullException("variable");
            var searchScope = new SearchScope(c => new FindLocalReferencesNavigator(variable));
            searchScope.declarationCompilation = compilation;
            FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
        }
Пример #56
0
 public ParsedSourceFile(SyntaxTree syntaxTree, CSharpUnresolvedFile parsedFile)
 {
     SyntaxTree = syntaxTree;
     ParsedFile = parsedFile;
 }
		public static TooltipInformation CreateTooltipInformation (CSharpCompletionTextEditorExtension ext, ICompilation compilation, CSharpUnresolvedFile file, IParameterizedMember entity, int currentParameter, bool smartWrap)
		{
			return CreateTooltipInformation (compilation, file, ext.TextEditorData, ext.FormattingPolicy, entity, currentParameter, smartWrap);
		}
		public static TooltipInformation CreateTooltipInformation (ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IParameterizedMember entity, int currentParameter, bool smartWrap)
		{
			var tooltipInfo = new TooltipInformation ();
			var resolver = file.GetResolver (compilation, textEditorData.Caret.Location);
			var sig = new SignatureMarkupCreator (resolver, formattingPolicy.CreateOptions ());
			sig.HighlightParameter = currentParameter;
			sig.BreakLineAfterReturnType = smartWrap;
			try {
				tooltipInfo.SignatureMarkup = sig.GetMarkup (entity);
			} catch (Exception e) {
				LoggingService.LogError ("Got exception while creating markup for :" + entity, e);
				return new TooltipInformation ();
			}
			tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup (entity) ?? "";
			
			if (entity is IMethod) {
				var method = (IMethod)entity;
				if (method.IsExtensionMethod) {
					tooltipInfo.AddCategory (GettextCatalog.GetString ("Extension Method from"), method.DeclaringTypeDefinition.FullName);
				}
			}
			int paramIndex = currentParameter;

			if (entity is IMethod && ((IMethod)entity).IsExtensionMethod)
				paramIndex++;
			paramIndex = Math.Min (entity.Parameters.Count - 1, paramIndex);

			var curParameter = paramIndex >= 0  && paramIndex < entity.Parameters.Count ? entity.Parameters [paramIndex] : null;
			if (curParameter != null) {

				string docText = AmbienceService.GetDocumentation (entity);
				if (!string.IsNullOrEmpty (docText)) {
					string text = docText;
					Regex paramRegex = new Regex ("(\\<param\\s+name\\s*=\\s*\"" + curParameter.Name + "\"\\s*\\>.*?\\</param\\>)", RegexOptions.Compiled);
					Match match = paramRegex.Match (docText);
					
					if (match.Success) {
						text = AmbienceService.GetDocumentationMarkup (entity, match.Groups [1].Value);
						if (!string.IsNullOrWhiteSpace (text))
							tooltipInfo.AddCategory (GettextCatalog.GetString ("Parameter"), text);
					}
				}
		
				if (curParameter.Type.Kind == TypeKind.Delegate)
					tooltipInfo.AddCategory (GettextCatalog.GetString ("Delegate Info"), sig.GetDelegateInfo (curParameter.Type));
			}
			return tooltipInfo;
		}
		protected MethodParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext) : base (ext, startOffset)
		{
			compilation = ext.UnresolvedFileCompilation;
			file = ext.CSharpUnresolvedFile;
		}
Пример #60
0
		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);
		}