public MemberCollectorTests() { _memberCollector = new CollectAllMembers.MemberCollector(); #region Initialize _compilation var referencedAssemblies = new Type[] { typeof (System.Exception), typeof (ICollection), typeof (IList<>) } .Select(t => t.Assembly.Location); IProjectContent dummyProject = new CSharpProjectContent(); dummyProject = dummyProject.AddAssemblyReferences( referencedAssemblies .Distinct() .Select( a => new CecilLoader().LoadAssemblyFile(a))); _compilation = new DefaultSolutionSnapshot(new []{dummyProject}) .GetCompilation(dummyProject); #endregion }
void Init(string program) { var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var syntaxTree = SyntaxTree.Parse(program, "program.cs"); compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation(); typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault(); }
public static void AddUsings(CodeElementsList<CodeElement> codeElements, UsingScope usingScope, ICompilation compilation) { var resolvedUsingScope = usingScope.Resolve(compilation); foreach (var ns in resolvedUsingScope.Usings) { codeElements.Add(new CodeImport(ns.FullName)); } }
public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, CompilerOptions options) { _errorReporter = errorReporter; _compilation = compilation; _minimizeNames = options.MinimizeScript; _systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object); _typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>(); _delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>(); _instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>(); _propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>(); _fieldSemantics = new Dictionary<IField, FieldScriptSemantics>(); _eventSemantics = new Dictionary<IEvent, EventScriptSemantics>(); _constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>(); _propertyBackingFieldNames = new Dictionary<IProperty, string>(); _eventBackingFieldNames = new Dictionary<IEvent, string>(); _backingFieldCountPerType = new Dictionary<ITypeDefinition, int>(); _internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>(); _ignoredMembers = new HashSet<IMember>(); var sna = compilation.MainAssembly.AssemblyAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(ScriptNamespaceAttribute).FullName); if (sna != null) { var data = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(sna); if (data.Name == null || (data.Name != "" && !data.Name.IsValidNestedJavaScriptIdentifier())) { Message(Messages._7002, sna.Region, "assembly"); } } }
void Init(string code) { syntaxTree = SyntaxTree.Parse(code, "test.cs"); unresolvedFile = syntaxTree.ToTypeSystem(); compilation = TypeSystemHelper.CreateCompilation(unresolvedFile); findReferences = new FindReferences(); }
IEnumerable<INamespace> ResolveNamespaces(ICompilation compilation) { IType xmlnsDefinition = compilation.FindType(typeof(System.Windows.Markup.XmlnsDefinitionAttribute)); if (XmlNamespace.StartsWith("clr-namespace:", StringComparison.Ordinal)) { string name = XmlNamespace.Substring("clr-namespace:".Length); IAssembly asm = compilation.MainAssembly; int asmIndex = name.IndexOf(";assembly=", StringComparison.Ordinal); if (asmIndex >= 0) { string asmName = name.Substring(asmIndex + ";assembly=".Length); asm = compilation.ReferencedAssemblies.FirstOrDefault(a => a.AssemblyName == asmName) ?? compilation.MainAssembly; name = name.Substring(0, asmIndex); } string[] parts = name.Split('.'); var @namespace = FindNamespace(asm, parts); if (@namespace != null) yield return @namespace; } else { foreach (IAssembly asm in compilation.Assemblies) { foreach (IAttribute attr in asm.AssemblyAttributes) { if (xmlnsDefinition.Equals(attr.AttributeType) && attr.PositionalArguments.Count == 2) { string xmlns = attr.PositionalArguments[0].ConstantValue as string; if (xmlns != XmlNamespace) continue; string ns = attr.PositionalArguments[1].ConstantValue as string; if (ns == null) continue; var @namespace = FindNamespace(asm, ns.Split('.')); if (@namespace != null) yield return @namespace; } } } } }
public DelegateDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType delegateType) : base (ext, startOffset) { compilation = ext.UnresolvedFileCompilation; file = ext.CSharpUnresolvedFile; // this.delegateType = delegateType; this.delegateMethod = delegateType.GetDelegateInvokeMethod (); }
public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, IAttributeStore attributeStore, CompilerOptions options) { _errorReporter = errorReporter; _compilation = compilation; _attributeStore = attributeStore; _minimizeNames = options.MinimizeScript; _systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object); _typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>(); _delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>(); _instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>(); _propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>(); _fieldSemantics = new Dictionary<IField, FieldScriptSemantics>(); _eventSemantics = new Dictionary<IEvent, EventScriptSemantics>(); _constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>(); _propertyBackingFieldNames = new Dictionary<IProperty, Tuple<string, bool>>(); _eventBackingFieldNames = new Dictionary<IEvent, Tuple<string, bool>>(); _backingFieldCountPerType = new Dictionary<ITypeDefinition, int>(); _internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>(); _ignoredMembers = new HashSet<IMember>(); var sna = _attributeStore.AttributesFor(compilation.MainAssembly).GetAttribute<ScriptNamespaceAttribute>(); if (sna != null) { if (sna.Name == null || (sna.Name != "" && !sna.Name.IsValidNestedJavaScriptIdentifier())) { Message(Messages._7002, default(DomRegion), "assembly"); } } }
public ResolveResult Resolve(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken) { var decompiledParseInfo = parseInfo as ILSpyFullParseInformation; if (decompiledParseInfo == null) throw new ArgumentException("ParseInfo does not have SyntaxTree"); return ResolveAtLocation.Resolve(compilation, null, decompiledParseInfo.SyntaxTree, location, cancellationToken); }
public TypeInference(ICompilation compilation) { if (compilation == null) throw new ArgumentNullException("compilation"); this.compilation = compilation; this.conversions = CSharpConversions.Get(compilation); }
internal TypeInference(ICompilation compilation, CSharpConversions conversions) { Debug.Assert(compilation != null); Debug.Assert(conversions != null); this.compilation = compilation; this.conversions = conversions; }
public SimpleTypeResolveContext(IAssembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); this.compilation = assembly.Compilation; this.currentAssembly = assembly; }
private SimpleTypeResolveContext(ICompilation compilation, IAssembly currentAssembly, ITypeDefinition currentTypeDefinition, IMember currentMember) { this.compilation = compilation; this.currentAssembly = currentAssembly; this.currentTypeDefinition = currentTypeDefinition; this.currentMember = currentMember; }
/// <summary> /// Determines if the given type is defined in source code, ie is part of the project /// </summary> public static bool IsDefinedInSource (this ITypeDefinition type, ICompilation compilation) { if (compilation == null) return false; return type.ParentAssembly.UnresolvedAssembly.Location == compilation.MainAssembly.UnresolvedAssembly.Location; }
public static string GetGenericMethodConstraints(this IMethod method, ICompilation compilation) { var sb = new StringBuilder(); foreach (var typeParam in method.Parts.SelectMany(p => p.TypeParameters.OfType<DefaultUnresolvedTypeParameter>())) { var resolvedParts = new List<string>(); if (typeParam.HasDefaultConstructorConstraint) resolvedParts.Add("new()"); if (typeParam.HasReferenceTypeConstraint) resolvedParts.Add("class"); if (typeParam.HasValueTypeConstraint) resolvedParts.Add("struct"); resolvedParts.AddRange( typeParam.Constraints.Resolve(compilation.TypeResolveContext) .Select(x => x.GetOriginalFullName())); if (resolvedParts.Any()) sb.Append("where ").Append(typeParam.Name).Append(" : ").Append(string.Join(",", resolvedParts)); } return sb.ToString(); }
void Init(string code) { compilationUnit = new CSharpParser().Parse(new StringReader(code), "test.cs"); parsedFile = compilationUnit.ToTypeSystem(); compilation = TypeSystemHelper.CreateCompilation(parsedFile); findReferences = new FindReferences(); }
public IndexerParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType type, IEnumerable<IProperty> indexers, AstNode resolvedExpression) : base (ext, startOffset) { compilation = ext.UnresolvedFileCompilation; file = ext.CSharpUnresolvedFile; // this.resolvedExpression = resolvedExpression; this.indexers = new List<IProperty> (indexers); }
void Init(string program) { var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var cu = new CSharpParser().Parse(new StringReader(program), "program.cs"); compilation = pc.UpdateProjectContent(null, cu.ToTypeSystem()).CreateCompilation(); typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault(); }
public CSharpResolver(ICompilation compilation) { if (compilation == null) throw new ArgumentNullException("compilation"); this.compilation = compilation; this.conversions = Conversions.Get(compilation); this.context = new CSharpTypeResolveContext(compilation.MainAssembly); }
public RuntimeLibrary(IMetadataImporter metadataImporter, IErrorReporter errorReporter, ICompilation compilation, INamer namer) { _metadataImporter = metadataImporter; _errorReporter = errorReporter; _compilation = compilation; _namer = namer; _omitDowncasts = MetadataUtils.OmitDowncasts(compilation); _omitNullableChecks = MetadataUtils.OmitNullableChecks(compilation); }
public SimpleTypeResolveContext(ITypeDefinition typeDefinition) { if (typeDefinition == null) throw new ArgumentNullException("typeDefinition"); this.compilation = typeDefinition.Compilation; this.currentAssembly = typeDefinition.ParentAssembly; this.currentTypeDefinition = typeDefinition; }
protected OOPEmulator CreateEmulator(ICompilation compilation, IErrorReporter errorReporter = null) { var n = new Namer(); errorReporter = errorReporter ?? new MockErrorReporter(); var md = new MetadataImporter(errorReporter, compilation, new CompilerOptions()); md.Prepare(compilation.GetAllTypeDefinitions()); var rtl = new RuntimeLibrary(md, errorReporter, compilation, n); return new OOPEmulator(compilation, md, rtl, n, new MockLinker(), errorReporter); }
public ExpressoResolver(ICompilation compilation) { if(compilation == null) throw new ArgumentNullException("compilation"); this.compilation = compilation; context = new ExpressoTypeResolveContext(compilation.MainAssembly); }
public SimpleTypeResolveContext(IEntity entity) { if (entity == null) throw new ArgumentNullException("entity"); this.compilation = entity.Compilation; this.currentAssembly = entity.ParentAssembly; this.currentTypeDefinition = (entity as ITypeDefinition) ?? entity.DeclaringTypeDefinition; this.currentMember = entity as IMember; }
public CSharpAmbienceTests() { ambience = new CSharpAmbience(); mscorlib = CecilLoaderTests.Mscorlib; var loader = new CecilLoader(); loader.IncludeInternalMembers = true; myLib = loader.LoadAssemblyFile(typeof(CSharpAmbienceTests).Assembly.Location); compilation = new SimpleCompilation(myLib, mscorlib); }
public void SetUp() { snippetGenerator = new SnippetGenerator(true); var loader = new CecilLoader(); loader.IncludeInternalMembers = true; myLib = loader.LoadAssemblyFile(typeof(SnippetGenerationTests).Assembly.Location); mscorlib = loader.LoadAssemblyFile(typeof(object).Assembly.Location); compilation = new SimpleCompilation(myLib, mscorlib); }
public void AddCompilation(IProjectContent project, ICompilation compilation) { if (project == null) throw new ArgumentNullException("project"); if (compilation == null) throw new ArgumentNullException("compilation"); if (!dictionary.TryAdd(project, compilation)) throw new InvalidOperationException(); }
private void RunAutomaticMetadataAttributeAppliers(IAttributeStore store, ICompilation compilation) { var processors = new IAutomaticMetadataAttributeApplier[] { new MakeMembersWithScriptableAttributesReflectable(store) }; foreach (var p in processors) { foreach (var asm in compilation.Assemblies) p.Process(asm); foreach (var t in compilation.GetAllTypeDefinitions()) p.Process(t); } }
public CompilationChanges(ICompilation original, ICompilation comparedTo, ContractChanges changes) { Contract.Requires(original != null || comparedTo != null); Contract.Requires(changes != null); Original = original; ComparedTo = comparedTo; Changes = changes; }
/// <summary> /// Gets the T in Task<T>. /// Returns void for non-generic Task. /// Any other type is returned unmodified. /// </summary> public static IType UnpackTask(ICompilation compilation, IType type) { if (!IsTask(type)) return type; if (type.TypeParameterCount == 0) return compilation.FindType(KnownTypeCode.Void); else return type.TypeArguments[0]; }
public TypeProvider(ICompilation compilation) { this.compilation = compilation; }
public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false) { return(CreateTooltipInformation(compilation, file, null, textEditorData, formattingPolicy, entity, smartWrap, createFooter)); }
private CSharpCompletionContext(ITextEditor editor, IList <string> conditionalSymbols, ICompilation compilation, IProjectContent projectContent, IDocument document, CSharpUnresolvedFile unresolvedFile, TextLocation caretLocation) { Debug.Assert(editor != null); Debug.Assert(unresolvedFile != null); Debug.Assert(compilation != null); Debug.Assert(projectContent != null); Debug.Assert(document != null); this.Editor = editor; this.Document = document; this.ConditionalSymbols = conditionalSymbols; this.Compilation = compilation; this.ProjectContent = projectContent; this.TypeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(compilation, caretLocation); this.CompletionContextProvider = new DefaultCompletionContextProvider(document, unresolvedFile); this.CompletionContextProvider.ConditionalSymbols.AddRange(conditionalSymbols); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceStatusViewComponent"/> class. /// </summary> /// <param name="compilation"> The service compilation service. </param> /// <param name="repository"> The service Repository Service. </param> public ServiceStatusViewComponent(ICompilation compilation, IRepository repository) { _compilation = compilation; _repository = repository; }
public static IType ApplyAttributesToType( IType inputType, ICompilation compilation, SRM.CustomAttributeHandleCollection?attributes, SRM.MetadataReader metadata, TypeSystemOptions options, bool typeChildrenOnly = false) { bool hasDynamicAttribute = false; bool[] dynamicAttributeData = null; string[] tupleElementNames = null; bool hasNullableAttribute = false; Nullability nullability = Nullability.Oblivious; Nullability[] nullableAttributeData = null; const TypeSystemOptions relevantOptions = TypeSystemOptions.Dynamic | TypeSystemOptions.Tuple | TypeSystemOptions.NullabilityAnnotations; if (attributes != null && (options & relevantOptions) != 0) { foreach (var attrHandle in attributes.Value) { var attr = metadata.GetCustomAttribute(attrHandle); var attrType = attr.GetAttributeType(metadata); if ((options & TypeSystemOptions.Dynamic) != 0 && attrType.IsKnownType(metadata, KnownAttribute.Dynamic)) { hasDynamicAttribute = true; var ctor = attr.DecodeValue(Metadata.MetadataExtensions.minimalCorlibTypeProvider); if (ctor.FixedArguments.Length == 1) { var arg = ctor.FixedArguments[0]; if (arg.Value is ImmutableArray <SRM.CustomAttributeTypedArgument <IType> > values && values.All(v => v.Value is bool)) { dynamicAttributeData = values.SelectArray(v => (bool)v.Value); } } } else if ((options & TypeSystemOptions.Tuple) != 0 && attrType.IsKnownType(metadata, KnownAttribute.TupleElementNames)) { var ctor = attr.DecodeValue(Metadata.MetadataExtensions.minimalCorlibTypeProvider); if (ctor.FixedArguments.Length == 1) { var arg = ctor.FixedArguments[0]; if (arg.Value is ImmutableArray <SRM.CustomAttributeTypedArgument <IType> > values && values.All(v => v.Value is string || v.Value == null)) { tupleElementNames = values.SelectArray(v => (string)v.Value); } } } else if ((options & TypeSystemOptions.NullabilityAnnotations) != 0 && attrType.IsKnownType(metadata, KnownAttribute.Nullable)) { hasNullableAttribute = true; var ctor = attr.DecodeValue(Metadata.MetadataExtensions.minimalCorlibTypeProvider); if (ctor.FixedArguments.Length == 1) { var arg = ctor.FixedArguments[0]; if (arg.Value is ImmutableArray <SRM.CustomAttributeTypedArgument <IType> > values && values.All(v => v.Value is byte b && b <= 2)) { nullableAttributeData = values.SelectArray(v => (Nullability)(byte)v.Value); } else if (arg.Value is byte b && b <= 2) { nullability = (Nullability)(byte)arg.Value; } } } } }
/// <summary> /// Gets all top level type definitions in the compilation. /// This may include types from referenced assemblies that are not accessible in the main assembly. /// </summary> public static IEnumerable <ITypeDefinition> GetTopLevelTypeDefinitions(this ICompilation compilation) { return(compilation.Assemblies.SelectMany(a => a.TopLevelTypeDefinitions)); }
/// <summary> /// Retrieves a built-in type using the specified type code. /// </summary> public static IType FindType(this ICompilation compilation, TypeCode typeCode) { return(compilation.FindType((KnownTypeCode)typeCode)); }
/// <summary> /// Initializes a new instance of the CompileController /// </summary> public CompileController(ILogger <CompileController> logger, ICompilation compilation) { _logger = logger; _compilation = compilation; }
public static CodeGenerator CreateCodeGenerator(this TextEditorData data, ICompilation compilation) { return(CodeGenerator.CreateGenerator(data, compilation)); }
/// <summary> /// Imports a member from another compilation. /// </summary> public static IProperty Import(this ICompilation compilation, IProperty property) { return((IProperty)compilation.Import((IMember)property)); }
/// <summary> /// Imports a member from another compilation. /// </summary> public static IEvent Import(this ICompilation compilation, IEvent ev) { return((IEvent)compilation.Import((IMember)ev)); }
public virtual void SetUp() { project = new CSharpProjectContent().AddAssemblyReferences(new [] { mscorlib, CecilLoaderTests.SystemCore }); compilation = project.CreateCompilation(); }
/// <summary> /// Imports a member from another compilation. /// </summary> public static IMethod Import(this ICompilation compilation, IMethod method) { return((IMethod)compilation.Import((IMember)method)); }
private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return(1); } if (_inputFilePaths.Count == 0) { throw new CommandLineException("No input files specified"); } if (_outputFilePath == null) { throw new CommandLineException("Output filename must be specified (/out <file>)"); } // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; var typeSystemContext = new CompilerTypeSystemContext(new TargetDetails(_targetArchitecture, _targetOS), genericsMode); typeSystemContext.InputFilePaths = _inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List <ICompilationRootProvider> compilationRoots = new List <ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) { throw new Exception("Multiple EXE modules"); } entrypointModule = module; } compilationRoots.Add(new ExportedMethodsRootProvider(module)); } if (entrypointModule != null) { LibraryInitializers libraryInitializers = new LibraryInitializers(typeSystemContext, _isCppCodegen); compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods)); } if (_multiFile) { List <EcmaModule> inputModules = new List <EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } if (entrypointModule == null) { compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); } else { compilationGroup = new MultiFileLeafCompilationModuleGroup(typeSystemContext, inputModules); } } else { if (entrypointModule == null) { throw new Exception("No entrypoint module"); } compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isCppCodegen) { builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); } else { builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); } var logger = _isVerbose ? new Logger(Console.Out, true) : Logger.Null; DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); ICompilation compilation = builder .UseBackendOptions(_codegenOptions) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfo(_enableDebugInfo) .ToCompilation(); compilation.Compile(_outputFilePath); if (_dgmlLogFileName != null) { compilation.WriteDependencyLog(_dgmlLogFileName); } return(0); }
/// <summary> /// Retrieves the specified type in this compilation. /// Returns <see cref="SpecialType.UnknownType"/> if the type cannot be found in this compilation. /// </summary> /// <remarks> /// This method cannot be used with open types; all type parameters will be substituted /// with <see cref="SpecialType.UnknownType"/>. /// </remarks> public static IType FindType(this ICompilation compilation, Type type) { return(type.ToTypeReference().Resolve(compilation.TypeResolveContext)); }
public TypeProvider(MetadataModule module) { this.module = module; this.compilation = module.Compilation; }
public static unsafe SRM.BlobReader GetInitialValue(this FieldDefinition field, PEReader pefile, ICompilation typeSystem) { if (!field.HasFlag(FieldAttributes.HasFieldRVA)) { return(default);
public ResolveResult ResolveSnippet(ParseInformation parseInfo, TextLocation location, string codeSnippet, ICompilation compilation, CancellationToken cancellationToken) { var csParseInfo = parseInfo as AlFullParseInformation; if (csParseInfo == null) throw new ArgumentException("Parse info does not have SyntaxTree"); AlAstResolver contextResolver = new AlAstResolver(compilation, csParseInfo.SyntaxTree, csParseInfo.UnresolvedFile); var node = csParseInfo.SyntaxTree.GetNodeAt(location); AlResolver context; if (node != null) context = contextResolver.GetResolverStateAfter(node, cancellationToken); else context = new AlResolver(compilation); AlParser parser = new AlParser(); var expr = parser.ParseExpression(codeSnippet); if (parser.HasErrors) return new ErrorResolveResult(SpecialType.UnknownType, PrintErrorsAsString(parser.Errors), TextLocation.Empty); AlAstResolver snippetResolver = new AlAstResolver(context, expr); return snippetResolver.Resolve(expr, cancellationToken); }
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")); 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); }
public ICodeContext ResolveContext(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken) { var csParseInfo = parseInfo as AlFullParseInformation; if (csParseInfo == null) throw new ArgumentException("Parse info does not have SyntaxTree"); AlUnresolvedFile unresolvedFile = csParseInfo.UnresolvedFile; var projectContents = compilation.Assemblies.Select(asm => asm.UnresolvedAssembly).OfType<IProjectContent>().ToList(); if (projectContents.All(pc => pc.GetFile(unresolvedFile.FileName) != unresolvedFile)) unresolvedFile = null; var syntaxTree = csParseInfo.SyntaxTree; var node = syntaxTree.GetNodeAt(location); if (node == null) return null; // null result is allowed; the parser service will substitute a dummy context var resolver = new AlAstResolver(compilation, syntaxTree, unresolvedFile); return resolver.GetResolverStateBefore(node); }
/// <summary> /// Gets all type definitions in the compilation. /// This may include types from referenced assemblies that are not accessible in the main assembly. /// </summary> public static IEnumerable <ITypeDefinition> GetAllTypeDefinitions(this ICompilation compilation) { return(compilation.Modules.SelectMany(a => a.TypeDefinitions)); }
private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return(1); } if (_outputFilePath == null) { throw new CommandLineException("Output filename must be specified (/out <file>)"); } // // Set target Architecture and OS // if (_targetArchitectureStr != null) { if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X86; } else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X64; } else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM; } else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARMEL; } else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM64; } else if (_targetArchitectureStr.Equals("wasm", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.Wasm32; _isWasmCodegen = true; } else { throw new CommandLineException("Target architecture is not supported"); } } if (_targetOSStr != null) { if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Windows; } else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Linux; } else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.OSX; } else { throw new CommandLineException("Target OS is not supported"); } } if (_isWasmCodegen) { _targetArchitecture = TargetArchitecture.Wasm32; } else if (_isCppCodegen) { _targetArchitecture = TargetArchitecture.Cpp64; } // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics || (!_isCppCodegen && !_isWasmCodegen) ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; // TODO: compiler switch for SIMD support? var simdVectorLength = (_isCppCodegen || _isWasmCodegen) ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, simdVectorLength); var typeSystemContext = new CompilerTypeSystemContext(targetDetails, genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary <string, string> inputFilePaths = new Dictionary <string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) { throw new CommandLineException("No input files specified"); } // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List <ICompilationRootProvider> compilationRoots = new List <ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) { throw new Exception("Multiple EXE modules"); } entrypointModule = module; } compilationRoots.Add(new ExportedMethodsRootProvider(module)); } if (entrypointModule != null) { compilationRoots.Add(new MainMethodRootProvider(entrypointModule, CreateInitializerList(typeSystemContext))); } if (_multiFile) { List <EcmaModule> inputModules = new List <EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); } else { if (entrypointModule == null && !_nativeLib) { throw new Exception("No entrypoint module"); } compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); compilationGroup = new SingleFileCompilationModuleGroup(); } if (_nativeLib) { // Set owning module of generated native library startup method to compiler generated module, // to ensure the startup method is included in the object file during multimodule mode build compilationRoots.Add(new NativeLibraryInitializerRootProvider(typeSystemContext.GeneratedAssembly, CreateInitializerList(typeSystemContext))); } if (_rdXmlFilePaths.Count > 0) { Console.WriteLine("Warning: RD.XML processing will change before release (https://github.com/dotnet/corert/issues/5001)"); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isWasmCodegen) { builder = new WebAssemblyCodegenCompilationBuilder(typeSystemContext, compilationGroup); } else if (_isCppCodegen) { builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); } else { builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); } var stackTracePolicy = _emitStackTraceData ? (StackTraceEmissionPolicy) new EcmaMethodStackTraceEmissionPolicy() : new NoStackTraceEmissionPolicy(); MetadataBlockingPolicy mdBlockingPolicy = _noMetadataBlocking ? (MetadataBlockingPolicy) new NoBlockingPolicy() : new BlockedInternalsBlockingPolicy(); UsageBasedMetadataManager metadataManager = new UsageBasedMetadataManager( compilationGroup, typeSystemContext, mdBlockingPolicy, _metadataLogFileName, stackTracePolicy); // Unless explicitly opted in at the command line, we enable scanner for retail builds by default. // We don't do this for CppCodegen and Wasm, because those codegens are behind. // We also don't do this for multifile because scanner doesn't simulate inlining (this would be // fixable by using a CompilationGroup for the scanner that has a bigger worldview, but // let's cross that bridge when we get there). bool useScanner = _useScanner || (_optimizationMode != OptimizationMode.None && !_isCppCodegen && !_isWasmCodegen && !_multiFile); useScanner &= !_noScanner; bool supportsReflection = !_isWasmCodegen && !_isCppCodegen && _systemModuleName == DefaultSystemModule; MetadataManager compilationMetadataManager = supportsReflection ? metadataManager : (MetadataManager) new EmptyMetadataManager(typeSystemContext); ILScanResults scanResults = null; if (useScanner) { ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder() .UseCompilationRoots(compilationRoots) .UseMetadataManager(metadataManager); if (_scanDgmlLogFileName != null) { scannerBuilder.UseDependencyTracking(_generateFullScanDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); } IILScanner scanner = scannerBuilder.ToILScanner(); scanResults = scanner.Scan(); compilationMetadataManager = metadataManager.ToAnalysisBasedMetadataManager(); } var logger = new Logger(Console.Out, _isVerbose); DebugInformationProvider debugInfoProvider = _enableDebugInfo ? (_ilDump == null ? new DebugInformationProvider() : new ILAssemblyGeneratingMethodDebugInfoProvider(_ilDump, new EcmaOnlyDebugInformationProvider())) : new NullDebugInformationProvider(); DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); compilationRoots.Add(compilationMetadataManager); builder .UseBackendOptions(_codegenOptions) .UseMetadataManager(compilationMetadataManager) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfoProvider(debugInfoProvider); if (scanResults != null) { // If we have a scanner, feed the vtable analysis results to the compilation. // This could be a command line switch if we really wanted to. builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo()); // If we have a scanner, feed the generic dictionary results to the compilation. // This could be a command line switch if we really wanted to. builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo()); // If we feed any outputs of the scanner into the compilation, it's essential // we use scanner's devirtualization manager. It prevents optimizing codegens // from accidentally devirtualizing cases that can never happen at runtime // (e.g. devirtualizing a method on a type that never gets allocated). builder.UseDevirtualizationManager(scanResults.GetDevirtualizationManager()); } ICompilation compilation = builder.ToCompilation(); ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null; CompilationResults compilationResults = compilation.Compile(_outputFilePath, dumper); if (_exportsFile != null) { ExportsFileWriter defFileWriter = new ExportsFileWriter(typeSystemContext, _exportsFile); foreach (var compilationRoot in compilationRoots) { if (compilationRoot is ExportedMethodsRootProvider provider) { defFileWriter.AddExportedMethods(provider.ExportedMethods); } } defFileWriter.EmitExportedMethods(); } if (_dgmlLogFileName != null) { compilationResults.WriteDependencyLog(_dgmlLogFileName); } if (scanResults != null) { SimdHelper simdHelper = new SimdHelper(); if (_scanDgmlLogFileName != null) { scanResults.WriteDependencyLog(_scanDgmlLogFileName); } // If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable. // We are going to check this two ways: // 1. The methods and types generated during compilation are a subset of method and types scanned // 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only). // Check that methods and types generated during compilation are a subset of method and types scanned bool scanningFail = false; DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scanResults.CompiledMethodBodies, "Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod)); DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scanResults.ConstructedEETypes, "EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType)); // If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc. // But there's at least some value in checking the scanner doesn't expand the universe too much in debug. if (_optimizationMode == OptimizationMode.None) { // Check that methods and types scanned are a subset of methods and types compiled // If we find diffs here, they're not critical, but still might be causing a Size on Disk regression. bool dummy = false; // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner // doesn't expand them. They would show up as noisy diffs. DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies, "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsSimdType(method.OwningType)); DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes, "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType)); } if (scanningFail) { throw new Exception("Scanning failure"); } } if (debugInfoProvider is IDisposable) { ((IDisposable)debugInfoProvider).Dispose(); } return(0); }
public void FindLocalReferences(ParseInformation parseInfo, ITextSource fileContent, IVariable variable, ICompilation compilation, Action<SearchResultMatch> callback, CancellationToken cancellationToken) { var csParseInfo = parseInfo as AlFullParseInformation; if (csParseInfo == null) throw new ArgumentException("Parse info does not have SyntaxTree"); ReadOnlyDocument document = null; IHighlighter highlighter = null; new FindReferences().FindLocalReferences( variable, csParseInfo.UnresolvedFile, csParseInfo.SyntaxTree, compilation, delegate (AstNode node, ResolveResult result) { if (document == null) { document = new ReadOnlyDocument(fileContent, parseInfo.FileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } var region = new DomRegion(parseInfo.FileName, node.StartLocation, node.EndLocation); int offset = document.GetOffset(node.StartLocation); int length = document.GetOffset(node.EndLocation) - offset; var builder = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter); var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null; callback(new SearchResultMatch(parseInfo.FileName, node.StartLocation, node.EndLocation, offset, length, builder, defaultTextColor)); }, cancellationToken); if (highlighter != null) { highlighter.Dispose(); } }
/// <summary> /// Initializes a new instance of the <see cref="ServiceController"/> class. /// </summary> /// <param name="repositoryService">The service repository service.</param> /// <param name="compilationService">the compilation service handler.</param> /// <param name="sourceControl">the source control service handler.</param> public ServiceController(IRepository repositoryService, ICompilation compilationService, ISourceControl sourceControl) { _repository = repositoryService; _compilation = compilationService; _sourceControl = sourceControl; }
internal static IType ResolveInAllAssemblies(ICompilation compilation, in FullTypeName fullTypeName)
internal CSharpAssembly(ICompilation compilation, CSharpProjectContent projectContent) { this.compilation = compilation; this.projectContent = projectContent; this.context = new SimpleTypeResolveContext(this); }
public OverloadResolution PerformOverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, bool allowExtensionMethods = true, bool allowExpandingParams = true, Conversions conversions = null) { Log.WriteLine("Performing overload resolution for " + this); Log.WriteCollection(" Arguments: ", arguments); var typeArgumentArray = this.TypeArguments.ToArray(); OverloadResolution or = new OverloadResolution(compilation, arguments, argumentNames, typeArgumentArray, conversions); or.AllowExpandingParams = allowExpandingParams; or.AddMethodLists(methodLists); if (allowExtensionMethods && !or.FoundApplicableCandidate) { // No applicable match found, so let's try extension methods. var extensionMethods = this.GetExtensionMethods(); if (extensionMethods.Count > 0) { Log.WriteLine("No candidate is applicable, trying {0} extension methods groups...", extensionMethods.Count); ResolveResult[] extArguments = new ResolveResult[arguments.Length + 1]; extArguments[0] = new ResolveResult(this.TargetType); arguments.CopyTo(extArguments, 1); string[] extArgumentNames = null; if (argumentNames != null) { extArgumentNames = new string[argumentNames.Length + 1]; argumentNames.CopyTo(extArgumentNames, 1); } var extOr = new OverloadResolution(compilation, extArguments, extArgumentNames, typeArgumentArray, conversions); extOr.AllowExpandingParams = allowExpandingParams; extOr.IsExtensionMethodInvocation = true; foreach (var g in extensionMethods) { foreach (var method in g) { Log.Indent(); OverloadResolutionErrors errors = extOr.AddCandidate(method); Log.Unindent(); or.LogCandidateAddingResult(" Extension", method, errors); } if (extOr.FoundApplicableCandidate) { break; } } // For the lack of a better comparison function (the one within OverloadResolution // cannot be used as it depends on the argument set): if (extOr.FoundApplicableCandidate || or.BestCandidate == null) { // Consider an extension method result better than the normal result only // if it's applicable; or if there is no normal result. or = extOr; } } } Log.WriteLine("Overload resolution finished, best candidate is {0}.", or.GetBestCandidateWithSubstitutedTypeArguments()); return(or); }
public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, CSharpResolver resolver, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false) { var tooltipInfo = new TooltipInformation(); if (resolver == null) { resolver = file != null?file.GetResolver(compilation, textEditorData.Caret.Location) : new CSharpResolver(compilation); } var sig = new SignatureMarkupCreator(resolver, formattingPolicy.CreateOptions()); sig.BreakLineAfterReturnType = smartWrap; try { tooltipInfo.SignatureMarkup = sig.GetMarkup(entity); } catch (Exception e) { LoggingService.LogError("Got exception while creating markup for :" + entity, e); return(new TooltipInformation()); } tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup(entity) ?? ""; if (entity is IMember) { var evt = (IMember)entity; if (evt.ReturnType.Kind == TypeKind.Delegate) { tooltipInfo.AddCategory(GettextCatalog.GetString("Delegate Info"), sig.GetDelegateInfo(evt.ReturnType)); } } if (entity is IMethod) { var method = (IMethod)entity; if (method.IsExtensionMethod) { tooltipInfo.AddCategory(GettextCatalog.GetString("Extension Method from"), method.DeclaringTypeDefinition.FullName); } } if (createFooter) { if (entity is IType) { var type = entity as IType; var def = type.GetDefinition(); if (def != null) { if (!string.IsNullOrEmpty(def.ParentAssembly.AssemblyName)) { var project = def.GetSourceProject(); if (project != null) { var relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, def.Region.FileName); tooltipInfo.FooterMarkup = "<small>" + GettextCatalog.GetString("Project:\t{0}", AmbienceService.EscapeText(def.ParentAssembly.AssemblyName)) + "</small>" + Environment.NewLine + "<small>" + GettextCatalog.GetString("File:\t\t{0} (line {1})", AmbienceService.EscapeText(relPath), def.Region.Begin.Line) + "</small>"; } } } } else if (entity.DeclaringTypeDefinition != null) { var project = entity.DeclaringTypeDefinition.GetSourceProject(); if (project != null) { var relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, entity.Region.FileName); tooltipInfo.FooterMarkup = "<small>" + GettextCatalog.GetString("Project:\t{0}", AmbienceService.EscapeText(project.Name)) + "</small>" + Environment.NewLine + "<small>" + GettextCatalog.GetString("From:\t{0}", AmbienceService.EscapeText(entity.DeclaringType.FullName)) + "</small>" + Environment.NewLine + "<small>" + GettextCatalog.GetString("File:\t\t{0} (line {1})", AmbienceService.EscapeText(relPath), entity.Region.Begin.Line) + "</small>"; } } } return(tooltipInfo); }
/// <summary> /// Imports a member from another compilation. /// </summary> public static IField Import(this ICompilation compilation, IField field) { return((IField)compilation.Import((IMember)field)); }
CSharpTypeResolveContext MapToNestedCompilation(CSharpTypeResolveContext context, ICompilation nestedCompilation) { var nestedContext = new CSharpTypeResolveContext(nestedCompilation.MainAssembly); if (context.CurrentUsingScope != null) { nestedContext = nestedContext.WithUsingScope(context.CurrentUsingScope.UnresolvedUsingScope.Resolve(nestedCompilation)); } if (context.CurrentTypeDefinition != null) { nestedContext = nestedContext.WithCurrentTypeDefinition(nestedCompilation.Import(context.CurrentTypeDefinition)); } return(nestedContext); }