public static void RunTest(CSharpFile file) { CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile); var navigator = new ValidatingResolveAllNavigator(file.FileName); resolver.ApplyNavigator(navigator, CancellationToken.None); navigator.Validate(resolver, file.SyntaxTree); }
public SemanticErrorsResponse FindSemanticErrors(Request request) { var clientFilename = request.FileName.ApplyPathReplacementsForClient(); var project = _solution.ProjectContainingFile(request.FileName); project.UpdateFile(request.FileName, request.Buffer); var solutionSnapshot = new DefaultSolutionSnapshot(_solution.Projects.Select(i => i.ProjectContent)); SyntaxTree syntaxTree; if(project.CompilerSettings!=null){ syntaxTree = new CSharpParser(project.CompilerSettings).Parse(request.Buffer, request.FileName); }else{ syntaxTree = new CSharpParser().Parse(request.Buffer, request.FileName); } var resolver = new CSharpAstResolver(solutionSnapshot.GetCompilation(project.ProjectContent), syntaxTree); var navigator = new SemanticErrorsNavigator(); resolver.ApplyNavigator(navigator); var errors = navigator.GetErrors() .Where(e => ShouldIncludeIssue(e.Message)) .Select(i => new Error { FileName = clientFilename, Message = i.Message, Line = i.StartLocation.Line, Column = i.EndLocation.Column, EndLine = i.EndLocation.Line, EndColumn = i.EndLocation.Column }); return new SemanticErrorsResponse { Errors = errors, }; }
public static void RunTest(CSharpFile file) { CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.CompilationUnit, file.ParsedFile); var navigator = new ValidatingResolveAllNavigator(file.FileName); resolver.ApplyNavigator(navigator, CancellationToken.None); navigator.Validate(file.CompilationUnit); }
/// <summary> /// Finds all references in the given file. /// </summary> /// <param name="searchScopes">The search scopes for which to look.</param> /// <param name="parsedFile">The type system representation of the file being searched.</param> /// <param name="compilationUnit">The compilation unit 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, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) { if (searchScopes == null) { throw new ArgumentNullException("searchScopes"); } if (parsedFile == null) { throw new ArgumentNullException("parsedFile"); } if (compilationUnit == null) { throw new ArgumentNullException("compilationUnit"); } 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, compilationUnit); cancellationToken.ThrowIfCancellationRequested(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, compilationUnit, parsedFile); resolver.ApplyNavigator(combinedNavigator, cancellationToken); foreach (var n in navigators) { var frn = n as FindReferenceNavigator; if (frn != null) { frn.NavigatorDone(resolver, cancellationToken); } } }
/// <summary> /// Returns a full C# syntax tree resolver which is shared between semantic highlighting, source analysis and refactoring. /// For code analysis tasks this should be used instead of generating an own resolver. Only exception is if a local resolving is done using a /// resolve navigator. /// Note: The shared resolver is fully resolved. /// </summary> public static Task<CSharpAstResolver> GetSharedResolver (this Document document) { var parsedDocument = document.ParsedDocument; if (parsedDocument == null) return null; var unit = parsedDocument.GetAst<SyntaxTree> (); var parsedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; if (unit == null || parsedFile == null) return null; var resolverAnnotation = document.Annotation<ResolverAnnotation> (); if (resolverAnnotation != null) { if (resolverAnnotation.ParsedFile == parsedFile) return resolverAnnotation.Task; document.RemoveAnnotations<ResolverAnnotation> (); } var resolveTask = Task.Factory.StartNew (delegate { var result = new CSharpAstResolver (document.Compilation, unit, parsedFile); result.ApplyNavigator (new ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null)); return result; }); document.AddAnnotation (new ResolverAnnotation { Task = resolveTask, ParsedFile = parsedFile }); return resolveTask; }
/// <summary> /// Returns a full C# syntax tree resolver which is shared between semantic highlighting, source analysis and refactoring. /// For code analysis tasks this should be used instead of generating an own resolver. Only exception is if a local resolving is done using a /// resolve navigator. /// Note: The shared resolver is fully resolved. /// </summary> public static Task<CSharpAstResolver> GetSharedResolver (this Document document) { var parsedDocument = document.ParsedDocument; if (parsedDocument == null || document.IsProjectContextInUpdate || document.Project != null && !(document.Project is DotNetProject)) return null; var unit = parsedDocument.GetAst<SyntaxTree> (); var parsedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; if (unit == null || parsedFile == null) return null; var compilation = document.Compilation; var resolverAnnotation = document.Annotation<ResolverAnnotation> (); if (resolverAnnotation != null) { if (resolverAnnotation.ParsedFile == parsedFile) return resolverAnnotation.Task; if (resolverAnnotation.SharedTokenSource != null) resolverAnnotation.SharedTokenSource.Cancel (); document.RemoveAnnotations<ResolverAnnotation> (); } var tokenSource = new CancellationTokenSource (); var token = tokenSource.Token; var resolveTask = Task.Factory.StartNew (delegate { try { using (var timer = ResolveCounter.BeginTiming ()) { var result = new CSharpAstResolver (compilation, unit, parsedFile); result.ApplyNavigator (new ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null), token); return result; } } catch (OperationCanceledException) { return null; } catch (Exception e) { LoggingService.LogError ("Error while creating the resolver.", e); return null; } }, token); var wrapper = resolveTask.ContinueWith (t => { if (t.IsCanceled) return null; if (t.IsFaulted) { var ex = t.Exception.Flatten ().InnerException; if (!(ex is TaskCanceledException)) LoggingService.LogWarning ("Exception while getting shared AST resolver.", ex); return null; } return t.Result; }, TaskContinuationOptions.ExecuteSynchronously); document.AddAnnotation (new ResolverAnnotation { Task = wrapper, ParsedFile = parsedFile, SharedTokenSource = tokenSource }); return wrapper; }
public static void RunTestWithoutUnresolvedFile(CSharpFile file) { CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree); var navigator = new ValidatingResolveAllNavigator(file.FileName); resolver.ApplyNavigator(navigator, CancellationToken.None); navigator.Validate(resolver, file.SyntaxTree); CSharpAstResolver originalResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile); foreach (var node in file.SyntaxTree.DescendantsAndSelf) { var originalResult = originalResolver.Resolve(node); var result = resolver.Resolve(node); if (!RandomizedOrderResolverTest.IsEqualResolveResult(result, originalResult)) { Console.WriteLine("Got different without IUnresolvedFile at " + file.FileName + ":" + node.StartLocation); } } }
public void Run() { using (new Timer("Finding referenced entities... ")) { foreach (var file in solution.AllFiles) { var navigator = new FindReferencedEntities( delegate (AstNode node, IEntity entity) { if (node == null) throw new ArgumentNullException("node"); if (entity == null) throw new ArgumentNullException("entity"); if (!IgnoreEntity(entity)) { HashSet<AstNode> list; if (!referenceDict.TryGetValue(entity, out list)) { list = new HashSet<AstNode>(); referenceDict.Add(entity, list); } list.Add(node); } } ); var resolver = new CSharpAstResolver(file.Project.Compilation, file.CompilationUnit, file.ParsedFile); resolver.ApplyNavigator(navigator); } } Console.WriteLine("For each entity, find all references..."); Stopwatch w = Stopwatch.StartNew(); foreach (var project in solution.Projects) { foreach (var type in project.Compilation.MainAssembly.GetAllTypeDefinitions()) { TestFindReferences(type); foreach (IMember m in type.Members) { TestFindReferences(m); } Console.Write('.'); } } w.Stop(); Console.WriteLine("FindReferencesConsistencyCheck is done ({0}).", w.Elapsed); PrintTimingsPerEntityType(); }
public SemanticErrorsResponse FindSemanticErrors(Request request) { var clientFilename = request.FileName.ApplyPathReplacementsForClient(); var project = _solution.ProjectContainingFile(request.FileName); project.UpdateFile(request.FileName, request.Buffer); var solutionSnapshot = new DefaultSolutionSnapshot(_solution.Projects.Select(i => i.ProjectContent)); var syntaxTree = new CSharpParser().Parse(request.Buffer, request.FileName); var resolver = new CSharpAstResolver(solutionSnapshot.GetCompilation(project.ProjectContent), syntaxTree); var navigator = new SemanticErrorsNavigator(); resolver.ApplyNavigator(navigator); var errors = navigator.GetErrors().Select(i => new Error { FileName = clientFilename, Message = i.Message, Line = i.TextLocation.Line, Column = i.TextLocation.Column, }); return new SemanticErrorsResponse { Errors = errors, }; }
public ResolveResult GetLanguageItem (MonoDevelop.Ide.Gui.Document doc, int offset, string expression) { if (offset < 0) { return null; } var parsedDocument = doc.ParsedDocument; if (parsedDocument == null) return null; var data = doc.Editor; var loc = data.OffsetToLocation (offset); var unit = parsedDocument.GetAst<SyntaxTree> (); var parsedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; if (unit == null || parsedFile == null) { return null; } var node = unit.GetNodeAt (loc); if (node == null) { return null; } var resolver = new CSharpAstResolver (doc.Compilation, unit, parsedFile); resolver.ApplyNavigator (new NodeListResolveVisitorNavigator (node), CancellationToken.None); var state = resolver.GetResolverStateBefore (node, CancellationToken.None); var list = new List<IType> (); int indexOf = expression.IndexOf ('`'); if (indexOf != -1) { var intType = new PrimitiveType ("int").ToTypeReference ().Resolve (doc.Compilation); var num = expression.Substring (indexOf + 1); int number = int.Parse (num); for (int i = 0; i < number; i++) list.Add (intType); expression = expression.Remove (indexOf); } return state.LookupSimpleNameOrTypeName (expression, list, NameLookupMode.Expression); }
public TooltipItem GetItem (Mono.TextEditor.TextEditor editor, int offset) { var doc = IdeApp.Workbench.ActiveDocument; if (doc == null || doc.ParsedDocument == null) return null; var unit = doc.ParsedDocument.GetAst<SyntaxTree> (); if (unit == null) return null; var file = doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile; if (file == null) return null; ResolveResult result; AstNode node; var loc = editor.OffsetToLocation (offset); if (!doc.TryResolveAt (loc, out result, out node)) return null; var resolver = new CSharpAstResolver (doc.Compilation, unit, file); resolver.ApplyNavigator (new NodeListResolveVisitorNavigator (node), CancellationToken.None); int startOffset = offset; int endOffset = offset; return new TooltipItem (new ToolTipData (unit, result, node, resolver), startOffset, endOffset - startOffset); }
public static ResolveResult Resolve(Func<ICompilation> compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, out AstNode node, CancellationToken cancellationToken = default(CancellationToken)) { node = cu.GetNodeAt(location); if (node == null) return null; 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) { // we also need to resolve the invocation parentInvocation = node.Parent as InvocationExpression; } CSharpAstResolver resolver = new CSharpAstResolver(compilation(), cu, parsedFile); resolver.ApplyNavigator(new NodeListResolveVisitorNavigator(node), cancellationToken); ResolveResult rr = resolver.Resolve(node, cancellationToken); if (rr is MethodGroupResolveResult && parentInvocation != null) return resolver.Resolve(parentInvocation); else return rr; }
public static ResolveResult Resolve(ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, out AstNode node, CancellationToken cancellationToken = default(CancellationToken)) { node = cu.GetNodeAt(location); if (node == null) { return(null); } 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) { // we also need to resolve the invocation parentInvocation = node.Parent as InvocationExpression; } CSharpAstResolver resolver = new CSharpAstResolver(compilation, cu, parsedFile); resolver.ApplyNavigator(new NodeListResolveVisitorNavigator(node), cancellationToken); ResolveResult rr = resolver.Resolve(node, cancellationToken); if (rr is MethodGroupResolveResult && parentInvocation != null) { return(resolver.Resolve(parentInvocation)); } else { return(rr); } }
bool TypeChangeResolvesCorrectly(ParameterDeclaration parameter, AstNode rootNode, IType type) { MethodResolveCount++; var resolver = ctx.GetResolverStateBefore(rootNode); resolver = resolver.AddVariable(new DefaultParameter(type, parameter.Name)); var astResolver = new CSharpAstResolver(resolver, rootNode, ctx.UnresolvedFile); var validator = new TypeChangeValidationNavigator(); astResolver.ApplyNavigator(validator, ctx.CancellationToken); return !validator.FoundErrors; }
/// <summary> /// Finds all references in the given file. /// </summary> /// <param name="searchScopes">The search scopes for which to look.</param> /// <param name="parsedFile">The type system representation of the file being searched.</param> /// <param name="compilationUnit">The compilation unit 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, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) { if (searchScopes == null) throw new ArgumentNullException("searchScopes"); if (parsedFile == null) throw new ArgumentNullException("parsedFile"); if (compilationUnit == null) throw new ArgumentNullException("compilationUnit"); if (compilation == null) throw new ArgumentNullException("compilation"); if (callback == null) throw new ArgumentNullException("callback"); if (searchScopes.Count == 0) return; IResolveVisitorNavigator navigator; if (searchScopes.Count == 1) { navigator = searchScopes[0].GetNavigator(compilation, callback); } else { IResolveVisitorNavigator[] navigators = new IResolveVisitorNavigator[searchScopes.Count]; for (int i = 0; i < navigators.Length; i++) { navigators[i] = searchScopes[i].GetNavigator(compilation, callback); } navigator = new CompositeResolveVisitorNavigator(navigators); } cancellationToken.ThrowIfCancellationRequested(); navigator = new DetectSkippableNodesNavigator(navigator, compilationUnit); cancellationToken.ThrowIfCancellationRequested(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, compilationUnit, parsedFile); resolver.ApplyNavigator(navigator, cancellationToken); }
/// <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); } }
public ResolveResult GetLanguageItem (MonoDevelop.Ide.Gui.Document doc, int offset, string expression) { if (offset < 0) { return null; } var parsedDocument = doc.ParsedDocument; if (parsedDocument == null) return null; var data = doc.Editor; var loc = data.OffsetToLocation (offset); var unit = parsedDocument.GetAst<CompilationUnit> (); var parsedFile = parsedDocument.ParsedFile as CSharpParsedFile; if (unit == null || parsedFile == null) { return null; } var node = unit.GetNodeAt (loc); if (node == null) { return null; } var resolver = new CSharpAstResolver (doc.Compilation, unit, parsedFile); resolver.ApplyNavigator (new NodeListResolveVisitorNavigator (node), CancellationToken.None); var state = resolver.GetResolverStateBefore (node, CancellationToken.None); return state.LookupSimpleNameOrTypeName (expression, new List<IType> (), NameLookupMode.Expression); }
/// <summary> /// Returns a full C# syntax tree resolver which is shared between semantic highlighting, source analysis and refactoring. /// For code analysis tasks this should be used instead of generating an own resolver. Only exception is if a local resolving is done using a /// resolve navigator. /// Note: The shared resolver is fully resolved. /// </summary> public static TaskWrapper GetSharedResolver (this Document document) { var parsedDocument = document.ParsedDocument; if (parsedDocument == null || document.IsProjectContextInUpdate) return null; var unit = parsedDocument.GetAst<SyntaxTree> (); var parsedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; if (unit == null || parsedFile == null) return null; var compilation = document.Compilation; var resolverAnnotation = document.Annotation<ResolverAnnotation> (); if (resolverAnnotation != null) { if (resolverAnnotation.ParsedFile == parsedFile) return resolverAnnotation.Task; if (resolverAnnotation.SharedTokenSource != null) resolverAnnotation.SharedTokenSource.Cancel (); document.RemoveAnnotations<ResolverAnnotation> (); } var tokenSource = new CancellationTokenSource (); var token = tokenSource.Token; var resolveTask = Task.Factory.StartNew (delegate { try { using (var timer = ResolveCounter.BeginTiming ()) { var result = new CSharpAstResolver (compilation, unit, parsedFile); result.ApplyNavigator (new ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null), token); return result; } } catch (OperationCanceledException) { return null; } catch (Exception e) { LoggingService.LogError ("Error while creating the resolver.", e); return null; } }, token); var wrapper = new TaskWrapper (resolveTask); document.AddAnnotation (new ResolverAnnotation { Task = wrapper, ParsedFile = parsedFile, SharedTokenSource = tokenSource }); return wrapper; }
public IEnumerable<JsType> Compile(PreparedCompilation compilation) { _compilation = compilation.Compilation; _metadataImporter.Prepare(_compilation.GetAllTypeDefinitions(), _compilation.MainAssembly, _errorReporter); _types = new Dictionary<ITypeDefinition, JsClass>(); _constructorDeclarations = new HashSet<Tuple<ConstructorDeclaration, CSharpAstResolver>>(); _instanceInitStatements = new Dictionary<JsClass, List<JsStatement>>(); var unsupportedConstructsScanner = new UnsupportedConstructsScanner(_errorReporter, compilation.Compilation.ReferencedAssemblies.Count == 0); bool hasUnsupported = false; foreach (var f in compilation.SourceFiles) { try { if (!AllowUnsupportedConstructs) { if (!unsupportedConstructsScanner.ProcessAndReturnTrueIfEverythingIsSupported(f.SyntaxTree)) { hasUnsupported = true; continue; } } _definedSymbols = f.DefinedSymbols; _resolver = new CSharpAstResolver(_compilation, f.SyntaxTree, f.ParsedFile); _resolver.ApplyNavigator(new ResolveAllNavigator()); f.SyntaxTree.AcceptVisitor(this); } catch (Exception ex) { _errorReporter.Region = _currentNode.GetRegion(); _errorReporter.InternalError(ex); } } if (hasUnsupported) return new JsType[0]; // Just to be safe // Handle constructors. We must do this after we have visited all the compilation units because field initializer (which change the InstanceInitStatements and StaticInitStatements) might appear anywhere. foreach (var n in _constructorDeclarations) { try { _resolver = n.Item2; HandleConstructorDeclaration(n.Item1); } catch (Exception ex) { _errorReporter.Region = n.Item1.GetRegion(); _errorReporter.InternalError(ex); } } // Add default constructors where needed. foreach (var toAdd in _types.Where(t => t.Value != null).SelectMany(kvp => kvp.Key.GetConstructors().Where(c => c.IsSynthetic).Select(c => new { jsClass = kvp.Value, c }))) { try { MaybeAddDefaultConstructorToType(toAdd.jsClass, toAdd.c); } catch (Exception ex) { _errorReporter.Region = toAdd.c.Region; _errorReporter.InternalError(ex, "Error adding default constructor to type"); } } _types.Values.Where(t => t != null).ForEach(t => t.Freeze()); var enums = new List<JsType>(); foreach (var e in _compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).Where(t => t.Kind == TypeKind.Enum)) { try { enums.Add(ConvertEnum(e.GetDefinition())); } catch (Exception ex) { _errorReporter.Region = e.GetDefinition().Region; _errorReporter.InternalError(ex); } } return _types.Values.Concat(enums).Where(t => t != null); }
void AnalyzeFile (JobSlice item, IEnumerable<BaseCodeIssueProvider> codeIssueProviders) { var file = item.File; if (file.BuildAction != BuildAction.Compile) return; if (!(file.Project is DotNetProject)) return; TextEditorData editor; try { editor = TextFileProvider.Instance.GetReadOnlyTextEditorData (file.FilePath); } catch (FileNotFoundException) { // Swallow exception and ignore this file return; } var document = TypeSystemService.ParseFile (file.Project, editor); if (document == null) return; var content = TypeSystemService.GetProjectContext (file.Project); var compilation = content.AddOrUpdateFiles (document.ParsedFile).CreateCompilation (); CSharpAstResolver resolver; using (var timer = ExtensionMethods.ResolveCounter.BeginTiming ()) { resolver = new CSharpAstResolver (compilation, document.GetAst<SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile); try { resolver.ApplyNavigator (new ExtensionMethods.ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null)); } catch (Exception e) { LoggingService.LogError ("Error while applying navigator", e); } } var context = document.CreateRefactoringContextWithEditor (editor, resolver, CancellationToken.None); foreach (var provider in codeIssueProviders) { if (item.CancellationToken.IsCancellationRequested) break; IList<IAnalysisJob> jobs; lock (_lock) jobs = item.GetJobs ().ToList (); var jobsForProvider = jobs.Where (j => j.GetIssueProviders (file).Contains (provider)).ToList(); try { var issues = provider.GetIssues (context, CancellationToken.None).ToList (); foreach (var job in jobsForProvider) { // Call AddResult even if issues.Count == 0, to enable a job implementation to keep // track of progress information. job.AddResult (file, provider, issues); } } catch (OperationCanceledException) { // The operation was cancelled, no-op as the user-visible parts are // handled elsewhere } catch (Exception e) { foreach (var job in jobsForProvider) { job.AddError (file, provider); } } } }
public CodeGenerationOptions () { currentState = new Lazy<CSharpResolver> (() => { var parsedDocument = Document.ParsedDocument; if (parsedDocument == null) return null; var unit = parsedDocument.GetAst<SyntaxTree> ().Clone (); var file = parsedDocument.ParsedFile as CSharpUnresolvedFile; var resolvedNode = unit.GetNodeAt<BlockStatement> (Document.Editor.Caret.Location); if (resolvedNode == null) return null; var expr = new IdentifierExpression ("foo"); resolvedNode.Add (expr); var ctx = file.GetTypeResolveContext (Document.Compilation, Document.Editor.Caret.Location); var resolver = new CSharpResolver (ctx); var astResolver = new CSharpAstResolver (resolver, unit, file); astResolver.ApplyNavigator (new NodeListResolveVisitorNavigator (expr), CancellationToken.None); astResolver.Resolve (expr); return astResolver.GetResolverStateBefore (expr); }); }
void ResolveButtonClick(object sender, EventArgs e) { IProjectContent project = new CSharpProjectContent(); var parsedFile = compilationUnit.ToTypeSystem(); project = project.UpdateProjectContent(null, parsedFile); project = project.AddAssemblyReferences(builtInLibs.Value); ICompilation compilation = project.CreateCompilation(); StoreInDictionaryNavigator navigator; if (csharpTreeView.SelectedNode != null) { navigator = new StoreInDictionaryNavigator((AstNode)csharpTreeView.SelectedNode.Tag); } else { navigator = new StoreInDictionaryNavigator(); } CSharpAstResolver resolver = new CSharpAstResolver(compilation, compilationUnit, parsedFile); resolver.ApplyNavigator(navigator); csharpTreeView.BeginUpdate(); ShowResolveResultsInTree(csharpTreeView.Nodes, navigator); csharpTreeView.EndUpdate(); }
IEnumerable<ICompletionData> MagicKeyCompletion(char completionChar, bool controlSpace) { Tuple<ResolveResult, CSharpResolver> resolveResult; switch (completionChar) { // Magic key completion case ':': case '.': if (IsInsideCommentStringOrDirective()) { return Enumerable.Empty<ICompletionData>(); } return HandleMemberReferenceCompletion(GetExpressionBeforeCursor()); case '#': if (!IsInPreprocessorDirective()) return null; return GetDirectiveCompletionData(); // XML doc completion case '<': if (IsInsideDocComment()) { return GetXmlDocumentationCompletionData(); } if (controlSpace) { return DefaultControlSpaceItems(); } return null; case '>': if (!IsInsideDocComment()) { return null; } string lineText = document.GetText(document.GetLineByNumber(location.Line)); int startIndex = Math.Min(location.Column - 1, lineText.Length - 1); while (startIndex >= 0 && lineText [startIndex] != '<') { --startIndex; if (lineText [startIndex] == '/') { // already closed. startIndex = -1; break; } } if (startIndex >= 0) { int endIndex = startIndex; while (endIndex <= location.Column && endIndex < lineText.Length && !Char.IsWhiteSpace (lineText [endIndex])) { endIndex++; } string tag = endIndex - startIndex - 1 > 0 ? lineText.Substring( startIndex + 1, endIndex - startIndex - 2 ) : null; if (!string.IsNullOrEmpty(tag) && commentTags.IndexOf(tag) >= 0) { document.Insert(offset, "</" + tag + ">"); } } return null; // Parameter completion case '(': if (IsInsideCommentStringOrDirective()) { return null; } var invoke = GetInvocationBeforeCursor(true); if (invoke == null) { if (controlSpace) return DefaultControlSpaceItems(invoke); return null; } if (invoke.Node is TypeOfExpression) { return CreateTypeList(); } var invocationResult = ResolveExpression(invoke); if (invocationResult == null) { return null; } var methodGroup = invocationResult.Item1 as MethodGroupResolveResult; if (methodGroup != null) { return CreateParameterCompletion( methodGroup, invocationResult.Item2, invoke.Node, invoke.Unit, 0, controlSpace ); } if (controlSpace) { return DefaultControlSpaceItems(invoke); } return null; case '=': return controlSpace ? DefaultControlSpaceItems() : null; case ',': int cpos2; if (!GetParameterCompletionCommandOffset(out cpos2)) { return null; } // completionContext = CompletionWidget.CreateCodeCompletionContext (cpos2); // int currentParameter2 = MethodParameterDataProvider.GetCurrentParameterIndex (CompletionWidget, completionContext) - 1; // return CreateParameterCompletion (CreateResolver (), location, ExpressionContext.MethodBody, provider.Methods, currentParameter); break; // Completion on space: case ' ': int tokenIndex = offset; string token = GetPreviousToken(ref tokenIndex, false); if (IsInsideCommentStringOrDirective()) { if (IsInPreprocessorDirective()) return HandleKeywordCompletion(tokenIndex, token); return null; } // check propose name, for context <variable name> <ctrl+space> (but only in control space context) //IType isAsType = null; var isAsExpression = GetExpressionAt(offset); if (controlSpace && isAsExpression != null && isAsExpression.Node is VariableDeclarationStatement && token != "new") { var parent = isAsExpression.Node as VariableDeclarationStatement; var proposeNameList = new CompletionDataWrapper(this); if (parent.Variables.Count != 1) return DefaultControlSpaceItems(isAsExpression, controlSpace); foreach (var possibleName in GenerateNameProposals (parent.Type)) { if (possibleName.Length > 0) { proposeNameList.Result.Add(factory.CreateLiteralCompletionData(possibleName.ToString())); } } AutoSelect = false; AutoCompleteEmptyMatch = false; return proposeNameList.Result; } // int tokenIndex = offset; // string token = GetPreviousToken (ref tokenIndex, false); // if (result.ExpressionContext == ExpressionContext.ObjectInitializer) { // resolver = CreateResolver (); // ExpressionContext exactContext = new NewCSharpExpressionFinder (dom).FindExactContextForObjectInitializer (document, resolver.Unit, Document.FileName, resolver.CallingType); // IReturnType objectInitializer = ((ExpressionContext.TypeExpressionContext)exactContext).UnresolvedType; // if (objectInitializer != null && objectInitializer.ArrayDimensions == 0 && objectInitializer.PointerNestingLevel == 0 && (token == "{" || token == ",")) // return CreateCtrlSpaceCompletionData (completionContext, result); // } if (token == "=") { int j = tokenIndex; string prevToken = GetPreviousToken(ref j, false); if (prevToken == "=" || prevToken == "+" || prevToken == "-") { token = prevToken + token; tokenIndex = j; } } switch (token) { case "(": case ",": int cpos; if (!GetParameterCompletionCommandOffset(out cpos)) { break; } int currentParameter = GetCurrentParameterIndex(cpos - 1, this.offset) - 1; if (currentParameter < 0) { return null; } invoke = GetInvocationBeforeCursor(token == "("); if (invoke == null) { return null; } invocationResult = ResolveExpression(invoke); if (invocationResult == null) { return null; } methodGroup = invocationResult.Item1 as MethodGroupResolveResult; if (methodGroup != null) { return CreateParameterCompletion( methodGroup, invocationResult.Item2, invoke.Node, invoke.Unit, currentParameter, controlSpace); } return null; case "=": case "==": GetPreviousToken(ref tokenIndex, false); var expressionOrVariableDeclaration = GetExpressionAt(tokenIndex); if (expressionOrVariableDeclaration == null) { return null; } resolveResult = ResolveExpression(expressionOrVariableDeclaration); if (resolveResult == null) { return null; } if (resolveResult.Item1.Type.Kind == TypeKind.Enum) { var wrapper = new CompletionDataWrapper(this); AddContextCompletion( wrapper, resolveResult.Item2, expressionOrVariableDeclaration.Node, expressionOrVariableDeclaration.Unit); AddEnumMembers(wrapper, resolveResult.Item1.Type, resolveResult.Item2); AutoCompleteEmptyMatch = false; return wrapper.Result; } // // if (resolvedType.FullName == DomReturnType.Bool.FullName) { // CompletionDataList completionList = new ProjectDomCompletionDataList (); // CompletionDataCollector cdc = new CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, resolver.CallingType, location); // completionList.AutoCompleteEmptyMatch = false; // cdc.Add ("true", "md-keyword"); // cdc.Add ("false", "md-keyword"); // resolver.AddAccessibleCodeCompletionData (result.ExpressionContext, cdc); // return completionList; // } // if (resolvedType.ClassType == ClassType.Delegate && token == "=") { // CompletionDataList completionList = new ProjectDomCompletionDataList (); // string parameterDefinition = AddDelegateHandlers (completionList, resolvedType); // string varName = GetPreviousMemberReferenceExpression (tokenIndex); // completionList.Add (new EventCreationCompletionData (document, varName, resolvedType, null, parameterDefinition, resolver.CallingMember, resolvedType)); // // CompletionDataCollector cdc = new CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, resolver.CallingType, location); // resolver.AddAccessibleCodeCompletionData (result.ExpressionContext, cdc); // foreach (var data in completionList) { // if (data is MemberCompletionData) // ((MemberCompletionData)data).IsDelegateExpected = true; // } // return completionList; // } return null; case "+=": case "-=": GetPreviousToken(ref tokenIndex, false); expressionOrVariableDeclaration = GetExpressionAt(tokenIndex); if (expressionOrVariableDeclaration == null) { return null; } resolveResult = ResolveExpression(expressionOrVariableDeclaration); if (resolveResult == null) { return null; } var mrr = resolveResult.Item1 as MemberResolveResult; if (mrr != null) { var evt = mrr.Member as IEvent; if (evt == null) { return null; } var delegateType = evt.ReturnType; if (delegateType.Kind != TypeKind.Delegate) { return null; } var wrapper = new CompletionDataWrapper(this); if (currentType != null) { // bool includeProtected = DomType.IncludeProtected (dom, typeFromDatabase, resolver.CallingType); foreach (var method in currentType.Methods) { if (MatchDelegate(delegateType, method) /*&& method.IsAccessibleFrom (dom, resolver.CallingType, resolver.CallingMember, includeProtected) &&*/) { wrapper.AddMember(method); // data.SetText (data.CompletionText + ";"); } } } if (token == "+=") { string parameterDefinition = AddDelegateHandlers( wrapper, delegateType ); string varName = GetPreviousMemberReferenceExpression(tokenIndex); wrapper.Result.Add( factory.CreateEventCreationCompletionData( varName, delegateType, evt, parameterDefinition, currentMember, currentType) ); } return wrapper.Result; } return null; case ":": if (currentMember == null) { token = GetPreviousToken(ref tokenIndex, false); token = GetPreviousToken(ref tokenIndex, false); if (token == "enum") return HandleEnumContext(); var wrapper = new CompletionDataWrapper(this); AddTypesAndNamespaces( wrapper, GetState(), null, t => currentType != null && !currentType.ReflectionName.Equals(t.ReflectionName) ? t : null ); return wrapper.Result; } return null; } var keywordCompletion = HandleKeywordCompletion(tokenIndex, token); if (keywordCompletion == null && controlSpace) { goto default; } return keywordCompletion; // Automatic completion default: if (IsInsideCommentStringOrDirective()) { return null; } if (IsInLinqContext(offset)) { if (!controlSpace && !(char.IsLetter(completionChar) || completionChar == '_')) { return null; } tokenIndex = offset; token = GetPreviousToken(ref tokenIndex, false); // token last typed if (!char.IsWhiteSpace(completionChar) && !linqKeywords.Contains(token)) { token = GetPreviousToken(ref tokenIndex, false); } // token last typed if (linqKeywords.Contains(token)) { if (token == "from") { // after from no auto code completion. return null; } return DefaultControlSpaceItems(); } var dataList = new CompletionDataWrapper(this); AddKeywords(dataList, linqKeywords); return dataList.Result; } if (currentType != null && currentType.Kind == TypeKind.Enum) { return HandleEnumContext(); } var contextList = new CompletionDataWrapper(this); var identifierStart = GetExpressionAtCursor(); if (identifierStart != null) { if (identifierStart.Node is TypeParameterDeclaration) { return null; } if (identifierStart.Node is MemberReferenceExpression) { return HandleMemberReferenceCompletion( new ExpressionResult( ((MemberReferenceExpression)identifierStart.Node).Target, identifierStart.Unit ) ); } if (identifierStart.Node is Identifier) { // May happen in variable names return controlSpace ? DefaultControlSpaceItems(identifierStart) : null; } if (identifierStart.Node is VariableInitializer && location <= ((VariableInitializer)identifierStart.Node).NameToken.EndLocation) { return controlSpace ? HandleAccessorContext() ?? DefaultControlSpaceItems(identifierStart) : null; } if (identifierStart.Node is CatchClause) { if (((CatchClause)identifierStart.Node).VariableNameToken.Contains(location)) { return null; } return HandleCatchClauseType(identifierStart); } } if (!(char.IsLetter(completionChar) || completionChar == '_') && (!controlSpace || identifierStart == null || !(identifierStart.Node.Parent is ArrayInitializerExpression))) { return controlSpace ? HandleAccessorContext() ?? DefaultControlSpaceItems(identifierStart) : null; } char prevCh = offset > 2 ? document.GetCharAt(offset - 2) : ';'; char nextCh = offset < document.TextLength ? document.GetCharAt(offset) : ' '; const string allowedChars = ";,.[](){}+-*/%^?:&|~!<>="; if (!Char.IsWhiteSpace(nextCh) && allowedChars.IndexOf(nextCh) < 0) { return null; } if (!(Char.IsWhiteSpace(prevCh) || allowedChars.IndexOf(prevCh) >= 0)) { return null; } // Do not pop up completion on identifier identifier (should be handled by keyword completion). tokenIndex = offset - 1; token = GetPreviousToken(ref tokenIndex, false); if (token == "class" || token == "interface" || token == "struct" || token == "enum" || token == "namespace") { // after these always follows a name return null; } var keywordresult = HandleKeywordCompletion(tokenIndex, token); if (keywordresult != null) { return keywordresult; } int prevTokenIndex = tokenIndex; var prevToken2 = GetPreviousToken(ref prevTokenIndex, false); if (prevToken2 == "delegate") { // after these always follows a name return null; } if (identifierStart == null && !string.IsNullOrEmpty(token) && !IsInsideCommentStringOrDirective() && (prevToken2 == ";" || prevToken2 == "{" || prevToken2 == "}")) { char last = token [token.Length - 1]; if (char.IsLetterOrDigit(last) || last == '_' || token == ">") { return HandleKeywordCompletion(tokenIndex, token); } } if (identifierStart == null) { var accCtx = HandleAccessorContext(); if (accCtx != null) { return accCtx; } return DefaultControlSpaceItems(null, controlSpace); } CSharpResolver csResolver; AstNode n = identifierStart.Node; if (n != null && n.Parent is AnonymousTypeCreateExpression) { AutoSelect = false; } // Handle foreach (type name _ if (n is IdentifierExpression) { var prev = n.GetPrevNode() as ForeachStatement; if (prev != null && prev.InExpression.IsNull) { if (controlSpace) { contextList.AddCustom("in"); return contextList.Result; } return null; } // var astResolver = new CSharpAstResolver( // GetState(), // identifierStart.Unit, // CSharpParsedFile // ); // // foreach (var type in CreateFieldAction.GetValidTypes(astResolver, (Expression)n)) { // if (type.Kind == TypeKind.Delegate) { // AddDelegateHandlers(contextList, type, false, false); // AutoSelect = false; // AutoCompleteEmptyMatch = false; // } // } } // Handle object/enumerable initialzer expressions: "new O () { P$" if (n is IdentifierExpression && n.Parent is ArrayInitializerExpression) { var result = HandleObjectInitializer(identifierStart.Unit, n); if (result != null) return result; } if (n != null && n.Parent is InvocationExpression) { var invokeParent = (InvocationExpression)n.Parent; var invokeResult = ResolveExpression( invokeParent.Target, identifierStart.Unit ); var mgr = invokeResult != null ? invokeResult.Item1 as MethodGroupResolveResult : null; if (mgr != null) { int idx = 0; foreach (var arg in invokeParent.Arguments) { if (arg == n) { break; } idx++; } foreach (var method in mgr.Methods) { if (idx < method.Parameters.Count && method.Parameters [idx].Type.Kind == TypeKind.Delegate) { AutoSelect = false; AutoCompleteEmptyMatch = false; } foreach (var p in method.Parameters) { contextList.AddNamedParameterVariable(p); } } idx++; foreach (var list in mgr.GetExtensionMethods ()) { foreach (var method in list) { if (idx < method.Parameters.Count && method.Parameters [idx].Type.Kind == TypeKind.Delegate) { AutoSelect = false; AutoCompleteEmptyMatch = false; } } } } } if (n != null && n.Parent is ObjectCreateExpression) { var invokeResult = ResolveExpression(n.Parent, identifierStart.Unit); var mgr = invokeResult != null ? invokeResult.Item1 as ResolveResult : null; if (mgr != null) { foreach (var constructor in mgr.Type.GetConstructors ()) { foreach (var p in constructor.Parameters) { contextList.AddVariable(p); } } } } if (n is IdentifierExpression) { var bop = n.Parent as BinaryOperatorExpression; Expression evaluationExpr = null; if (bop != null && bop.Right == n && (bop.Operator == BinaryOperatorType.Equality || bop.Operator == BinaryOperatorType.InEquality)) { evaluationExpr = bop.Left; } // check for compare to enum case if (evaluationExpr != null) { resolveResult = ResolveExpression(evaluationExpr, identifierStart.Unit); if (resolveResult != null && resolveResult.Item1.Type.Kind == TypeKind.Enum) { var wrapper = new CompletionDataWrapper(this); AddContextCompletion( wrapper, resolveResult.Item2, evaluationExpr, identifierStart.Unit ); AddEnumMembers(wrapper, resolveResult.Item1.Type, resolveResult.Item2); AutoCompleteEmptyMatch = false; return wrapper.Result; } } } if (n is Identifier && n.Parent is ForeachStatement) { if (controlSpace) { return DefaultControlSpaceItems(); } return null; } if (n is ArrayInitializerExpression) { // check for new [] {...} expression -> no need to resolve the type there var parent = n.Parent as ArrayCreateExpression; if (parent != null && parent.Type.IsNull) { return DefaultControlSpaceItems(); } var initalizerResult = ResolveExpression(n.Parent, identifierStart.Unit); var concreteNode = identifierStart.Unit.GetNodeAt<IdentifierExpression>(location); // check if we're on the right side of an initializer expression if (concreteNode != null && concreteNode.Parent != null && concreteNode.Parent.Parent != null && concreteNode.Identifier != "a" && concreteNode.Parent.Parent is NamedExpression) { return DefaultControlSpaceItems(); } if (initalizerResult != null && initalizerResult.Item1.Type.Kind != TypeKind.Unknown) { foreach (var property in initalizerResult.Item1.Type.GetProperties ()) { if (!property.IsPublic) { continue; } contextList.AddMember(property); } foreach (var field in initalizerResult.Item1.Type.GetFields ()) { if (!field.IsPublic) { continue; } contextList.AddMember(field); } return contextList.Result; } return DefaultControlSpaceItems(); } if (IsAttributeContext(n)) { // add attribute targets if (currentType == null) { contextList.AddCustom("assembly"); contextList.AddCustom("module"); contextList.AddCustom("type"); } else { contextList.AddCustom("param"); contextList.AddCustom("field"); contextList.AddCustom("property"); contextList.AddCustom("method"); contextList.AddCustom("event"); } contextList.AddCustom("return"); } if (n is MemberType) { resolveResult = ResolveExpression( ((MemberType)n).Target, identifierStart.Unit ); return CreateTypeAndNamespaceCompletionData( location, resolveResult.Item1, ((MemberType)n).Target, resolveResult.Item2 ); } if (n != null/* && !(identifierStart.Item2 is TypeDeclaration)*/) { csResolver = new CSharpResolver(ctx); var nodes = new List<AstNode>(); nodes.Add(n); if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute) { nodes.Add(n.Parent); } var astResolver = new CSharpAstResolver( csResolver, identifierStart.Unit, CSharpParsedFile ); astResolver.ApplyNavigator(new NodeListResolveVisitorNavigator(nodes)); try { csResolver = astResolver.GetResolverStateBefore(n); } catch (Exception) { csResolver = GetState(); } // add attribute properties. if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute) { var resolved = astResolver.Resolve(n.Parent); if (resolved != null && resolved.Type != null) { foreach (var property in resolved.Type.GetProperties (p => p.Accessibility == Accessibility.Public)) { contextList.AddMember(property); } foreach (var field in resolved.Type.GetFields (p => p.Accessibility == Accessibility.Public)) { contextList.AddMember(field); } } } } else { csResolver = GetState(); } // identifier has already started with the first letter offset--; AddContextCompletion( contextList, csResolver, identifierStart.Node, identifierStart.Unit ); return contextList.Result; // if (stub.Parent is BlockStatement) // result = FindExpression (dom, completionContext, -1); // if (result == null) // return null; // else if (result.ExpressionContext != ExpressionContext.IdentifierExpected) { // triggerWordLength = 1; // bool autoSelect = true; // IType returnType = null; // if ((prevCh == ',' || prevCh == '(') && GetParameterCompletionCommandOffset (out cpos)) { // ctx = CompletionWidget.CreateCodeCompletionContext (cpos); // NRefactoryParameterDataProvider dataProvider = ParameterCompletionCommand (ctx) as NRefactoryParameterDataProvider; // if (dataProvider != null) { // int i = dataProvider.GetCurrentParameterIndex (CompletionWidget, ctx) - 1; // foreach (var method in dataProvider.Methods) { // if (i < method.Parameters.Count) { // returnType = dom.GetType (method.Parameters [i].ReturnType); // autoSelect = returnType == null || returnType.ClassType != ClassType.Delegate; // break; // } // } // } // } // // Bug 677531 - Auto-complete doesn't always highlight generic parameter in method signature // //if (result.ExpressionContext == ExpressionContext.TypeName) // // autoSelect = false; // CompletionDataList dataList = CreateCtrlSpaceCompletionData (completionContext, result); // AddEnumMembers (dataList, returnType); // dataList.AutoSelect = autoSelect; // return dataList; // } else { // result = FindExpression (dom, completionContext, 0); // tokenIndex = offset; // // // check foreach case, unfortunately the expression finder is too dumb to handle full type names // // should be overworked if the expression finder is replaced with a mcs ast based analyzer. // var possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // starting letter // possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // varname // // // read return types to '(' token // possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // varType // if (possibleForeachToken == ">") { // while (possibleForeachToken != null && possibleForeachToken != "(") { // possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // } // } else { // possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // ( // if (possibleForeachToken == ".") // while (possibleForeachToken != null && possibleForeachToken != "(") // possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // } // possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // foreach // // if (possibleForeachToken == "foreach") { // result.ExpressionContext = ExpressionContext.ForeachInToken; // } else { // return null; // // result.ExpressionContext = ExpressionContext.IdentifierExpected; // } // result.Expression = ""; // result.Region = DomRegion.Empty; // // return CreateCtrlSpaceCompletionData (completionContext, result); // } // break; } return null; }
void AnalyzeFile (ProjectFile file, IProjectContent content) { var me = new object (); var owner = processedFiles.AddOrUpdate (file.Name, me, (key, old) => old); if (me != owner) return; if (file.BuildAction != BuildAction.Compile || tokenSource.IsCancellationRequested) return; TextEditorData editor; try { editor = TextFileProvider.Instance.GetReadOnlyTextEditorData (file.FilePath); } catch (FileNotFoundException) { // Swallow exception and ignore this file return; } var document = TypeSystemService.ParseFile (file.Project, editor); if (document == null) return; var compilation = content.AddOrUpdateFiles (document.ParsedFile).CreateCompilation (); CSharpAstResolver resolver; using (var timer = ExtensionMethods.ResolveCounter.BeginTiming ()) { resolver = new CSharpAstResolver (compilation, document.GetAst<SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile); resolver.ApplyNavigator (new ExtensionMethods.ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null)); } var context = document.CreateRefactoringContextWithEditor (editor, resolver, tokenSource.Token); var codeIssueProviders = RefactoringService.GetInspectors (editor.MimeType) .SelectMany (p => p.GetEffectiveProviderSet ()) .ToList (); foreach (var provider in codeIssueProviders) { var severity = provider.GetSeverity (); if (severity == Severity.None || !provider.GetIsEnabled () || tokenSource.IsCancellationRequested) continue; try { foreach (var issue in provider.GetIssues (context, tokenSource.Token)) { AddIssue (file, provider, issue); } } catch (OperationCanceledException) { // The operation was cancelled, no-op as the user-visible parts are // handled elsewhere } } }