Microsoft.CodeAnalysis.Diagnostic.Create(string, string, Microsoft.CodeAnalysis.LocalizableString, Microsoft.CodeAnalysis.DiagnosticSeverity, Microsoft.CodeAnalysis.DiagnosticSeverity, bool, int, bool, Microsoft.CodeAnalysis.LocalizableString, Microsoft.CodeAnalysis.LocalizableString, string, Microsoft.CodeAnalysis.Location, System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable, System.Collections.Immutable.ImmutableDictionary)

Here are the examples of the csharp api Microsoft.CodeAnalysis.Diagnostic.Create(string, string, Microsoft.CodeAnalysis.LocalizableString, Microsoft.CodeAnalysis.DiagnosticSeverity, Microsoft.CodeAnalysis.DiagnosticSeverity, bool, int, bool, Microsoft.CodeAnalysis.LocalizableString, Microsoft.CodeAnalysis.LocalizableString, string, Microsoft.CodeAnalysis.Location, System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable, System.Collections.Immutable.ImmutableDictionary) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

790 Examples 7

19 View Source File : GodotOnReadySourceGenerator.cs
License : MIT License
Project Creator : 31

public void Execute(GeneratorExecutionContext context)
		{
			// If this isn't working, run 'dotnet build-server shutdown' first.
			if (Environment
				.GetEnvironmentVariable($"Debug{nameof(GodotOnReadySourceGenerator)}") == "true")
			{
				Debugger.Launch();
			}

			var receiver = context.SyntaxReceiver as OnReadyReceiver ?? throw new Exception();

			INamedTypeSymbol GetSymbolByName(string fullName) =>
				context.Compilation.GetTypeByMetadataName(fullName)
				?? throw new Exception($"Can't find {fullName}");

			var onReadyGetSymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyGetAttribute");
			var onReadySymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyAttribute");
			var generateDataSelectorEnumSymbol =
				GetSymbolByName("GodotOnReady.Attributes.GenerateDataSelectorEnumAttribute");

			var resourceSymbol = GetSymbolByName("Godot.Resource");
			var nodeSymbol = GetSymbolByName("Godot.Node");

			List<PartialClreplacedAddition> additions = new();

			var clreplacedSymbols = receiver.AllClreplacedes
				.Select(clreplacedDecl =>
				{
					INamedTypeSymbol? clreplacedSymbol = context.Compilation
						.GetSemanticModel(clreplacedDecl.SyntaxTree)
						.GetDeclaredSymbol(clreplacedDecl);

					if (clreplacedSymbol is null)
					{
						context.ReportDiagnostic(
							Diagnostic.Create(
								new DiagnosticDescriptor(
									"GORSG0001",
									"Inspection",
									$"Unable to find declared symbol for {clreplacedDecl}. Skipping.",
									"GORSG.Parsing",
									DiagnosticSeverity.Warning,
									true
								),
								clreplacedDecl.GetLocation()
							)
						);
					}

					return clreplacedSymbol;
				})
				.Distinct(SymbolEqualityComparer.Default)
				.OfType<INamedTypeSymbol>();

			foreach (var clreplacedSymbol in clreplacedSymbols)
			{
				foreach (var attribute in clreplacedSymbol.GetAttributes()
					.Where(a => Equal(a.AttributeClreplaced, generateDataSelectorEnumSymbol)))
				{
					var fields = clreplacedSymbol.GetMembers()
						.OfType<IFieldSymbol>()
						.Where(f => f.IsReadOnly && f.IsStatic)
						.ToArray();

					additions.Add(new DataSelectorEnumAddition(
						fields,
						new AttributeSite(clreplacedSymbol, attribute)));
				}

				var members = Enumerable
					.Concat(
						clreplacedSymbol.GetMembers().OfType<IPropertySymbol>().Select(MemberSymbol.Create),
						clreplacedSymbol.GetMembers().OfType<IFieldSymbol>().Select(MemberSymbol.Create))
					.ToArray();

				foreach (var member in members)
				{
					foreach (var attribute in member.Symbol
						.GetAttributes()
						.Where(a => Equal(a.AttributeClreplaced, onReadyGetSymbol)))
					{
						var site = new MemberAttributeSite(
							member,
							new AttributeSite(clreplacedSymbol, attribute));

						if (site.AttributeSite.Attribute.NamedArguments.Any(
							a => a.Key == "Property" && a.Value.Value is string { Length: > 0 }))
						{
							additions.Add(new OnReadyGetNodePropertyAddition(site));
						}
						else if (member.Type.IsOfBaseType(nodeSymbol))
						{
							additions.Add(new OnReadyGetNodeAddition(site));
						}
						else if (member.Type.IsOfBaseType(resourceSymbol))
						{
							additions.Add(new OnReadyGetResourceAddition(site));
						}
						else
						{
							string issue =
								$"The type '{member.Type}' of '{member.Symbol}' is not supported." +
								" Expected a Resource or Node subclreplaced.";

							context.ReportDiagnostic(
								Diagnostic.Create(
									new DiagnosticDescriptor(
										"GORSG0002",
										"Inspection",
										issue,
										"GORSG.Parsing",
										DiagnosticSeverity.Error,
										true
									),
									member.Symbol.Locations.FirstOrDefault()
								)
							);
						}
					}
				}

				foreach (var methodSymbol in clreplacedSymbol.GetMembers().OfType<IMethodSymbol>())
				{
					foreach (var attribute in methodSymbol
						.GetAttributes()
						.Where(a => Equal(a.AttributeClreplaced, onReadySymbol)))
					{
						additions.Add(new OnReadyAddition(methodSymbol, attribute, clreplacedSymbol));
					}
				}
			}

			foreach (var clreplacedAdditionGroup in additions.GroupBy(a => a.Clreplaced))
			{
				SourceStringBuilder source = CreateInitializedSourceBuilder();

				if (clreplacedAdditionGroup.Key is not { } clreplacedSymbol) continue;

				source.NamespaceBlockBraceIfExists(clreplacedSymbol.GetSymbolNamespaceName(), () =>
				{
					source.Line("public partial clreplaced ", clreplacedAdditionGroup.Key.Name);
					source.BlockBrace(() =>
					{
						foreach (var addition in clreplacedAdditionGroup)
						{
							addition.DeclarationWriter?.Invoke(source);
						}

						if (clreplacedAdditionGroup.Any(a => a.ConstructorStatementWriter is not null))
						{
							source.Line();
							source.Line("public ", clreplacedAdditionGroup.Key.Name, "()");
							source.BlockBrace(() =>
							{
								foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
								{
									addition.ConstructorStatementWriter?.Invoke(source);
								}

								source.Line("Constructor();");
							});

							source.Line("partial void Constructor();");
						}

						if (clreplacedAdditionGroup.Any(a => a.OnReadyStatementWriter is not null))
						{
							source.Line();
							source.Line("public override void _Ready()");
							source.BlockBrace(() =>
							{
								source.Line("base._Ready();");

								// OrderBy is a stable sort.
								// Sort by Order, then by discovery order (implicitly).
								foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
								{
									addition.OnReadyStatementWriter?.Invoke(source);
								}
							});
						}
					});

					foreach (var addition in clreplacedAdditionGroup)
					{
						addition.OutsideClreplacedStatementWriter?.Invoke(source);
					}
				});

				string escapedNamespace =
					clreplacedAdditionGroup.Key.GetSymbolNamespaceName()?.Replace(".", "_") ?? "";

				context.AddSource(
					$"Partial_{escapedNamespace}_{clreplacedAdditionGroup.Key.Name}",
					source.ToString());
			}
		}

19 View Source File : CompilationProcessor.cs
License : MIT License
Project Creator : 71

