public IEnumerable <ILLocalVariable> GetLocalVariables(IMethod method) { string id = IdStringProvider.GetIdString(method.MemberDefinition); var file = GetSymbols(method); if (file == null || !file.DebugSymbols.ContainsKey(id)) { return(Enumerable.Empty <ILLocalVariable>()); } var symbols = file.DebugSymbols[id]; var context = new SimpleTypeResolveContext(method); var loader = new CecilLoader(); return(symbols.LocalVariables.Where(v => v.OriginalVariable != null).Select( v => new Debugger.ILLocalVariable() { Index = v.OriginalVariable.Index, Type = loader.ReadTypeReference(v.Type).Resolve(context), Name = v.Name, IsCompilerGenerated = false, ILRanges = new [] { new ILRange(0, int.MaxValue) } })); }
void AddCodeElements() { ICompilation compilation = project.GetCompilationUnit(); var projectContent = compilation.MainAssembly.UnresolvedAssembly as IProjectContent; if (projectContent != null) { IUnresolvedFile file = projectContent.GetFile(context.FilteredFileName); if (file != null) { var csharpFile = file as CSharpUnresolvedFile; if (csharpFile != null) { AddUsings(csharpFile.RootUsingScope, compilation); } var resolveContext = new SimpleTypeResolveContext(compilation.MainAssembly); AddTypes( file.TopLevelTypeDefinitions .Select(td => td.Resolve(resolveContext) as ITypeDefinition) .Where(td => td != null) .Distinct()); } } }
public static IList <ITypeDefinition> GetNestedTypes(AssemblyDefinition assemblyDefinition, string fullTypeName) { var loader = new CecilLoader(); loader.IncludeInternalMembers = true; var bridgeAssemblyDefinition = MonoCecilAssemblyHelper.GetBridgeAssemlyDefinition(); var bridgeAssembly = loader.LoadAssembly(bridgeAssemblyDefinition); IProjectContent project = new CSharpProjectContent(); project = project.AddAssemblyReferences(bridgeAssembly); var compilation = project.CreateCompilation(); var ctx = new SimpleTypeResolveContext(compilation); var unresolvedAssembly = loader.LoadAssembly(assemblyDefinition); var assembly = unresolvedAssembly.Resolve(ctx); var parentType = assembly.GetAllTypeDefinitions().FirstOrDefault(x => x.FullName == fullTypeName); if (parentType == null) { return(new List <ITypeDefinition>()); } var nested = parentType.NestedTypes; return(nested); }
public static void ResolvedUnresolvedMembers(Solution solution) { foreach (var project in solution.Projects) { var compilation = project.Compilation; var assemblyContext = new SimpleTypeResolveContext(compilation.MainAssembly); foreach (var typeDef in compilation.MainAssembly.GetAllTypeDefinitions()) { foreach (var part in typeDef.Parts) { if (!typeDef.Equals(part.Resolve(assemblyContext))) throw new InvalidOperationException(); } foreach (var member in IncludeAccessors(typeDef.Members)) { var resolvedMember = member.UnresolvedMember.Resolve(assemblyContext); if (!member.Equals(resolvedMember)) throw new InvalidOperationException(); } // ToMemberReference() requires an appropriate generic context if the member // contains open generics; otherwise the main context of the compilation is sufficient. ITypeResolveContext context; if (typeDef.TypeParameterCount > 0) context = new SimpleTypeResolveContext(typeDef); else context = compilation.TypeResolveContext; // Include (potentially specialized) inherited members when testing ToMemberReference() foreach (var member in IncludeAccessors(typeDef.GetMembers())) { var resolvedMember = member.ToMemberReference().Resolve(context); if (!member.Equals(resolvedMember)) throw new InvalidOperationException(); } } } }
static IEnumerable <ITypeDefinition> LoadTypes() { var tt = typeof(File).Assembly.Location; Reflector.OutputDir = Environment.CurrentDirectory; var asmFile = Assembly.GetExecutingAssembly().Location; //asmFile = "".GetType().Assembly.Location; string xmlFile = Path.GetFullPath(Path.GetFileNameWithoutExtension(asmFile) + ".xml"); XmlDocumentationProvider doc = MonoCompletionEngine.GetXmlDocumentation(asmFile); if (doc == null && File.Exists(xmlFile)) { doc = new XmlDocumentationProvider(xmlFile); } var loader = new CecilLoader { DocumentationProvider = doc }; var unresolvedAsm = loader.LoadAssemblyFile(asmFile); var compilation = new SimpleCompilation(unresolvedAsm); var context = new SimpleTypeResolveContext(compilation); var asm = unresolvedAsm.Resolve(context); return(asm.GetAllTypeDefinitions().ToArray()); }
public BVE5Resolver(BVE5Compilation compilation, SimpleTypeResolveContext context, Dictionary<string, ResolveResult> nameLookupCache, ImmutableStack<IVariable> stack) { this.compilation = compilation; this.context = context; user_defined_name_lookup_cache = nameLookupCache; local_variable_stack = stack; }
IMethod MakeMethod(params object[] parameterTypesOrDefaultValues) { var context = new SimpleTypeResolveContext(compilation.MainModule); var m = new FakeMethod(compilation, SymbolKind.Method); m.Name = "Method"; var parameters = new List <IParameter>(); foreach (var typeOrDefaultValue in parameterTypesOrDefaultValues) { Type type = typeOrDefaultValue as Type; if (type != null) { parameters.Add(new DefaultParameter(compilation.FindType(type), string.Empty, owner: m)); } else if (Type.GetTypeCode(typeOrDefaultValue.GetType()) > TypeCode.Object) { parameters.Add(new DefaultParameter(compilation.FindType(typeOrDefaultValue.GetType()), string.Empty, owner: m, isOptional: true, defaultValue: typeOrDefaultValue)); } else { throw new ArgumentException(typeOrDefaultValue.ToString()); } } m.Parameters = parameters; return(m); }
public void Run(ILFunction function, ILTransformContext context) { try { if (this.context != null) { throw new InvalidOperationException("Reentrancy in " + nameof(TransformDisplayClassUsage)); } this.context = context; var decompilationContext = new SimpleTypeResolveContext(context.Function.Method); // Traverse nested functions in post-order: // Inner functions are transformed before outer functions foreach (var f in function.Descendants.OfType <ILFunction>()) { foreach (var v in f.Variables.ToArray()) { if (context.Settings.YieldReturn && HandleMonoStateMachine(function, v, decompilationContext, f)) { continue; } if ((context.Settings.AnonymousMethods || context.Settings.ExpressionTrees) && IsClosure(context, v, out ITypeDefinition closureType, out var inst)) { if (!CanRemoveAllReferencesTo(context, v)) { continue; } if (inst is StObj || inst is StLoc) { instructionsToRemove.Add(inst); } AddOrUpdateDisplayClass(f, v, closureType, inst, localFunctionClosureParameter: false); continue; } if (context.Settings.LocalFunctions && f.Kind == ILFunctionKind.LocalFunction && v.Kind == VariableKind.Parameter && v.Index > -1 && f.Method.Parameters[v.Index.Value] is IParameter p && LocalFunctionDecompiler.IsClosureParameter(p, decompilationContext)) { AddOrUpdateDisplayClass(f, v, ((ByReferenceType)p.Type).ElementType.GetDefinition(), f.Body, localFunctionClosureParameter: true); continue; } AnalyzeUseSites(v); } } VisitILFunction(function); if (instructionsToRemove.Count > 0) { context.Step($"Remove instructions", function); foreach (var store in instructionsToRemove) { if (store.Parent is Block containingBlock) { containingBlock.Instructions.Remove(store); } } } RemoveDeadVariableInit.ResetHasInitialValueFlag(function, context); } finally { instructionsToRemove.Clear(); displayClasses.Clear(); fieldAssignmentsWithVariableValue.Clear(); this.context = null; } }
IMethod MakeParamsMethod(params object[] parameterTypesOrDefaultValues) { var m = MakeUnresolvedMethod(parameterTypesOrDefaultValues); ((DefaultUnresolvedParameter)m.Parameters.Last()).IsParams = true; var context = new SimpleTypeResolveContext(compilation.MainAssembly); return (IMethod)m.CreateResolved(context); }
public void Run(ILFunction function, ILTransformContext context) { try { if (this.context != null || this.currentFunction != null) { throw new InvalidOperationException("Reentrancy in " + nameof(TransformDisplayClassUsage)); } this.context = context; var decompilationContext = new SimpleTypeResolveContext(context.Function.Method); // Traverse nested functions in post-order: // Inner functions are transformed before outer functions foreach (var f in function.Descendants.OfType <ILFunction>()) { foreach (var v in f.Variables.ToArray()) { if (HandleMonoStateMachine(function, v, decompilationContext, f)) { continue; } if (!(v.IsSingleDefinition && v.StoreInstructions.SingleOrDefault() is StLoc inst)) { continue; } if (IsClosureInit(inst, out ITypeDefinition closureType)) { // TODO : figure out whether it is a mono compiled closure, without relying on the type name bool isMono = f.StateMachineCompiledWithMono || closureType.Name.Contains("AnonStorey"); displayClasses.Add(inst.Variable, new DisplayClass { IsMono = isMono, Initializer = inst, Variable = v, Definition = closureType, Variables = new Dictionary <IField, DisplayClassVariable>(), CaptureScope = isMono && IsMonoNestedCaptureScope(closureType) ? null : inst.Variable.CaptureScope }); instructionsToRemove.Add(inst); } } foreach (var displayClass in displayClasses.Values.OrderByDescending(d => d.Initializer.StartILOffset).ToArray()) { context.Step($"Transform references to " + displayClass.Variable, displayClass.Initializer); this.currentFunction = f; VisitILFunction(f); } } context.Step($"Remove instructions", function); foreach (var store in instructionsToRemove) { if (store.Parent is Block containingBlock) { containingBlock.Instructions.Remove(store); } } } finally { instructionsToRemove.Clear(); displayClasses.Clear(); this.context = null; this.currentFunction = null; } }
public BVE5Resolver(BVE5Compilation compilation) { if(compilation == null) throw new ArgumentNullException("compilation"); this.compilation = compilation; this.context = new SimpleTypeResolveContext(compilation.MainAssembly); }
IMethod MakeParamsMethod(params object[] parameterTypesOrDefaultValues) { var m = MakeUnresolvedMethod(parameterTypesOrDefaultValues); ((DefaultUnresolvedParameter)m.Parameters.Last()).IsParams = true; var context = new SimpleTypeResolveContext(compilation.MainAssembly); return((IMethod)m.CreateResolved(context)); }
public BVE5Resolver(SimpleTypeResolveContext context) { if(context == null) throw new ArgumentNullException("context"); this.compilation = (BVE5Compilation)context.Compilation; this.context = context; if(context.CurrentTypeDefinition != null) user_defined_name_lookup_cache = new Dictionary<string, ResolveResult>(); }
public void Run(ILFunction function, ILTransformContext context) { try { if (this.context != null || this.currentFunction != null) { throw new InvalidOperationException("Reentrancy in " + nameof(TransformDisplayClassUsage)); } this.context = context; var decompilationContext = new SimpleTypeResolveContext(context.Function.Method); // Traverse nested functions in post-order: // Inner functions are transformed before outer functions foreach (var f in function.Descendants.OfType <ILFunction>()) { foreach (var v in f.Variables.ToArray()) { if (HandleMonoStateMachine(function, v, decompilationContext, f)) { continue; } if (IsClosure(v, out ITypeDefinition closureType, out var inst)) { AddOrUpdateDisplayClass(f, v, closureType, inst, localFunctionClosureParameter: false); } if (context.Settings.LocalFunctions && f.Kind == ILFunctionKind.LocalFunction && v.Kind == VariableKind.Parameter && v.Index > -1 && f.Method.Parameters[v.Index.Value] is IParameter p && LocalFunctionDecompiler.IsClosureParameter(p, decompilationContext)) { AddOrUpdateDisplayClass(f, v, ((ByReferenceType)p.Type).ElementType.GetDefinition(), f.Body, localFunctionClosureParameter: true); } } foreach (var displayClass in displayClasses.Values.OrderByDescending(d => d.Initializer.StartILOffset).ToArray()) { context.Step($"Transform references to " + displayClass.Variable, displayClass.Initializer); this.currentFunction = f; VisitILFunction(f); } } if (instructionsToRemove.Count > 0) { context.Step($"Remove instructions", function); foreach (var store in instructionsToRemove) { if (store.Parent is Block containingBlock) { containingBlock.Instructions.Remove(store); } } } RemoveDeadVariableInit.ResetHasInitialValueFlag(function, context); } finally { instructionsToRemove.Clear(); displayClasses.Clear(); this.context = null; this.currentFunction = null; } }
public AnonymousType(ICompilation compilation, IList<IUnresolvedProperty> properties) { if (compilation == null) throw new ArgumentNullException("compilation"); if (properties == null) throw new ArgumentNullException("properties"); this.compilation = compilation; this.unresolvedProperties = properties.ToArray(); var context = new SimpleTypeResolveContext(compilation.MainAssembly); this.resolvedProperties = new ProjectedList<ITypeResolveContext, IUnresolvedProperty, IProperty>(context, unresolvedProperties, (c, p) => new AnonymousTypeProperty(p, c, this)); }
void ProcessUpdates() { var compilation = SD.ParserService.GetCompilation(project); var context = new SimpleTypeResolveContext(compilation.MainAssembly); foreach (var dirtyTypeDef in dirtyTypeDefinitions) { ITypeDefinition typeDef = compilation.MainAssembly.GetTypeDefinition(dirtyTypeDef.Namespace, dirtyTypeDef.Name, dirtyTypeDef.TypeParameterCount); UpdateType(dirtyTypeDef, typeDef); } dirtyTypeDefinitions.Clear(); }
public void AnErrorIsIssuedIfTheMainMethodHasParameters() { var er = new MockErrorReporter(); var invoker = new OOPEmulatorInvoker(new MockOOPEmulator(), new MockMetadataImporter(), er); var cu = new CSharpParser().Parse(@"class MyClass { public void Main(string[] args) { } }", "file.cs").ToTypeSystem(); var compilation = new CSharpProjectContent().AddOrUpdateFiles(new IUnresolvedFile[] { cu }).AddAssemblyReferences(new[] { MinimalCorlib.Instance }).CreateCompilation(); var typeResolveContext = new SimpleTypeResolveContext(compilation.MainAssembly); invoker.Process(cu.GetAllTypeDefinitions().Select(t => new JsClass(t.Resolve(typeResolveContext).GetDefinition())).ToList <JsType>(), compilation.FindType(new FullTypeName("MyClass")).GetMethods().Single(m => m.Name == "Main")); Assert.That(er.AllMessages, Has.Count.EqualTo(1)); Assert.That(er.AllMessages.Any(m => m.Code == 7800 && (string)m.Args[0] == "MyClass.Main")); }
string GetString(Ambience amb, IUnresolvedEntity x) { var ctx = new SimpleTypeResolveContext(Document.Compilation.MainAssembly); IEntity rx = null; if (x is IUnresolvedMember) { rx = ((IUnresolvedMember)x).CreateResolved(ctx); } if (tag is IUnresolvedFile) { return(amb.GetString(rx, OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters | OutputFlags.UseFullInnerTypeName | OutputFlags.ReformatDelegates)); } return(amb.GetString(rx, OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters | OutputFlags.ReformatDelegates)); }
static void AddAttachedEvents(ITypeDefinition td, List <ICompletionItem> result) { var attachedEvents = td.Fields.Where(f => f.IsAttached(false, true)); var unresolvedType = td.Parts.First(); var resolveContext = new SimpleTypeResolveContext(td); result.AddRange( attachedEvents.Select( field => { string eventName = GetEventNameFromField(field); IUnresolvedEvent item = new DefaultUnresolvedEvent(unresolvedType, eventName); IMember entity = item.CreateResolved(resolveContext); return(new XamlCompletionItem(eventName, entity)); } ) ); }
public static void AddAttachedProperties(ITypeDefinition td, List <ICompletionItem> result) { var attachedProperties = td.Fields.Where(f => f.IsAttached(true, false)); var unresolvedType = td.Parts.First(); var resolveContext = new SimpleTypeResolveContext(td); result.AddRange( attachedProperties.Select( property => { string propertyName = property.Name.Remove(property.Name.Length - "Property".Length); IUnresolvedProperty item = new DefaultUnresolvedProperty(unresolvedType, propertyName); IMember entity = item.CreateResolved(resolveContext); return(new XamlCompletionItem(propertyName, entity)); } ) ); }
public static void ResolvedUnresolvedMembers(Solution solution) { foreach (var project in solution.Projects) { var compilation = project.Compilation; var assemblyContext = new SimpleTypeResolveContext(compilation.MainAssembly); foreach (var typeDef in compilation.MainAssembly.GetAllTypeDefinitions()) { foreach (var part in typeDef.Parts) { if (!typeDef.Equals(part.Resolve(assemblyContext))) { throw new InvalidOperationException(); } } foreach (var member in IncludeAccessors(typeDef.Members)) { var resolvedMember = member.UnresolvedMember.Resolve(assemblyContext); if (!member.Equals(resolvedMember)) { throw new InvalidOperationException(); } } // ToMemberReference() requires an appropriate generic context if the member // contains open generics; otherwise the main context of the compilation is sufficient. ITypeResolveContext context; if (typeDef.TypeParameterCount > 0) { context = new SimpleTypeResolveContext(typeDef); } else { context = compilation.TypeResolveContext; } // Include (potentially specialized) inherited members when testing ToMemberReference() foreach (var member in IncludeAccessors(typeDef.GetMembers())) { var resolvedMember = member.ToReference().Resolve(context); if (!member.Equals(resolvedMember)) { throw new InvalidOperationException(); } } } } }
IMember FindAttachedMember(IType type, string propertyName, out IMember underlyingMember) { underlyingMember = type .GetMethods(m => m.IsPublic && m.IsStatic && m.Parameters.Count == 1 && m.Name == "Get" + propertyName) .FirstOrDefault(); var definition = type.GetDefinition(); if (definition != null) { ITypeResolveContext localContext = new SimpleTypeResolveContext(definition); if (underlyingMember != null) { return new DefaultUnresolvedProperty { Name = propertyName } }
ICodeContext CreateContext(ITextEditor editor) { var compilation = SD.ParserService.GetCompilationForFile(editor.FileName); var project = SD.ProjectService.FindProjectContainingFile(editor.FileName); var resolveContext = new SimpleTypeResolveContext(compilation.MainAssembly); var currentTypeDefinition = new DefaultUnresolvedTypeDefinition(project.RootNamespace, Path.GetFileNameWithoutExtension(editor.FileName)); ITypeReference baseTypeReference = new GetClassTypeReference("System.Web.Mvc", "WebViewPage", 1); baseTypeReference = new ParameterizedTypeReference(baseTypeReference, new[] { FindModelType(editor) }); currentTypeDefinition.BaseTypes.Add(baseTypeReference); var currentMethod = new DefaultUnresolvedMethod(currentTypeDefinition, "__ContextStub__"); currentMethod.ReturnType = KnownTypeReference.Void; currentTypeDefinition.Members.Add(currentMethod); var currentResolvedTypeDef = new DefaultResolvedTypeDefinition(resolveContext, currentTypeDefinition); var projectContent = compilation.MainAssembly.UnresolvedAssembly as IProjectContent; var currentFile = new CSharpUnresolvedFile(); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Mvc"); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Mvc.Ajax"); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Mvc.Html"); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Routing"); currentFile.TopLevelTypeDefinitions.Add(currentTypeDefinition); if (projectContent != null) { compilation = projectContent.AddOrUpdateFiles(currentFile).CreateCompilation(SD.ParserService.GetCurrentSolutionSnapshot()); } var context = new CSharpTypeResolveContext(compilation.MainAssembly, currentFile.RootUsingScope.Resolve(compilation), currentResolvedTypeDef, currentMethod.CreateResolved(resolveContext.WithCurrentTypeDefinition(currentResolvedTypeDef))); return(new CSharpResolver(context)); }
protected void Init(IModuleReference mainAssembly, IEnumerable <IModuleReference> assemblyReferences) { if (mainAssembly == null) { throw new ArgumentNullException(nameof(mainAssembly)); } if (assemblyReferences == null) { throw new ArgumentNullException(nameof(assemblyReferences)); } var context = new SimpleTypeResolveContext(this); this.mainModule = mainAssembly.Resolve(context); List <IModule> assemblies = new List <IModule>(); assemblies.Add(this.mainModule); List <IModule> referencedAssemblies = new List <IModule>(); foreach (var asmRef in assemblyReferences) { IModule asm; try { asm = asmRef.Resolve(context); } catch (InvalidOperationException) { throw new InvalidOperationException("Tried to initialize compilation with an invalid assembly reference. (Forgot to load the assembly reference ? - see CecilLoader)"); } if (asm != null && !assemblies.Contains(asm)) { assemblies.Add(asm); } if (asm != null && !referencedAssemblies.Contains(asm)) { referencedAssemblies.Add(asm); } } this.assemblies = assemblies.AsReadOnly(); this.referencedAssemblies = referencedAssemblies.AsReadOnly(); this.knownTypeCache = new KnownTypeCache(this); this.initialized = true; }
public EventBuilderCompiler(InputAssembliesGroup input, NuGetFramework framework) { _knownTypeCache = new KnownTypeCache(this); if (input == null) { throw new ArgumentNullException(nameof(input)); } var context = new SimpleTypeResolveContext(this); var moduleReferences = input.IncludeGroup.GetAllFileNames() .Where(file => AssemblyHelpers.AssemblyFileExtensionsSet.Contains(Path.GetExtension(file))) .Select(x => (IModuleReference) new PEFile(x, PEStreamOptions.PrefetchMetadata)); _assemblies.AddRange(moduleReferences.Select(x => x.Resolve(context))); _referencedAssemblies.AddRange(GetReferenceModules(_assemblies, input, framework, context)); _rootNamespace = CreateRootNamespace(); }
T FindEntity <T>(string targetClass) where T : IEntity { var compilation = SD.ParserService.GetCompilationForFile(textEditor.FileName); var parseInfo = SD.ParserService.Parse(textEditor.FileName, textEditor.Document); int i = textEditor.Document.IndexOf(targetClass, 0, textEditor.Document.TextLength, StringComparison.Ordinal); Assert.Greater(i, -1); TextLocation location = textEditor.Document.GetLocation(i); var member = parseInfo.UnresolvedFile.GetMember(location); var type = parseInfo.UnresolvedFile.GetInnermostTypeDefinition(location); var context = new SimpleTypeResolveContext(compilation.MainAssembly); var rt = type.Resolve(context).GetDefinition(); if (member != null) { return((T)member.CreateResolved(context.WithCurrentTypeDefinition(rt))); } return((T)rt); }
ICodeContext CreateContext(ITextEditor editor) { var compilation = SD.ParserService.GetCompilationForFile(editor.FileName); var project = SD.ProjectService.FindProjectContainingFile(editor.FileName); var resolveContext = new SimpleTypeResolveContext(compilation.MainAssembly); var currentTypeDefinition = new DefaultUnresolvedTypeDefinition(project.RootNamespace, Path.GetFileNameWithoutExtension(editor.FileName)); ITypeReference baseTypeReference = new GetClassTypeReference("System.Web.Mvc", "WebViewPage", 1); baseTypeReference = new ParameterizedTypeReference(baseTypeReference, new[] { FindModelType(editor) }); currentTypeDefinition.BaseTypes.Add(baseTypeReference); var currentMethod = new DefaultUnresolvedMethod(currentTypeDefinition, "__ContextStub__"); currentMethod.ReturnType = KnownTypeReference.Void; currentTypeDefinition.Members.Add(currentMethod); var currentResolvedTypeDef = new DefaultResolvedTypeDefinition(resolveContext, currentTypeDefinition); var projectContent = compilation.MainAssembly.UnresolvedAssembly as IProjectContent; var currentFile = new CSharpUnresolvedFile(); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Mvc"); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Mvc.Ajax"); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Mvc.Html"); currentFile.RootUsingScope.AddSimpleUsing("System.Web.Routing"); currentFile.TopLevelTypeDefinitions.Add(currentTypeDefinition); if (projectContent != null) { compilation = projectContent.AddOrUpdateFiles(currentFile).CreateCompilation(SD.ParserService.GetCurrentSolutionSnapshot()); } var context = new CSharpTypeResolveContext(compilation.MainAssembly, currentFile.RootUsingScope.Resolve(compilation), currentResolvedTypeDef, currentMethod.CreateResolved(resolveContext.WithCurrentTypeDefinition(currentResolvedTypeDef))); return new CSharpResolver(context); }
void classComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { // The selected class was changed. // Update the list of member items to be the list of members of the current class. EntityItem item = classComboBox.SelectedItem as EntityItem; IUnresolvedTypeDefinition selectedClass = item != null ? item.Entity as IUnresolvedTypeDefinition : null; memberItems = new List <EntityItem>(); if (selectedClass != null) { ICompilation compilation = SD.ParserService.GetCompilationForFile(FileName.Create(selectedClass.UnresolvedFile.FileName)); var context = new SimpleTypeResolveContext(compilation.MainAssembly); ITypeDefinition compoundClass = selectedClass.Resolve(context).GetDefinition(); if (compoundClass != null) { var ambience = compilation.GetAmbience(); foreach (var member in compoundClass.Members) { if (member.IsSynthetic) { continue; } bool isInSamePart = string.Equals(member.Region.FileName, selectedClass.Region.FileName, StringComparison.OrdinalIgnoreCase); memberItems.Add(new EntityItem(member, ambience) { IsInSamePart = isInSamePart }); } memberItems.Sort(); if (jumpOnSelectionChange) { SD.AnalyticsMonitor.TrackFeature(GetType(), "JumpToClass"); JumpTo(item, selectedClass.Region); } } } membersComboBox.ItemsSource = memberItems; }
public IList <IAttribute> Resolve(IAssembly currentAssembly) { // TODO: make this a per-assembly cache // CacheManager cache = currentAssembly.Compilation.CacheManager; // IList<IAttribute> result = (IList<IAttribute>)cache.GetShared(this); // if (result != null) // return result; ITypeResolveContext context = new SimpleTypeResolveContext(currentAssembly); BlobReader reader = new BlobReader(blob, currentAssembly); if (reader.ReadByte() != '.') { // should not use UnresolvedSecurityDeclaration for XML secdecls throw new InvalidOperationException(); } ResolveResult securityActionRR = securityAction.Resolve(context); uint attributeCount = reader.ReadCompressedUInt32(); IAttribute[] attributes = new IAttribute[attributeCount]; try { ReadSecurityBlob(reader, attributes, context, securityActionRR); } catch (NotSupportedException ex) { // ignore invalid blobs Debug.WriteLine(ex.ToString()); } for (int i = 0; i < attributes.Length; i++) { if (attributes[i] == null) { attributes[i] = new CecilResolvedAttribute(context, SpecialType.UnknownType); } } return(attributes); // return (IList<IAttribute>)cache.GetOrAddShared(this, attributes); }
public void ParseReflectionName() { var context = new SimpleTypeResolveContext(compilation.MainAssembly); Assert.AreEqual("System.Int32", ReflectionHelper.ParseReflectionName("System.Int32").Resolve(context).ReflectionName); Assert.AreEqual("System.Int32&", ReflectionHelper.ParseReflectionName("System.Int32&").Resolve(context).ReflectionName); Assert.AreEqual("System.Int32*&", ReflectionHelper.ParseReflectionName("System.Int32*&").Resolve(context).ReflectionName); Assert.AreEqual("System.Int32", ReflectionHelper.ParseReflectionName(typeof(int).AssemblyQualifiedName).Resolve(context).ReflectionName); Assert.AreEqual("System.Action`1[[System.String]]", ReflectionHelper.ParseReflectionName("System.Action`1[[System.String]]").Resolve(context).ReflectionName); Assert.AreEqual("System.Action`1[[System.String]]", ReflectionHelper.ParseReflectionName("System.Action`1[[System.String, mscorlib]]").Resolve(context).ReflectionName); Assert.AreEqual("System.Int32[,,][,]", ReflectionHelper.ParseReflectionName(typeof(int[,][,,]).AssemblyQualifiedName).Resolve(context).ReflectionName); Assert.AreEqual("System.Environment+SpecialFolder", ReflectionHelper.ParseReflectionName("System.Environment+SpecialFolder").Resolve(context).ReflectionName); }
public void SkeetEvilOverloadResolution() { // http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx // static void Foo<T>(T? ignored = default(T?)) where T : struct var m1 = MakeUnresolvedMethod(); m1.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.Method, 0, "T") { HasValueTypeConstraint = true }); m1.Parameters.Add(MakeOptionalParameter( NullableType.Create(new TypeParameterReference(EntityType.Method, 0)), "ignored" )); // class ClassConstraint<T> where T : class {} var classConstraint = new DefaultUnresolvedTypeDefinition(string.Empty, "ClassConstraint"); classConstraint.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "T") { HasReferenceTypeConstraint = true }); // static void Foo<T>(ClassConstraint<T> ignored = default(ClassConstraint<T>)) // where T : class var m2 = MakeUnresolvedMethod(); m2.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.Method, 0, "T") { HasReferenceTypeConstraint = true }); m2.Parameters.Add(MakeOptionalParameter( new ParameterizedTypeReference(classConstraint, new[] { new TypeParameterReference(EntityType.Method, 0) }), "ignored" )); // static void Foo<T>() var m3 = MakeUnresolvedMethod(); m3.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.Method, 0, "T")); var context = new SimpleTypeResolveContext(compilation.MainAssembly); IMethod resolvedM1 = (IMethod)m1.CreateResolved(context); IMethod resolvedM2 = (IMethod)m2.CreateResolved(context); IMethod resolvedM3 = (IMethod)m3.CreateResolved(context); // Call: Foo<int>(); OverloadResolution o; o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(int)) }); Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM1)); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM2)); Assert.AreSame(resolvedM1, o.BestCandidate); // Call: Foo<string>(); o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(string)) }); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM1)); Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM2)); Assert.AreSame(resolvedM2, o.BestCandidate); // Call: Foo<int?>(); o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(int?)) }); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM1)); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM2)); Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM3)); Assert.AreSame(resolvedM3, o.BestCandidate); }
public static void AddAttachedProperties(ITypeDefinition td, List<ICompletionItem> result) { var attachedProperties = td.Fields.Where(f => f.IsAttached(true, false)); var unresolvedType = td.Parts.First(); var resolveContext = new SimpleTypeResolveContext(td); result.AddRange( attachedProperties.Select( property => { string propertyName = property.Name.Remove(property.Name.Length - "Property".Length); IUnresolvedProperty item = new DefaultUnresolvedProperty(unresolvedType, propertyName); IMember entity = item.CreateResolved(resolveContext); return new XamlCompletionItem(propertyName, entity); } ) ); }
static void AddAttachedEvents(ITypeDefinition td, List<ICompletionItem> result) { var attachedEvents = td.Fields.Where(f => f.IsAttached(false, true)); var unresolvedType = td.Parts.First(); var resolveContext = new SimpleTypeResolveContext(td); result.AddRange( attachedEvents.Select( field => { string eventName = GetEventNameFromField(field); IUnresolvedEvent item = new DefaultUnresolvedEvent(unresolvedType, eventName); IMember entity = item.CreateResolved(resolveContext); return new XamlCompletionItem(eventName, entity); } ) ); }
internal static bool IsPotentialClosure(ILTransformContext context, NewObj inst) { var decompilationContext = new SimpleTypeResolveContext(context.Function.Ancestors.OfType <ILFunction>().Last().Method); return(IsPotentialClosure(decompilationContext.CurrentTypeDefinition, inst.Method.DeclaringTypeDefinition)); }
internal static bool IsPotentialClosure(ILTransformContext context, ITypeDefinition potentialDisplayClass) { var decompilationContext = new SimpleTypeResolveContext(context.Function.Ancestors.OfType <ILFunction>().Last().Method); return(IsPotentialClosure(decompilationContext.CurrentTypeDefinition, potentialDisplayClass)); }
bool IsMonoNestedCaptureScope(ITypeDefinition closureType) { var decompilationContext = new SimpleTypeResolveContext(context.Function.Method); return(closureType.Fields.Any(f => IsPotentialClosure(decompilationContext.CurrentTypeDefinition, f.ReturnType.GetDefinition()))); }
/// <summary> /// mcs likes to optimize closures in yield state machines away by moving the captured variables' fields into the state machine type, /// We construct a <see cref="DisplayClass"/> that spans the whole method body. /// </summary> bool HandleMonoStateMachine(ILFunction currentFunction, ILVariable thisVariable, SimpleTypeResolveContext decompilationContext, ILFunction nestedFunction) { if (!(nestedFunction.StateMachineCompiledWithMono && thisVariable.IsThis())) { return(false); } // Special case for Mono-compiled yield state machines ITypeDefinition closureType = thisVariable.Type.GetDefinition(); if (!(closureType != decompilationContext.CurrentTypeDefinition && IsPotentialClosure(decompilationContext.CurrentTypeDefinition, closureType, allowTypeImplementingInterfaces: true))) { return(false); } var displayClass = new DisplayClass { IsMono = true, Initializer = nestedFunction.Body, Variable = thisVariable, Definition = thisVariable.Type.GetDefinition(), Variables = new Dictionary <IField, ILVariable>(), CaptureScope = (BlockContainer)nestedFunction.Body }; displayClasses.Add(thisVariable, displayClass); foreach (var stateMachineVariable in nestedFunction.Variables) { if (stateMachineVariable.StateMachineField == null || displayClass.Variables.ContainsKey(stateMachineVariable.StateMachineField)) { continue; } displayClass.Variables.Add(stateMachineVariable.StateMachineField, stateMachineVariable); } if (!currentFunction.Method.IsStatic && FindThisField(out var thisField)) { var thisVar = currentFunction.Variables .FirstOrDefault(t => t.IsThis() && t.Type.GetDefinition() == decompilationContext.CurrentTypeDefinition); if (thisVar == null) { thisVar = new ILVariable(VariableKind.Parameter, decompilationContext.CurrentTypeDefinition, -1) { Name = "this" }; currentFunction.Variables.Add(thisVar); } displayClass.Variables.Add(thisField, thisVar); } return(true); bool FindThisField(out IField foundField) { foundField = null; foreach (var field in closureType.GetFields(f2 => !f2.IsStatic && !displayClass.Variables.ContainsKey(f2) && f2.Type.GetDefinition() == decompilationContext.CurrentTypeDefinition)) { thisField = field; return(true); } return(false); } }
public IList<IAttribute> Resolve(IAssembly currentAssembly) { // TODO: make this a per-assembly cache // CacheManager cache = currentAssembly.Compilation.CacheManager; // IList<IAttribute> result = (IList<IAttribute>)cache.GetShared(this); // if (result != null) // return result; var context = new SimpleTypeResolveContext(currentAssembly); var reader = new BlobReader(blob, currentAssembly); if (reader.ReadByte() != '.') { // should not use UnresolvedSecurityDeclaration for XML secdecls throw new InvalidOperationException(); } var securityActionRR = securityAction.Resolve(context); uint attributeCount = reader.ReadCompressedUInt32(); var attributes = new IAttribute[attributeCount]; try { ReadSecurityBlob(reader, attributes, context, securityActionRR); } catch (NotSupportedException ex) { // ignore invalid blobs Debug.WriteLine(ex.ToString()); } for (int i = 0; i < attributes.Length; i++) { if (attributes[i] == null) attributes[i] = new CecilResolvedAttribute(context, SpecialType.UnknownType); } return attributes; // return (IList<IAttribute>)cache.GetOrAddShared(this, attributes); }
public void AnErrorIsIssuedIfTheMainMethodIsNotImplementedAsANormalMethod() { var er = new MockErrorReporter(); var invoker = new OOPEmulatorInvoker(new MockOOPEmulator(), new MockMetadataImporter { GetMethodSemantics = m => m.Name == "Main" ? MethodScriptSemantics.InlineCode("X") : MethodScriptSemantics.NormalMethod(m.Name) }, er); var cu = new CSharpParser().Parse(@"class MyClass { public void Main() { } }", "file.cs").ToTypeSystem(); var compilation = new CSharpProjectContent().AddOrUpdateFiles(new IUnresolvedFile[] { cu }).AddAssemblyReferences(new[] { MinimalCorlib.Instance }).CreateCompilation(); var typeResolveContext = new SimpleTypeResolveContext(compilation.MainAssembly); invoker.Process(cu.GetAllTypeDefinitions().Select(t => new JsClass(t.Resolve(typeResolveContext).GetDefinition())).ToList<JsType>(), compilation.FindType(new FullTypeName("MyClass")).GetMethods().Single(m => m.Name == "Main")); Assert.That(er.AllMessages, Has.Count.EqualTo(1)); Assert.That(er.AllMessages.Any(m => m.Code == 7801 && (string)m.Args[0] == "MyClass.Main")); }
IMember FindAttachedMember(IType type, string propertyName, out IMember underlyingMember) { underlyingMember = type .GetMethods(m => m.IsPublic && m.IsStatic && m.Parameters.Count == 1 && m.Name == "Get" + propertyName) .FirstOrDefault(); var definition = type.GetDefinition(); if (definition != null) { ITypeResolveContext localContext = new SimpleTypeResolveContext(definition); if (underlyingMember != null) return new DefaultUnresolvedProperty { Name = propertyName } .CreateResolved(localContext); underlyingMember = type .GetMethods(m => m.IsPublic && m.IsStatic && m.Parameters.Count == 2 && m.Name == "Add" + propertyName + "Handler") .FirstOrDefault(); if (underlyingMember != null) return new DefaultUnresolvedEvent { Name = propertyName } .CreateResolved(localContext); } return null; }
public void SkeetEvilOverloadResolution() { // http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx // static void Foo<T>(T? ignored = default(T?)) where T : struct var m1 = MakeUnresolvedMethod(); m1.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.Method, 0, "T") { HasValueTypeConstraint = true }); m1.Parameters.Add(MakeOptionalParameter( NullableType.Create(new TypeParameterReference(SymbolKind.Method, 0)), "ignored" )); // class ClassConstraint<T> where T : class {} var classConstraint = new DefaultUnresolvedTypeDefinition(string.Empty, "ClassConstraint"); classConstraint.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.TypeDefinition, 0, "T") { HasReferenceTypeConstraint = true }); // static void Foo<T>(ClassConstraint<T> ignored = default(ClassConstraint<T>)) // where T : class var m2 = MakeUnresolvedMethod(); m2.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.Method, 0, "T") { HasReferenceTypeConstraint = true }); m2.Parameters.Add(MakeOptionalParameter( new ParameterizedTypeReference(classConstraint, new[] { new TypeParameterReference(SymbolKind.Method, 0) }), "ignored" )); // static void Foo<T>() var m3 = MakeUnresolvedMethod(); m3.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.Method, 0, "T")); ICompilation compilation = TypeSystemHelper.CreateCompilation(classConstraint); var context = new SimpleTypeResolveContext(compilation.MainAssembly); IMethod resolvedM1 = (IMethod)m1.CreateResolved(context); IMethod resolvedM2 = (IMethod)m2.CreateResolved(context); IMethod resolvedM3 = (IMethod)m3.CreateResolved(context); // Call: Foo<int>(); OverloadResolution o; o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(int)) }); Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM1)); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM2)); Assert.AreSame(resolvedM1, o.BestCandidate); // Call: Foo<string>(); o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(string)) }); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM1)); Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM2)); Assert.AreSame(resolvedM2, o.BestCandidate); // Call: Foo<int?>(); o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(int?)) }); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM1)); Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM2)); Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM3)); Assert.AreSame(resolvedM3, o.BestCandidate); }
void ProcessUpdates() { var compilation = SD.ParserService.GetCompilation(project); var context = new SimpleTypeResolveContext(compilation.MainAssembly); foreach (var dirtyTypeDef in dirtyTypeDefinitions) { ITypeDefinition typeDef = compilation.MainAssembly.GetTypeDefinition(dirtyTypeDef.Namespace, dirtyTypeDef.Name, dirtyTypeDef.TypeParameterCount); UpdateType(dirtyTypeDef, typeDef); } dirtyTypeDefinitions.Clear(); }
IMethod MakeMethod(params object[] parameterTypesOrDefaultValues) { var context = new SimpleTypeResolveContext(compilation.MainAssembly); return (IMethod)MakeUnresolvedMethod(parameterTypesOrDefaultValues).CreateResolved(context); }
IMethod MakeMethod(params object[] parameterTypesOrDefaultValues) { var context = new SimpleTypeResolveContext(compilation.MainAssembly); return((IMethod)MakeUnresolvedMethod(parameterTypesOrDefaultValues).CreateResolved(context)); }
public void ArrayOfTypeParameter() { var context = new SimpleTypeResolveContext(compilation.MainAssembly); Assert.AreEqual("`0[,]", ReflectionHelper.ParseReflectionName("`0[,]").Resolve(context).ReflectionName); }
internal static bool IsPotentialClosure(ILTransformContext context, NewObj inst) { var decompilationContext = new SimpleTypeResolveContext(context.TypeSystem.Resolve(context.Function.Method)); return(IsPotentialClosure(decompilationContext.CurrentTypeDefinition, inst.Method.DeclaringTypeDefinition)); }