public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { if (symbol.TypeKind != TypeKind.Enum) { return; } var flagsAttribute = WellKnownTypes.FlagsAttribute(compilation); if (flagsAttribute == null) { return; } var zeroValuedFields = GetZeroValuedFields(symbol).ToImmutableArray(); bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass == flagsAttribute); if (hasFlagsAttribute) { CheckFlags(symbol, zeroValuedFields, addDiagnostic); } else { CheckNonFlags(symbol, zeroValuedFields, addDiagnostic); } }
public ICompilationEndedAnalyzer OnCompilationStarted(Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { if (AssemblyHasPublicTypes(compilation.Assembly)) { var comVisibleAttributeSymbol = WellKnownTypes.ComVisibleAttribute(compilation); if (comVisibleAttributeSymbol == null) { return null; } var attributeInstance = compilation.Assembly.GetAttributes().FirstOrDefault(a => a.AttributeClass.Equals(comVisibleAttributeSymbol)); if (attributeInstance != null) { if (attributeInstance.ConstructorArguments.Length > 0 && attributeInstance.ConstructorArguments[0].Kind == TypedConstantKind.Primitive && attributeInstance.ConstructorArguments[0].Value != null & attributeInstance.ConstructorArguments[0].Value.Equals(true)) { // Has the attribute, with the value 'true'. addDiagnostic(Diagnostic.Create(Rule, Location.None, string.Format(FxCopRulesResources.CA1017_AttributeTrue, compilation.Assembly.Name))); } } else { // No ComVisible attribute at all. addDiagnostic(Diagnostic.Create(Rule, Location.None, string.Format(FxCopRulesResources.CA1017_NoAttribute, compilation.Assembly.Name))); } } return null; }
public CompilationResult Compile(Compilation compilation) { var result = new CompilationResult(); result.Success = CompileInternal(compilation); result.References = _references; return result; }
public override void AnalyzeSymbol(INamedTypeSymbol namedTypeSymbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { if (namedTypeSymbol.IsValueType && IsOverridesEquals(namedTypeSymbol) && !IsEqualityOperatorImplemented(namedTypeSymbol)) { addDiagnostic(namedTypeSymbol.CreateDiagnostic(Rule)); } }
private static bool ShouldOmitThisDiagnostic(ISymbol symbol, Compilation compilation) { // This diagnostic is only relevant in constructors. // TODO: should this apply to instance field initializers for VB? var m = symbol as IMethodSymbol; if (m == null || m.MethodKind != MethodKind.Constructor) { return true; } var containingType = m.ContainingType; if (containingType == null) { return true; } // special case ASP.NET and WinForms constructors INamedTypeSymbol webUiControlType = compilation.GetTypeByMetadataName("System.Web.UI.Control"); if (containingType.Inherits(webUiControlType)) { return true; } INamedTypeSymbol windowsFormsControlType = compilation.GetTypeByMetadataName("System.Windows.Forms.Control"); if (containingType.Inherits(windowsFormsControlType)) { return true; } return false; }
private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, Compilation compilation) { if (context.IsGenerated()) return; var methodInvokeSyntax = context.Node as InvocationExpressionSyntax; var childNodes = methodInvokeSyntax.ChildNodes(); var methodCaller = childNodes.OfType<MemberAccessExpressionSyntax>().FirstOrDefault(); if (methodCaller == null) return; var argumentsCount = CountArguments(childNodes); var classSymbol = GetCallerClassSymbol(context.SemanticModel, methodCaller.Expression); if (classSymbol == null || !classSymbol.MightContainExtensionMethods) return; var methodSymbol = GetCallerMethodSymbol(context.SemanticModel, methodCaller.Name, argumentsCount); if (methodSymbol == null || !methodSymbol.IsExtensionMethod) return; if (ContainsDynamicArgument(context.SemanticModel, childNodes)) return; ExpressionSyntax invocationStatement; if (methodInvokeSyntax.Parent.IsNotKind(SyntaxKind.ArrowExpressionClause)) { invocationStatement = (methodInvokeSyntax.FirstAncestorOrSelfThatIsAStatement() as ExpressionStatementSyntax).Expression; } else { invocationStatement = methodInvokeSyntax.FirstAncestorOrSelfOfType<ArrowExpressionClauseSyntax>().Expression; } if (invocationStatement == null) return; if (IsSelectingADifferentMethod(childNodes, methodCaller.Name, context.Node.SyntaxTree, methodSymbol, invocationStatement, compilation)) return; context.ReportDiagnostic(Diagnostic.Create(Rule, methodCaller.GetLocation(), methodSymbol.Name, classSymbol.Name)); }
private IMethodSymbol GenerateSetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, INamedTypeSymbol[] attributesToRemove, CancellationToken cancellationToken) { if (property.SetMethod == null) { return null; } var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( this.State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( setMethod, attributes: null, accessibility: accessibility, explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null, statements: GetSetAccessorStatements(compilation, property, generateAbstractly, cancellationToken)); }
private static bool IsMethodCandidate(IMethodSymbol methodSymbol, Compilation compilation) { return methodSymbol.IsAsync && methodSymbol.ReturnsVoid && methodSymbol.IsChangeable() && !methodSymbol.IsProbablyEventHandler(compilation); }
public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken) { if (symbol.GetMembers().Any(member => IsDllImport(member)) && !IsTypeNamedCorrectly(symbol.Name)) { addDiagnostic(symbol.CreateDiagnostic(Rule)); } }
/// <summary> /// Return the extension method in reduced form if the extension method /// is applicable, and satisfies type parameter constraints, based on the /// "this" argument type. Otherwise, returns null. /// </summary> public static MethodSymbol Create(MethodSymbol method, TypeSymbol receiverType, Compilation compilation) { Debug.Assert(method.IsExtensionMethod && method.MethodKind != MethodKind.ReducedExtension); Debug.Assert(method.ParameterCount > 0); Debug.Assert((object)receiverType != null); HashSet<DiagnosticInfo> useSiteDiagnostics = null; method = method.InferExtensionMethodTypeArguments(receiverType, compilation, ref useSiteDiagnostics); if ((object)method == null) { return null; } var conversions = new TypeConversions(method.ContainingAssembly.CorLibrary); var conversion = conversions.ConvertExtensionMethodThisArg(method.Parameters[0].Type, receiverType, ref useSiteDiagnostics); if (!conversion.Exists) { return null; } if (useSiteDiagnostics != null) { foreach (var diag in useSiteDiagnostics) { if (diag.Severity == DiagnosticSeverity.Error) { return null; } } } return Create(method); }
/// <summary> /// Given a set of compiler or <see cref="DiagnosticAnalyzer"/> generated <paramref name="diagnostics"/>, returns the effective diagnostics after applying the below filters: /// 1) <see cref="CompilationOptions.SpecificDiagnosticOptions"/> specified for the given <paramref name="compilation"/>. /// 2) <see cref="CompilationOptions.GeneralDiagnosticOption"/> specified for the given <paramref name="compilation"/>. /// 3) Diagnostic suppression through applied <see cref="System.Diagnostics.CodeAnalysis.SuppressMessageAttribute"/>. /// 4) Pragma directives for the given <paramref name="compilation"/>. /// </summary> public static IEnumerable<Diagnostic> GetEffectiveDiagnostics(IEnumerable<Diagnostic> diagnostics, Compilation compilation) { if (diagnostics == null) { throw new ArgumentNullException(nameof(diagnostics)); } if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } var suppressMessageState = AnalyzerDriver.SuppressMessageStateByCompilation.GetValue(compilation, (c) => new SuppressMessageAttributeState(c)); foreach (var diagnostic in diagnostics.ToImmutableArray()) { if (diagnostic != null) { var effectiveDiagnostic = compilation.FilterDiagnostic(diagnostic); if (effectiveDiagnostic != null && !suppressMessageState.IsDiagnosticSuppressed(effectiveDiagnostic)) { yield return effectiveDiagnostic; } } } }
public IDiagnosticAnalyzer CreateAnalyzerWithinCompilation(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) { var iserializableTypeSymbol = compilation.GetTypeByMetadataName("System.Runtime.Serialization.ISerializable"); if (iserializableTypeSymbol == null) { return null; } var serializationInfoTypeSymbol = compilation.GetTypeByMetadataName("System.Runtime.Serialization.SerializationInfo"); if (serializationInfoTypeSymbol == null) { return null; } var streamingContextTypeSymbol = compilation.GetTypeByMetadataName("System.Runtime.Serialization.StreamingContext"); if (streamingContextTypeSymbol == null) { return null; } var serializableAttributeTypeSymbol = compilation.GetTypeByMetadataName("System.SerializableAttribute"); if (serializableAttributeTypeSymbol == null) { return null; } return new Analyzer(iserializableTypeSymbol, serializationInfoTypeSymbol, streamingContextTypeSymbol, serializableAttributeTypeSymbol); }
private static ImmutableArray<INamedTypeSymbol> GetTaskTypes(Compilation compilation) { INamedTypeSymbol taskType = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task"); INamedTypeSymbol taskOfTType = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1"); return ImmutableArray.Create(taskType, taskOfTType); }
protected override bool IsAssignableTo(Compilation compilation, ITypeSymbol fromSymbol, ITypeSymbol toSymbol) { return fromSymbol != null && toSymbol != null && ((CSharpCompilation)compilation).ClassifyConversion(fromSymbol, toSymbol).IsImplicit; }
public static MetadataOnlyImage Create(ITemporaryStorageService service, Compilation compilation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_EmitMetadataOnlyImage, cancellationToken)) { // TODO: make it to use SerializableBytes.WritableStream rather than MemoryStream so that // we don't allocate anything for skeleton assembly. using (var stream = SerializableBytes.CreateWritableStream()) { // note: cloning compilation so we don't retain all the generated symbols after its emitted. // * REVIEW * is cloning clone p2p reference compilation as well? var emitResult = compilation.Clone().Emit(stream, options: s_emitOptions, cancellationToken: cancellationToken); if (emitResult.Success) { var storage = service.CreateTemporaryStreamStorage(cancellationToken); stream.Position = 0; storage.WriteStream(stream, cancellationToken); return new MetadataOnlyImage(storage, compilation.AssemblyName); } } } return Empty; }
public ICompilationEndedAnalyzer OnCompilationStarted(Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { var eventHandler = WellKnownTypes.EventHandler(compilation); if (eventHandler == null) { return null; } var genericEventHandler = WellKnownTypes.GenericEventHandler(compilation); if (genericEventHandler == null) { return null; } var eventArgs = WellKnownTypes.EventArgs(compilation); if (eventArgs == null) { return null; } var comSourceInterfacesAttribute = WellKnownTypes.ComSourceInterfaceAttribute(compilation); if (comSourceInterfacesAttribute == null) { return null; } return GetAnalyzer(compilation, eventHandler, genericEventHandler, eventArgs, comSourceInterfacesAttribute); }
public StatMachineGeneratorFixer(Compilation compilation, SyntaxTree syntaxTree, SemanticModel semanticModel, string enclosingTypeName) { this.compilation = compilation; this.syntaxTree = syntaxTree; this.semanticModel = semanticModel; this.enclosingTypeName = enclosingTypeName; }
public CompilationSecurityTypes(Compilation compilation) { HandleProcessCorruptedStateExceptionsAttribute = SecurityTypes.HandleProcessCorruptedStateExceptionsAttribute(compilation); SystemObject = SecurityTypes.SystemObject(compilation); SystemException = SecurityTypes.SystemException(compilation); SystemSystemException = SecurityTypes.SystemSystemException(compilation); DES = SecurityTypes.DES(compilation); DSA = SecurityTypes.DSA(compilation); DSASignatureFormatter = SecurityTypes.DSASignatureFormatter(compilation); HMACMD5 = SecurityTypes.HMACMD5(compilation); RC2 = SecurityTypes.RC2(compilation); TripleDES = SecurityTypes.TripleDES(compilation); RIPEMD160 = SecurityTypes.RIPEMD160(compilation); HMACRIPEMD160 = SecurityTypes.HMACRIPEMD160(compilation); XmlDocument = SecurityTypes.XmlDocument(compilation); XPathDocument = SecurityTypes.XPathDocument(compilation); XmlSchema = SecurityTypes.XmlSchema(compilation); DataSet = SecurityTypes.DataSet(compilation); XmlSerializer = SecurityTypes.XmlSerializer(compilation); DataTable = SecurityTypes.DataTable(compilation); XmlNode = SecurityTypes.XmlNode(compilation); DataViewManager = SecurityTypes.DataViewManager(compilation); XmlTextReader = SecurityTypes.XmlTextReader(compilation); XmlReader = SecurityTypes.XmlReader(compilation); DtdProcessing = SecurityTypes.DtdProcessing(compilation); XmlReaderSettings = SecurityTypes.XmlReaderSettings(compilation); XslCompiledTransform = SecurityTypes.XslCompiledTransform(compilation); XmlResolver = SecurityTypes.XmlResolver(compilation); XmlSecureResolver = SecurityTypes.XmlSecureResolver(compilation); XsltSettings = SecurityTypes.XsltSettings(compilation); }
// TODO: remove -- workaround for bugs in Portable PDB handling in EE internal static void WithRuntimeInstancePortableBug(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator) { using (var instance = RuntimeInstance.Create(compilation, references, DebugInformationFormat.Pdb, true)) { validator(instance); } }
/// <summary> /// Constructor. /// </summary> /// <param name="project">Project</param> private AnalysisContext(Project project) { this.Solution = project.Solution; this.Compilation = project.GetCompilationAsync().Result; this.RegisteredImmutableTypes = new HashSet<Type>(); this.GivesUpOwnershipMethods = new Dictionary<string, ISet<int>>(); }
public CppWriter(Compilation compilation) { _compilation = compilation; _out = new StreamWriter(new FileStream(compilation.Options.OutputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, false)); // Unify this list with the one in CppCodegenNodeFactory SetWellKnownTypeSignatureName(WellKnownType.Void, "void"); SetWellKnownTypeSignatureName(WellKnownType.Boolean, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Char, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.SByte, "int8_t"); SetWellKnownTypeSignatureName(WellKnownType.Byte, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Int16, "int16_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt16, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.Int32, "int32_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt32, "uint32_t"); SetWellKnownTypeSignatureName(WellKnownType.Int64, "int64_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt64, "uint64_t"); SetWellKnownTypeSignatureName(WellKnownType.IntPtr, "intptr_t"); SetWellKnownTypeSignatureName(WellKnownType.UIntPtr, "uintptr_t"); SetWellKnownTypeSignatureName(WellKnownType.Single, "float"); SetWellKnownTypeSignatureName(WellKnownType.Double, "double"); BuildExternCSignatureMap(); }
public IDiagnosticAnalyzer CreateAnalyzerWithinCompilation(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) { var eventHandler = WellKnownTypes.EventHandler(compilation); if (eventHandler == null) { return null; } var genericEventHandler = WellKnownTypes.GenericEventHandler(compilation); if (genericEventHandler == null) { return null; } var eventArgs = WellKnownTypes.EventArgs(compilation); if (eventArgs == null) { return null; } var comSourceInterfacesAttribute = WellKnownTypes.ComSourceInterfaceAttribute(compilation); if (comSourceInterfacesAttribute == null) { return null; } return GetAnalyzer(compilation, eventHandler, genericEventHandler, eventArgs, comSourceInterfacesAttribute); }
public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName) { this.compilation = compilation; this.scope = scope; this.name = fullyQualifiedName; this.index = 0; }
public CppWriter(Compilation compilation) { _compilation = compilation; SetWellKnownTypeSignatureName(WellKnownType.Void, "void"); SetWellKnownTypeSignatureName(WellKnownType.Boolean, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Char, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.SByte, "int8_t"); SetWellKnownTypeSignatureName(WellKnownType.Byte, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Int16, "int16_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt16, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.Int32, "int32_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt32, "uint32_t"); SetWellKnownTypeSignatureName(WellKnownType.Int64, "int64_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt64, "uint64_t"); SetWellKnownTypeSignatureName(WellKnownType.IntPtr, "intptr_t"); SetWellKnownTypeSignatureName(WellKnownType.UIntPtr, "uintptr_t"); SetWellKnownTypeSignatureName(WellKnownType.Single, "float"); SetWellKnownTypeSignatureName(WellKnownType.Double, "double"); // TODO: For now, ensure that all types/methods referenced by unmanaged helpers are present var stringType = _compilation.TypeSystemContext.GetWellKnownType(WellKnownType.String); AddInstanceFields(stringType); var stringArrayType = stringType.MakeArrayType(); _compilation.AddType(stringArrayType); _compilation.MarkAsConstructed(stringArrayType); }
internal ReferencedTypeCache(Compilation compilation,IFactoryAccess factoryAccess) { this.compilation = compilation; this.factoryAccess = factoryAccess; metadataLookup = new Dictionary<string, IType>(); builtTrees = new Dictionary<SyntaxTree, IRoot>(); }
public CompilationData(Compilation comp) { _semanticModelsMap = new Dictionary<SyntaxTree, SemanticModel>(); this.SuppressMessageAttributeState = new SuppressMessageAttributeState(comp); _declarationAnalysisDataMap = new Dictionary<SyntaxReference, DeclarationAnalysisData>(); _declarationAnalysisDataPool = new ObjectPool<DeclarationAnalysisData>(() => new DeclarationAnalysisData()); }
private SyntaxNode GetInvertedStatement( SyntaxGenerator generator, IMethodSymbol containingOperator, Compilation compilation) { if (containingOperator.Name == WellKnownMemberNames.EqualityOperatorName) { return generator.ReturnStatement( generator.LogicalNotExpression( generator.ValueEqualsExpression( generator.IdentifierName(containingOperator.Parameters[0].Name), generator.IdentifierName(containingOperator.Parameters[1].Name)))); } else if (containingOperator.Name == WellKnownMemberNames.InequalityOperatorName) { return generator.ReturnStatement( generator.LogicalNotExpression( generator.ValueNotEqualsExpression( generator.IdentifierName(containingOperator.Parameters[0].Name), generator.IdentifierName(containingOperator.Parameters[1].Name)))); } else { // If it's a < > <= or >= operator then we can't simply invert a call // to the existing operator. i.e. the body of the "<" method should *not* be: // return !(a > b); // Just provide a throwing impl for now. return generator.DefaultMethodStatement(compilation); } }
private bool TypeHasWeakIdentity(ITypeSymbol type, Compilation compilation) { switch (type.TypeKind) { case TypeKind.Array: var arrayType = type as IArrayTypeSymbol; return arrayType != null && IsPrimitiveType(arrayType.ElementType); case TypeKind.Class: case TypeKind.TypeParameter: INamedTypeSymbol marshalByRefObjectTypeSymbol = compilation.GetTypeByMetadataName("System.MarshalByRefObject"); INamedTypeSymbol executionEngineExceptionTypeSymbol = compilation.GetTypeByMetadataName("System.ExecutionEngineException"); INamedTypeSymbol outOfMemoryExceptionTypeSymbol = compilation.GetTypeByMetadataName("System.OutOfMemoryException"); INamedTypeSymbol stackOverflowExceptionTypeSymbol = compilation.GetTypeByMetadataName("System.StackOverflowException"); INamedTypeSymbol memberInfoTypeSymbol = compilation.GetTypeByMetadataName("System.Reflection.MemberInfo"); INamedTypeSymbol parameterInfoTypeSymbol = compilation.GetTypeByMetadataName("System.Reflection.ParameterInfo"); INamedTypeSymbol threadTypeSymbol = compilation.GetTypeByMetadataName("System.Threading.Thread"); return type.SpecialType == SpecialType.System_String || type.Equals(executionEngineExceptionTypeSymbol) || type.Equals(outOfMemoryExceptionTypeSymbol) || type.Equals(stackOverflowExceptionTypeSymbol) || type.Inherits(marshalByRefObjectTypeSymbol) || type.Inherits(memberInfoTypeSymbol) || type.Inherits(parameterInfoTypeSymbol) || type.Inherits(threadTypeSymbol); // What about struct types? default: return false; } }
private void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic) { if (symbol.GetMembers().Any(member => IsDllImport(member)) && !IsTypeNamedCorrectly(symbol.Name)) { addDiagnostic(symbol.CreateDiagnostic(Rule)); } }
public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName) { _compilation = compilation; _scope = scope; _name = fullyQualifiedName; _index = 0; }
public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; }
public SemanticModelProvider(Compilation compilation) { Compilation = compilation; _semanticModelMap = new ConcurrentDictionary <SyntaxTree, SemanticModel>(); }
private void SetupsConfig(string solutionPath, int iden) { // Attempt to set the version of MSBuild. var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray(); VisualStudioInstance instance; if (visualStudioInstances.Length > 1) { instance = visualStudioInstances[1]; } else { instance = visualStudioInstances[0]; } //Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects."); // NOTE: Be sure to register an instance with the MSBuildLocator // before calling MSBuildWorkspace.Create() // otherwise, MSBuildWorkspace won't MEF compose. MSBuildLocator.RegisterInstance(instance); using (var workspace = MSBuildWorkspace.Create()) { // Print message for WorkspaceFailed event to help diagnosing project load failures. workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message); //Console.WriteLine($"Loading solution '{solutionPath}'"); // Attach progress reporter so we print projects as they are loaded. workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter()).Wait(); var solution = workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter()).Result; //Console.WriteLine($"Finished loading solution '{solutionPath}'"); // TODO: Do analysis on the projects in the loaded solution CSharpParseOptions options = CSharpParseOptions.Default .WithFeatures(new[] { new KeyValuePair <string, string>("control-flow-analysis", "") }); var projIds = solution.ProjectIds; Project project; if (projIds.Count > 1 && projIds.Count > iden) { project = solution.GetProject(projIds[iden]); } else { project = solution.GetProject(projIds[0]); } projectName = project.Name; project.GetCompilationAsync().Wait(); compilation = project.GetCompilationAsync().Result; if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName)) { syntaxTree = compilation.SyntaxTrees.First(); } } }
public CompilationCompletedEvent(Compilation compilation) : base(compilation) { }
public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { }
public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; }
protected VariableSymbol(Compilation compilation, ITypeSymbol type) { this.OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType(); this.OriginalType = this.OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type; }
private static IEnumerable <INamespaceOrTypeSymbol> GetContainers(IEnumerable <ISymbol> symbols, Compilation compilation) { foreach (var symbol in symbols) { var containingSymbol = symbol.ContainingSymbol as INamespaceOrTypeSymbol; if (containingSymbol is INamespaceSymbol) { containingSymbol = compilation.GetCompilationNamespace((INamespaceSymbol)containingSymbol); } if (containingSymbol != null) { yield return(containingSymbol); } } }
protected abstract bool IsAssignableTo(Compilation compilation, ITypeSymbol fromSymbol, ITypeSymbol toSymbol);
protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
/// <summary> /// Gets the <see cref="DisposeMethodKind"/> for the given method. /// </summary> public static DisposeMethodKind GetDisposeMethodKind(this IMethodSymbol method, Compilation compilation) { INamedTypeSymbol? iDisposable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIDisposable); INamedTypeSymbol? iAsyncDisposable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIAsyncDisposable); INamedTypeSymbol? task = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); INamedTypeSymbol? valueTask = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask); return method.GetDisposeMethodKind(iDisposable, iAsyncDisposable, task, valueTask); }
protected abstract AnalyzerBase GetAnalyzer( Compilation compilation, INamedTypeSymbol eventHandler, INamedTypeSymbol genericEventHandler, INamedTypeSymbol eventArgs, INamedTypeSymbol comSourceInterfacesAttribute);
public static INamedTypeSymbol SuppressMessageAttributeType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute")); }
/// <summary> /// Returns the topmost <see cref="IBlockOperation"/> for given <paramref name="method"/>. /// </summary> public static IBlockOperation? GetTopmostOperationBlock(this IMethodSymbol method, Compilation compilation, CancellationToken cancellationToken = default) { var methodToBlockMap = s_methodToTopmostOperationBlockCache.GetOrCreateValue(compilation); return methodToBlockMap.GetOrAdd(method, ComputeTopmostOperationBlock); // Local functions. IBlockOperation? ComputeTopmostOperationBlock(IMethodSymbol unused) { if (!Equals(method.ContainingAssembly, compilation.Assembly)) { return null; } foreach (var decl in method.DeclaringSyntaxReferences) { var syntax = decl.GetSyntax(cancellationToken); // VB Workaround: declaration.GetSyntax returns StatementSyntax nodes instead of BlockSyntax nodes // GetOperation returns null for StatementSyntax, and the method's operation block for BlockSyntax. if (compilation.Language == LanguageNames.VisualBasic) { syntax = syntax.Parent; } var semanticModel = compilation.GetSemanticModel(syntax.SyntaxTree); foreach (var descendant in syntax.DescendantNodesAndSelf()) { var operation = semanticModel.GetOperation(descendant, cancellationToken); if (operation is IBlockOperation blockOperation) { return blockOperation; } } } return null; } }
public static INamedTypeSymbol AttributeType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.Attribute")); }
/// <summary> /// Checks if the given method implements IDisposable.Dispose() /// </summary> public static bool IsDisposeImplementation(this IMethodSymbol method, Compilation compilation) { INamedTypeSymbol? iDisposable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIDisposable); return method.IsDisposeImplementation(iDisposable); }
public static INamedTypeSymbol EditorBrowsableStateType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.ComponentModel.EditorBrowsableState")); }
public static INamedTypeSymbol ComAliasNameAttributeType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.Runtime.InteropServices.ComAliasNameAttribute")); }
public static INamedTypeSymbol EqualityComparerOfTType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.Collections.Generic.EqualityComparer`1")); }
public static INamedTypeSymbol TaskOfTType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1")); }
public static INamedTypeSymbol EventArgsType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.EventArgs")); }
public static INamedTypeSymbol ExpressionOfTType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1")); }
public static INamedTypeSymbol DesignerGeneratedAttributeType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute")); }
public static INamedTypeSymbol NotImplementedExceptionType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.NotImplementedException")); }
private static int VerifyForwardedTypes( Dictionary <INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies, Compilation compilation, HashSet <INamedTypeSymbol> verifiedKeys, bool isSearchSymbolCompilation) { Contract.ThrowIfNull(compilation); Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies); Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any()); // Must contain equivalents named types residing in different assemblies. Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly))); // Must contain non-nested named types. Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null)); Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null)); var referencedAssemblies = new MultiDictionary <string, IAssemblySymbol>(); foreach (var assembly in compilation.GetReferencedAssemblySymbols()) { referencedAssemblies.Add(assembly.Name, assembly); } var verifiedCount = 0; foreach (var kvp in equivalentTypesWithDifferingAssemblies) { if (!verifiedKeys.Contains(kvp.Key)) { INamedTypeSymbol originalType, expectedForwardedType; if (isSearchSymbolCompilation) { originalType = kvp.Value.OriginalDefinition; expectedForwardedType = kvp.Key.OriginalDefinition; } else { originalType = kvp.Key.OriginalDefinition; expectedForwardedType = kvp.Value.OriginalDefinition; } foreach (var referencedAssembly in referencedAssemblies[originalType.ContainingAssembly.Name]) { var fullyQualifiedTypeName = originalType.MetadataName; if (originalType.ContainingNamespace != null) { fullyQualifiedTypeName = originalType.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat) + "." + fullyQualifiedTypeName; } // Resolve forwarded type and verify that the types from different assembly are indeed equivalent. var forwardedType = referencedAssembly.ResolveForwardedType(fullyQualifiedTypeName); if (Equals(forwardedType, expectedForwardedType)) { verifiedKeys.Add(kvp.Key); verifiedCount++; } } } } return(verifiedCount); }
public static INamedTypeSymbol HideModuleNameAttribute(this Compilation compilation) { return(compilation.GetTypeByMetadataName("Microsoft.VisualBasic.HideModuleNameAttribute")); }
public static INamedTypeSymbol ExecutionEngineException(Compilation compilation) { return(compilation.GetTypeByMetadataName("System.ExecutionEngineException")); }
public static INamedTypeSymbol DesignerCategoryAttributeType(this Compilation compilation) { return(compilation.GetTypeByMetadataName("System.ComponentModel.DesignerCategoryAttribute")); }
public static INamedTypeSymbol MarshalByRefObject(Compilation compilation) { return(compilation.GetTypeByMetadataName("System.MarshalByRefObject")); }
public static INamedTypeSymbol OutOfMemoryException(Compilation compilation) { return(compilation.GetTypeByMetadataName("System.OutOfMemoryException")); }