public bool TryInitialize(CSharpCompilation compilation, CancellationToken cancellationToken)
        {
            if (IsInitialized && IsInitializationSuccessful)
                return true;

            List<CompilationEditor> editors = Editors;
            var addDiagnostic = AddDiagnostic;
            CSharpCompilation clone = compilation.Clone();

            IsInitialized = true;

            // Log all previously encountered exceptions
            initializationExceptions.Capacity = initializationExceptions.Count;

            var exceptions = initializationExceptions.MoveToImmutable();

            for (int i = 0; i < exceptions.Length; i++)
            {
                var (exception, data) = exceptions[i];
                var location = data.ApplicationSyntaxReference.ToLocation();

                addDiagnostic(Diagnostic.Create(InitializationError, location, data.AttributeClreplaced, exception.Message.Filter(), exception.StackTrace.Filter()));
            }

            if (exceptions.Length > 0)
                return false;

            // Initialize all editors
            int editorsCount = editors.Count;

            for (int i = 0; i < editorsCount; i++)
            {
                CompilationEditor editor = editors[i];

                try
                {
                    // Register
                    if (!editor.TryRegister(this, addDiagnostic, clone, cancellationToken, out var children, out var exception))
                    {
                        addDiagnostic(Diagnostic.Create(EditorError, Location.None, editor.ToString(), exception.ToString()));
                        return false;
                    }

                    // Make sure no error was diagnosed by the editor
                    if (GetDiagnostics().Any(x => x.Severity == DiagnosticSeverity.Error))
                    {
                        return false;
                    }

                    // Optionally register some children
                    if (children == null || children.Length == 0)
                        continue;

                    editors.Capacity += children.Length;

                    for (int j = 0; j < children.Length; j++)
                    {
                        CompilationEditor child = children[j];

                        if (child == null)
                        {
                            addDiagnostic(Diagnostic.Create(
                                id: "MissingChild", category: Common.DiagnosticsCategory,
                                message: $"A child returned by the '{editor}' editor is null.",
                                severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning,
                                isEnabledByDefault: true, warningLevel: 1, isSuppressed: false));

                            continue;
                        }

                        editors.Insert(i + j + 1, child);
                        editorsCount++;
                    }
                    // Since we insert them right after this one, the for loop will take care of initializing them easily
                    // => No recursion, baby
                }
                catch (Exception e)
                {
                    while (e is TargetInvocationException tie)
                        e = tie.InnerException;

                    addDiagnostic(Diagnostic.Create(EditorError, Location.None, editor.ToString(), e.Message.Filter()));

                    return false;
                }
            }

            // We got this far: the initialization is a success.
            IsInitializationSuccessful = true;
            return true;
        }

19 View Source File : CompilationProcessor.cs
License : MIT License
Project Creator : 71

public void ReportDiagnostic(string step, string message, string stackTrace)
        {
            AddDiagnostic(Diagnostic.Create(ProcessingError, Location.None, step, message.Filter(), stackTrace.Filter()));
        }

19 View Source File : Hooks.cs
License : MIT License
Project Creator : 71

private static void CheckOptionsAndCreateModuleBuilder(RedirectionContext context)
        {
            // Sender is a CSharpCompilation
            CSharpCompilation compilation = (CSharpCompilation)context.Sender;
            CSharpCompilation clone = compilation.Clone();

            // First argument is a DiagnosticBag
            object diagnosticBag = context.Arguments[0];

            Action<Diagnostic> addDiagnostic = Helpers.MakeAddDiagnostic(diagnosticBag);
            Func<IEnumerable<Diagnostic>> getDiagnostics = Helpers.MakeGetDiagnostics(diagnosticBag);

            object GetOriginal(CSharpCompilation newCompilation)
            {
                object[] args = new object[context.Arguments.Count];
                context.Arguments.CopyTo(args, 0);

                newCompilation.CopyTo(compilation);

                return context.Invoke(args);
            }

            // CancellationToken should be last argument, but whatever.
            CancellationToken cancellationToken = context.Arguments.OfType<CancellationToken>().FirstOrDefault();

            // Edit the compilation (if a matching CometaryManager is found)
            CompilationRedirection.Stop();

            using (CompilationProcessor manager = CompilationProcessor.Create(GetOriginal, addDiagnostic, getDiagnostics))
            {
                manager.RegisterAttributes(compilation.replacedembly);

                // Edit the compilation, and emit it.
                if (manager.TryEditCompilation(compilation, cancellationToken, out CSharpCompilation _, out object moduleBuilder))
                {
                    // No error, we can keep going
                    context.ReturnValue = moduleBuilder;

                    addDiagnostic(Diagnostic.Create(
                        id: "ProcessSuccess",
                        category: Common.DiagnosticsCategory,
                        message: "Successfully edited the emitted compilation.",
                        severity: DiagnosticSeverity.Info,
                        defaultSeverity: DiagnosticSeverity.Info,
                        isEnabledByDefault: true,
                        warningLevel: -1,
                        isSuppressed: false));
                }
                else
                {
                    // Keep going as if we were never here (the errors will be reported anyways)
                    clone.CopyTo(compilation);

                    context.ReturnValue = context.Invoke(context.Arguments.ToArray());
                }
            }

            CompilationRedirection.Start();
        }

19 View Source File : SelfEditor.cs
License : MIT License
Project Creator : 71

protected override void Initialize(CSharpCompilation compilation, CancellationToken cancellationToken)
        {
            if (editing)
                return;

            using (MemoryStream replacedemblyStream = new MemoryStream())
            using (MemoryStream symbolsStream = new MemoryStream())
            {
                // Define the 'META' constant
                compilation = compilation
                    .WithreplacedemblyName(compilation.replacedemblyName + "+Metaprogramming")
                    .RecomputeCompilationWithOptions(opts => opts.WithPreprocessorSymbols("META"), cancellationToken);

                // Reactivate the emit hook to run Cometary on the upcoming editor
                editing = true;
                Hooks.EnsureActive();

                // Emit stream for the first time
                EmitResult result = compilation.Emit(
                    peStream: replacedemblyStream,
                    pdbStream: symbolsStream,
                    options: new EmitOptions(
                        tolerateErrors: true, includePrivateMembers: true,
                        debugInformationFormat: DebugInformationFormat.PortablePdb),
                    cancellationToken: cancellationToken);

                editing = false;

                // Ensure everything is good
                if (!result.Success)
                {
                    foreach (Diagnostic diag in result.Diagnostics)
                    {
                        Report(diag);
                    }

                    Report(Diagnostic.Create(EmitError, Location.None, result.Diagnostics.Length.ToString()));

                    return;
                }

                replacedembly TryResolve(replacedemblyLoadContext sender, replacedemblyName replacedemblyName)
                {
                    if (replacedemblyName.Name == compilation.replacedemblyName)
                        return null;
                    return null;
                }

                try
                {
                    replacedemblyStream.Position = 0;
                    symbolsStream.Position = 0;

                    replacedemblyLoadContext.Default.Resolving += TryResolve;

                    // Set up custom load context for execution
                    // Note: This causes exceptions when loading already loaded replacedemblies (ie: System.Threading.Tasks),
                    // which is why I'm using the Default load context, already set up by the replacedyzer
                    // If no bugs show up, I'll simply remove CompilationLoadcontext at some point
                    //
                    //CompilationLoadContext compilationLoadContext = new CompilationLoadContext(compilation);
                    //
                    replacedembly producedreplacedembly = replacedemblyLoadContext.Default.LoadFromStream(replacedemblyStream, symbolsStream);

                    //
                    //compilationLoadContext.Producedreplacedembly = producedreplacedembly;

                    children = GetreplacedemblyChildren(producedreplacedembly);
                }
                catch (TypeLoadException e)
                {
                    Report(Diagnostic.Create(LoadError, Location.None, e.TypeName));
                }
                catch (ReflectionTypeLoadException e)
                {
                    Report(Diagnostic.Create(LoadError, Location.None, e.Message));
                }
                catch (TargetInvocationException e)
                {
                    Report(Diagnostic.Create(LoadError, Location.None, e.InnerException.Message));
                }
                finally
                {
                    replacedemblyLoadContext.Default.Resolving -= TryResolve;
                }
            }
        }

19 View Source File : ActionHandlerAttributesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void CheckActionHandler(SymbolreplacedysisContext context, PXContext pxContext, IMethodSymbol symbol, MethodDeclarationSyntax node,
										GraphType graphType)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var attributes = symbol.GetAttributes();
			var pxUIFieldAttributeType = pxContext.AttributeTypes.PXUIFieldAttribute.Type;
			var pxButtonAttributeType = pxContext.AttributeTypes.PXButtonAttribute;
			var pxOverrideAttributeType = pxContext.AttributeTypes.PXOverrideAttribute;
			var hasPXUIFieldAttribute = false;
			var hasPXButtonAttribute = false;
			var hasPXOverrideAttribute = false;

			foreach (var attr in attributes)
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				if (attr.AttributeClreplaced == null)
				{
					continue;
				}

				if (attr.AttributeClreplaced.InheritsFromOrEquals(pxUIFieldAttributeType))
				{
					hasPXUIFieldAttribute = true;
				}

				if (attr.AttributeClreplaced.InheritsFromOrEquals(pxButtonAttributeType))
				{
					hasPXButtonAttribute = true;
				}

				if (hasPXUIFieldAttribute && hasPXButtonAttribute)
				{
					return;
				}

				if (attr.AttributeClreplaced.InheritsFromOrEquals(pxOverrideAttributeType))
				{
					hasPXOverrideAttribute = true;
				}

				if (graphType == GraphType.PXGraphExtension && hasPXOverrideAttribute)
				{
					return;
				}
			}

			var fixOption = !hasPXUIFieldAttribute && !hasPXButtonAttribute ? FixOption.AddBothAttributes :
				!hasPXUIFieldAttribute ? FixOption.AddPXUIFieldAttribute :
				FixOption.AddPXButtonAttribute;
			var properties = ImmutableDictionary<string, string>.Empty
				.Add(FixOptionKey, fixOption.ToString());
			var diagnostic = Diagnostic.Create(
				Descriptors.PX1092_MissingAttributesOnActionHandler,
				node.Identifier.GetLocation(),
				properties);

			context.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
		}

19 View Source File : ActionHandlerReturnTypeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void CheckActionHandlerReturnType(SymbolreplacedysisContext context, PXContext pxContext, MethodDeclarationSyntax node, IMethodSymbol symbol)
        {
            context.CancellationToken.ThrowIfCancellationRequested();

            if (pxContext.SystemTypes.IEnumerable.Equals(symbol.ReturnType))
            {
                return;
            }

            if (!StartsLongOperation(pxContext, context.Compilation, node, context.CancellationToken))
            {
                return;
            }

            var diagnostic = Diagnostic.Create(
                Descriptors.PX1013_PXActionHandlerInvalidReturnType,
                node.Identifier.GetLocation());

            context.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
        }

19 View Source File : DacNonAbstractFieldTypeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void replacedyzeDacField(DacFieldInfo dacFieldInfo, SymbolreplacedysisContext symbolContext, PXContext pxContext)
		{
			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			if (dacFieldInfo.Symbol.IsAbstract)
				return;

			symbolContext.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1024_DacNonAbstractFieldType, dacFieldInfo.Node.Identifier.GetLocation()),
				pxContext.CodereplacedysisSettings);
		}

19 View Source File : DacPropertyAttributesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void ReportIncompatibleTypesDiagnostics(DacPropertyInfo property, AttributeInfo fieldAttribute,
															   SymbolreplacedysisContext symbolContext, PXContext pxContext, bool registerCodeFix)
		{
			var diagnosticProperties = ImmutableDictionary.Create<string, string>()
														  .Add(DiagnosticProperty.RegisterCodeFix, registerCodeFix.ToString());
			Location propertyTypeLocation = property.Node.Type.GetLocation();
			Location attributeLocation = fieldAttribute.AttributeData.GetLocation(symbolContext.CancellationToken);

			if (propertyTypeLocation != null)
			{
				symbolContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1021_PXDBFieldAttributeNotMatchingDacProperty, propertyTypeLocation, attributeLocation.ToEnumerable(),
									  diagnosticProperties),
					pxContext.CodereplacedysisSettings);
			}

			if (attributeLocation != null)
			{
				symbolContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1021_PXDBFieldAttributeNotMatchingDacProperty, attributeLocation, propertyTypeLocation.ToEnumerable(),
									  diagnosticProperties),
					pxContext.CodereplacedysisSettings);
			}
		}

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dac)
		{
			if (dac.Symbol.BaseType.Name == TypeNames.PXCacheExtension)
			{
				if (!dac.Symbol.IsSealed)
				{
					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1011_InheritanceFromPXCacheExtension, dac.Symbol.Locations.First()),
						pxContext.CodereplacedysisSettings);
				}
			}
			else
			{
				context.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1009_InheritanceFromPXCacheExtension, dac.Symbol.Locations.First()),
					pxContext.CodereplacedysisSettings);
			}
		}

19 View Source File : InvalidPXActionSignatureAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext symbolContext, PXContext pxContext, PXGraphSemanticModel pxGraph)
		{
			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			var actionHandlerWithBadSignature = from method in pxGraph.Symbol.GetMembers().OfType<IMethodSymbol>()
												where pxGraph.Symbol.Equals(method.ContainingType) &&
													  CheckIfDiagnosticShouldBeRegisteredForMethod(method, pxContext) &&
													  pxGraph.ActionsByNames.ContainsKey(method.Name)
												select method;

			foreach (IMethodSymbol method in actionHandlerWithBadSignature)
			{
				symbolContext.CancellationToken.ThrowIfCancellationRequested();
				Location methodLocation = method.Locations.FirstOrDefault();

				if (methodLocation != null)
				{
					symbolContext.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1000_InvalidPXActionHandlerSignature, methodLocation),
						pxContext.CodereplacedysisSettings);
				}
			}
		}

19 View Source File : LegacyBqlConstantAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void replacedyze(SymbolreplacedysisContext context, PXContext pxContext)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			if (context.Symbol is INamedTypeSymbol constant)
			{
				if (!IsConstant(constant, pxContext, out string constantType) || LegacyBqlFieldreplacedyzer.AlreadyStronglyTyped(constant, pxContext))
					return;

				Location location = constant.Locations.FirstOrDefault();
				if (location != null)
				{
					var properties = ImmutableDictionary.CreateBuilder<string, string>();
					properties.Add(CorrespondingType, constantType);

					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1061_LegacyBqlConstant, location, properties.ToImmutable(), constant.Name),
						pxContext.CodereplacedysisSettings); 
				}
			}
		}

19 View Source File : LocalizationMessageHelper.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public void ValidateMessage()
        {
            bool isHardcodedMessage = _messageExpression is LiteralExpressionSyntax;
            if (isHardcodedMessage)
            {
                _syntaxContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1050_HardcodedStringInLocalizationMethod, _messageExpression.GetLocation()),
					_pxContext.CodereplacedysisSettings);
                return;
            }

            ITypeSymbol messageType = ReadMessageInfo();
            if (messageType != null && _messageMember != null)
            {
                if (IsNonLocalizableMessageType(messageType))
                {
                    _syntaxContext.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1051_NonLocalizableString, _messageExpression.GetLocation()),
						_pxContext.CodereplacedysisSettings);
                }

                if (IsIncorrectStringToFormat())
                {
                    _syntaxContext.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1052_IncorrectStringToFormat, _messageExpression.GetLocation()),
						_pxContext.CodereplacedysisSettings);
                }
            }
            else if (IsStringConcatenation())
            {
                _syntaxContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1053_ConcatenationPriorLocalization, _messageExpression.GetLocation()),
					_pxContext.CodereplacedysisSettings);
            }
        }

19 View Source File : MethodsUsageInDacAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void replacedyzeMethodInvocationInDacProperty(DacPropertyInfo property, HashSet<INamedTypeSymbol> whiteList,
														  SymbolreplacedysisContext context, PXContext pxContext, SemanticModel semanticModel)
		{
			foreach (SyntaxNode node in property.Node.DescendantNodes())
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				if (node is InvocationExpressionSyntax invocation)
				{
					ISymbol symbol = semanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol;

                    if (symbol == null || !(symbol is IMethodSymbol method) || method.IsStatic || method.IsExtensionMethod)
                        continue;

					bool inWhitelist = whiteList.Contains(method.ContainingType) ||
									   whiteList.Contains(method.ContainingType.ConstructedFrom);
                    if (inWhitelist)
                        continue;

                    context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1032_DacPropertyCannotContainMethodInvocations, invocation.GetLocation()),
						pxContext.CodereplacedysisSettings);
                }
				else if (node is ObjectCreationExpressionSyntax)
				{
					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1032_DacPropertyCannotContainMethodInvocations, node.GetLocation()),
						pxContext.CodereplacedysisSettings);
				}
			}
		}

19 View Source File : NonNullableTypeForBqlFieldAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dac)
		{
			foreach (DacPropertyInfo property in dac.AllDeclaredProperties)
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				if (!dac.FieldsByNames.TryGetValue(property.Name, out DacFieldInfo field))
					continue;

				if (property.Symbol.Type is INamedTypeSymbol propertyType && propertyType.IsValueType &&
					propertyType.ConstructedFrom?.SpecialType != SpecialType.System_Nullable_T)
				{
					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1014_NonNullableTypeForBqlField, property.Symbol.Locations.First()),
						pxContext.CodereplacedysisSettings);
				}
			}			
		}

