private static bool HasNeutralResourcesLanguageAttribute(IAssemblySymbol assemblySymbol) { return(assemblySymbol.GetAttributes(KnownType.System_Resources_NeutralResourcesLanguageAttribute) .Any(attribute => attribute.ConstructorArguments.Any( constructorArg => constructorArg.Type.Is(KnownType.System_String) && !string.IsNullOrWhiteSpace((string)constructorArg.Value)))); }
public static bool IsRazorViewsAssembly(IAssemblySymbol assemblySymbol) { if (assemblySymbol.Name.EndsWith(".Views") != true) { return(false); } var attributes = assemblySymbol.GetAttributes(); var applicationPartFactoryAttribute = attributes.FirstOrDefault(attr => attr.AttributeClass?.ToString() == "Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute"); if (applicationPartFactoryAttribute is null) { return(false); } var factoryType = applicationPartFactoryAttribute.ConstructorArguments.FirstOrDefault().Value as string; if (factoryType is null) { return(false); } if (factoryType != "Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFactory, Microsoft.AspNetCore.Mvc.Razor") { return(false); } return(true); }
private static bool GetForceGenerateCollectionSerializable(IAssemblySymbol assembly) { var attributes = assembly.GetAttributes() .Where(a => a.AttributeClass.Name == "JsonSerializationConfigurationAttribute") .Select(a => { bool.TryParse(a.NamedArguments.FirstOrDefault(kvp => kvp.Key == "GenerateOnlyRegisteredTypes").Value.Value?.ToString(), out var value); return(value); }) .ToArray(); //Don't use single. We want to have a clear error message. var attributesCount = attributes.Length; if (attributesCount == 0) { throw new Exception("Static Serializer must have JsonSerializationConfigurationAttribute, please add it to SerializableTypes.cs"); } else if (attributesCount > 1) { throw new Exception("JsonSerializationConfigurationAttribute must be set only one time"); } return(attributes.First()); }
private void GenerateAssemblyAttributes(IAssemblySymbol assembly, IProjectFileSystem fileSystem) { var assemblyAttributes = assembly.GetAttributes() .AddRange(PseudoCustomAttributeFacts.GenerateApiAttributes(assembly)); if (options.RemoveAssemblySigningAttributes) { assemblyAttributes = assemblyAttributes.RemoveAll(a => a.AttributeClass?.Name is "AssemblyDelaySignAttribute" or "AssemblyKeyFileAttribute" or "AssemblyKeyNameAttribute" or "AssemblySignatureKeyAttribute" && a.AttributeClass.ContainingNamespace.HasFullName("System", "Reflection")); } GenerateAttributesFile(fileSystem, "Properties/AssemblyInfo.cs", assemblyAttributes, "assembly", initialLines: ImmutableArray.Create( "[assembly: System.Runtime.CompilerServices.ReferenceAssembly]", $"[assembly: System.Reflection.AssemblyVersion(\"{assembly.Identity.Version}\")]")); if (!MetadataFacts.CanAccessType(assembly, "System.Runtime.CompilerServices.ReferenceAssemblyAttribute")) { fileSystem.WriteAllLines( "System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs", "namespace System.Runtime.CompilerServices", "{", " internal sealed class ReferenceAssemblyAttribute : Attribute { }", "}"); } }
internal static bool ExposesInternalsTo(this IAssemblySymbol self, IAssemblySymbol other) { if (self.Equals(other, SymbolEqualityComparer.Default)) { return(true); } else { var internalsVisibleToAttribute = typeof(InternalsVisibleToAttribute); var internalsVisibleTo = self.GetAttributes().SingleOrDefault( _ => _.AttributeClass is not null && _.AttributeClass.Name == internalsVisibleToAttribute.Name && _.AttributeClass.ContainingNamespace.ToDisplayString() == internalsVisibleToAttribute.Namespace && _.AttributeClass.ContainingAssembly.Name == internalsVisibleToAttribute.Assembly.GetName().Name); if (internalsVisibleTo is not null) { if ((string)internalsVisibleTo.ConstructorArguments[0].Value ! == other.Name) { return(true); } } return(false); } }
/// <summary> /// This method creates an initial cheap InternalsVisibleTo map from the given <paramref name="assembly"/> to the assembly names that have friend access to this assembly. /// This map is a superset of the actual InternalsVisibleTo map and is used for performance reasons only. /// While identifying depend projects that can reference a given symbol (see method <see cref="AddNonSubmissionDependentProjectsAsync"/>), we need to know a symbol's /// accessibility from referencing projects. This requires us to create a compilation for the referencing project just to check accessibility and can be performance intensive. /// Instead, we crack the assembly attributes just for the symbol's containing assembly here to enable cheap checks for friend assemblies in <see cref="AddNonSubmissionDependentProjectsAsync"/>. /// </summary> private static Lazy <HashSet <string> > CreateInternalsVisibleToMap(IAssemblySymbol assembly) { var internalsVisibleToMap = new Lazy <HashSet <string> >(() => { var map = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var attr in assembly.GetAttributes().Where(IsInternalsVisibleToAttribute)) { var typeNameConstant = attr.ConstructorArguments.FirstOrDefault(); if (typeNameConstant.Type == null || typeNameConstant.Type.SpecialType != SpecialType.System_String) { continue; } var value = (string)typeNameConstant.Value; if (value == null) { continue; } var commaIndex = value.IndexOf(','); var assemblyName = commaIndex >= 0 ? value.Substring(0, commaIndex).Trim() : value; map.Add(assemblyName); } return(map); }, isThreadSafe: true); return(internalsVisibleToMap); }
/// <summary> /// Enumerates all top level property container types. /// /// This includes the following: /// * Types attributed with <see cref="Unity.Properties.GeneratePropertyBagAttribute"/>. /// * Types specified by the assembly level attribute <see cref="Unity.Properties.GeneratePropertyBagsForTypesQualifiedWithAttribute"/>. /// * Types specified by the assembly level attribute <see cref="Unity.Properties.GeneratePropertyBagsForTypeAttribute"/>. /// </summary> /// <param name="assembly">The assembly to gather types from.</param> /// <returns>An enumeration of all top level types which should have property bags generated.</returns> static IEnumerable <ITypeSymbol> GetTopLevelPropertyContainerTypes(IAssemblySymbol assembly) { // Fetch assembly level attributes which drive property bag generation via interfaces. var generatePropertyBagsForTypesQualifiedWithAttributes = assembly.Modules.First().ReferencedAssemblySymbols .Append(assembly) .SelectMany(x => x.GetAttributes()) .Where(x => x.AttributeClass.Name == "GeneratePropertyBagsForTypesQualifiedWithAttribute").ToImmutableHashSet(); // Fetch any assembly declared property bag types. These are typically used for open generics or abstract types which can not be inferred at compile time. var generatePropertyBagsForTypes = assembly.GetAttributes() .Where(x => x.AttributeClass.Name == "GeneratePropertyBagsForTypeAttribute") .Select(x => x.ConstructorArguments[0].Value as ITypeSymbol) .Where(x => x != null); var visited = new HashSet <ISymbol>(); bool IsRootContainerType(ITypeSymbol symbol) { if (symbol is INamedTypeSymbol named && named.IsGenericType) { return(false); } if (!IsContainerType(symbol)) { return(false); } if (!symbol.HasAttribute("GeneratePropertyBagAttribute") && !MatchesAnyQualifiedWithAttribute(symbol, generatePropertyBagsForTypesQualifiedWithAttributes)) { return(false); } return(true); } foreach (var symbol in generatePropertyBagsForTypes) { if (!visited.Add(symbol)) { // This type was declared multiple times explicitly. We can safely ignore it. continue; } if (symbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsUnboundGenericType) { // This is an explicitly declared open generic. We can safely ignore it. continue; } // This type was explicitly declared and can should be included. yield return(symbol); } foreach (var symbol in assembly.GlobalNamespace.GetTypeMembersRecurse(visited).Where(IsRootContainerType)) { yield return(symbol); } }
public static IEnumerable<string> GetAssemblyAttributes(IAssemblySymbol assemblySymbol) { var attributes = assemblySymbol.GetAttributes(); foreach (var attribute in attributes) { yield return attribute.ToString(); } }
private static bool IsInAssemblyWhichExposesInternals( this ISymbol field, ISymbol internalsVisibleToAttribute) { IAssemblySymbol assembly = field.ContainingAssembly; return(assembly.GetAttributes().Any(a => Equals(a.AttributeClass, internalsVisibleToAttribute))); }
private static bool IsVisibleOutsideSolution( ISymbol field, ISymbol internalsVisibleToAttribute) { IAssemblySymbol assembly = field.ContainingAssembly; return(assembly.GetAttributes().Any(a => Equals(a.AttributeClass, internalsVisibleToAttribute))); }
public static IEnumerable <string> GetAssemblyAttributes(IAssemblySymbol assemblySymbol) { var attributes = assemblySymbol.GetAttributes(); foreach (var attribute in attributes) { yield return(attribute.ToString()); } }
public static bool IsReferenceAssembly(IAssemblySymbol assemblySymbol) { foreach (var attribute in assemblySymbol.GetAttributes()) { if (attribute.AttributeClass?.Name == nameof(ReferenceAssemblyAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName) { return(true); } } return(false); }
public static IEnumerable <KeyValuePair <string, string> > GetNamespaceRenames(IAssemblySymbol assemblySymbol) { var namespaceRenamedAttributeDatas = assemblySymbol.GetAttributes().Where( a => a.AttributeClass.GetFullName() == typeof(NamespaceRenamedAttribute).FullName ); foreach (var attributeData in namespaceRenamedAttributeDatas) { var newNamespaceName = attributeData.ConstructorArguments[1].Value as string; if (attributeData.ConstructorArguments[0].Value is string oldNamespaceName && newNamespaceName != null) { yield return(new KeyValuePair <string, string>(oldNamespaceName, newNamespaceName)); } } }
private IEnumerable <ITypeSymbol> GetSerializableTypesFromAttribute(IAssemblySymbol assembly) { return(assembly.GetAttributes() .Where(a => a.AttributeClass.Name == "JsonSerializableTypeAttribute") .Select(a => { if (a.ConstructorArguments[0].Value is ITypeSymbol type && a.ConstructorArguments.Length == 2) { _fallbackValueOverrides[type] = a.ConstructorArguments[1]; } return a.ConstructorArguments[0].Value as ITypeSymbol; }) .Distinct() .Trim()); }
/// <summary> /// Gets the version comparison name for the specified <see cref="Assembly"/>, which is the name by which assemblies across versions can be /// matched up to be treated as logically equivalent. /// </summary> /// <param name="assemblySymbol">The Assembly of which to get the version comparison name.</param> /// <returns></returns> public static string GetVersionComparisonName(IAssemblySymbol assemblySymbol) { var versionComparisonNameAttributeData = assemblySymbol.GetAttributes().FirstOrDefault( a => a.AttributeClass.GetFullName() == typeof(VersionComparisonNameAttribute).FullName ); if (versionComparisonNameAttributeData != null) { if (versionComparisonNameAttributeData.ConstructorArguments[0].Value is string value) { return(value); } } return(assemblySymbol.Name); }
private void AppendAssemblyAttributes(IAssemblySymbol assemblySymbol) { ImmutableArray <AttributeData> attributes = assemblySymbol.GetAttributes(); ImmutableArray <SymbolDisplayPart> attributeParts = SymbolDeclarationBuilder.GetAttributesParts( attributes, IsVisibleAttribute, splitAttributes: Options.SplitAttributes, includeAttributeArguments: Options.IncludeAttributeArguments, isAssemblyAttribute: true); if (attributeParts.Any()) { Append("// "); AppendLine(assemblySymbol.Identity.Name); Append(attributeParts); AppendLine(); } }
public static Version GetFrameworkVersionFromCompilation(Compilation compilation) { if (compilation == null) { return(null); } IAssemblySymbol assemblySymbol = compilation.Assembly; INamedTypeSymbol targetFrameworkAttribute = compilation.GetTypeByMetadataName("System.Runtime.Versioning.TargetFrameworkAttribute"); AttributeData attrData = assemblySymbol.GetAttributes().FirstOrDefault(a => a.AttributeClass == targetFrameworkAttribute); if (attrData == null) { return(null); } //constructor signature: //public TargetFrameworkAttribute(string frameworkName) string fxName = (string)attrData.ConstructorArguments[0].Value; return(ParseFrameworkName(fxName)); }
/// <summary> /// This method creates an initial cheap InternalsVisibleTo map from the given <paramref name="assembly"/> to the assembly names that have friend access to this assembly. /// This map is a superset of the actual InternalsVisibleTo map and is used for performance reasons only. /// While identifying depend projects that can reference a given symbol (see method <see cref="M:AddNonSubmissionDependentProjectsAsync"/>), we need to know a symbol's /// accessibility from referencing projects. This requires us to create a compilation for the referencing project just to check accessibility and can be performance intensive. /// Instead, we crack the assembly attributes just for the symbol's containing assembly here to enable cheap checks for friend assemblies in <see cref="M:AddNonSubmissionDependentProjectsAsync"/>. /// </summary> private static Lazy<HashSet<string>> CreateInternalsVisibleToMap(IAssemblySymbol assembly) { var internalsVisibleToMap = new Lazy<HashSet<string>>(() => { var map = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var attr in assembly.GetAttributes().Where(IsInternalsVisibleToAttribute)) { var typeNameConstant = attr.ConstructorArguments.FirstOrDefault(); if (typeNameConstant.Type == null || typeNameConstant.Type.SpecialType != SpecialType.System_String) { continue; } var value = (string)typeNameConstant.Value; var commaIndex = value.IndexOf(","); var assemblyName = commaIndex >= 0 ? value.Substring(0, commaIndex).Trim() : value; map.Add(assemblyName); } return map; }, isThreadSafe: true); return internalsVisibleToMap; }
private Assembly TranslateMetadata(IAssemblySymbol assemblySymbol) { Contract.Requires(assemblySymbol != null); Contract.Ensures(Contract.Result<Assembly>() != null); IAssemblyReference cciAssemblyReference = null; Assembly cciAssembly = null; if (assemblySymbolCache.TryGetValue(assemblySymbol, out cciAssemblyReference)) { cciAssembly = cciAssemblyReference as Assembly; System.Diagnostics.Debug.Assert(cciAssembly != null); return cciAssembly; } var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity); var name = assemblySymbol.Identity.Name; var iname = nameTable.GetNameFor(name); cciAssembly = new Assembly() { Attributes = this.TranslateMetadata(assemblySymbol.GetAttributes()), Name = iname, Locations = Helper.WrapLocations(assemblySymbol.Locations), ModuleName = iname, Kind = ModuleKind.DynamicallyLinkedLibrary, RequiresStartupStub = this.host.PointerSize == 4, TargetRuntimeVersion = coreAssembly.TargetRuntimeVersion, Version = assemblySymbol.Identity.Version, }; cciAssembly.AssemblyReferences.Add(coreAssembly); this.assemblySymbolCache.Add(assemblySymbol, cciAssembly); this.module = cciAssembly; var rootUnitNamespace = new RootUnitNamespace(); cciAssembly.UnitNamespaceRoot = rootUnitNamespace; rootUnitNamespace.Unit = cciAssembly; this.namespaceSymbolCache.Add(assemblySymbol.GlobalNamespace, rootUnitNamespace); var moduleClass = new NamespaceTypeDefinition() { ContainingUnitNamespace = rootUnitNamespace, InternFactory = host.InternFactory, IsClass = true, Name = nameTable.GetNameFor("<Module>"), }; cciAssembly.AllTypes.Add(moduleClass); foreach (var m in assemblySymbol.GlobalNamespace.GetMembers()) { var namespaceSymbol = m as INamespaceSymbol; if (namespaceSymbol != null) { var cciNtd = TranslateMetadata(namespaceSymbol); rootUnitNamespace.Members.Add(cciNtd); continue; } var typeSymbol = m as ITypeSymbol; if (typeSymbol != null) { var namedType = TranslateMetadata((INamedTypeSymbol) typeSymbol); // TODO: fix //namedType.Attributes = TranslateMetadata(typeSymbol.GetAttributes()); var cciType = (INamespaceTypeDefinition) namedType; rootUnitNamespace.Members.Add(cciType); //cciAssembly.AllTypes.Add(cciType); continue; } } //if (this.entryPoint != null) { // cciAssembly.Kind = ModuleKind.ConsoleApplication; // cciAssembly.EntryPoint = this.entryPoint; //} return cciAssembly; }
private Assembly TranslateMetadata(IAssemblySymbol assemblySymbol) { Contract.Requires(assemblySymbol != null); Contract.Ensures(Contract.Result <Assembly>() != null); IAssemblyReference cciAssemblyReference = null; Assembly cciAssembly = null; if (assemblySymbolCache.TryGetValue(assemblySymbol, out cciAssemblyReference)) { cciAssembly = cciAssemblyReference as Assembly; System.Diagnostics.Debug.Assert(cciAssembly != null); return(cciAssembly); } var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity); var name = assemblySymbol.Identity.Name; var iname = nameTable.GetNameFor(name); cciAssembly = new Assembly() { Attributes = this.TranslateMetadata(assemblySymbol.GetAttributes()), Name = iname, Locations = Helper.WrapLocations(assemblySymbol.Locations), ModuleName = iname, Kind = ModuleKind.DynamicallyLinkedLibrary, RequiresStartupStub = this.host.PointerSize == 4, TargetRuntimeVersion = coreAssembly.TargetRuntimeVersion, Version = assemblySymbol.Identity.Version, }; cciAssembly.AssemblyReferences.Add(coreAssembly); this.assemblySymbolCache.Add(assemblySymbol, cciAssembly); this.module = cciAssembly; var rootUnitNamespace = new RootUnitNamespace(); cciAssembly.UnitNamespaceRoot = rootUnitNamespace; rootUnitNamespace.Unit = cciAssembly; this.namespaceSymbolCache.Add(assemblySymbol.GlobalNamespace, rootUnitNamespace); var moduleClass = new NamespaceTypeDefinition() { ContainingUnitNamespace = rootUnitNamespace, InternFactory = host.InternFactory, IsClass = true, Name = nameTable.GetNameFor("<Module>"), }; cciAssembly.AllTypes.Add(moduleClass); foreach (var m in assemblySymbol.GlobalNamespace.GetMembers()) { var namespaceSymbol = m as INamespaceSymbol; if (namespaceSymbol != null) { var cciNtd = TranslateMetadata(namespaceSymbol); rootUnitNamespace.Members.Add(cciNtd); continue; } var typeSymbol = m as ITypeSymbol; if (typeSymbol != null) { var namedType = TranslateMetadata((INamedTypeSymbol)typeSymbol); // TODO: fix //namedType.Attributes = TranslateMetadata(typeSymbol.GetAttributes()); var cciType = (INamespaceTypeDefinition)namedType; rootUnitNamespace.Members.Add(cciType); //cciAssembly.AllTypes.Add(cciType); continue; } } //if (this.entryPoint != null) { // cciAssembly.Kind = ModuleKind.ConsoleApplication; // cciAssembly.EntryPoint = this.entryPoint; //} return(cciAssembly); }
private static bool IsMarkedWithAttribute(IAssemblySymbol symbol, string attribute) { return(symbol.GetAttributes().Any(x => x.AttributeClass.ToDisplayString() == attribute)); }
internal static int MapNamespaces(NamespaceInfoMap nsInfoMap, IAssemblySymbol assSymbol, bool isRef) { var count = 0; foreach (AttributeData attData in assSymbol.GetAttributes()) { if (attData.AttributeClass.FullNameEquals(isRef ? __CompilerSchemaNamespaceAttributeNameParts : SchemaNamespaceAttributeNameParts)) { var ctorArgs = attData.ConstructorArguments; string uri = null, dottedString = null; var ctorArgsLength = ctorArgs.Length; if (ctorArgsLength >= 2) { uri = ctorArgs[0].Value as string; if (uri != null) { dottedString = ctorArgs[1].Value as string; } } if (dottedString == null) { if (isRef) { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Invalid__CompilerSchemaNamespaceAttribute, assSymbol.Identity.Name), default(TextSpan)); } else { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaNamespaceAttribute), GetTextSpan(attData)); } } NamespaceInfo nsInfo; if (!nsInfoMap.TryGetValue(uri, out nsInfo)) { if (isRef) { continue; } else { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaNamespaceAttributeUri, uri), GetTextSpan(attData)); } } if (nsInfo.DottedName != null) { if (isRef) { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Duplicate__CompilerSchemaNamespaceAttributeUri, uri, assSymbol.Identity.Name), default(TextSpan)); } else { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.DuplicateSchemaNamespaceAttributeUri, uri), GetTextSpan(attData)); } } CSDottedName dottedName; if (!CSDottedName.TryParse(dottedString, out dottedName)) { if (isRef) { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Invalid__CompilerSchemaNamespaceAttributeNamespaceName, dottedString, assSymbol.Identity.Name), default(TextSpan)); } else { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.InvalidSchemaNamespaceAttributeNamespaceName, dottedString), GetTextSpan(attData)); } } nsInfo.DottedName = dottedName; nsInfo.IsRef = isRef; ++count; if (isRef) { if (ctorArgsLength >= 4) { var ca2 = ctorArgs[2]; var ca3 = ctorArgs[3]; nsInfo.SetRefData(ca2.IsNull ? null : ca2.Values.Select(i => i.Value as string), ca3.IsNull ? null : ca3.Values.Select(i => i.Value as string)); } else { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.Invalid__CompilerSchemaNamespaceAttribute, assSymbol.Identity.Name), default(TextSpan)); } } } } return count; }
public static int GetMaxLineCount(IAssemblySymbol assembly) { return(assembly.GetAttributes().Where(data => data.AttributeClass.Name == typeof(MaxTypeLength).Name && data.ConstructorArguments.Length == 1). Select(data => data.ConstructorArguments[0].Value as int?).FirstOrDefault() ?? DefaultMaximumTypeLength); }
public static bool GetIgnoreDesignerTypes(IAssemblySymbol assembly) { return(assembly.GetAttributes().Where(data => data.AttributeClass.Name == typeof(IgnoreDesignerTypes).Name && data.ConstructorArguments.Length == 1). Select(data => data.ConstructorArguments[0].Value as bool?).FirstOrDefault() ?? DefaultIgnoreDesignerTypes); }