Example #1
0
        private static bool ProcessMethod(GeneratorExecutionContext context, StringBuilder source, IMethodSymbol methodSymbol, ISymbol attributeSymbol, ISymbol taskSymbol)
        {
            // Get the name and type of the field
            var methodName = methodSymbol.Name;
            var methodType = methodSymbol.ReturnType;

            if (methodType.SpecialType != SpecialType.System_Void && !methodType.Equals(taskSymbol, SymbolEqualityComparer.Default))
            {
                context.ReportDiagnostic(methodSymbol, "SG0002", $"Only methods with return type of void or Task can use {attributeSymbol.Name}");
                return(false);
            }

            // Get the Command attribute from the method, and any associated data
            var attributeData    = methodSymbol.GetAttributes().Single(x => x.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default));
            var overridenNameOpt = attributeData.NamedArguments.SingleOrDefault(x => x.Key == "Name").Value;

            var propertyName = ChoosePropertyName(methodName, overridenNameOpt);

            if (propertyName.Length == 0)
            {
                context.ReportDiagnostic(methodSymbol, "SG0003", $"The resulting command property name cannot be processed for method {methodName}");
                return(false);
            }

            if (methodSymbol.Parameters.Length > 1)
            {
                context.ReportDiagnostic(methodSymbol, "SG0004", $"Only methods with 0 or 1 parameters can use {attributeSymbol.Name}");
                return(false);
            }

            var fieldName = propertyName.ToFieldName();

            var commandType = methodType.SpecialType == SpecialType.System_Void ? RelayCommandReference : AsyncCommandReference;
            var suffix      = methodSymbol.Parameters.Length == 0 ? string.Empty : $"<{methodSymbol.Parameters[0].Type.ToDisplayString()}>";

            //context.ReportDiagnostic(methodSymbol, "SG9999", $"Doc ID for {methodSymbol.Name}: {methodSymbol.GetDocumentationCommentId()}");

            var text = $@"
        private {commandType}{suffix}? {fieldName};
{methodSymbol.GetDocstring()}
        public {commandType}{suffix} {propertyName} => {fieldName} ??= new {commandType}{suffix}({methodName});
";

            source.Append(text);

            return(true);
        }