19 View Source File : NoPrimaryViewForPrimaryDacAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, PXGraphSemanticModel graph)
		{
			ITypeSymbol declaredPrimaryDacType = graph.Symbol.GetDeclaredPrimaryDacFromGraphOrGraphExtension(pxContext);

			if (declaredPrimaryDacType == null || context.CancellationToken.IsCancellationRequested)
				return;

			bool hasViewForPrimaryDac = graph.Views.Select(view => view.DAC).Contains(declaredPrimaryDacType);

			if (hasViewForPrimaryDac || context.CancellationToken.IsCancellationRequested)
				return;

			Location location = GetLocation(graph, declaredPrimaryDacType, context);

			if (location == null)
				return;

			context.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1018_NoPrimaryViewForPrimaryDac, location),
				pxContext.CodereplacedysisSettings);
		}

19 View Source File : DiagnosticWalker.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void VisitInvocationExpression(InvocationExpressionSyntax node)
			{
				_context.CancellationToken.ThrowIfCancellationRequested();

				var methodSymbol = _semanticModel.GetSymbolInfo(node).Symbol as IMethodSymbol;

				if (methodSymbol != null && IsMethodForbidden(methodSymbol))
				{
					bool found = node.ArgumentList.Arguments
						.Where(arg => arg.Expression != null)
						.Select(arg => _semanticModel.GetSymbolInfo(arg.Expression).Symbol as ILocalSymbol)
						.Any(variable => variable != null && _rowVariables.Contains(variable));

					if (!found)
					{
						var walker = new EventArgsRowWalker(_semanticModel, _pxContext);
						node.ArgumentList.Accept(walker);

						found = walker.Success;
					}

					if (found && _replacedysisMode == RowChangesreplacedysisMode.ChangesForbiddenForRowFromEventArgs)
					{
						_context.ReportDiagnosticWithSuppressionCheck(
							Diagnostic.Create(
								_pxContext.CodereplacedysisSettings.IsvSpecificreplacedyzersEnabled 
									? Descriptors.PX1047_RowChangesInEventHandlersForbiddenForArgs
									: Descriptors.PX1047_RowChangesInEventHandlersForbiddenForArgs_NonISV, 
								node.GetLocation(),
								_messageArgs), 
							_pxContext.CodereplacedysisSettings);
					}
					else if (!found && _replacedysisMode == RowChangesreplacedysisMode.ChangesAllowedOnlyForRowFromEventArgs)
					{
						_context.ReportDiagnosticWithSuppressionCheck(
							Diagnostic.Create(
								Descriptors.PX1048_RowChangesInEventHandlersAllowedForArgsOnly, 
								node.GetLocation(), 
								_messageArgs), 
							_pxContext.CodereplacedysisSettings);
					}
				}
			}

19 View Source File : DacAutoNumberAttributeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void ReportDacPropertyTypeIsNotString(SymbolreplacedysisContext context, PXContext pxContext, DacPropertyInfo dacProperty)
		{
			var autoNumberingAttribute = dacProperty.Attributes.FirstOrDefault(a => a.IsAutoNumberAttribute);
			var propertyTypeLocation = dacProperty.Node.Type.GetLocation();

			if (propertyTypeLocation != null)
			{
				var diagnostic = Diagnostic.Create(Descriptors.PX1019_AutoNumberOnDacPropertyWithNonStringType, propertyTypeLocation);

				context.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
			}

			var attributeLocation = autoNumberingAttribute?.AttributeData.GetLocation(context.CancellationToken);
			
			if (attributeLocation != null)
			{
				var diagnostic = Diagnostic.Create(Descriptors.PX1019_AutoNumberOnDacPropertyWithNonStringType, attributeLocation);

				context.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
			}
		}

19 View Source File : DacAutoNumberAttributeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void CheckIfStringLengthIsSufficientForAutoNumbering(SymbolreplacedysisContext context, AttributeInformation attributeInformation,
																	 DacPropertyInfo dacProperty)
		{
			var dbBoundStringAttribute = attributeInformation.Context.FieldAttributes.PXDBStringAttribute;
			var unboundStringAttribute = attributeInformation.Context.FieldAttributes.PXStringAttribute;
			var stringAttributes = dacProperty.Attributes
											  .Where(a => IsStringAttribute(a, attributeInformation, dbBoundStringAttribute, unboundStringAttribute))
											  .ToList();
			if (stringAttributes.Count != 1)
				return;

			AttributeInfo stringAttribute = stringAttributes[0];
			int? stringLength = GetStringLengthFromStringAttribute(stringAttribute);
			int minAllowedLength = attributeInformation.Context.AttributeTypes.AutoNumberAttribute.MinAutoNumberLength;

			if (stringLength.HasValue && stringLength < minAllowedLength)
			{
				var attributeLocation = GetLocationToReportInsufficientStringLength(context, stringAttribute, stringLength.Value);
				var diagnostic = Diagnostic.Create(Descriptors.PX1020_InsufficientStringLengthForDacPropertyWithAutoNumbering, attributeLocation, minAllowedLength);
				context.ReportDiagnosticWithSuppressionCheck(diagnostic, attributeInformation.Context.CodereplacedysisSettings);
			}
		}

19 View Source File : DacKeyDeclarationAnalyzerBase.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private bool ReportKeyWithUnboundDacField(SymbolreplacedysisContext symbolContext, PXContext context, INamedTypeSymbol key, ClreplacedDeclarationSyntax keyNode,
												  ITypeSymbol unboundDacFielreplacedey)
		{
			var location = GetUnboundDacFieldLocation(keyNode, unboundDacFielreplacedey) ?? keyNode.Identifier.GetLocation() ?? keyNode.GetLocation();

			if (location == null)
				return false;

			symbolContext.ReportDiagnosticWithSuppressionCheck(
							Diagnostic.Create(Descriptors.PX1037_UnboundDacFielreplacedeyDeclaration, location),
							context.CodereplacedysisSettings);
			return true;
		}

19 View Source File : DacKeyDeclarationAnalyzerBase.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private bool CheckThatAllKeysHaveUniqueSetsOfFields(SymbolreplacedysisContext symbolContext, PXContext context,
															List<INamedTypeSymbol> keyDeclarations, Dictionary<INamedTypeSymbol, List<ITypeSymbol>> dacFieldsByKey)
		{
			if (keyDeclarations.Count < 2 || dacFieldsByKey.Count == 0)
				return true;

			// First obtain groups of keys which use same DAC fields.
			var keysGroupedByFields = GetKeysGroupedBySetOfFields(keyDeclarations, dacFieldsByKey, symbolContext.CancellationToken);

			// Get the groups of more than one key which use the same DAC fields set. Split these groups by their target DAC.
			// We don't do this for all keys at the previous step as a optimization for the most frequent case. 
			// To split the key groups by their target DACs we need to extract the target DAC from them. Most of the keys use a unique set of DAC fields anyway, 
			// so we don't need to make this redundant extraction for them.
			var duplicateKeySets = keysGroupedByFields.Values.Where(keys => keys.Count > 1)
															 .SelectMany(keys => GetDuplicateKeysGroupsForSameTargetDAC(context, keys));
			bool allFieldsUnique = true;

			// We group keys by sets of used fields and then report each set with duplicate keys separately,
			// preplaceding the locations of other duplicate fields in a set to code fix. 
			// This way if there are two different sets of duplicate keys the code fix will affect only the set to which it was applied
			foreach (List<INamedTypeSymbol> duplicateKeys in duplicateKeySets)
			{
				allFieldsUnique = false;
				var locations = duplicateKeys.Select(declaration => declaration.GetSyntax(symbolContext.CancellationToken))
											 .OfType<ClreplacedDeclarationSyntax>()
											 .Select(keyClreplacedDeclaration => keyClreplacedDeclaration.Identifier.GetLocation() ??
																			keyClreplacedDeclaration.GetLocation())
											 .Where(location => location != null)
											 .ToList(capacity: duplicateKeys.Count);

				for (int i = 0; i < locations.Count; i++)
				{
					Location location = locations[i];
					var otherLocations = locations.Where((_, index) => index != i);

					symbolContext.ReportDiagnosticWithSuppressionCheck(
									Diagnostic.Create(Descriptors.PX1035_MultipleKeyDeclarationsInDacWithSameFields, location, otherLocations),
									context.CodereplacedysisSettings);
				}
			}

			return allFieldsUnique;
		}

