From e8736f146c262e0a89db3a19806d6224bb9186a5 Mon Sep 17 00:00:00 2001 From: Daniel Woodward <16451892+DrBarnabus@users.noreply.github.com> Date: Fri, 20 Feb 2026 22:54:39 +0000 Subject: [PATCH] docs: Add CLAUDE.md, update README with installation and diagnostics, add analyzer rule docs Add CLAUDE.md for Claude Code guidance, update README with installation section, repeating section example, and diagnostics link. Add per-rule documentation for all 11 analyzer diagnostics (COMPOSITE0001-COMPOSITE0011) with cause, fix, and code examples. Update .gitignore for Claude Code. --- .gitignore | 4 +++ CLAUDE.md | 68 +++++++++++++++++++++++++++++++++++++ README.md | 19 ++++++++--- docs/rules/COMPOSITE0001.md | 23 +++++++++++++ docs/rules/COMPOSITE0002.md | 25 ++++++++++++++ docs/rules/COMPOSITE0003.md | 35 +++++++++++++++++++ docs/rules/COMPOSITE0004.md | 32 +++++++++++++++++ docs/rules/COMPOSITE0005.md | 34 +++++++++++++++++++ docs/rules/COMPOSITE0006.md | 25 ++++++++++++++ docs/rules/COMPOSITE0007.md | 33 ++++++++++++++++++ docs/rules/COMPOSITE0008.md | 32 +++++++++++++++++ docs/rules/COMPOSITE0009.md | 30 ++++++++++++++++ docs/rules/COMPOSITE0010.md | 25 ++++++++++++++ docs/rules/COMPOSITE0011.md | 32 +++++++++++++++++ docs/rules/README.md | 17 ++++++++++ 15 files changed, 429 insertions(+), 5 deletions(-) create mode 100644 CLAUDE.md create mode 100644 docs/rules/COMPOSITE0001.md create mode 100644 docs/rules/COMPOSITE0002.md create mode 100644 docs/rules/COMPOSITE0003.md create mode 100644 docs/rules/COMPOSITE0004.md create mode 100644 docs/rules/COMPOSITE0005.md create mode 100644 docs/rules/COMPOSITE0006.md create mode 100644 docs/rules/COMPOSITE0007.md create mode 100644 docs/rules/COMPOSITE0008.md create mode 100644 docs/rules/COMPOSITE0009.md create mode 100644 docs/rules/COMPOSITE0010.md create mode 100644 docs/rules/COMPOSITE0011.md create mode 100644 docs/rules/README.md diff --git a/.gitignore b/.gitignore index b786bc3..0f0f4e1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,7 @@ # SourceGenerator Launch Settings src/CompositeKey.SourceGeneration/Properties/launchSettings.json + +# Claude Code +.claude/settings.local.json +.claude/todos/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e7b3551 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,68 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +CompositeKey is a .NET source generation library that produces optimal parsing and formatting code for composite identifiers (partition key + sort key patterns common in NoSQL databases like DynamoDB). + +## Build & Test Commands + +```bash +dotnet build -c Release # Build all projects +dotnet test -c Release # Run all tests +dotnet pack src/CompositeKey -c Release # Create NuGet package + +# Run specific test projects +dotnet test src/CompositeKey.SourceGeneration.UnitTests -c Release +dotnet test src/CompositeKey.Analyzers.Common.UnitTests -c Release +dotnet test src/CompositeKey.Analyzers.UnitTests -c Release +dotnet test src/CompositeKey.SourceGeneration.FunctionalTests -c Release + +# Run a single test by fully-qualified name +dotnet test src/CompositeKey.SourceGeneration.UnitTests -c Release --filter "FullyQualifiedName~TestMethodName" +``` + +Requires .NET SDK 10.0 (see `global.json`). CI also tests against net8.0 and net9.0. + +## Architecture + +The solution is split into four main projects plus corresponding test projects: + +**CompositeKey** (`src/CompositeKey/`) — Public API surface. Contains `[CompositeKey]` attribute, `[CompositeKeyConstructor]` attribute, and the `IPrimaryKey` / `ICompositePrimaryKey` interfaces. This is the NuGet package users install; analyzers and source generator ship embedded inside it. + +**CompositeKey.SourceGeneration** (`src/CompositeKey.SourceGeneration/`) — Incremental source generator implementing `IIncrementalGenerator`. Three key phases: +- `SourceGenerator.cs` — Entry point; uses `ForAttributeWithMetadataName` for incremental pipeline +- `SourceGenerator.Parser.cs` — Extracts attribute data, validates types, builds `GenerationSpec` model +- `SourceGenerator.Emitter.cs` — Generates `ToString()`, `Parse()`, `TryParse()`, `ToPartitionKeyString()`, `ToSortKeyString()`, partial formatting methods, and `ISpanParsable` implementations + +**CompositeKey.Analyzers.Common** (`src/CompositeKey.Analyzers.Common/`) — Shared validation logic used by both the source generator and IDE analyzers. Contains `TemplateStringTokenizer`, type/template/property validation, and all `DiagnosticDescriptor` definitions (COMPOSITE0001–COMPOSITE0008+). + +**CompositeKey.Analyzers** (`src/CompositeKey.Analyzers/`) — IDE-time analyzers for real-time feedback: `TypeStructureAnalyzer`, `TemplateStringAnalyzer`, `PropertyAnalyzer`. + +## Key Domain Concepts + +**Template string**: The format pattern in `[CompositeKey("{Prop1}#{Prop2:N}")]`. Tokenized into key parts: `PropertyKeyPart`, `ConstantKeyPart`, `DelimiterKeyPart`, `PrimaryDelimiterKeyPart`, `RepeatingPropertyKeyPart`. + +**PrimaryKeySeparator**: Optional separator in the template that divides partition key from sort key, enabling `ToPartitionKeyString()` / `ToSortKeyString()` generation. + +**Repeating sections**: `{Collection...delimiter}` syntax for `IReadOnlyList`, `List`, `ImmutableArray` properties. + +**FormatType / ParseType**: Enums that control code generation strategy per property type (string, guid, enum, int, etc.) with fast-path optimizations for strings and enums. + +## Build Configuration + +- **TreatWarningsAsErrors**: enabled (except CS0618) +- **Nullable**: enabled globally +- **C# LangVersion**: 12 +- **RestorePackagesWithLockFile**: true (uses `packages.lock.json` files) +- **Central Package Management**: via `Directory.Packages.props` +- Analyzer projects target both `net8.0` and `netstandard2.0` + +## Conventions + +- Commit messages follow Conventional Commits (`feat:`, `fix:`, `perf:`, etc.) — GitVersion and `.versionrc` drive versioning and changelog +- EditorConfig: 4-space indent, UTF-8, LF line endings, 120-char max line length +- Test stack: xunit + Shouldly + AutoFixture +- Unit tests use `CompilationHelper` to create in-memory Roslyn compilations +- Functional tests define real key types and test format/parse round-trips diff --git a/README.md b/README.md index 99a8177..ee9cbfe 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,16 @@ --- +## Installation + +```shell +dotnet add package CompositeKey +``` + ## What is CompositeKey **CompositeKey** is a library for source generating optimal parsing and formatting code for composite identifiers in dotnet. - Implementing concepts widely used in NoSQL databases, such as [Amazon DynamoDb][dynamodb], a composite key is where multiple discrete keys are combined to form a more complex structure for use as the primary key of an item in the data. @@ -24,19 +29,23 @@ public sealed partial record PrimaryKey(Guid PartitionKey, Guid SortKey); Console.WriteLine(PrimaryKey.Parse($"{Guid.NewGuid()}#{Guid.NewGuid():N}")); -// Or they can be more complex -[CompositeKey("{PartitionKey}|{AnyParsableValue:0.00}#ConstantValueAsPartOfKey@{FirstPartOfSortKey}~{SecondPartOfSortKey}", PrimaryKeySeparator = '#')] -public sealed partial record ComplexKey(string PartitionKey, SomeEnum FirstPartOfSortKey, Guid SecondPartOfSortKey) +// Or they can be more complex, with partition/sort separation and repeating sections +[CompositeKey("{PartitionKey}|{AnyParsableValue:0.00}#ConstantValueAsPartOfKey@{FirstPartOfSortKey}~{Values...~}", PrimaryKeySeparator = '#')] +public sealed partial record ComplexKey(string PartitionKey, SomeEnum FirstPartOfSortKey, ImmutableArray Values) { public required int AnyParsableValue { get; init; } } -var complexKey = new ComplexKey(Guid.NewGuid().ToString(), SomeEnum.Value, Guid.NewGuid()) { AnyParsableValue = 123 }; +var complexKey = new ComplexKey(Guid.NewGuid().ToString(), SomeEnum.Value, [Guid.NewGuid(), Guid.NewGuid()]) { AnyParsableValue = 123 }; Console.WriteLine(complexKey.ToString()); Console.WriteLine(complexKey.ToPartitionKeyString()); Console.WriteLine(complexKey.ToSortKeyString()); ``` +## Diagnostics + +CompositeKey includes analyzers that provide real-time feedback in your IDE. See the [diagnostics documentation](docs/rules/) for a full list of rules and how to resolve them. + [gh-release-badge]: https://img.shields.io/github/v/release/DrBarnabus/CompositeKey?color=g&style=for-the-badge [gh-release]: https://github.com/DrBarnabus/CompositeKey/releases/latest diff --git a/docs/rules/COMPOSITE0001.md b/docs/rules/COMPOSITE0001.md new file mode 100644 index 0000000..86b729f --- /dev/null +++ b/docs/rules/COMPOSITE0001.md @@ -0,0 +1,23 @@ +# COMPOSITE0001: C# language version not supported + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0001 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The project is using a C# language version that is not supported by the CompositeKey source generator. The source generator requires C# 11 or later. + +## How to fix + +Update the `LangVersion` in your project file to 11 or later: + +```xml + + 11 + +``` + +Or target a framework that defaults to C# 11+ (e.g. net7.0 or later). diff --git a/docs/rules/COMPOSITE0002.md b/docs/rules/COMPOSITE0002.md new file mode 100644 index 0000000..272745d --- /dev/null +++ b/docs/rules/COMPOSITE0002.md @@ -0,0 +1,25 @@ +# COMPOSITE0002: Unsupported type + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0002 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The `[CompositeKey]` attribute was applied to a type that is not a record. Only record types are currently supported. + +## How to fix + +Change the type to a record: + +```csharp +// Before (error) +[CompositeKey("{Id}#{Name}")] +public sealed partial class MyKey { ... } + +// After (fixed) +[CompositeKey("{Id}#{Name}")] +public sealed partial record MyKey(Guid Id, string Name); +``` diff --git a/docs/rules/COMPOSITE0003.md b/docs/rules/COMPOSITE0003.md new file mode 100644 index 0000000..3a7a35d --- /dev/null +++ b/docs/rules/COMPOSITE0003.md @@ -0,0 +1,35 @@ +# COMPOSITE0003: Type must be partial + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0003 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The type annotated with `[CompositeKey]` (and/or its containing types) is not declared as `partial`. The source generator needs the `partial` modifier to emit additional members into the type. + +## How to fix + +Add the `partial` modifier to the type and all containing types: + +```csharp +// Before (error) +[CompositeKey("{Id}#{Name}")] +public sealed record MyKey(Guid Id, string Name); + +// After (fixed) +[CompositeKey("{Id}#{Name}")] +public sealed partial record MyKey(Guid Id, string Name); +``` + +If the type is nested, the containing type must also be partial: + +```csharp +public partial class Outer +{ + [CompositeKey("{Id}")] + public sealed partial record MyKey(Guid Id); +} +``` diff --git a/docs/rules/COMPOSITE0004.md b/docs/rules/COMPOSITE0004.md new file mode 100644 index 0000000..8620a24 --- /dev/null +++ b/docs/rules/COMPOSITE0004.md @@ -0,0 +1,32 @@ +# COMPOSITE0004: No obvious constructor + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0004 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The type annotated with `[CompositeKey]` has multiple constructors and the source generator cannot determine which one to use. The generator needs a single obvious constructor to know how to instantiate the type during parsing. + +## How to fix + +Either ensure the type has only one constructor, or mark the intended constructor with `[CompositeKeyConstructor]`: + +```csharp +// Before (error — two constructors, generator can't choose) +[CompositeKey("{GuidValue}#{IntValue}~{StringValue}#{EnumValue}")] +public sealed partial record MixedKey(Guid GuidValue, int IntValue, string StringValue, MyEnum EnumValue) +{ + public MixedKey(Guid guidValue) : this(guidValue, default, string.Empty, default) { } +} + +// After (fixed — attribute marks the primary constructor) +[CompositeKey("{GuidValue}#{IntValue}~{StringValue}#{EnumValue}")] +[method: CompositeKeyConstructor] +public sealed partial record MixedKey(Guid GuidValue, int IntValue, string StringValue, MyEnum EnumValue) +{ + public MixedKey(Guid guidValue) : this(guidValue, default, string.Empty, default) { } +} +``` diff --git a/docs/rules/COMPOSITE0005.md b/docs/rules/COMPOSITE0005.md new file mode 100644 index 0000000..4cc8b92 --- /dev/null +++ b/docs/rules/COMPOSITE0005.md @@ -0,0 +1,34 @@ +# COMPOSITE0005: Empty or invalid template string + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0005 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The template string provided to the `[CompositeKey]` attribute is either empty or could not be parsed. Template strings must contain at least one dynamic property reference and follow the correct syntax. + +## How to fix + +Provide a valid template string using `{PropertyName}` for dynamic values and literal characters for delimiters/constants: + +```csharp +// Before (error — empty template) +[CompositeKey("")] +public sealed partial record MyKey(Guid Id); + +// After (fixed) +[CompositeKey("{Id}")] +public sealed partial record MyKey(Guid Id); +``` + +Template syntax reference: + +| Syntax | Description | Example | +|--------|-------------|---------| +| `{PropertyName}` | Dynamic property value | `{Id}` | +| `{PropertyName:format}` | Dynamic value with format specifier | `{Id:N}` | +| `{PropertyName...separator}` | Repeating collection with separator | `{Tags...,}` | +| Literal characters | Constants or delimiters outside braces | `PREFIX#`, `~`, `@` | diff --git a/docs/rules/COMPOSITE0006.md b/docs/rules/COMPOSITE0006.md new file mode 100644 index 0000000..b698849 --- /dev/null +++ b/docs/rules/COMPOSITE0006.md @@ -0,0 +1,25 @@ +# COMPOSITE0006: PrimaryKeySeparator not found in template string + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0006 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The `PrimaryKeySeparator` character was specified in the `[CompositeKey]` attribute but does not appear as a delimiter in the template string. The separator must exist in the template to divide the partition key from the sort key. + +## How to fix + +Ensure the `PrimaryKeySeparator` character is used as a delimiter in the template: + +```csharp +// Before (error — '|' not in template) +[CompositeKey("{PartitionKey}#{SortKey}", PrimaryKeySeparator = '|')] +public sealed partial record MyKey(Guid PartitionKey, Guid SortKey); + +// After (fixed — '|' separates partition and sort) +[CompositeKey("{PartitionKey}|{SortKey}", PrimaryKeySeparator = '|')] +public sealed partial record MyKey(Guid PartitionKey, Guid SortKey); +``` diff --git a/docs/rules/COMPOSITE0007.md b/docs/rules/COMPOSITE0007.md new file mode 100644 index 0000000..ac11803 --- /dev/null +++ b/docs/rules/COMPOSITE0007.md @@ -0,0 +1,33 @@ +# COMPOSITE0007: Property missing accessible getter or setter + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0007 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +A property referenced in the template string does not have both an accessible getter and setter. The source generator needs both to format (get) and parse (set) the value. + +## How to fix + +Ensure the property has both accessible `get` and `set` (or `init`) methods: + +```csharp +// Before (error — no setter) +[CompositeKey("{Id}#{Name}")] +public sealed partial record MyKey(Guid Id) +{ + public string Name { get; } +} + +// After (fixed) +[CompositeKey("{Id}#{Name}")] +public sealed partial record MyKey(Guid Id) +{ + public required string Name { get; init; } +} +``` + +Record primary constructor parameters automatically have accessible getters and init setters, so they work by default. diff --git a/docs/rules/COMPOSITE0008.md b/docs/rules/COMPOSITE0008.md new file mode 100644 index 0000000..5b35e2b --- /dev/null +++ b/docs/rules/COMPOSITE0008.md @@ -0,0 +1,32 @@ +# COMPOSITE0008: Invalid or unsupported format specifier + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0008 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +A property in the template uses a format specifier that is invalid or unsupported for its type. The source generator validates format specifiers at compile time to ensure the generated code will work correctly. + +## How to fix + +Use a format specifier that is valid for the property's type: + +| Type | Supported formats | +|------|-------------------| +| `Guid` | `D`, `N`, `B`, `P`, `X` | +| `Enum` | `G` | +| `string` | *(none — format specifiers are not supported)* | +| Numeric types | Standard .NET numeric format strings (e.g. `0.00`, `F2`) | + +```csharp +// Before (error — 'Z' is not a valid Guid format) +[CompositeKey("{Id:Z}")] +public sealed partial record MyKey(Guid Id); + +// After (fixed) +[CompositeKey("{Id:N}")] +public sealed partial record MyKey(Guid Id); +``` diff --git a/docs/rules/COMPOSITE0009.md b/docs/rules/COMPOSITE0009.md new file mode 100644 index 0000000..4711009 --- /dev/null +++ b/docs/rules/COMPOSITE0009.md @@ -0,0 +1,30 @@ +# COMPOSITE0009: Repeating syntax used on non-collection property + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0009 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +The template uses repeating syntax (`{Property...separator}`) for a property that is not a supported collection type. + +Supported collection types are: +- `IReadOnlyList` +- `List` +- `ImmutableArray` + +## How to fix + +Either change the property to a supported collection type or remove the repeating syntax: + +```csharp +// Before (error — Guid is not a collection) +[CompositeKey("{Id...#}")] +public sealed partial record MyKey(Guid Id); + +// After (fixed — use a collection type) +[CompositeKey("{Ids...#}")] +public sealed partial record MyKey(IReadOnlyList Ids); +``` diff --git a/docs/rules/COMPOSITE0010.md b/docs/rules/COMPOSITE0010.md new file mode 100644 index 0000000..ca10a6a --- /dev/null +++ b/docs/rules/COMPOSITE0010.md @@ -0,0 +1,25 @@ +# COMPOSITE0010: Collection property without repeating syntax + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0010 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +A property in the template is a collection type (`List`, `IReadOnlyList`, or `ImmutableArray`) but the template does not use repeating syntax for it. Collection properties must use the `{Property...separator}` syntax so the generator knows how to format and parse multiple values. + +## How to fix + +Add repeating syntax with a separator character: + +```csharp +// Before (error — collection without repeating syntax) +[CompositeKey("{Ids}")] +public sealed partial record MyKey(IReadOnlyList Ids); + +// After (fixed — repeating syntax with '#' separator) +[CompositeKey("{Ids...#}")] +public sealed partial record MyKey(IReadOnlyList Ids); +``` diff --git a/docs/rules/COMPOSITE0011.md b/docs/rules/COMPOSITE0011.md new file mode 100644 index 0000000..dea870c --- /dev/null +++ b/docs/rules/COMPOSITE0011.md @@ -0,0 +1,32 @@ +# COMPOSITE0011: Repeating property is not last in its key section + +| Property | Value | +|----------|-------| +| Rule ID | COMPOSITE0011 | +| Category | CompositeKey.SourceGeneration | +| Severity | Error | + +## Cause + +A repeating property is not the last value part in its key section. Because repeating sections produce a variable number of values, they must appear at the end of their section (the partition key portion or the sort key portion) so the parser can correctly determine where the repeating values end. + +## How to fix + +Move the repeating property to the end of its key section: + +```csharp +// Before (error — repeating property is followed by another property) +[CompositeKey("{Tags...,}#{Name}", PrimaryKeySeparator = '#')] +public sealed partial record MyKey(List Tags, string Name); + +// After (fixed — repeating property is last in the partition section) +[CompositeKey("{Name}#{Tags...,}", PrimaryKeySeparator = '#')] +public sealed partial record MyKey(string Name, List Tags); +``` + +In a composite key with `PrimaryKeySeparator`, repeating properties can appear at the end of either the partition or sort section: + +```csharp +[CompositeKey("{TenantId}|LOCATION#{LocationIds...#}", PrimaryKeySeparator = '|')] +public sealed partial record MyKey(Guid TenantId, IReadOnlyList LocationIds); +``` diff --git a/docs/rules/README.md b/docs/rules/README.md new file mode 100644 index 0000000..f32723b --- /dev/null +++ b/docs/rules/README.md @@ -0,0 +1,17 @@ +# CompositeKey Analyzer Rules + +All diagnostics are in the `CompositeKey.SourceGeneration` category with a default severity of **Error**. + +| Rule ID | Description | +|---------|-------------| +| [COMPOSITE0001](COMPOSITE0001.md) | C# language version not supported | +| [COMPOSITE0002](COMPOSITE0002.md) | Unsupported type (only records are supported) | +| [COMPOSITE0003](COMPOSITE0003.md) | Type must be declared as partial | +| [COMPOSITE0004](COMPOSITE0004.md) | No obvious constructor found | +| [COMPOSITE0005](COMPOSITE0005.md) | Empty or invalid template string | +| [COMPOSITE0006](COMPOSITE0006.md) | PrimaryKeySeparator not found in template string | +| [COMPOSITE0007](COMPOSITE0007.md) | Property missing accessible getter or setter | +| [COMPOSITE0008](COMPOSITE0008.md) | Invalid or unsupported format specifier | +| [COMPOSITE0009](COMPOSITE0009.md) | Repeating syntax used on non-collection property | +| [COMPOSITE0010](COMPOSITE0010.md) | Collection property without repeating syntax | +| [COMPOSITE0011](COMPOSITE0011.md) | Repeating property is not last in its key section |