Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@

# SourceGenerator Launch Settings
src/CompositeKey.SourceGeneration/Properties/launchSettings.json

# Claude Code
.claude/settings.local.json
.claude/todos/
68 changes: 68 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -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<TSelf>` / `ICompositePrimaryKey<TSelf>` 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<TSelf>` 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<T>`, `List<T>`, `ImmutableArray<T>` 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
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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<Guid> 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.

<!-- Badges -->
[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
Expand Down
23 changes: 23 additions & 0 deletions docs/rules/COMPOSITE0001.md
Original file line number Diff line number Diff line change
@@ -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
<PropertyGroup>
<LangVersion>11</LangVersion>
</PropertyGroup>
```

Or target a framework that defaults to C# 11+ (e.g. net7.0 or later).
25 changes: 25 additions & 0 deletions docs/rules/COMPOSITE0002.md
Original file line number Diff line number Diff line change
@@ -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);
```
35 changes: 35 additions & 0 deletions docs/rules/COMPOSITE0003.md
Original file line number Diff line number Diff line change
@@ -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);
}
```
32 changes: 32 additions & 0 deletions docs/rules/COMPOSITE0004.md
Original file line number Diff line number Diff line change
@@ -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) { }
}
```
34 changes: 34 additions & 0 deletions docs/rules/COMPOSITE0005.md
Original file line number Diff line number Diff line change
@@ -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#`, `~`, `@` |
25 changes: 25 additions & 0 deletions docs/rules/COMPOSITE0006.md
Original file line number Diff line number Diff line change
@@ -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);
```
33 changes: 33 additions & 0 deletions docs/rules/COMPOSITE0007.md
Original file line number Diff line number Diff line change
@@ -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.
32 changes: 32 additions & 0 deletions docs/rules/COMPOSITE0008.md
Original file line number Diff line number Diff line change
@@ -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);
```
Loading
Loading