19 View Source File : DacKeyDeclarationAnalyzerBase.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected virtual void ReportKeyDeclarationWithWrongName(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac,
																 INamedTypeSymbol keyDeclaration, RefIntegrityDacKeyType dacKeyType)
		{
			var keyDeclarationNode = keyDeclaration.GetSyntax(symbolContext.CancellationToken);
			Location location = (keyDeclarationNode as ClreplacedDeclarationSyntax)?.Identifier.GetLocation() ?? keyDeclarationNode?.GetLocation();
			Location dacLocation = dac.Node.GetLocation();
			DiagnosticDescriptor px1036Descriptor = GetWrongKeyNameDiagnosticDescriptor(dacKeyType);

			if (location == null || dacLocation == null || px1036Descriptor == null)
				return;

			var additionalLocations = new[] { dacLocation };
			var diagnosticProperties = new Dictionary<string, string>
			{
				{ nameof(RefIntegrityDacKeyType),  dacKeyType.ToString() }
			};

			if (dacKeyType == RefIntegrityDacKeyType.UniqueKey)
			{
				diagnosticProperties.Add(nameof(UniqueKeyCodeFixType), UniqueKeyCodeFixType.SingleUniqueKey.ToString());
			}
			
			symbolContext.ReportDiagnosticWithSuppressionCheck(
										Diagnostic.Create(px1036Descriptor, location, additionalLocations, diagnosticProperties.ToImmutableDictionary()),
										context.CodereplacedysisSettings);
		}

19 View Source File : MissingTypeListAttributeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void replacedyzeProperty(DacPropertyInfo property, SymbolreplacedysisContext context, PXContext pxContext,
											IEnumerable<INamedTypeSymbol> typeAttributesSet)
		{
			var attributeTypes = property.Symbol.GetAttributes()
												.Select(a => a.AttributeClreplaced)
												.ToList(capacity: 4);

			bool hasListAttribute = attributeTypes.Any(type => type.ImplementsInterface(pxContext.IPXLocalizableList));

			if (!hasListAttribute)
				return;

			//TODO we need to use FieldTypeAttributesRegister to perform complete replacedysis with consideration for aggregate attributes 
			bool hasTypeAttribute = attributeTypes.Any(propertyAttributeType => 
										typeAttributesSet.Any(typeAttribute => propertyAttributeType.InheritsFromOrEquals(typeAttribute)));
			if (!hasTypeAttribute)
			{
				context.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1002_MissingTypeListAttributereplacedyzer, property.Symbol.Locations.FirstOrDefault()),
					pxContext.CodereplacedysisSettings);
			}
		}

19 View Source File : NoIsActiveMethodForExtensionAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public void replacedyze(SymbolreplacedysisContext symbolContext, PXContext pxContext, DacSemanticModel dacExtension)
		{
			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			// Shouldreplacedyze already filtered everything and left only DAC extensions without IsActive
			// We just need to report them
			Location location = dacExtension.Node.Identifier.GetLocation();

			if (location == null)
				return;

			symbolContext.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1016_NoIsActiveMethodForDacExtension, location), 
				pxContext.CodereplacedysisSettings);
		}

19 View Source File : NoIsActiveMethodForExtensionAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public void replacedyze(SymbolreplacedysisContext symbolContext, PXContext pxContext, PXGraphSemanticModel graphExtension)
		{
			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			// Shouldreplacedyze already filtered everything and left only graph extensions without IsActive
			// We just need to report them
			var syntaxNode = graphExtension.Symbol.GetSyntax(symbolContext.CancellationToken);
			Location location = (syntaxNode as ClreplacedDeclarationSyntax)?.Identifier.GetLocation() ?? syntaxNode?.GetLocation();

			if (location == null)
				return;

			symbolContext.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1016_NoIsActiveMethodForGraphExtension, location),
				pxContext.CodereplacedysisSettings);
		}

19 View Source File : XmlCommentsWalker.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void ReportDiagnostic(SyntaxNodereplacedysisContext syntaxContext, MemberDeclarationSyntax memberDeclaration,
									  Location location, XmlCommentParseResult parseResult)
		{
			syntaxContext.CancellationToken.ThrowIfCancellationRequested();

			var memberCategory = GetMemberCategory(memberDeclaration);
			var properties = ImmutableDictionary<string, string>.Empty
																.Add(XmlreplacedyzerConstants.XmlCommentParseResultKey, parseResult.ToString());
			var noXmlCommentDiagnostic = Diagnostic.Create(Descriptors.PX1007_PublicClreplacedXmlComment, location, properties, memberCategory);

			syntaxContext.ReportDiagnosticWithSuppressionCheck(noXmlCommentDiagnostic, _codereplacedysisSettings);
		}

19 View Source File : PXActionOnNonPrimaryViewAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void RegisterDiagnosticForAction(ISymbol actionSymbol, string primaryDacName, 
														ImmutableDictionary<string, string> diagnosticProperties,
														SymbolreplacedysisContext symbolContext, PXContext pxContext)
		{
			SyntaxNode symbolSyntax = actionSymbol.GetSyntax(symbolContext.CancellationToken);
			Location location = GetLocation(symbolSyntax);

			if (location == null)
				return;

			symbolContext.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1012_PXActionOnNonPrimaryView, location, diagnosticProperties,
								  actionSymbol.Name, primaryDacName), pxContext.CodereplacedysisSettings);
		}

19 View Source File : PXGraphCreationForBqlQueriesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void replacedyzeCodeBlock(CodeBlockreplacedysisContext context, PXContext pxContext)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			// Get body from a method or property
			CSharpSyntaxNode body = context.CodeBlock?.GetBody();
			if (body == null) return;

			// Collect all PXGraph-typed method parameters preplaceded to BQL queries
			var walker = new BqlGraphArgWalker(context.SemanticModel, pxContext);
			body.Accept(walker);
			if (walker.GraphArguments.IsEmpty) return;

			// Collect all available PXGraph instances (@this, method parameters, local variables)
			var existingGraphs = GetExistingGraphInstances(body, context.SemanticModel, pxContext);
			if (existingGraphs.IsEmpty) return;

			// Determine if available PXGraph instance is used outside of BQL queries
			var usedGraphs = GetSymbolUsages(body, existingGraphs, context.SemanticModel, walker.GraphArguments)
				.ToImmutableHashSet();
			var availableGraphs = existingGraphs.Except(usedGraphs).ToArray();

			// replacedyze each PXGraph-typed parameter in BQL queries
			foreach (var graphArgSyntax in walker.GraphArguments)
			{
				var instantiationType = graphArgSyntax.GetGraphInstantiationType(context.SemanticModel, pxContext);

				// New PXGraph() / new TGraph() / PXGraph.CreateInstance<TGraph> are reported at all times
				// All other usages are reported only if:
				// 1. There is at least one existing PXGraph instance available
				// 2. PXGraph parameter is not used in any way because its modifications might affect the BQL query results
				if (instantiationType != GraphInstantiationType.None)
				{
					context.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(Descriptors.PX1072_PXGraphCreationForBqlQueries,
						graphArgSyntax.GetLocation(),
						CreateDiagnosticProperties(availableGraphs, pxContext)),
						pxContext.CodereplacedysisSettings);
				}
				else if (availableGraphs.Length > 0 && context.SemanticModel.GetSymbolInfo(graphArgSyntax).Symbol is ILocalSymbol localVar 
				                                    && !usedGraphs.Contains(localVar))
				{
					context.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(Descriptors.PX1072_PXGraphCreationForBqlQueries,
						graphArgSyntax.GetLocation(),
						CreateDiagnosticProperties(availableGraphs.Where(g => !Equals(g, localVar)), pxContext)),
						pxContext.CodereplacedysisSettings);
				}
			}
		}

private void replacedyzeGraphDeclarationTypeParameter(SyntaxNodereplacedysisContext context, PXContext pxContext)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			if (!(context.Node is ClreplacedDeclarationSyntax clreplacedDeclaration))
			{
				return;
			}

			var typeSymbol = context.SemanticModel.GetDeclaredSymbol(clreplacedDeclaration);
			if (typeSymbol == null || !typeSymbol.IsPXGraph(pxContext))
			{
				return;
			}

			if (clreplacedDeclaration.BaseList == null)
			{
				return;
			}

			var graphArgumentNode = GetBaseGraphTypeNode(context, pxContext, clreplacedDeclaration.BaseList.Types);
			if (graphArgumentNode == null)
			{
				return;
			}

			// Get last identifier to handle cases like SO.SOSetupMaint
			var graphArgumentIdentifier = graphArgumentNode
				.DescendantNodesAndSelf()
				.OfType<IdentifierNameSyntax>()
				.Last();

			var graphTypeArgument = context.SemanticModel.GetTypeInfo(graphArgumentIdentifier).Type;

			if (typeSymbol.Equals(graphTypeArgument) || graphTypeArgument?.Kind == SymbolKind.TypeParameter)
			{
				return;
			}

			context.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1093_GraphDeclarationViolation, graphArgumentIdentifier.GetLocation()),
				pxContext.CodereplacedysisSettings);
		}

