// 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 IParameterDataProvider HandleParameterCompletion(CodeCompletionContext completionContext, char completionChar) { if (!EnableCodeCompletion) { return(null); } if (Unit == null || CSharpParsedFile == null) { return(null); } try { var engine = new CSharpParameterCompletionEngine( textEditorData.Document, this, Document.GetProjectContext(), CSharpParsedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext, Unit, CSharpParsedFile ); engine.MemberProvider = typeSystemSegmentTree; return(engine.GetParameterDataProvider(completionContext.TriggerOffset, completionChar)); } 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 (); } }
public static ResolveResult Resolve(ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, CancellationToken cancellationToken = default(CancellationToken)) { AstNode node; return(Resolve(compilation, parsedFile, cu, location, out node, cancellationToken)); }
void Init(string code) { compilationUnit = new CSharpParser().Parse(new StringReader(code), "test.cs"); parsedFile = compilationUnit.ToTypeSystem(); compilation = TypeSystemHelper.CreateCompilation(parsedFile); findReferences = new FindReferences(); }
public TestRefactoringContext(string content) { int idx = content.IndexOf("$"); if (idx >= 0) { content = content.Substring(0, idx) + content.Substring(idx + 1); } doc = new ReadOnlyDocument(content); var parser = new CSharpParser(); Unit = parser.Parse(content, "program.cs"); if (parser.HasErrors) { parser.ErrorPrinter.Errors.ForEach(e => Console.WriteLine(e.Message)); } Assert.IsFalse(parser.HasErrors, "File contains parsing errors."); parsedFile = Unit.ToTypeSystem(); IProjectContent pc = new CSharpProjectContent(); pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); compilation = pc.CreateCompilation(); resolver = new CSharpAstResolver(compilation, Unit, parsedFile); if (idx >= 0) { Location = doc.GetLocation(idx); } }
public AstType CreateShortType(ICompilation compilation, CSharpParsedFile parsedFile, TextLocation loc, IType fullType) { var csResolver = parsedFile.GetResolver(compilation, loc); var builder = new ICSharpCode.NRefactory.CSharp.Refactoring.TypeSystemAstBuilder(csResolver); return(builder.ConvertType(fullType)); }
protected ResolveResult Resolve(string code) { CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", "")), "code.cs"); TextLocation[] dollars = FindDollarSigns(code).ToArray(); Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node"); SetUp(); CSharpParsedFile parsedFile = cu.ToTypeSystem(); project = project.UpdateProjectContent(null, parsedFile); compilation = project.CreateCompilation(); FindNodeVisitor fnv = new FindNodeVisitor(dollars[0], dollars[1]); cu.AcceptVisitor(fnv, null); Assert.IsNotNull(fnv.ResultNode, "Did not find DOM node at the specified location"); Debug.WriteLine(new string('=', 70)); Debug.WriteLine("Starting new resolver for " + fnv.ResultNode); CSharpAstResolver resolver = new CSharpAstResolver(compilation, cu, parsedFile); ResolveResult rr = resolver.Resolve(fnv.ResultNode); Assert.IsNotNull(rr, "ResolveResult is null - did something go wrong while navigating to the target node?"); Debug.WriteLine("ResolveResult is " + rr); return(rr); }
protected void SetOffset(int offset) { Reset(); this.offset = offset; this.location = document.GetLocation(offset); this.currentType = CSharpParsedFile.GetInnermostTypeDefinition(location); this.currentMember = null; if (this.currentType != null) { foreach (var member in currentType.Members) { if (member.Region.Begin < location && (currentMember == null || currentMember.Region.Begin < member.Region.Begin)) { currentMember = member; } } } var stack = GetBracketStack(GetMemberTextToCaret().Item1); if (stack.Count == 0) { currentMember = null; } }
protected Tuple <ResolveResult, CSharpResolver> ResolveExpression(CSharpParsedFile file, AstNode expr, CompilationUnit unit) { if (expr == null) { return(null); } AstNode resolveNode; if (expr is Expression || expr is AstType) { resolveNode = expr; } else if (expr is VariableDeclarationStatement) { resolveNode = ((VariableDeclarationStatement)expr).Type; } else { resolveNode = expr; } // var newContent = ProjectContent.UpdateProjectContent (CSharpParsedFile, file); var csResolver = new CSharpResolver(ctx); var navigator = new NodeListResolveVisitorNavigator(new[] { resolveNode }); var visitor = new ResolveVisitor(csResolver, CSharpParsedFile, navigator); visitor.Scan(unit); var state = visitor.GetResolverStateBefore(resolveNode); var result = visitor.GetResolveResult(resolveNode); return(Tuple.Create(result, state)); }
protected ResolveResult Resolve(string code) { CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", ""))); TextLocation[] dollars = FindDollarSigns(code).ToArray(); Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node"); SetUp(); CSharpParsedFile parsedFile = new CSharpParsedFile("test.cs", resolver.CurrentUsingScope); TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile, resolver.CurrentUsingScope, null); cu.AcceptVisitor(convertVisitor, null); project.UpdateProjectContent(null, convertVisitor.ParsedFile); FindNodeVisitor fnv = new FindNodeVisitor(dollars[0], dollars[1]); cu.AcceptVisitor(fnv, null); Assert.IsNotNull(fnv.ResultNode, "Did not find DOM node at the specified location"); Debug.WriteLine(new string('=', 70)); Debug.WriteLine("Starting new resolver for " + fnv.ResultNode); var navigator = new NodeListResolveVisitorNavigator(new[] { fnv.ResultNode }); ResolveResult rr; using (var context = this.context.Synchronize()) { ResolveVisitor rv = new ResolveVisitor(new CSharpResolver(context), convertVisitor.ParsedFile, navigator); rv.Scan(cu); rr = rv.GetResolveResult(fnv.ResultNode); } Assert.IsNotNull(rr, "ResolveResult is null - did something go wrong while navigating to the target node?"); Debug.WriteLine("ResolveResult is " + rr); return(rr); }
public static ICompilation CreateCompilation(params IUnresolvedTypeDefinition[] unresolvedTypeDefinitions) { var parsedFile = new CSharpParsedFile("dummy.cs"); foreach (var typeDef in unresolvedTypeDefinitions) parsedFile.TopLevelTypeDefinitions.Add(typeDef); return CreateCompilation(parsedFile); }
CSharpParsedFile Parse(string program) { CompilationUnit cu = new CSharpParser().Parse(new StringReader(program), "test.cs"); CSharpParsedFile parsedFile = cu.ToTypeSystem(); project = project.UpdateProjectContent(null, parsedFile); compilation = project.CreateCompilation(); return parsedFile; }
public DefaultCompletionContextProvider (IDocument document, CSharpParsedFile parsedFile) { if (document == null) throw new ArgumentNullException("document"); if (parsedFile == null) throw new ArgumentNullException("parsedFile"); this.document = document; this.parsedFile = parsedFile; }
/// <summary> /// Finds all references in the given file. /// </summary> /// <param name="searchScope">The search scope 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="context">The type resolve context to use for resolving the file.</param> /// <param name="callback">Callback used to report the references that were found.</param> public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) { if (searchScope == null) { throw new ArgumentNullException("searchScope"); } FindReferencesInFile(new[] { searchScope }, parsedFile, compilationUnit, compilation, callback, cancellationToken); }
void HandleDocumentParsed(object sender, EventArgs e) { if (src != null) { src.Cancel(); } resolver = null; if (guiDocument != null && MonoDevelop.Core.PropertyService.Get("EnableSemanticHighlighting", true)) { var parsedDocument = guiDocument.ParsedDocument; if (parsedDocument != null) { unit = parsedDocument.GetAst <CompilationUnit> (); parsedFile = parsedDocument.ParsedFile as CSharpParsedFile; if (guiDocument.Project != null && guiDocument.IsCompileableInProject) { src = new CancellationTokenSource(); var cancellationToken = src.Token; System.Threading.Tasks.Task.Factory.StartNew(delegate { Thread.Sleep(100); compilation = guiDocument.Compilation; var newResolver = new CSharpAstResolver(compilation, unit, parsedFile); var visitor = new QuickTaskVisitor(newResolver, cancellationToken); unit.AcceptVisitor(visitor); if (!cancellationToken.IsCancellationRequested) { Gtk.Application.Invoke(delegate { if (cancellationToken.IsCancellationRequested) { return; } var editorData = guiDocument.Editor; if (editorData == null) { return; } resolver = newResolver; quickTasks = visitor.QuickTasks; OnTasksUpdated(EventArgs.Empty); var textEditor = editorData.Parent; if (textEditor != null) { var margin = textEditor.TextViewMargin; if (!parsedDocument.HasErrors) { highlightedSegmentCache.Clear(); margin.PurgeLayoutCache(); textEditor.QueueDraw(); } } }); } }, cancellationToken); } } } }
public CSharpParameterCompletionEngine (IDocument document, IParameterCompletionDataFactory factory, IProjectContent content, CSharpTypeResolveContext ctx, CompilationUnit unit, CSharpParsedFile parsedFile) : base (content, ctx, unit, parsedFile) { if (document == null) throw new ArgumentNullException ("document"); if (factory == null) throw new ArgumentNullException ("factory"); this.document = document; this.factory = factory; }
/// <summary> /// Finds all references in the given file. /// </summary> /// <param name="searchScope">The search scope 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="context">The type resolve context to use for resolving the file.</param> /// <param name="callback">Callback used to report the references that were found.</param> public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ITypeResolveContext context, FoundReferenceCallback callback) { if (searchScope == null) { throw new ArgumentNullException("searchScope"); } FindReferencesInFile(new[] { searchScope }, parsedFile, compilationUnit, context, callback); }
public static ResolveResult Resolve(ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, CancellationToken cancellationToken = default(CancellationToken)) { AstNode node = cu.GetNodeAt(location); if (node == null) return null; AstNode resolvableNode; if (node is AstType) { resolvableNode = node; if (resolvableNode.Parent is ComposedType) { while (resolvableNode.Parent is ComposedType) resolvableNode = resolvableNode.Parent; //node is preffered over the resolvable node. Which shouldn't be done in the case of nullables, arrays etc. node = resolvableNode; } } else if (node is Identifier) { resolvableNode = node.Parent; } else if (node.NodeType == NodeType.Token) { if (node.Parent is ConstructorInitializer) { resolvableNode = node.Parent; } else { return null; } } else { // don't resolve arbitrary nodes - we don't want to show tooltips for everything return null; } if (resolvableNode != null && resolvableNode.Parent is ObjectCreateExpression) { resolvableNode = resolvableNode.Parent; } InvocationExpression parentInvocation = null; if ((resolvableNode is IdentifierExpression || resolvableNode is MemberReferenceExpression || resolvableNode is PointerReferenceExpression)) { // we also need to resolve the invocation parentInvocation = resolvableNode.Parent as InvocationExpression; } IResolveVisitorNavigator navigator; if (parentInvocation != null) navigator = new NodeListResolveVisitorNavigator(new[] { resolvableNode, parentInvocation }); else navigator = new NodeListResolveVisitorNavigator(new[] { resolvableNode }); CSharpResolver resolver = new CSharpResolver(compilation); ResolveVisitor v = new ResolveVisitor(resolver, parsedFile, navigator); v.Scan(cu); // Prefer the RR from the token itself, if it was assigned a ResolveResult // (this can happen with the identifiers in various nodes such as catch clauses or foreach statements) ResolveResult rr = v.GetResolveResult(node) ?? v.GetResolveResult(resolvableNode); if (rr is MethodGroupResolveResult && parentInvocation != null) return v.GetResolveResult(parentInvocation); else return rr; }
public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, out AstNode node, CancellationToken cancellationToken = default(CancellationToken)) { node = cu.GetNodeAt(location); if (node == null || node is ArrayInitializerExpression) 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) { Console.WriteLine (2); // 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, cu, parsedFile); ResolveResult rr = resolver.Resolve(node, cancellationToken); if (rr is MethodGroupResolveResult && parentInvocation != null) return resolver.Resolve(parentInvocation); else return rr; }
public static ICompilation CreateCompilation(params IUnresolvedTypeDefinition[] unresolvedTypeDefinitions) { var parsedFile = new CSharpParsedFile("dummy.cs"); foreach (var typeDef in unresolvedTypeDefinitions) { parsedFile.TopLevelTypeDefinitions.Add(typeDef); } return(CreateCompilation(parsedFile)); }
/// <summary> /// Creates a new C# AST resolver. /// </summary> /// <param name="resolver">The resolver state at the root node.</param> /// <param name="rootNode">The root node of the resolved tree.</param> /// <param name="parsedFile">The parsed file for the nodes being resolved. This parameter is used only /// when the root node is on the type level; it is not necessary when an expression is passed. /// This parameter may be null.</param> public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpParsedFile parsedFile = null) { if (resolver == null) throw new ArgumentNullException("resolver"); if (rootNode == null) throw new ArgumentNullException("rootNode"); this.initialResolverState = resolver; this.rootNode = rootNode; this.parsedFile = parsedFile; }
ICompletionData ICompletionDataFactory.CreateEntityCompletionData(IUnresolvedEntity entity, string text) { var context = CSharpParsedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location); var resolvedEntity = ((IUnresolvedMember)entity).CreateResolved(context); return(new MemberCompletionData(this, resolvedEntity, OutputFlags.IncludeGenerics | OutputFlags.HideArrayBrackets | OutputFlags.IncludeParameterName) { HideExtensionParameter = true }); }
/// <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="compilationUnit">The compilation unit corresponding to the specified parsed file.</param> /// <param name="parsedFile"> /// Optional: Result of the <see cref="TypeSystemConvertVisitor"/> for the file being resolved. /// <para> /// This is used for setting up the context on the resolver. The parsed file must be registered in the compilation. /// </para> /// <para> /// When a parsedFile 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 parsedFile 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, CompilationUnit compilationUnit, CSharpParsedFile parsedFile = null) { if (compilation == null) throw new ArgumentNullException("compilation"); if (compilationUnit == null) throw new ArgumentNullException("compilationUnit"); this.initialResolverState = new CSharpResolver(compilation); this.rootNode = compilationUnit; this.parsedFile = parsedFile; this.resolveVisitor = new ResolveVisitor(initialResolverState, parsedFile); }
public override void SetUp() { base.SetUp(); parsedFile = new CSharpParsedFile("test.cs", new UsingScope()); parsedFile.RootUsingScope.Usings.Add(MakeReference("System")); parsedFile.RootUsingScope.Usings.Add(MakeReference("System.Collections.Generic")); parsedFile.RootUsingScope.Usings.Add(MakeReference("System.Linq")); convertVisitor = new CodeDomConvertVisitor(); convertVisitor.UseFullyQualifiedTypeNames = true; }
/// <summary> /// Finds all references of a given variable. /// </summary> /// <param name="variable">The variable 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.</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, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, 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, parsedFile, compilationUnit, compilation, callback, cancellationToken); }
public DefaultCompletionContextProvider(IDocument document, CSharpParsedFile parsedFile) { if (document == null) { throw new ArgumentNullException("document"); } if (parsedFile == null) { throw new ArgumentNullException("parsedFile"); } this.document = document; this.parsedFile = parsedFile; }
public CSharpCompletionEngine (IDocument document, ICompletionDataFactory factory, IProjectContent content, CSharpTypeResolveContext ctx, CompilationUnit unit, CSharpParsedFile parsedFile) : base (content, ctx, unit, parsedFile) { if (document == null) throw new ArgumentNullException ("document"); if (factory == null) throw new ArgumentNullException ("factory"); this.document = document; this.factory = factory; // Set defaults for additional input properties this.FormattingPolicy = new CSharpFormattingOptions(); this.EolMarker = Environment.NewLine; this.IndentString = "\t"; }
public void SetUp() { pc = new SimpleProjectContent(); var cu = new CSharpParser().Parse(new StringReader(program)); parsedFile = new TypeSystemConvertVisitor(pc, "program.cs").Convert(cu); pc.UpdateProjectContent(null, parsedFile); ctx = new CompositeTypeResolveContext(new[] { pc, CecilLoaderTests.Mscorlib }); baseClass = pc.GetTypeDefinition(string.Empty, "Base", 1, StringComparer.Ordinal); nestedClass = baseClass.NestedTypes.Single(); derivedClass = pc.GetTypeDefinition(string.Empty, "Derived", 2, StringComparer.Ordinal); systemClass = pc.GetTypeDefinition("NS", "System", 0, StringComparer.Ordinal); }
/// <summary> /// Creates a new C# AST resolver. /// </summary> /// <param name="resolver">The resolver state at the root node.</param> /// <param name="rootNode">The root node of the resolved tree.</param> /// <param name="parsedFile">The parsed file for the nodes being resolved. This parameter is used only /// when the root node is on the type level; it is not necessary when an expression is passed. /// This parameter may be null.</param> public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpParsedFile parsedFile = null) { if (resolver == null) { throw new ArgumentNullException("resolver"); } if (rootNode == null) { throw new ArgumentNullException("rootNode"); } this.initialResolverState = resolver; this.rootNode = rootNode; this.parsedFile = parsedFile; }
public override int GetCurrentParameterIndex(int startOffset) { var engine = new CSharpParameterCompletionEngine( textEditorData.Document, this, Document.GetProjectContext(), CSharpParsedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext, Unit, CSharpParsedFile ); engine.MemberProvider = typeSystemSegmentTree; return(engine.GetCurrentParameterIndex(startOffset, document.Editor.Caret.Offset)); }
/// <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="compilationUnit">The compilation unit corresponding to the specified parsed file.</param> /// <param name="parsedFile"> /// Optional: Result of the <see cref="TypeSystemConvertVisitor"/> for the file being resolved. /// <para> /// This is used for setting up the context on the resolver. The parsed file must be registered in the compilation. /// </para> /// <para> /// When a parsedFile 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 parsedFile 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, CompilationUnit compilationUnit, CSharpParsedFile parsedFile = null) { if (compilation == null) { throw new ArgumentNullException("compilation"); } if (compilationUnit == null) { throw new ArgumentNullException("compilationUnit"); } this.initialResolverState = new CSharpResolver(compilation); this.rootNode = compilationUnit; this.parsedFile = parsedFile; this.resolveVisitor = new ResolveVisitor(initialResolverState, parsedFile); }
public void SetUp() { pc = new CSharpProjectContent(); pc = pc.SetAssemblyName("MyAssembly"); parsedFile = new CSharpParser().Parse(new StringReader(program), "program.cs").ToTypeSystem(); pc = pc.UpdateProjectContent(null, parsedFile); 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); }
public override bool GetParameterCompletionCommandOffset(out int cpos) { var engine = new CSharpParameterCompletionEngine( textEditorData.Document, this, Document.GetProjectContext(), CSharpParsedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext, Unit, CSharpParsedFile ); engine.MemberProvider = typeSystemSegmentTree; engine.SetOffset(document.Editor.Caret.Offset); return(engine.GetParameterCompletionCommandOffset(out cpos)); }
protected CSharpCompletionEngineBase (IProjectContent content, CSharpTypeResolveContext ctx, CompilationUnit unit, CSharpParsedFile parsedFile) { if (content == null) throw new ArgumentNullException ("content"); if (ctx == null) throw new ArgumentNullException ("ctx"); if (unit == null) throw new ArgumentNullException ("unit"); if (parsedFile == null) throw new ArgumentNullException ("parsedFile"); this.ProjectContent = content; this.ctx = ctx; this.Unit = unit; this.CSharpParsedFile = parsedFile; }
protected ResolveResult ResolveAtLocation(string code) { CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", "")), "test.cs"); TextLocation[] dollars = FindDollarSigns(code).ToArray(); Assert.AreEqual(1, dollars.Length, "Expected 1 dollar signs marking the location"); SetUp(); CSharpParsedFile parsedFile = cu.ToTypeSystem(); project = project.UpdateProjectContent(null, parsedFile); compilation = project.CreateCompilation(); ResolveResult rr = Resolver.ResolveAtLocation.Resolve(compilation, parsedFile, cu, dollars[0]); return(rr); }
protected Tuple <CSharpAstResolver, AstNode> PrepareResolver(string code) { CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", "")), "code.cs"); TextLocation[] dollars = FindDollarSigns(code).ToArray(); Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node"); SetUp(); CSharpParsedFile parsedFile = cu.ToTypeSystem(); project = project.UpdateProjectContent(null, parsedFile); compilation = project.CreateCompilation(); CSharpAstResolver resolver = new CSharpAstResolver(compilation, cu, parsedFile); return(Tuple.Create(resolver, FindNode(cu, dollars[0], dollars[1]))); }
protected ResolveResult ResolveAtLocation(string code) { CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", ""))); TextLocation[] dollars = FindDollarSigns(code).ToArray(); Assert.AreEqual(1, dollars.Length, "Expected 1 dollar signs marking the location"); SetUp(); CSharpParsedFile parsedFile = new CSharpParsedFile("test.cs", resolver.CurrentUsingScope); TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile, resolver.CurrentUsingScope, null); cu.AcceptVisitor(convertVisitor, null); project.UpdateProjectContent(null, convertVisitor.ParsedFile); ResolveResult rr = Resolver.ResolveAtLocation.Resolve(this.context, parsedFile, cu, dollars[0]); return(rr); }
public CSharpFile(CSharpProject project, string fileName) { this.Project = project; this.FileName = fileName; this.Content = new StringTextSource(File.ReadAllText(FileName)); this.LinesOfCode = 1 + this.Content.Text.Count(c => c == '\n'); CSharpParser p = project.CreateParser(); this.CompilationUnit = p.Parse(Content.CreateReader(), fileName); if (p.HasErrors) { Console.WriteLine("Error parsing " + fileName + ":"); foreach (var error in p.ErrorPrinter.Errors) { Console.WriteLine(" " + error.Region + " " + error.Message); } } this.ParsedFile = this.CompilationUnit.ToTypeSystem(); }
public TestRefactoringContext(string content) { int idx = content.IndexOf ("$"); if (idx >= 0) content = content.Substring (0, idx) + content.Substring (idx + 1); doc = new ReadOnlyDocument (content); var parser = new CSharpParser (); Unit = parser.Parse (content, "program.cs"); if (parser.HasErrors) parser.ErrorPrinter.Errors.ForEach (e => Console.WriteLine (e.Message)); Assert.IsFalse (parser.HasErrors, "File contains parsing errors."); parsedFile = Unit.ToTypeSystem(); IProjectContent pc = new CSharpProjectContent(); pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); compilation = pc.CreateCompilation(); resolver = new CSharpAstResolver(compilation, Unit, parsedFile); if (idx >= 0) Location = doc.GetLocation (idx); }
List <string> GetUsedNamespaces() { var scope = CSharpParsedFile.GetUsingScope(document.Editor.Caret.Location); var result = new List <string> (); while (scope != null) { result.Add(scope.NamespaceName); var ctx = CSharpParsedFile.GetResolver(Document.Compilation, scope.Region.Begin); foreach (var u in scope.Usings) { var ns = u.ResolveNamespace(ctx); if (ns == null) { continue; } result.Add(ns.FullName); } scope = scope.Parent; } return(result); }
ICompletionDataList InternalHandleCodeCompletion(CodeCompletionContext completionContext, char completionChar, bool ctrlSpace, ref int triggerWordLength) { /* * if (textEditorData.CurrentMode is CompletionTextLinkMode) { * if (!((CompletionTextLinkMode)textEditorData.CurrentMode).TriggerCodeCompletion) * return null; * } else if (textEditorData.CurrentMode is Mono.TextEditor.TextLinkEditMode) { * return null; * }*/ if (Unit == null || CSharpParsedFile == null) { return(null); } var list = new CompletionDataList(); var engine = new CSharpCompletionEngine( textEditorData.Document, this, Document.GetProjectContext(), CSharpParsedFile.GetTypeResolveContext(Document.Compilation, document.Editor.Caret.Location) as CSharpTypeResolveContext, Unit, CSharpParsedFile ); engine.MemberProvider = typeSystemSegmentTree; engine.FormattingPolicy = FormattingPolicy.CreateOptions(); engine.EolMarker = textEditorData.EolMarker; engine.IndentString = textEditorData.Options.IndentationString; list.AddRange(engine.GetCompletionData(completionContext.TriggerOffset, ctrlSpace)); list.AutoCompleteEmptyMatch = engine.AutoCompleteEmptyMatch; list.AutoSelect = engine.AutoSelect; list.DefaultCompletionString = engine.DefaultCompletionString; list.CloseOnSquareBrackets = engine.CloseOnSquareBrackets; if (ctrlSpace) { list.AutoCompleteUniqueMatch = true; } return(list.Count > 0 ? list : null); }
List <string> GetUsedNamespaces() { var scope = CSharpParsedFile.GetUsingScope(location); var result = new List <string> (); var resolver = new CppResolver(ctx); while (scope != null) { result.Add(scope.NamespaceName); foreach (var u in scope.Usings) { var ns = u.ResolveNamespace(resolver); if (ns == null) { continue; } result.Add(ns.FullName); } scope = scope.Parent; } return(result); }
/// <summary> /// Finds all references in the given file. /// </summary> /// <param name="searchScope">The search scope 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="context">The type resolve context to use for resolving the file.</param> /// <param name="callback">Callback used to report the references that were found.</param> public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ITypeResolveContext context, FoundReferenceCallback callback) { if (searchScope == null) throw new ArgumentNullException("searchScope"); FindReferencesInFile(new[] { searchScope }, parsedFile, compilationUnit, context, callback); }
/// <summary> /// Finds all references in the given file. /// </summary> /// <param name="searchScope">The search scope 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(IFindReferenceSearchScope searchScope, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) { if (searchScope == null) throw new ArgumentNullException("searchScope"); FindReferencesInFile(new[] { searchScope }, parsedFile, compilationUnit, compilation, callback, cancellationToken); }
public CSharpFile(CSharpProject project, string fileName) { this.Project = project; this.FileName = fileName; this.Content = new StringTextSource(File.ReadAllText(FileName)); this.LinesOfCode = 1 + this.Content.Text.Count(c => c == '\n'); CSharpParser p = new CSharpParser(project.CompilerSettings); this.CompilationUnit = p.Parse(Content.CreateReader(), fileName); if (p.HasErrors) { Console.WriteLine("Error parsing " + fileName + ":"); foreach (var error in p.ErrorsAndWarnings) { Console.WriteLine(" " + error.Region + " " + error.Message); } } this.ParsedFile = this.CompilationUnit.ToTypeSystem(); }
public override void VisitCompilationUnit(CompilationUnit unit) { IProjectContent project = new CSharpProjectContent(); _parsedFile = unit.ToTypeSystem(); project = project.UpdateProjectContent(null, _parsedFile); project = project.AddAssemblyReferences(builtInLibs.Value); _compilation = project.CreateCompilation(); _compilationUnit = unit; _resolver = new CSharpAstResolver(_compilation, _compilationUnit, _parsedFile); base.VisitCompilationUnit(unit); }
protected Tuple<ResolveResult, CSharpResolver> ResolveExpression (CSharpParsedFile file, AstNode expr, CompilationUnit unit) { if (expr == null) return null; AstNode resolveNode; if (expr is Expression || expr is AstType) { resolveNode = expr; } else if (expr is VariableDeclarationStatement) { resolveNode = ((VariableDeclarationStatement)expr).Type; } else { resolveNode = expr; } // var newContent = ProjectContent.UpdateProjectContent (CSharpParsedFile, file); var csResolver = new CSharpAstResolver(new CSharpResolver (ctx), unit, CSharpParsedFile); var result = csResolver.Resolve (resolveNode); var state = csResolver.GetResolverStateBefore (resolveNode); return Tuple.Create (result, state); }
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 CSharpParsedFile("File.cs"); var cu = parser.Parse(rdr, pf.FileName); cu.AcceptVisitor(new TypeSystemConvertVisitor(pf)); project = project.UpdateProjectContent(null, pf); } project = project.AddAssemblyReferences(new[] { Common.Mscorlib }); var compilation = project.CreateCompilation(); errorReporter = new MockErrorReporter(!expectErrors); Metadata = new MetadataImporter.ScriptSharpMetadataImporter(minimizeNames); Metadata.Prepare(compilation.GetAllTypeDefinitions(), compilation.MainAssembly, errorReporter); AllErrors = errorReporter.AllMessages.ToList().AsReadOnly(); AllErrorTexts = errorReporter.AllMessagesText.ToList().AsReadOnly(); if (expectErrors) { AllErrorTexts.Should().NotBeEmpty("Compile should have generated errors"); } else { AllErrorTexts.Should().BeEmpty("Compile should not generate errors"); } AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName); }
/// <summary> /// Finds all references of a given variable. /// </summary> /// <param name="variable">The variable 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.</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, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, 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, parsedFile, compilationUnit, compilation, callback, cancellationToken); }
public static ResolveResult Resolve (ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, CancellationToken cancellationToken = default(CancellationToken)) { return Resolve (new Lazy<ICompilation>(() => compilation), parsedFile, cu, location, cancellationToken); }
/// <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); } }
public static ResolveResult Resolve(ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location, CancellationToken cancellationToken = default(CancellationToken)) { AstNode node; return Resolve(compilation, parsedFile, cu, location, out node, cancellationToken); }
public ParsedSourceFile(CompilationUnit compilationUnit, CSharpParsedFile parsedFile, ISet<string> definedSymbols) { CompilationUnit = compilationUnit; ParsedFile = parsedFile; DefinedSymbols = definedSymbols; }
protected Tuple<ResolveResult, CSharpResolver> ResolveExpression(CSharpParsedFile file, AstNode expr, CompilationUnit unit) { if (expr == null) return null; AstNode resolveNode; if (expr is Expression || expr is AstType) { resolveNode = expr; } else if (expr is VariableDeclarationStatement) { resolveNode = ((VariableDeclarationStatement)expr).Type; } else { resolveNode = expr; } // var newContent = ProjectContent.UpdateProjectContent (CSharpParsedFile, file); var csResolver = new CSharpResolver (ctx); var navigator = new NodeListResolveVisitorNavigator (new[] { resolveNode }); var visitor = new ResolveVisitor (csResolver, CSharpParsedFile, navigator); visitor.Scan (unit); var state = visitor.GetResolverStateBefore (resolveNode); var result = visitor.GetResolveResult (resolveNode); return Tuple.Create (result, state); }
/// <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="context">The type resolve context to use for resolving the file.</param> /// <param name="callback">Callback used to report the references that were found.</param> public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, ITypeResolveContext context, FoundReferenceCallback callback) { if (searchScopes == null) throw new ArgumentNullException("searchScopes"); if (parsedFile == null) throw new ArgumentNullException("parsedFile"); if (compilationUnit == null) throw new ArgumentNullException("compilationUnit"); if (context == null) throw new ArgumentNullException("context"); this.CancellationToken.ThrowIfCancellationRequested(); if (searchScopes.Count == 0) return; using (var ctx = context.Synchronize()) { IResolveVisitorNavigator navigator; if (searchScopes.Count == 1) navigator = searchScopes[0].GetNavigator(callback); else navigator = new CompositeResolveVisitorNavigator(searchScopes.Select(s => s.GetNavigator(callback)).ToArray()); navigator = new DetectSkippableNodesNavigator(navigator, compilationUnit); CSharpResolver resolver = new CSharpResolver(ctx, this.CancellationToken); ResolveVisitor v = new ResolveVisitor(resolver, parsedFile, navigator); v.Scan(compilationUnit); } }
public AstType CreateShortType (ICompilation compilation, CSharpParsedFile parsedFile, TextLocation loc, IType fullType) { var csResolver = parsedFile.GetResolver (compilation, loc); var builder = new ICSharpCode.NRefactory.CSharp.Refactoring.TypeSystemAstBuilder (csResolver); return builder.ConvertType (fullType); }
/// <summary> /// Finds all references of a given type parameter. /// </summary> /// <param name="typeParameter">The type parameter 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.</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, CSharpParsedFile parsedFile, CompilationUnit compilationUnit, 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, parsedFile, compilationUnit, compilation, callback, cancellationToken); }