STJ generator with external (generated) context class

Open
#108,317 14 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
csharp
Domain
tooling

Research direction

Start by reading the System.Text.Json source-generator handling for JsonSerializerContext and JsonSerializable attributes. Consider how an external GeneratedContext from another project could be supplied to the generator, and define completion as supporting that external context while preserving normal context generation; the proposed JsonSerializerExternalContext attribute is only an example.

Written by the indexing model from the issue text.

Description

area-System.Text.Json

Currently, you cannot stack Roslyn source generators to operate on generated code. As a workaround I opted into running my own generators in a separate project. That is, [JsonSerializable(...)] class MyContext : JsonSerializerContext is generated elsewhere, however this requires the STJ generator to recognize external context classes.

Project1:

// use a custom generator to generate the context, 
// note this is only a "blueprint" since STJ generator is not yet run.

// <auto-genreated/>
[JsonSerializable(...)] 
[JsonSerializable(...)] 
public class GeneratedContext /* : JsonSerializerContex; */

Project2 references Project1:

// STJ generator won't recognize GeneratedContext in scope
// but perhaps we can use something like this to hint on that:

[JsonSerializerExternalContext(typeof(GeneratedContext))] // use as attribute source
partial class MyContext : JsonSerializerContex;

This way we can stack generators using separate projects but the workaround only works if the final generator can work with external types.

(PS: this is not a problem specific to STJ though, every time you want to stack generators this can be a blocker, so maybe a more generic solution can be implemented instead)

Dominant language
C#
Stars
18.3k
Forks
5.6k
Avg merge
2d 19h
Merged PRs (30d)
589

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.