19 View Source File : DiagnosticWalker.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void VisitreplacedignmentExpression(replacedignmentExpressionSyntax node)
			{
				if (node.Left != null)
				{
					var walker = new EventArgsRowWalker(_semanticModel, _pxContext);
					node.Left.Accept(walker);
					bool found = walker.Success;

					if (!found)
					{
						_variableMemberAccessWalker.Reset();
						node.Left.Accept(_variableMemberAccessWalker);
						found = _variableMemberAccessWalker.Success;
					}
					
					if (found && _replacedysisMode == RowChangesreplacedysisMode.ChangesForbiddenForRowFromEventArgs)
					{
						_context.ReportDiagnosticWithSuppressionCheck(
							Diagnostic.Create(
								_pxContext.CodereplacedysisSettings.IsvSpecificreplacedyzersEnabled
									? Descriptors.PX1047_RowChangesInEventHandlersForbiddenForArgs 
									: Descriptors.PX1047_RowChangesInEventHandlersForbiddenForArgs_NonISV, 
								node.GetLocation(), _messageArgs),
							_pxContext.CodereplacedysisSettings);
					}
					else if (!found && _replacedysisMode == RowChangesreplacedysisMode.ChangesAllowedOnlyForRowFromEventArgs)
					{
						_dacInstanceAccessWalker.Reset();
						node.Left.Accept(_dacInstanceAccessWalker);

						if (_dacInstanceAccessWalker.Success)
						{
							_context.ReportDiagnosticWithSuppressionCheck(
								Diagnostic.Create(
									Descriptors.PX1048_RowChangesInEventHandlersAllowedForArgsOnly,
									node.GetLocation(), 
									_messageArgs), 
								_pxContext.CodereplacedysisSettings);
						}
					}
				}
			}

19 View Source File : BqlParameterMismatchAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void VerifyBqlArgumentsCount(int argsCount, ParametersCounter parametersCounter, SyntaxNodereplacedysisContext syntaxContext,
													InvocationExpressionSyntax invocation, IMethodSymbol methodSymbol, PXContext pxContext)
		{
			syntaxContext.CancellationToken.ThrowIfCancellationRequested();

			if (!parametersCounter.IsCountingValid)
				return;

			int searchMethodParametersCount = 0;

			if (methodSymbol.Name == SearchMethodName && methodSymbol.IsGenericMethod)
			{
				searchMethodParametersCount = methodSymbol.TypeParameters.Length;
			}

			int maxCount = parametersCounter.OptionalParametersCount + parametersCounter.RequiredParametersCount + searchMethodParametersCount;
			int minCount = parametersCounter.RequiredParametersCount + searchMethodParametersCount;

			if (argsCount < minCount || argsCount > maxCount)
			{
				Location location = invocation.GetMethodNameLocation();

				if (parametersCounter.OptionalParametersCount == 0)
				{
					syntaxContext.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(
						Descriptors.PX1015_PXBqlParametersMismatchWithOnlyRequiredParams,
						location, methodSymbol.Name, minCount), pxContext.CodereplacedysisSettings);
				}
				else
				{
					syntaxContext.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(
						Descriptors.PX1015_PXBqlParametersMismatchWithRequiredAndOptionalParams,
						location, methodSymbol.Name, minCount, maxCount), pxContext.CodereplacedysisSettings);
				}
			}
		}

19 View Source File : ConstructorInGraphExtensionAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, PXGraphSemanticModel pxGraph)
		{
			context.CancellationToken.ThrowIfCancellationRequested();
			var constructorLocations = pxGraph.Symbol.InstanceConstructors.Where(constructor => !constructor.IsImplicitlyDeclared)
																		  .SelectMany(constructor => constructor.Locations);
			foreach (Location location in constructorLocations)
			{
				context.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1040_ConstructorInGraphExtension, location), 
					pxContext.CodereplacedysisSettings);
			}
		}

19 View Source File : DacExtensionDefaultAttributeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void replacedyzeUnboundProperty(SymbolreplacedysisContext symbolContext, PXContext pxContext, DacSemanticModel dacOrExtension,
												   DacPropertyInfo property)
        {
            var (pxDefaultAttribute, hasPersistingCheckNothing) = GetPXDefaultInfo(pxContext, property);

            if (pxDefaultAttribute == null || hasPersistingCheckNothing)
                return;

            var attributeLocation = GetAttributeLocation(pxDefaultAttribute, symbolContext.CancellationToken);
            if (attributeLocation == null)
            {
                return;
            }

            var diagnosticProperties = ImmutableDictionary<string, string>.Empty
																		  .Add(DiagnosticProperty.IsBoundField, bool.FalseString);
            var descriptor = dacOrExtension.DacType == DacType.Dac
				? Descriptors.PX1030_DefaultAttibuteToExistingRecordsOnDAC 
				: Descriptors.PX1030_DefaultAttibuteToExistingRecordsError;
            var diagnostic = Diagnostic.Create(descriptor, attributeLocation, diagnosticProperties);

            symbolContext.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
        }

19 View Source File : DacExtensionDefaultAttributeAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void replacedyzeBoundPropertyAttributes(SymbolreplacedysisContext symbolContext, PXContext pxContext, DacPropertyInfo property)
        {
            var pxDefaultAttribute = GetInvalidPXDefaultAttributeFromBoundProperty(pxContext, property);

            if (pxDefaultAttribute == null)
                return;

            var attributeLocation = GetAttributeLocation(pxDefaultAttribute, symbolContext.CancellationToken);
            if (attributeLocation == null)
                return;

            var diagnosticProperties = ImmutableDictionary<string, string>.Empty
																		  .Add(DiagnosticProperty.IsBoundField, bool.TrueString);
            var diagnostic = Diagnostic.Create(Descriptors.PX1030_DefaultAttibuteToExistingRecordsWarning, attributeLocation, diagnosticProperties);

            symbolContext.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
        }

19 View Source File : LegacyBqlFieldAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dac)
		{
			foreach (DacFieldInfo dacField in dac.DeclaredFields)
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				if (dacField.Symbol.BaseType.SpecialType != SpecialType.System_Object || AlreadyStronglyTyped(dacField.Symbol, pxContext))
					continue;

				Location location = dacField.Symbol.Locations.FirstOrDefault();

				if (location != null && dac.PropertiesByNames.TryGetValue(dacField.Name, out DacPropertyInfo property))
				{
					string propertyTypeName = GetPropertyTypeName(property.Symbol, pxContext);

					if (propertyTypeName == null || !PropertyTypeToFieldType.ContainsKey(propertyTypeName))
						continue;

					var args = ImmutableDictionary.CreateBuilder<string, string>();
					args.Add(CorrespondingPropertyType, propertyTypeName);
					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1060_LegacyBqlField, location, args.ToImmutable(), dacField.Name),
						pxContext.CodereplacedysisSettings);
				}
			}
		}

19 View Source File : PXGraphCreateInstanceAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
            {
                if (node.Type == null || !(_semanticModel.GetSymbolInfo(node.Type).Symbol is ITypeSymbol typeSymbol))
                {
                    base.VisitObjectCreationExpression(node);
                    return;
                }

                DiagnosticDescriptor descriptor = GetDiagnosticDescriptor(typeSymbol);

                if (descriptor != null)
                {
                    _context.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(descriptor, node.GetLocation()), 
						_pxContext.CodereplacedysisSettings);
                }

                base.VisitObjectCreationExpression(node);
            }

19 View Source File : TypoInViewDelegateNameAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, PXGraphSemanticModel graphModel)
		{
			var viewWithoutDelegatesNames = graphModel.Views.Where(view => !graphModel.ViewDelegatesByNames.ContainsKey(view.Symbol.Name))
															.Select(view => view.Symbol.Name)
															.ToList(capacity: graphModel.ViewsByNames.Count);
			if (viewWithoutDelegatesNames.Count == 0)
				return;

			var delegateCandidates = from method in graphModel.Symbol.GetMembers().OfType<IMethodSymbol>()
									 where method.ContainingType.Equals(graphModel.Symbol) && !method.IsOverride &&
										   (!graphModel.ViewDelegatesByNames.TryGetValue(method.Name, out var delegateInfo) || method != delegateInfo.Symbol) &&
										   method.IsValidViewDelegate(pxContext) && !method.IsValidActionHandler(pxContext)
									 select method;

			foreach (IMethodSymbol method in delegateCandidates)
			{
				if (viewWithoutDelegatesNames.Any(viewName => viewName == method.Name))
					continue;

				string nearestViewName = FindNearestView(viewWithoutDelegatesNames, method);

				if (nearestViewName != null && !method.Locations.IsEmpty)
				{
					var properties = ImmutableDictionary.CreateBuilder<string, string>();
					properties.Add(ViewFieldNameProperty, nearestViewName);

					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(Descriptors.PX1005_TypoInViewDelegateName, method.Locations.First(), properties.ToImmutable(), nearestViewName),
						pxContext.CodereplacedysisSettings);
				}
			}
		}

19 View Source File : UnderscoresInDacAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void CheckIdentifierForUnderscores(SyntaxToken identifier, SymbolreplacedysisContext context, PXContext pxContext)
		{
			if (!identifier.ValueText.Contains("_"))
				return;

			bool registerCodeFix = !IdentifierContainsOnlyUnderscores(identifier.ValueText);

			var diagnosticProperties = new Dictionary<string, string>
			{
				{ DiagnosticProperty.RegisterCodeFix, registerCodeFix.ToString() }
			}.ToImmutableDictionary();

			context.ReportDiagnosticWithSuppressionCheck(
				Diagnostic.Create(Descriptors.PX1026_UnderscoresInDacDeclaration, identifier.GetLocation(), diagnosticProperties),
				pxContext.CodereplacedysisSettings);
		}

19 View Source File : InternalApiCallsWalker.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void ReportInternalApiDiagnostic(Location? location)
		{
			CancellationToken.ThrowIfCancellationRequested();

			if (location == null || _reportedLocations.Contains(location))
				return;

			var internalApiDiagnostic = Diagnostic.Create(Descriptors.PX1076_CallToPXInternalUseOnlyAPI_OnlyISV, location);
			_syntaxContext.ReportDiagnosticWithSuppressionCheck(internalApiDiagnostic, _pxContext.CodereplacedysisSettings);
			_reportedLocations.Add(location);
		}

19 View Source File : ConstructorInDacAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dacOrDacExtenstion)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var dacConstructors = dacOrDacExtenstion.GetMemberNodes<ConstructorDeclarationSyntax>();

			foreach (var constructor in dacConstructors)
			{
				context.CancellationToken.ThrowIfCancellationRequested();
			
				context.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1028_ConstructorInDacDeclaration, constructor.Identifier.GetLocation()),
					pxContext.CodereplacedysisSettings);
			}
		}

19 View Source File : KeyFieldDeclarationAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dac)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var keyAttributes = new List<AttributeInfo>(capacity: 2);
			var declaredInDacKeyAttributes = new List<AttributeInfo>(capacity: 2);
			bool containsIdenreplacedyKeys = false;

			foreach (DacPropertyInfo property in dac.DacProperties.Where(p => p.IsKey))
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				IEnumerable<AttributeInfo> propertyKeyAttributes = property.Attributes.Where(a => a.IsKey);
				containsIdenreplacedyKeys = containsIdenreplacedyKeys || property.IsIdenreplacedy;

				keyAttributes.AddRange(propertyKeyAttributes);

				if (property.Symbol.ContainingType == dac.Symbol)
				{
					declaredInDacKeyAttributes.AddRange(propertyKeyAttributes);
				}
			}

			if (keyAttributes.Count > 1 && containsIdenreplacedyKeys && declaredInDacKeyAttributes.Count > 0)
			{		
				var locations = declaredInDacKeyAttributes.Select(attribute => GetAttributeLocation(attribute.AttributeData, context.CancellationToken)).ToList();

				foreach (Location attributeLocation in locations)
				{
					var extraLocations = locations.Where(l => l != attributeLocation);

					context.ReportDiagnosticWithSuppressionCheck(
						Diagnostic.Create(
							Descriptors.PX1055_DacKeyFieldsWithIdenreplacedyKeyField, attributeLocation, extraLocations),
							pxContext.CodereplacedysisSettings);
				}
			}
		}

19 View Source File : DacPropertyAttributesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void CheckForPXDBCalcedAndUnboundTypeAttributes(SymbolreplacedysisContext symbolContext, PXContext pxContext, IPropertySymbol propertySymbol,
																	   List<(AttributeInfo Attribute, List<FieldTypeAttributeInfo> Infos)> attributesWithInfos)
		{
			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			var (pxDBCalcedAttribute, _) = attributesWithInfos.FirstOrDefault(attrWithInfos => 
																				attrWithInfos.Infos.Any(i => i.Kind == FieldTypeAttributeKind.PXDBCalcedAttribute));
			if (pxDBCalcedAttribute == null)
				return;

			bool hasUnboundTypeAttribute = attributesWithInfos.Any(attrWithInfos => !ReferenceEquals(attrWithInfos.Attribute, pxDBCalcedAttribute) &&
																					attrWithInfos.Attribute.BoundType == BoundType.Unbound);
			if (hasUnboundTypeAttribute)
				return;

			if (!(propertySymbol.GetSyntax(symbolContext.CancellationToken) is PropertyDeclarationSyntax propertyNode))
				return;

			var diagnostic = Diagnostic.Create(Descriptors.PX1095_PXDBCalcedMustBeAccompaniedNonDBTypeAttribute, propertyNode.Identifier.GetLocation());
			symbolContext.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
		}

19 View Source File : DacForeignKeyDeclarationAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected override void MakeSpecificDacKeysreplacedysis(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac,
															List<INamedTypeSymbol> dacForeignKeys, Dictionary<INamedTypeSymbol, List<ITypeSymbol>> dacFieldsByKey)
		{
			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			if (dacForeignKeys.Count == 0)
			{
				ReportNoForeignKeyDeclarationsInDac(symbolContext, context, dac);
				return;
			}

			INamedTypeSymbol foreignKeysContainer = dac.Symbol.GetTypeMembers(ReferentialIntegrity.ForeignKeyClreplacedName)
															  .FirstOrDefault();

			//We can register code fix only if there is no FK nested type in DAC or there is a public static FK clreplaced. Otherwise we will break the code.
			bool registerCodeFix = foreignKeysContainer == null ||
								   (foreignKeysContainer.DeclaredAccessibility == Accessibility.Public && foreignKeysContainer.IsStatic);

			List<INamedTypeSymbol> keysNotInContainer = GetKeysNotInContainer(dacForeignKeys, foreignKeysContainer);

			if (keysNotInContainer.Count == 0)
				return;

			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			Location dacLocation = dac.Node.GetLocation();
			var keysNotInContainerLocations = GetKeysLocations(keysNotInContainer, symbolContext.CancellationToken).ToList(capacity: keysNotInContainer.Count);

			if (dacLocation == null || keysNotInContainerLocations.Count == 0)
				return;

			var dacLocationArray = new[] { dacLocation };
			var diagnosticProperties = new Dictionary<string, string>
			{
				{ nameof(RefIntegrityDacKeyType), RefIntegrityDacKeyType.ForeignKey.ToString() },
				{ DiagnosticProperty.RegisterCodeFix, registerCodeFix.ToString() }
			}
			.ToImmutableDictionary();

			foreach (Location keyLocation in keysNotInContainerLocations)
			{
				var otherKeyLocations = keysNotInContainerLocations.Where(location => location != keyLocation);
				var additionalLocations = dacLocationArray.Concat(otherKeyLocations);

				symbolContext.ReportDiagnosticWithSuppressionCheck(
									Diagnostic.Create(Descriptors.PX1036_WrongDacForeignKeyDeclaration, keyLocation, additionalLocations, diagnosticProperties),
									context.CodereplacedysisSettings);
			}
		}

19 View Source File : DacForeignKeyDeclarationAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void ReportNoForeignKeyDeclarationsInDac(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac)
		{
			Location location = dac.Node.Identifier.GetLocation() ?? dac.Node.GetLocation();

			if (location != null)
			{
				symbolContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1034_MissingDacForeignKeyDeclaration, location),
					context.CodereplacedysisSettings);
			} 
		}

