Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
beyaz committed Sep 9, 2024
1 parent 4bf6405 commit 965681b
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,14 @@ public void Execute(GeneratorExecutionContext context)
lines.Add($" writer.WritePropertyName(\"{propertyName}\");");
lines.Add($" writer.WriteBooleanValue(value.{propertyName}.Value);");
lines.Add("}");
continue;
}

lines.Add($"if ({propertyTypeName}HasValueChecker.HasValue(value.{propertyName}))");
lines.Add("{");
lines.Add($" writer.WritePropertyName(\"{propertyName}\");");
lines.Add($" JsonSerializer.Serialize(writer, value.{propertyName}, options);");
lines.Add("}");
}
}

Expand All @@ -79,7 +86,7 @@ public void Execute(GeneratorExecutionContext context)

public void Initialize(GeneratorInitializationContext context)
{
// AttachToDebugger();
AttachToDebugger();

// Register a syntax receiver to collect classes with the custom attribute
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
Expand Down
108 changes: 108 additions & 0 deletions ReactWithDotNet.SourceGenerator/HasValueMethodGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace ReactWithDotNet;

[Generator]
public class HasValueMethodGenerator : ISourceGenerator

Check warning on line 12 in ReactWithDotNet.SourceGenerator/HasValueMethodGenerator.cs

View workflow job for this annotation

GitHub Actions / build

'ReactWithDotNet.HasValueMethodGenerator': A project containing analyzers or source generators should specify the property '<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>'

Check warning on line 12 in ReactWithDotNet.SourceGenerator/HasValueMethodGenerator.cs

View workflow job for this annotation

GitHub Actions / build

'ReactWithDotNet.HasValueMethodGenerator': A project containing analyzers or source generators should specify the property '<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>'
{
public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not SyntaxReceiver receiver)
{
return;
}

// Loop through collected classes
foreach (var classDeclaration in receiver.CandidateClasses)
{
// Get the class name
var className = classDeclaration.Identifier.Text;

var lines = new List<string>
{
$"namespace {GetNamespace(classDeclaration)};",

$"static class {className}HasValueChecker",
"{",
$" public static bool HasValue({className} value)",
" {",
" if(value == null)",
" {",
" return false;",
" }"
};

foreach (var member in classDeclaration.Members)
{
if (member is PropertyDeclarationSyntax propertyDeclarationSyntax)
{
var propertyTypeName = propertyDeclarationSyntax.Type.ToFullString().Trim();
var propertyName = propertyDeclarationSyntax.Identifier.ValueText;

if (propertyTypeName == "double?"|| propertyTypeName == "bool?")
{
lines.Add($"if (value.{propertyName}.HasValue)");
lines.Add(" return true;");
continue;
}


}
}

lines.Add(" return false;");
lines.Add(" }"); // close method
lines.Add("}"); // close class

context.AddSource($"{className}HasValueChecker.generated", SourceText.From(string.Join(Environment.NewLine, lines), Encoding.UTF8));
}
}

public void Initialize(GeneratorInitializationContext context)
{
// AttachToDebugger();

// Register a syntax receiver to collect classes with the custom attribute
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}

// Helper to extract namespace
static string GetNamespace(ClassDeclarationSyntax classDeclaration)
{
var fileScopedNamespaceName = classDeclaration.FirstAncestorOrSelf<FileScopedNamespaceDeclarationSyntax>()?.Name;
if (fileScopedNamespaceName != null)
{
return fileScopedNamespaceName.ToString();
}

var namespaceDeclaration = classDeclaration.Ancestors()
.OfType<NamespaceDeclarationSyntax>()
.FirstOrDefault();

return namespaceDeclaration?.Name.ToString() ?? "global";
}

class SyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> CandidateClasses { get; } = new();

// Called for every syntax node in the compilation, we gather candidates here
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// Check if the node is a class declaration with the [AddExtraProperties] attribute
if (syntaxNode is ClassDeclarationSyntax classDeclaration &&
classDeclaration.AttributeLists
.SelectMany(al => al.Attributes)
.Any(ad => ad.Name.ToString() == "GenerateHasValue"))
{
CandidateClasses.Add(classDeclaration);
}
}
}
}
3 changes: 3 additions & 0 deletions ReactWithDotNet/Attributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,6 @@ public sealed class SkipRenderAttribute: Attribute;
[AttributeUsage(AttributeTargets.Class)]
sealed class FastSerializeAttribute: Attribute;

[AttributeUsage(AttributeTargets.Class)]
sealed class GenerateHasValueAttribute: Attribute;

4 changes: 4 additions & 0 deletions ReactWithDotNet/ThirdPartyLibraries/_Swiper_/Swiper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,15 @@ internal static (bool needToExport, object value)
}
}

[GenerateHasValue]
public sealed class SwiperNavigationOption
{
public bool? enabled { get; set; }
public string nextEl { get; set; }
public string prevEl { get; set; }
}

[GenerateHasValue]
public sealed class SwiperGridOption
{
public double? rows { get; set; }
Expand All @@ -195,6 +197,7 @@ public sealed class SwiperFadeEffect
public bool? crossFade { get; set; }
}

[GenerateHasValue]
public sealed class SwiperPagination
{
public bool? clickable { get; set; }
Expand All @@ -205,6 +208,7 @@ public sealed class SwiperScrollbar
public bool? draggable { get; set; }
}

[GenerateHasValue]
public sealed class SwiperAutoplay
{
public double? delay { get; set; }
Expand Down

0 comments on commit 965681b

Please sign in to comment.