public override void StartNode(AstNode node) { base.StartNode(node); if (node.Annotation<MethodDebugSymbols>() != null) { symbolsStack.Push(node.Annotation<MethodDebugSymbols>()); } }
public override void EndNode(AstNode node) { base.EndNode(node); if (node is EntityDeclaration && node.Annotation<MemberReference>() != null) { MemberLocations[XmlDocKeyProvider.GetKey(node.Annotation<MemberReference>())] = node.StartLocation; } // code mappings var ranges = node.Annotation<List<ILRange>>(); if (symbolsStack.Count > 0 && ranges != null && ranges.Count > 0) { symbolsStack.Peek().SequencePoints.Add( new SequencePoint() { ILRanges = ILRange.OrderAndJoin(ranges).ToArray(), StartLocation = node.StartLocation, EndLocation = node.EndLocation }); } if (node.Annotation<MethodDebugSymbols>() != null) { var symbols = symbolsStack.Pop(); symbols.SequencePoints = symbols.SequencePoints.OrderBy(s => s.ILOffset).ToList(); symbols.StartLocation = node.StartLocation; symbols.EndLocation = node.EndLocation; DebugSymbols[XmlDocKeyProvider.GetKey(symbols.CecilMethod)] = symbols; } }
public void StartNode(AstNode node) { nodeStack.Push(node); MethodDebugInfoBuilder mapping = node.Annotation<MethodDebugInfoBuilder>(); if (mapping != null) { parentMethodDebugInfoBuilder.Push(currentMethodDebugInfoBuilder); currentMethodDebugInfoBuilder = mapping; } // For ctor/cctor field initializers var mms = node.Annotation<List<Tuple<MethodDebugInfoBuilder, List<BinSpan>>>>(); if (mms != null) { Debug.Assert(multiMappings == null); multiMappings = mms; } }
public override void EndNode(AstNode node) { if (nodeStack.Pop() != node) throw new InvalidOperationException(); var startLocation = startLocations.Pop(); // code mappings var ranges = node.Annotation<List<ILRange>>(); if (symbolsStack.Count > 0 && ranges != null && ranges.Count > 0) { // Ignore the newline which was printed at the end of the statement TextLocation endLocation = (node is Statement) ? (lastEndOfLine ?? output.Location) : output.Location; symbolsStack.Peek().SequencePoints.Add( new SequencePoint() { ILRanges = ILRange.OrderAndJoin(ranges).ToArray(), StartLocation = startLocation, EndLocation = endLocation }); } if (node.Annotation<MethodDebugSymbols>() != null) { symbolsStack.Peek().EndLocation = output.Location; output.AddDebugSymbols(symbolsStack.Pop()); } }
public void EndNode(AstNode node) { if (nodeStack.Pop() != node) throw new InvalidOperationException(); if (node.Annotation<MethodDebugInfoBuilder>() != null) { output.AddDebugInfo(currentMethodDebugInfoBuilder.Create()); currentMethodDebugInfoBuilder = parentMethodDebugInfoBuilder.Pop(); } var mms = node.Annotation<List<Tuple<MethodDebugInfoBuilder, List<BinSpan>>>>(); if (mms != null) { Debug.Assert(mms == multiMappings); if (mms == multiMappings) { foreach (var mm in mms) output.AddDebugInfo(mm.Item1.Create()); multiMappings = null; } } }
public Instruction GetInstruction(AstNode node) { var range = node.Annotation<List<ILRange>>(); if (range != null && range.Count > 0) { return _instructions.First(i => i.Offset == range[0].From); } return null; }
public bool TryGetOpCode(AstNode node, OpCode[] opCodes, out Instruction instruction) { List<ILRange> ilRanges = node.Annotation<List<ILRange>>(); instruction = null; foreach (var opCode in opCodes) { if (TryGetInstruction(ilRanges, opCode, out instruction)) { return true; } } return false; }
public void StartNode(AstNode node) { // var ranges = node.Annotation<List<ILRange>>(); // if (ranges != null && ranges.Count > 0) // { // // find the ancestor that has method mapping as annotation // if (node.Ancestors != null && node.Ancestors.Count() > 0) // { // var n = node.Ancestors.FirstOrDefault(a => a.Annotation<MemberMapping>() != null); // if (n != null) { // MemberMapping mapping = n.Annotation<MemberMapping>(); // // // add all ranges // foreach (var range in ranges) { // mapping.MemberCodeMappings.Add(new SourceCodeMapping { // ILInstructionOffset = range, // SourceCodeLine = output.CurrentLine, // MemberMapping = mapping // }); // } // } // } // } nodeStack.Push(node); MemberMapping mapping = node.Annotation<MemberMapping>(); if (mapping != null) { parentMemberMappings.Push(currentMemberMapping); currentMemberMapping = mapping; } // For ctor/cctor field initializers var mms = node.Annotation<List<Tuple<MemberMapping, List<ILRange>>>>(); if (mms != null) { Debug.Assert(multiMappings == null); multiMappings = mms; } }
public void Run(AstNode node) { if (node is EntityDeclaration) { IMemberRef mr = node.Annotation<IMemberRef>(); if (mr != null && mr.Module != null) { var xmldoc = XmlDocLoader.LoadDocumentation(mr.Module); if (xmldoc != null) { string doc = xmldoc.GetDocumentation(XmlDocKeyProvider.GetKey(mr, stringBuilder)); if (!string.IsNullOrEmpty(doc)) { InsertXmlDocumentation(node, doc); } } } if (!(node is TypeDeclaration)) return; // don't recurse into attributed nodes, except for type definitions } foreach (AstNode child in node.Children) Run(child); }
public void EndNode(AstNode node) { if (nodeStack.Pop() != node) throw new InvalidOperationException(); if (node.Annotation<MemberMapping>() != null) { output.AddDebugSymbols(currentMemberMapping); currentMemberMapping = parentMemberMappings.Pop(); } var mms = node.Annotation<List<Tuple<MemberMapping, List<ILRange>>>>(); if (mms != null) { Debug.Assert(mms == multiMappings); if (mms == multiMappings) { foreach (var mm in mms) output.AddDebugSymbols(mm.Item1); multiMappings = null; } } }
public static void Run(AstNode node) { if (node is AttributedNode) { MemberReference mr = node.Annotation<MemberReference>(); if (mr != null && mr.Module != null) { var xmldoc = XmlDocLoader.LoadDocumentation(mr.Module); if (xmldoc != null) { string doc = xmldoc.GetDocumentation(XmlDocKeyProvider.GetKey(mr)); if (doc != null) { InsertXmlDocumentation(node, new StringReader(doc)); } } } if (!(node is TypeDeclaration)) return; // don't recurse into attributed nodes, except for type definitions } foreach (AstNode child in node.Children) Run(child); }
public static ResolveResultInfo GetInfo(this AstNode node) { return(node.Annotation <ResolveResultInfo>()); }
public override void StartNode(AstNode node) { if (nodeStack.Count == 0) { if (IsUsingDeclaration(node)) { firstUsingDeclaration = !IsUsingDeclaration(node.PrevSibling); lastUsingDeclaration = !IsUsingDeclaration(node.NextSibling); } else { firstUsingDeclaration = false; lastUsingDeclaration = false; } } nodeStack.Push(node); MemberMapping mapping = node.Annotation<MemberMapping>(); if (mapping != null) { parentMemberMappings.Push(currentMemberMapping); currentMemberMapping = mapping; } // For ctor/cctor field initializers var mms = node.Annotation<List<Tuple<MemberMapping, List<ILRange>>>>(); if (mms != null) { Debug.Assert(multiMappings == null); multiMappings = mms; } }
IEnumerable<ICompletionData> CreateCompletionData (TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CppResolver state) { if (resolveResult == null /*|| resolveResult.IsError*/) return null; if (resolveResult is NamespaceResolveResult) { var nr = (NamespaceResolveResult)resolveResult; var namespaceContents = new CompletionDataWrapper (this); foreach (var cl in nr.Namespace.Types) { namespaceContents.AddType (cl, cl.Name); } foreach (var ns in nr.Namespace.ChildNamespaces) { namespaceContents.AddNamespace (ns.Name); } return namespaceContents.Result; } IType type = resolveResult.Type; var typeDef = resolveResult.Type.GetDefinition (); var result = new CompletionDataWrapper (this); bool includeStaticMembers = false; if (resolveResult is LocalResolveResult) { if (resolvedNode is IdentifierExpression) { var mrr = (LocalResolveResult)resolveResult; includeStaticMembers = mrr.Variable.Name == mrr.Type.Name; } } if (resolveResult is TypeResolveResult && type.Kind == TypeKind.Enum) { foreach (var field in type.GetFields ()) { result.AddMember (field); } foreach (var m in type.GetMethods ()) { if (m.Name == "TryParse") result.AddMember (m); } return result.Result; } if (resolveResult is MemberResolveResult && resolvedNode is IdentifierExpression) { var mrr = (MemberResolveResult)resolveResult; includeStaticMembers = mrr.Member.Name == mrr.Type.Name; // ADD Aliases var scope = CSharpParsedFile.GetUsingScope (location).Resolve (Compilation); for (var n = scope; n != null; n = n.Parent) { foreach (var pair in n.UsingAliases) { if (pair.Key == mrr.Member.Name) { foreach (var r in CreateCompletionData (location, pair.Value, resolvedNode, state)) { if (r is IEntityCompletionData && ((IEntityCompletionData)r).Entity is IMember) { result.AddMember ((IMember)((IEntityCompletionData)r).Entity); } else { result.Add (r); } } } } } } if (resolveResult is TypeResolveResult && (resolvedNode is IdentifierExpression || resolvedNode is MemberReferenceExpression)) { includeStaticMembers = true; } // Console.WriteLine ("type:" + type +"/"+type.GetType ()); // Console.WriteLine ("current:" + ctx.CurrentTypeDefinition); // Console.WriteLine ("IS PROT ALLOWED:" + isProtectedAllowed + " static: "+ includeStaticMembers); // Console.WriteLine (resolveResult); // Console.WriteLine ("node:" + resolvedNode); // Console.WriteLine (currentMember != null ? currentMember.IsStatic : "currentMember == null"); if (resolvedNode.Annotation<ObjectCreateExpression> () == null) { //tags the created expression as part of an object create expression. var lookup = new MemberLookup (ctx.CurrentTypeDefinition, Compilation.MainAssembly); bool isProtectedAllowed = resolveResult is ThisResolveResult ? true : lookup.IsProtectedAccessAllowed (type); var filteredList = new List<IMember> (); foreach (var member in type.GetMembers ()) { // Console.WriteLine ("member:" + member + member.IsShadowing); if (!lookup.IsAccessible (member, isProtectedAllowed)) { // Console.WriteLine ("skip access: " + member.FullName); continue; } if (resolvedNode is BaseReferenceExpression && member.IsAbstract) continue; bool memberIsStatic = member.IsStatic; if (!includeStaticMembers && memberIsStatic && !(resolveResult is TypeResolveResult)) { // Console.WriteLine ("skip static member: " + member.FullName); continue; } var field = member as IField; if (field != null) memberIsStatic |= field.IsConst; if (!memberIsStatic && (resolveResult is TypeResolveResult)) { continue; } if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") continue; if (member.EntityType == EntityType.Operator) continue; if (member.IsShadowing) filteredList.RemoveAll (m => m.Name == member.Name); filteredList.Add (member); } foreach (var member in filteredList) { // Console.WriteLine ("add : "+ member.FullName + " --- " + member.IsStatic); result.AddMember (member); } } if (resolveResult is TypeResolveResult || includeStaticMembers) { foreach (var nested in type.GetNestedTypes ()) { result.AddType (nested, nested.Name); } } else { foreach (var meths in state.GetExtensionMethods (type)) { foreach (var m in meths) { result.AddMember (m); } } } // IEnumerable<object> objects = resolveResult.CreateResolveResult (dom, resolver != null ? resolver.CallingMember : null); // CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, resolver != null ? resolver.CallingType : null, location); // col.HideExtensionParameter = !resolveResult.StaticResolve; // col.NamePrefix = expressionResult.Expression; // bool showOnlyTypes = expressionResult.Contexts.Any (ctx => ctx == ExpressionContext.InheritableType || ctx == ExpressionContext.Constraints); // if (objects != null) { // foreach (object obj in objects) { // if (expressionResult.ExpressionContext != null && expressionResult.ExpressionContext.FilterEntry (obj)) // continue; // if (expressionResult.ExpressionContext == ExpressionContext.NamespaceNameExcepted && !(obj is Namespace)) // continue; // if (showOnlyTypes && !(obj is IType)) // continue; // CompletionData data = col.Add (obj); // if (data != null && expressionResult.ExpressionContext == ExpressionContext.Attribute && data.CompletionText != null && data.CompletionText.EndsWith ("Attribute")) { // string newText = data.CompletionText.Substring (0, data.CompletionText.Length - "Attribute".Length); // data.SetText (newText); // } // } // } return result.Result; }
string GetClassAndLink(AstNode n, out string link, out string id) { link = null; id = null; if (n == null || n == AstNode.Null) { return("c-uk"); } while (n != null && n.Annotations.Count() == 0) { n = n.Parent; } if (n == null || n == AstNode.Null) { return("c-uk"); } var t = n.Annotation <TypeResolveResult> (); if (t != null) { if (n.NodeType == NodeType.TypeDeclaration) { return("c-td"); } var name = t.Type.FullName; if (t.Type.TypeParameterCount > 0 && name.IndexOf('`') < 0) { name += "`" + t.Type.TypeParameterCount; } if (t.Type.Kind != TypeKind.TypeParameter) { link = framework.FindTypeUrl(name); } return("c-tr"); } var u = n.Annotation <UsingScope> (); if (u != null) { return("c-nr"); } var m = n.Annotation <MemberResolveResult> (); if (m != null) { if (m.Member.SymbolKind == SymbolKind.Method) { if (n is MethodDeclaration md) { if (md.GetSymbol() is DefaultResolvedMethod r) { id = r.GetIdString(); } return("c-md"); } return("c-mr"); } if (m.Member.SymbolKind == SymbolKind.Field) { if (n is FieldDeclaration fd) { if (fd.GetSymbol() is DefaultResolvedField r) { id = r.GetIdString(); } return("c-fd"); } return("c-fr"); } if (m.Member.SymbolKind == SymbolKind.Event) { if (n is EventDeclaration ed) { if (ed.GetSymbol() is DefaultResolvedEvent r) { id = r.GetIdString(); } return("c-ed"); } if (n is CustomEventDeclaration ed2) { if (ed2.GetSymbol() is DefaultResolvedEvent r) { id = r.GetIdString(); } return("c-ed"); } return("c-er"); } if (m.Member.SymbolKind == SymbolKind.Constructor) { if (n is ConstructorDeclaration cd) { if (cd.GetSymbol() is DefaultResolvedEvent r) { id = r.GetIdString(); } return("c-cd"); } return("c-cr"); } if (n is PropertyDeclaration pd) { if (pd.GetSymbol() is DefaultResolvedProperty r) { id = r.GetIdString(); } return("c-pd"); } return("c-pr"); } var mg = n.Annotation <MethodGroupResolveResult> (); if (mg != null) { return("c-mr"); } var v = n.Annotation <ILVariableResolveResult> (); if (v != null) { if (v.Variable.Kind == VariableKind.Parameter) { return("c-ar"); } return("c-uk"); } var c = n.Annotation <ConstantResolveResult> (); if (c != null) { return("c-fr"); } // Console.WriteLine(n.Annotations.FirstOrDefault()); return("c-uk"); }
public void StartNode(AstNode node) { // code mappings var ranges = node.Annotation<List<ILRange>>(); if (ranges != null && ranges.Count > 0) { // find the ancestor that has method mapping as annotation if (node.Parent != null) { var n = node.Ancestors.FirstOrDefault(a => a.Annotation<MemberMapping>() != null); if (n != null) { MemberMapping mapping = n.Annotation<MemberMapping>(); // add all ranges foreach (var range in ranges) { mapping.MemberCodeMappings.Add(new SourceCodeMapping { ILInstructionOffset = range, SourceCodeLine = output.CurrentLine, MemberMapping = mapping }); } } } } // definitions of types and their members Predicate<AstNode> predicate = n => n is AttributedNode; if (predicate(node)) { var n = node as AttributedNode; int c = 0; if (n != null) c = n.Attributes.Count; node.AddAnnotation(Tuple.Create(output.CurrentLine + c, output.CurrentColumn)); } nodeStack.Push(node); }
static TypeReference GetTypeRef (AstNode expr) { var td = expr.Annotation<TypeDefinition> (); if (td != null) { return td; } var tr = expr.Annotation<TypeReference> (); if (tr != null) { return tr; } var ti = expr.Annotation<ICSharpCode.Decompiler.Ast.TypeInformation> (); if (ti != null) { return ti.InferredType; } var ilv = expr.Annotation<ICSharpCode.Decompiler.ILAst.ILVariable> (); if (ilv != null) { return ilv.Type; } var fr = expr.Annotation<FieldDefinition> (); if (fr != null) { return fr.FieldType; } var pr = expr.Annotation<PropertyDefinition> (); if (pr != null) { return pr.PropertyType; } return null; }
public Instruction GetLastInstructionInRange(AstNode node) { List<ILRange> ilRanges = node.Annotation<List<ILRange>>(); if (ilRanges != null && ilRanges.Count > 0) { var lastRange = ilRanges[ilRanges.Count - 1]; var instruction = InstructionAt(lastRange.To); if (instruction != null) { return instruction.Previous; } } return null; }
static CodeBracesRangeFlags GetTypeBlockKind(AstNode node) { var td = node.Annotation<TypeDef>(); if (td != null) { if (td.IsInterface) return CodeBracesRangeFlags.InterfaceBraces; if (td.IsValueType) return CodeBracesRangeFlags.ValueTypeBraces; } return CodeBracesRangeFlags.TypeBraces; }
private static object GetDefinition(AstNode node) { if (node is EntityDeclaration || node is FixedVariableInitializer) return node.Annotation<IMemberRef>(); else if (node is VariableInitializer && node.Parent is FieldDeclaration) return node.Parent.Annotation<IMemberRef>(); else return null; }
public bool TryGetInstruction(AstNode node, OpCode opCode, out Instruction instruction) { List <ILRange> ilRanges = node.Annotation <List <ILRange> >(); return(TryGetInstruction(ilRanges, opCode, out instruction)); }
object GetCurrentLocalDefinition() { AstNode node = nodeStack.Peek(); if (node is Identifier && node.Parent is CatchBlock) { node = node.Parent; } var parameterDef = node.Annotation <Parameter>(); if (parameterDef != null) { return(parameterDef); } if (node is ParameterDeclaration) { node = ((ParameterDeclaration)node).Name; parameterDef = node.Annotation <Parameter>(); if (parameterDef != null) { return(parameterDef); } } if (node is VariableIdentifier) { var variable = ((VariableIdentifier)node).Name.Annotation <ILVariable>(); if (variable != null) { if (variable.OriginalParameter != null) { return(variable.OriginalParameter); } if (variable.OriginalVariable != null) { return(variable.OriginalVariable); } return(variable.Id); } node = node.Parent ?? node; } if (node is VariableDeclaratorWithTypeAndInitializer || node is VariableInitializer || node is CatchBlock || node is ForEachStatement) { var variable = node.Annotation <ILVariable>(); if (variable != null) { if (variable.OriginalParameter != null) { return(variable.OriginalParameter); } if (variable.OriginalVariable != null) { return(variable.OriginalVariable); } return(variable.Id); } } var label = node as LabelDeclarationStatement; if (label != null) { var method = nodeStack.Select(nd => nd.Annotation <IMethod>()).FirstOrDefault(mr => mr != null && mr.IsMethod); if (method != null) { return(method.ToString() + label.Label); } } return(null); }
/// <summary> /// Retrieves the <see cref="ResolveResult"/> associated with this <see cref="AstNode"/>, or <see cref="ErrorResolveResult.UnknownError"/> if no resolve result is associated with the node. /// </summary> public static ResolveResult GetResolveResult(this AstNode node) { return(node.Annotation <ResolveResult>() ?? ErrorResolveResult.UnknownError); }
public Type ResoleClrType(AstNode node) => node.Annotation <TypeInformation>()?.InferredType?.ResolveClrType() ?? node.Annotation <PropertyDefinition>()?.PropertyType?.ResolveClrType() ?? node.Annotation <EventDefinition>()?.EventType?.ResolveClrType() ?? node.Annotation <MethodDefinition>()?.ReturnType?.ResolveClrType() ?? node.Annotation <FieldDefinition>()?.FieldType?.ResolveClrType();
internal static bool HasAnnotationOf <T>(this AstNode node, out T annotation) where T : class { annotation = node.Annotation <T>(); return(annotation != null); }
static MethodReference GetMethodRef (AstNode node) { var mr = node.Annotation<MethodReference> (); if (mr != null) return mr; mr = node.Annotation<MethodDefinition> (); if (mr != null) return mr; return null; }
public override object VisitBlockStatement(BlockStatement blockStatement, object data) { int numberOfVariablesOutsideBlock = currentlyUsedVariableNames.Count; base.VisitBlockStatement(blockStatement, data); foreach (ExpressionStatement stmt in blockStatement.Statements.OfType <ExpressionStatement>().ToArray()) { Match displayClassAssignmentMatch = displayClassAssignmentPattern.Match(stmt); if (!displayClassAssignmentMatch.Success) { continue; } ILVariable variable = displayClassAssignmentMatch.Get <AstNode>("variable").Single().Annotation <ILVariable>(); if (variable == null) { continue; } TypeDefinition type = variable.Type.ResolveWithinSameModule(); if (!IsPotentialClosure(context, type)) { continue; } if (displayClassAssignmentMatch.Get <AstType>("type").Single().Annotation <TypeReference>().ResolveWithinSameModule() != type) { continue; } // Looks like we found a display class creation. Now let's verify that the variable is used only for field accesses: bool ok = true; foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>()) { if (identExpr.Identifier == variable.Name && identExpr != displayClassAssignmentMatch.Get("variable").Single()) { if (!(identExpr.Parent is MemberReferenceExpression && identExpr.Parent.Annotation <FieldReference>() != null)) { ok = false; } } } if (!ok) { continue; } Dictionary <FieldReference, AstNode> dict = new Dictionary <FieldReference, AstNode>(); // Delete the variable declaration statement: VariableDeclarationStatement displayClassVarDecl = PatternStatementTransform.FindVariableDeclaration(stmt, variable.Name); if (displayClassVarDecl != null) { displayClassVarDecl.Remove(); } // Delete the assignment statement: AstNode cur = stmt.NextSibling; stmt.Remove(); // Delete any following statements as long as they assign parameters to the display class BlockStatement rootBlock = blockStatement.Ancestors.OfType <BlockStatement>().LastOrDefault() ?? blockStatement; List <ILVariable> parameterOccurrances = rootBlock.Descendants.OfType <IdentifierExpression>() .Select(n => n.Annotation <ILVariable>()).Where(p => p != null && p.IsParameter).ToList(); AstNode next; for (; cur != null; cur = next) { next = cur.NextSibling; // Test for the pattern: // "variableName.MemberName = right;" ExpressionStatement closureFieldAssignmentPattern = new ExpressionStatement( new AssignmentExpression( new NamedNode("left", new MemberReferenceExpression { Target = new IdentifierExpression(variable.Name), MemberName = Pattern.AnyString }), new AnyNode("right") ) ); Match m = closureFieldAssignmentPattern.Match(cur); if (m.Success) { FieldDefinition fieldDef = m.Get <MemberReferenceExpression>("left").Single().Annotation <FieldReference>().ResolveWithinSameModule(); AstNode right = m.Get <AstNode>("right").Single(); bool isParameter = false; bool isDisplayClassParentPointerAssignment = false; if (right is ThisReferenceExpression) { isParameter = true; } else if (right is IdentifierExpression) { // handle parameters only if the whole method contains no other occurrence except for 'right' ILVariable v = right.Annotation <ILVariable>(); isParameter = v.IsParameter && parameterOccurrances.Count(c => c == v) == 1; if (!isParameter && IsPotentialClosure(context, v.Type.ResolveWithinSameModule())) { // parent display class within the same method // (closure2.localsX = closure1;) isDisplayClassParentPointerAssignment = true; } } else if (right is MemberReferenceExpression) { // copy of parent display class reference from an outer lambda // closure2.localsX = this.localsY MemberReferenceExpression mre = m.Get <MemberReferenceExpression>("right").Single(); do { // descend into the targets of the mre as long as the field types are closures FieldDefinition fieldDef2 = mre.Annotation <FieldReference>().ResolveWithinSameModule(); if (fieldDef2 == null || !IsPotentialClosure(context, fieldDef2.FieldType.ResolveWithinSameModule())) { break; } // if we finally get to a this reference, it's copying a display class parent pointer if (mre.Target is ThisReferenceExpression) { isDisplayClassParentPointerAssignment = true; } mre = mre.Target as MemberReferenceExpression; } while (mre != null); } if (isParameter || isDisplayClassParentPointerAssignment) { dict[fieldDef] = right; cur.Remove(); } else { break; } } else { break; } } // Now create variables for all fields of the display class (except for those that we already handled as parameters) List <Tuple <AstType, ILVariable> > variablesToDeclare = new List <Tuple <AstType, ILVariable> >(); foreach (FieldDefinition field in type.Fields) { if (field.IsStatic) { continue; // skip static fields } if (dict.ContainsKey(field)) // skip field if it already was handled as parameter { continue; } string capturedVariableName = field.Name; if (capturedVariableName.StartsWith("$VB$Local_", StringComparison.Ordinal) && capturedVariableName.Length > 10) { capturedVariableName = capturedVariableName.Substring(10); } EnsureVariableNameIsAvailable(blockStatement, capturedVariableName); currentlyUsedVariableNames.Add(capturedVariableName); ILVariable ilVar = new ILVariable { IsGenerated = true, Name = capturedVariableName, Type = field.FieldType, }; variablesToDeclare.Add(Tuple.Create(AstBuilder.ConvertType(field.FieldType, field), ilVar)); dict[field] = new IdentifierExpression(capturedVariableName).WithAnnotation(ilVar); } // Now figure out where the closure was accessed and use the simpler replacement expression there: foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>()) { if (identExpr.Identifier == variable.Name) { MemberReferenceExpression mre = (MemberReferenceExpression)identExpr.Parent; AstNode replacement; if (dict.TryGetValue(mre.Annotation <FieldReference>().ResolveWithinSameModule(), out replacement)) { mre.ReplaceWith(replacement.Clone()); } } } // Now insert the variable declarations (we can do this after the replacements only so that the scope detection works): Statement insertionPoint = blockStatement.Statements.FirstOrDefault(); foreach (var tuple in variablesToDeclare) { var newVarDecl = new VariableDeclarationStatement(tuple.Item1, tuple.Item2.Name); newVarDecl.Variables.Single().AddAnnotation(new CapturedVariableAnnotation()); newVarDecl.Variables.Single().AddAnnotation(tuple.Item2); blockStatement.Statements.InsertBefore(insertionPoint, newVarDecl); } } currentlyUsedVariableNames.RemoveRange(numberOfVariablesOutsideBlock, currentlyUsedVariableNames.Count - numberOfVariablesOutsideBlock); return(null); }
public void EndNode(AstNode node) { if (nodeStack.Pop() != node) throw new InvalidOperationException(); var startLocation = startLocations.Pop(); // code mappings if (currentMemberMapping != null) { var ranges = node.Annotation<List<ILRange>>(); if (ranges != null && ranges.Count > 0) { // add all ranges foreach (var range in ranges) { currentMemberMapping.MemberCodeMappings.Add( new SourceCodeMapping { ILInstructionOffset = range, StartLocation = startLocation, EndLocation = output.Location, MemberMapping = currentMemberMapping }); } } } if (node.Annotation<MemberMapping>() != null) { output.AddDebuggerMemberMapping(currentMemberMapping); currentMemberMapping = parentMemberMappings.Pop(); } }
IEnumerable<ICompletionData> CreateCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state) { if (resolveResult == null /*|| resolveResult.IsError*/) return null; if (resolveResult is NamespaceResolveResult) { var nr = (NamespaceResolveResult)resolveResult; var namespaceContents = new CompletionDataWrapper (this); foreach (var cl in nr.Namespace.Types) { namespaceContents.AddType (cl, cl.Name); } foreach (var ns in nr.Namespace.ChildNamespaces) { namespaceContents.AddNamespace (ns.Name); } return namespaceContents.Result; } IType type = resolveResult.Type; var typeDef = resolveResult.Type.GetDefinition (); var lookup = new MemberLookup (ctx.CurrentTypeDefinition, Compilation.MainAssembly); var result = new CompletionDataWrapper (this); bool isProtectedAllowed = false; bool includeStaticMembers = false; if (resolveResult is LocalResolveResult) { isProtectedAllowed = currentType != null && typeDef != null ? typeDef.GetAllBaseTypeDefinitions ().Any (bt => bt.Equals (currentType)) : false; if (resolvedNode is IdentifierExpression) { var mrr = (LocalResolveResult)resolveResult; includeStaticMembers = mrr.Variable.Name == mrr.Type.Name; } } else { isProtectedAllowed = currentType != null && typeDef != null ? currentType.Resolve (ctx).GetDefinition ().GetAllBaseTypeDefinitions ().Any (bt => bt.Equals (typeDef)) : false; } if (resolveResult is TypeResolveResult && type.Kind == TypeKind.Enum) { foreach (var field in type.GetFields ()) { result.AddMember (field); } foreach (var m in type.GetMethods ()) { if (m.Name == "TryParse") result.AddMember (m); } return result.Result; } if (resolveResult is MemberResolveResult && resolvedNode is IdentifierExpression) { var mrr = (MemberResolveResult)resolveResult; includeStaticMembers = mrr.Member.Name == mrr.Type.Name; } // Console.WriteLine ("type:" + type +"/"+type.GetType ()); // Console.WriteLine ("IS PROT ALLOWED:" + isProtectedAllowed); // Console.WriteLine (resolveResult); // Console.WriteLine (currentMember != null ? currentMember.IsStatic : "currentMember == null"); if (resolvedNode.Annotation<ObjectCreateExpression> () == null) { //tags the created expression as part of an object create expression. foreach (var member in type.GetMembers ()) { if (!lookup.IsAccessible (member, isProtectedAllowed)) { // Console.WriteLine ("skip access: " + member.FullName); continue; } if (resolvedNode is BaseReferenceExpression && member.IsAbstract) continue; if (!includeStaticMembers && member.IsStatic && !(resolveResult is TypeResolveResult)) { // Console.WriteLine ("skip static member: " + member.FullName); continue; } if (!member.IsStatic && (resolveResult is TypeResolveResult)) { // Console.WriteLine ("skip non static member: " + member.FullName); continue; } // Console.WriteLine ("add : "+ member.FullName + " --- " + member.IsStatic); result.AddMember (member); } } if (resolveResult is TypeResolveResult || includeStaticMembers) { foreach (var nested in type.GetNestedTypes ()) { result.AddType (nested, nested.Name); } } else { foreach (var meths in state.GetAllExtensionMethods (type)) { foreach (var m in meths) { result.AddMember (m); } } } // IEnumerable<object> objects = resolveResult.CreateResolveResult (dom, resolver != null ? resolver.CallingMember : null); // CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, resolver != null ? resolver.CallingType : null, location); // col.HideExtensionParameter = !resolveResult.StaticResolve; // col.NamePrefix = expressionResult.Expression; // bool showOnlyTypes = expressionResult.Contexts.Any (ctx => ctx == ExpressionContext.InheritableType || ctx == ExpressionContext.Constraints); // if (objects != null) { // foreach (object obj in objects) { // if (expressionResult.ExpressionContext != null && expressionResult.ExpressionContext.FilterEntry (obj)) // continue; // if (expressionResult.ExpressionContext == ExpressionContext.NamespaceNameExcepted && !(obj is Namespace)) // continue; // if (showOnlyTypes && !(obj is IType)) // continue; // CompletionData data = col.Add (obj); // if (data != null && expressionResult.ExpressionContext == ExpressionContext.Attribute && data.CompletionText != null && data.CompletionText.EndsWith ("Attribute")) { // string newText = data.CompletionText.Substring (0, data.CompletionText.Length - "Attribute".Length); // data.SetText (newText); // } // } // } return result.Result; }
public void StartNode(AstNode node) { var ranges = node.Annotation<List<ILRange>>(); if (ranges != null && ranges.Count > 0) { // find the ancestor that has method mapping as annotation if (node.Ancestors != null && node.Ancestors.Count() > 0) { var n = node.Ancestors.FirstOrDefault(a => a.Annotation<MemberMapping>() != null); if (n != null) { MemberMapping mapping = n.Annotation<MemberMapping>(); // add all ranges foreach (var range in ranges) { mapping.MemberCodeMappings.Add(new SourceCodeMapping { ILInstructionOffset = range, SourceCodeLine = output.CurrentLine, MemberMapping = mapping }); } } } } nodeStack.Push(node); }
public bool TryGetInstruction(AstNode node, OpCode opCode, out Instruction instruction) { List<ILRange> ilRanges = node.Annotation<List<ILRange>>(); return TryGetInstruction(ilRanges, opCode, out instruction); }
public override object VisitBlockStatement(BlockStatement blockStatement, object data) { base.VisitBlockStatement(blockStatement, data); foreach (ExpressionStatement stmt in blockStatement.Statements.OfType <ExpressionStatement>().ToArray()) { Match displayClassAssignmentMatch = displayClassAssignmentPattern.Match(stmt); if (displayClassAssignmentMatch == null) { continue; } ILVariable variable = displayClassAssignmentMatch.Get("variable").Single().Annotation <ILVariable>(); if (variable == null) { continue; } TypeDefinition type = variable.Type.ResolveWithinSameModule(); if (!IsPotentialClosure(context, type)) { continue; } if (displayClassAssignmentMatch.Get("type").Single().Annotation <TypeReference>().ResolveWithinSameModule() != type) { continue; } // Looks like we found a display class creation. Now let's verify that the variable is used only for field accesses: bool ok = true; foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>()) { if (identExpr.Identifier == variable.Name && identExpr != displayClassAssignmentMatch.Get("variable").Single()) { if (!(identExpr.Parent is MemberReferenceExpression && identExpr.Parent.Annotation <FieldReference>() != null)) { ok = false; } } } if (!ok) { continue; } Dictionary <FieldReference, AstNode> dict = new Dictionary <FieldReference, AstNode>(); // Delete the variable declaration statement: AstNode cur = stmt.NextSibling; stmt.Remove(); if (blockStatement.Parent.NodeType == NodeType.Member || blockStatement.Parent is Accessor) { // Delete any following statements as long as they assign parameters to the display class // Do parameter handling only for closures created in the top scope (direct child of method/accessor) List <ILVariable> parameterOccurrances = blockStatement.Descendants.OfType <IdentifierExpression>() .Select(n => n.Annotation <ILVariable>()).Where(p => p != null && p.IsParameter).ToList(); AstNode next; for (; cur != null; cur = next) { next = cur.NextSibling; // Test for the pattern: // "variableName.MemberName = right;" ExpressionStatement closureFieldAssignmentPattern = new ExpressionStatement( new AssignmentExpression( new NamedNode("left", new MemberReferenceExpression { Target = new IdentifierExpression(variable.Name) }), new AnyNode("right") ) ); Match m = closureFieldAssignmentPattern.Match(cur); if (m != null) { AstNode right = m.Get("right").Single(); bool isParameter = false; if (right is ThisReferenceExpression) { isParameter = true; } else if (right is IdentifierExpression) { // handle parameters only if the whole method contains no other occurrance except for 'right' ILVariable param = right.Annotation <ILVariable>(); isParameter = param.IsParameter && parameterOccurrances.Count(c => c == param) == 1; } if (isParameter) { dict[m.Get <MemberReferenceExpression>("left").Single().Annotation <FieldReference>().ResolveWithinSameModule()] = right; cur.Remove(); } else { break; } } else { break; } } } // Now create variables for all fields of the display class (except for those that we already handled as parameters) List <Tuple <AstType, string> > variablesToDeclare = new List <Tuple <AstType, string> >(); foreach (FieldDefinition field in type.Fields) { if (dict.ContainsKey(field)) { continue; } variablesToDeclare.Add(Tuple.Create(AstBuilder.ConvertType(field.FieldType, field), field.Name)); dict[field] = new IdentifierExpression(field.Name); } // Now figure out where the closure was accessed and use the simpler replacement expression there: foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>()) { if (identExpr.Identifier == variable.Name) { MemberReferenceExpression mre = (MemberReferenceExpression)identExpr.Parent; AstNode replacement; if (dict.TryGetValue(mre.Annotation <FieldReference>().ResolveWithinSameModule(), out replacement)) { mre.ReplaceWith(replacement.Clone()); } } } // Now insert the variable declarations (we can do this after the replacements only so that the scope detection works): Statement insertionPoint = blockStatement.Statements.FirstOrDefault(); foreach (var tuple in variablesToDeclare) { var newVarDecl = new VariableDeclarationStatement(tuple.Item1, tuple.Item2); newVarDecl.Variables.Single().AddAnnotation(new CapturedVariableAnnotation()); blockStatement.Statements.InsertBefore(insertionPoint, newVarDecl); } } return(null); }
private Collection<Instruction> GetInstructions(AstNode node) { while(node.NodeType != NodeType.Member && !(node is Accessor)){ node = node.Parent; } return node.Annotation<MethodDefinition>().Body.Instructions; }
public void Run(AstNode rootNode, TransformContext context) { this.context = context; InitializeContext(rootNode.Annotation <UsingScope>()); rootNode.AcceptVisitor(this); }
public void StartNode(AstNode node) { if (nodeStack.Count == 0) { if (IsUsingDeclaration(node)) { firstUsingDeclaration = !IsUsingDeclaration(node.PrevSibling); lastUsingDeclaration = !IsUsingDeclaration(node.NextSibling); } else { firstUsingDeclaration = false; lastUsingDeclaration = false; } } nodeStack.Push(node); startLocations.Push(output.Location); if (node is EntityDeclaration && node.Annotation<MemberReference>() != null && node.GetChildByRole(Roles.Identifier).IsNull) output.WriteDefinition("", node.Annotation<MemberReference>(), false); MemberMapping mapping = node.Annotation<MemberMapping>(); if (mapping != null) { parentMemberMappings.Push(currentMemberMapping); currentMemberMapping = mapping; } }
public void StartNode(AstNode node) { if (nodeStack.Count == 0) { if (IsUsingDeclaration(node)) { firstUsingDeclaration = !IsUsingDeclaration(node.PrevSibling); lastUsingDeclaration = !IsUsingDeclaration(node.NextSibling); } else { firstUsingDeclaration = false; lastUsingDeclaration = false; } } nodeStack.Push(node); startLocations.Push(output.Location); MemberMapping mapping = node.Annotation<MemberMapping>(); if (mapping != null) { parentMemberMappings.Push(currentMemberMapping); currentMemberMapping = mapping; } }
public override void StartNode(AstNode node) { if (nodeStack.Count == 0) { if (IsUsingDeclaration(node)) { firstUsingDeclaration = !IsUsingDeclaration(node.PrevSibling); lastUsingDeclaration = !IsUsingDeclaration(node.NextSibling); } else { firstUsingDeclaration = false; lastUsingDeclaration = false; } } nodeStack.Push(node); startLocations.Push(output.Location); if (node is EntityDeclaration && node.Annotation<MemberReference>() != null && node.GetChildByRole(Roles.Identifier).IsNull) output.WriteDefinition("", node.Annotation<MemberReference>(), false); if (node.Annotation<MethodDebugSymbols>() != null) { symbolsStack.Push(node.Annotation<MethodDebugSymbols>()); symbolsStack.Peek().StartLocation = startLocations.Peek(); } }
public static DebugType GetStaticType(this AstNode expr) { return(expr.Annotation <DebugType>()); }
IEnumerable<ICompletionData> CreateCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state, Func<IType, IType> typePred = null) { if (resolveResult == null /* || resolveResult.IsError*/) { return null; } var lookup = new MemberLookup( ctx.CurrentTypeDefinition, Compilation.MainAssembly ); if (resolveResult is NamespaceResolveResult) { var nr = (NamespaceResolveResult)resolveResult; var namespaceContents = new CompletionDataWrapper(this); foreach (var cl in nr.Namespace.Types) { if (!lookup.IsAccessible(cl, false)) continue; IType addType = typePred != null ? typePred(cl) : cl; if (addType != null) namespaceContents.AddType(addType, false); } foreach (var ns in nr.Namespace.ChildNamespaces) { namespaceContents.AddNamespace(lookup, ns); } return namespaceContents.Result; } IType type = resolveResult.Type; if (type.Namespace == "System" && type.Name == "Void") return null; if (resolvedNode.Parent is PointerReferenceExpression && (type is PointerType)) { resolveResult = new OperatorResolveResult(((PointerType)type).ElementType, System.Linq.Expressions.ExpressionType.Extension, resolveResult); } //var typeDef = resolveResult.Type.GetDefinition(); var result = new CompletionDataWrapper(this); bool includeStaticMembers = false; if (resolveResult is LocalResolveResult) { if (resolvedNode is IdentifierExpression) { var mrr = (LocalResolveResult)resolveResult; includeStaticMembers = mrr.Variable.Name == mrr.Type.Name; } } if (resolveResult is TypeResolveResult && type.Kind == TypeKind.Enum) { foreach (var field in type.GetFields ()) { if (!lookup.IsAccessible(field, false)) continue; result.AddMember(field); } return result.Result; } bool isProtectedAllowed = resolveResult is ThisResolveResult ? true : lookup.IsProtectedAccessAllowed(type); bool skipNonStaticMembers = (resolveResult is TypeResolveResult); if (resolveResult is MemberResolveResult && resolvedNode is IdentifierExpression) { var mrr = (MemberResolveResult)resolveResult; includeStaticMembers = mrr.Member.Name == mrr.Type.Name; TypeResolveResult trr; if (state.IsVariableReferenceWithSameType( resolveResult, ((IdentifierExpression)resolvedNode).Identifier, out trr )) { if (currentMember != null && mrr.Member.IsStatic ^ currentMember.IsStatic) { skipNonStaticMembers = true; if (trr.Type.Kind == TypeKind.Enum) { foreach (var field in trr.Type.GetFields ()) { if (lookup.IsAccessible(field, false)) result.AddMember(field); } return result.Result; } } } // ADD Aliases var scope = ctx.CurrentUsingScope; for (var n = scope; n != null; n = n.Parent) { foreach (var pair in n.UsingAliases) { if (pair.Key == mrr.Member.Name) { foreach (var r in CreateCompletionData (location, pair.Value, resolvedNode, state)) { if (r is IEntityCompletionData && ((IEntityCompletionData)r).Entity is IMember) { result.AddMember((IMember)((IEntityCompletionData)r).Entity); } else { result.Add(r); } } } } } } if (resolveResult is TypeResolveResult && (resolvedNode is IdentifierExpression || resolvedNode is MemberReferenceExpression)) { includeStaticMembers = true; } // Console.WriteLine ("type:" + type +"/"+type.GetType ()); // Console.WriteLine ("current:" + ctx.CurrentTypeDefinition); // Console.WriteLine ("IS PROT ALLOWED:" + isProtectedAllowed + " static: "+ includeStaticMembers); // Console.WriteLine (resolveResult); // Console.WriteLine ("node:" + resolvedNode); // Console.WriteLine (currentMember != null ? currentMember.IsStatic : "currentMember == null"); if (resolvedNode.Annotation<ObjectCreateExpression>() == null) { //tags the created expression as part of an object create expression. /* var filteredList = new List<IMember>(); foreach (var member in type.GetMembers ()) { filteredList.Add(member); } foreach (var member in filteredList) { // Console.WriteLine ("add:" + member + "/" + member.IsStatic); result.AddMember(member); }*/ foreach (var member in lookup.GetAccessibleMembers (resolveResult)) { if (member.SymbolKind == SymbolKind.Indexer || member.SymbolKind == SymbolKind.Operator || member.SymbolKind == SymbolKind.Constructor || member.SymbolKind == SymbolKind.Destructor) { continue; } if (resolvedNode is BaseReferenceExpression && member.IsAbstract) { continue; } if (member is IType) { if (resolveResult is TypeResolveResult || includeStaticMembers) { if (!lookup.IsAccessible(member, isProtectedAllowed)) continue; result.AddType((IType)member, false); continue; } } bool memberIsStatic = member.IsStatic; if (!includeStaticMembers && memberIsStatic && !(resolveResult is TypeResolveResult)) { // Console.WriteLine ("skip static member: " + member.FullName); continue; } var field = member as IField; if (field != null) { memberIsStatic |= field.IsConst; } if (!memberIsStatic && skipNonStaticMembers) { continue; } if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") { continue; } if (member.SymbolKind == SymbolKind.Operator) { continue; } if (member is IMember) { result.AddMember((IMember)member); } } } if (!(resolveResult is TypeResolveResult || includeStaticMembers)) { foreach (var meths in state.GetExtensionMethods (type)) { foreach (var m in meths) { if (!lookup.IsAccessible(m, isProtectedAllowed)) continue; result.AddMember(new ReducedExtensionMethod(m)); } } } // IEnumerable<object> objects = resolveResult.CreateResolveResult (dom, resolver != null ? resolver.CallingMember : null); // CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, resolver != null ? resolver.CallingType : null, location); // col.HideExtensionParameter = !resolveResult.StaticResolve; // col.NamePrefix = expressionResult.Expression; // bool showOnlyTypes = expressionResult.Contexts.Any (ctx => ctx == ExpressionContext.InheritableType || ctx == ExpressionContext.Constraints); // if (objects != null) { // foreach (object obj in objects) { // if (expressionResult.ExpressionContext != null && expressionResult.ExpressionContext.FilterEntry (obj)) // continue; // if (expressionResult.ExpressionContext == ExpressionContext.NamespaceNameExcepted && !(obj is Namespace)) // continue; // if (showOnlyTypes && !(obj is IType)) // continue; // CompletionData data = col.Add (obj); // if (data != null && expressionResult.ExpressionContext == ExpressionContext.Attribute && data.CompletionText != null && data.CompletionText.EndsWith ("Attribute")) { // string newText = data.CompletionText.Substring (0, data.CompletionText.Length - "Attribute".Length); // data.SetText (newText); // } // } // } return result.Result; }
/// <summary> /// Retrieves the symbol associated with this AstNode, or null if no symbol is associated with the node. /// </summary> public static ISymbol GetSymbol(this AstNode node) { var rr = node.Annotation <ResolveResult>(); return(rr != null?rr.GetSymbol() : null); }
object GetDefinition(AstNode node) { if (node is Identifier) { node = node.Parent; if (node is VariableInitializer) node = node.Parent; // get FieldDeclaration / EventDeclaration } if (IsDefinition(node)) return node.Annotation<IMemberRef>(); return null; }
public void StartNode(AstNode node) { this.nodes.Push(node); if (this.highlightItems.Count > 0) { this.startLocations.Push(this.CurrentLocation); MemberMapping mapping = node.Annotation<MemberMapping>(); if (mapping != null) { this.memberMapping.Push(this.currentMapping); this.currentMapping = mapping; } } }