private void ReportNoPrimaryKeyDeclarationsInDac(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac)
		{
			Location location = dac.Node.Identifier.GetLocation() ?? dac.Node.GetLocation();

			if (location != null)
			{
				symbolContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1033_MissingDacPrimaryKeyDeclaration, location),
					context.CodereplacedysisSettings);
			} 
		}

private void CheckBigGroupOfKeysForPrimaryKeyAndUniqueKeysContainer(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac,
																			List<INamedTypeSymbol> keyDeclarations, 
																			Dictionary<INamedTypeSymbol, List<ITypeSymbol>> dacFieldsByKey)
		{
			var primaryKey = keyDeclarations.Find(key => key.Name == ReferentialIntegrity.PrimaryKeyClreplacedName);
	
			if (primaryKey == null)
			{
				//If there is no primary key - try to find suitable unique key and rename it. Otherwise report no primary key in DAC
				ProcessDacWithoutPrimaryKeyAndWithSeveralUniqueKeys(symbolContext, context, dac, keyDeclarations, dacFieldsByKey);
				return;
			}

			INamedTypeSymbol uniqueKeysContainer = dac.Symbol.GetTypeMembers(ReferentialIntegrity.UniqueKeyClreplacedName)
															 .FirstOrDefault();
			
			//We can register code fix only if there is no UK nested type in DAC or there is a public static UK clreplaced. Otherwise we will break the code.
			bool registerCodeFix = uniqueKeysContainer == null || 
								   (uniqueKeysContainer.DeclaredAccessibility == Accessibility.Public && uniqueKeysContainer.IsStatic);

			List<INamedTypeSymbol> keysNotInContainer = GetKeysNotInContainer(keyDeclarations, uniqueKeysContainer, primaryKey);

			if (keysNotInContainer.Count == 0)
				return;

			symbolContext.CancellationToken.ThrowIfCancellationRequested();

			Location dacLocation = dac.Node.GetLocation();
			var keysNotInContainerLocations = GetKeysLocations(keysNotInContainer, symbolContext.CancellationToken).ToList(capacity: keysNotInContainer.Count);

			if (dacLocation == null || keysNotInContainerLocations.Count == 0)
				return;

			var dacLocationArray = new[] { dacLocation };
			var diagnosticProperties = new Dictionary<string, string>
			{
				{ nameof(RefIntegrityDacKeyType), RefIntegrityDacKeyType.UniqueKey.ToString() },
				{ nameof(UniqueKeyCodeFixType), UniqueKeyCodeFixType.MultipleUniqueKeys.ToString() },
				{ DiagnosticProperty.RegisterCodeFix, registerCodeFix.ToString() }
			}
			.ToImmutableDictionary();	
			
			foreach (Location keyLocation in keysNotInContainerLocations)
			{
				var otherKeyLocations = keysNotInContainerLocations.Where(location => location != keyLocation);
				var additionalLocations = dacLocationArray.Concat(otherKeyLocations);

				symbolContext.ReportDiagnosticWithSuppressionCheck(
									Diagnostic.Create(Descriptors.PX1036_WrongDacMultipleUniqueKeyDeclarations, keyLocation, additionalLocations, diagnosticProperties),
									context.CodereplacedysisSettings);			
			}
		}

19 View Source File : DacUiAttributesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dac)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var dacAttributes = dac.Symbol.GetAttributes();
			var pxCacheNameAttribute = pxContext.AttributeTypes.PXCacheNameAttribute;
			var pxHiddenAttribute = pxContext.AttributeTypes.PXHiddenAttribute;
			bool hasPXCacheNameAttribute = false;
			bool hasPXHiddenAttribute = false;

			foreach (var attribute in dacAttributes.Where(a => a.AttributeClreplaced != null))
			{
				if (attribute.AttributeClreplaced.InheritsFromOrEquals(pxCacheNameAttribute))
				{
					hasPXCacheNameAttribute = true;
				}

				if (attribute.AttributeClreplaced.InheritsFromOrEquals(pxHiddenAttribute))
				{
					hasPXHiddenAttribute = true;
				}

				if (hasPXCacheNameAttribute || hasPXHiddenAttribute)
					return;
			}

			var diagnostic = Diagnostic.Create(Descriptors.PX1094_DacShouldHaveUiAttribute,
											   dac.Node.Identifier.GetLocation());

			context.ReportDiagnosticWithSuppressionCheck(diagnostic, pxContext.CodereplacedysisSettings);
		}

private static void replacedyzeSetProcessDelegateMethod(SyntaxNodereplacedysisContext syntaxContext, PXContext pxContext)
		{
			var setDelegateInvocation = syntaxContext.Node as InvocationExpressionSyntax;

			if (!CheckIfDiagnosticIsValid(setDelegateInvocation, syntaxContext, pxContext))
				return;
            
            DataFlowreplacedysis dfa = null;

            switch (setDelegateInvocation.ArgumentList.Arguments[0].Expression)
            {
                case IdentifierNameSyntax ins:
					ISymbol identifierSymbol = syntaxContext.SemanticModel.GetSymbolInfo(ins, syntaxContext.CancellationToken).Symbol;

					if (identifierSymbol != null && !identifierSymbol.IsStatic)
                    {
                        syntaxContext.ReportDiagnosticWithSuppressionCheck(
                            Diagnostic.Create(
                                Descriptors.PX1008_LongOperationDelegateClosures, setDelegateInvocation.GetLocation()),
							pxContext.CodereplacedysisSettings);
                    }

                    return;
				case MemberAccessExpressionSyntax memberAccess 
				when memberAccess.Expression is ElementAccessExpressionSyntax arrayIndexAccess:
					replacedyzeMemberAccessExpressions(arrayIndexAccess.Expression, syntaxContext, pxContext);
					return;
				case MemberAccessExpressionSyntax memberAccess:
					replacedyzeMemberAccessExpressions(memberAccess.Expression, syntaxContext, pxContext);
					return;
				case ConditionalAccessExpressionSyntax conditionalAccess 
				when conditionalAccess.Expression is ElementAccessExpressionSyntax arrayIndexAccess:
					replacedyzeMemberAccessExpressions(arrayIndexAccess.Expression, syntaxContext, pxContext);
					return;
				case ConditionalAccessExpressionSyntax conditionalAccess:
					replacedyzeMemberAccessExpressions(conditionalAccess.Expression, syntaxContext, pxContext);
					return;
                case AnonymousMethodExpressionSyntax anonMethodNode:
                    dfa = syntaxContext.SemanticModel.replacedyzeDataFlow(anonMethodNode);
                    break;
                case LambdaExpressionSyntax lambdaNode:
                    dfa = syntaxContext.SemanticModel.replacedyzeDataFlow(lambdaNode);
                    break;
            }

            if (dfa != null && dfa.DataFlowsIn.OfType<IParameterSymbol>().Any(p => p.IsThis))
            {
                syntaxContext.ReportDiagnosticWithSuppressionCheck(
                    Diagnostic.Create(
                        Descriptors.PX1008_LongOperationDelegateClosures, setDelegateInvocation.GetLocation()),
					pxContext.CodereplacedysisSettings);
            }
        }

private static void replacedyzeMemberAccessExpressions(ExpressionSyntax expression, SyntaxNodereplacedysisContext syntaxContext, 
														   PXContext pxContext)
		{
			if (!(expression is IdentifierNameSyntax identifier))
				return;

			ISymbol identifierSymbol = syntaxContext.SemanticModel.GetSymbolInfo(identifier, syntaxContext.CancellationToken).Symbol;

			if (identifierSymbol == null || syntaxContext.CancellationToken.IsCancellationRequested)
				return;

			if ((identifierSymbol.Kind == SymbolKind.Field || identifierSymbol.Kind == SymbolKind.Property) && !identifierSymbol.IsStatic)
			{
				var setDelegateInvocation = syntaxContext.Node as InvocationExpressionSyntax;
				syntaxContext.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(
						Descriptors.PX1008_LongOperationDelegateClosures, setDelegateInvocation.GetLocation()),
					pxContext.CodereplacedysisSettings);
			}
		}

19 View Source File : MethodsUsageInDacAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void replacedyzeMethodDeclarationInDac(MethodDeclarationSyntax method, SymbolreplacedysisContext context, PXContext pxContext)
		{
			if (!method.IsStatic())
			{
				context.ReportDiagnosticWithSuppressionCheck(
					Diagnostic.Create(Descriptors.PX1031_DacCannotContainInstanceMethods, method.Identifier.GetLocation()),
					pxContext.CodereplacedysisSettings);
			}
		}

See More Examples