Source Generator: does not exist in current context

Hey all,

I'm currently looking into Source Generators and I'm immediately struggling with a simple HelloWorld-project.

I'm following the steps described here and when I want to run my console app that references my Source Gen class lib I constantly get the error " Program.cs(9, 13): [CS0103] The name "HelloWorldGenerated" does not exist in the current context.".

 

Nothing in the line in question has a squiggly in Rider and I can use F12 to get to the generated file "HelloWorldGenerated".

My Generator project csproj:

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.0.1" />
</ItemGroup>

</Project>

MyGenerator.cs:

using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace SourceGeneratorPlayground
{
[Generator]
public class MyGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{

}

public void Execute(GeneratorExecutionContext context)
{
var sourceBuilder = new StringBuilder(@"
using System;
namespace HelloWorldGenerated
{
public static class HelloWorld
{
public static void SayHello()
{
Console.WriteLine(""Hello from generated code!"");
Console.WriteLine(""The following syntax trees existed in the compilation that created this program:"");
");
// using the context, get a list of syntax trees in the users compilation
var syntaxTrees = context.Compilation.SyntaxTrees;

// add the filepath of each tree to the class we're building
foreach (SyntaxTree tree in syntaxTrees)
{
sourceBuilder.AppendLine($@"Console.WriteLine(@"" - {tree.FilePath}"");");
}

// finish creating the source to inject
sourceBuilder.Append(@"
}
}
}");

// inject the created source into the users compilation
context.AddSource("helloWorldGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}
}
}

My console test project csproj:

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

<ItemGroup>
<!-- Note that this is not a "normal" ProjectReference.
It needs the additional 'OutputItemType' and 'ReferenceOutputAssmbly' attributes. -->
<ProjectReference Include="..\SourceGeneratorPlayground\SourceGeneratorPlayground.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>


</Project>

 

My Program.cs:

using System;

namespace TestSourceGen
{
class Program
{
static void Main(string[] args)
{
HelloWorldGenerated.HelloWorld.SayHello();
}
}
}

 

What am I doing wrong?

4 comments
Comment actions Permalink

Which version of the .NET SDK are you using?

In the generator project, you are referring to

<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.0.1" />
</ItemGroup>
</Project>

For Roslyn 4.0 you need to use the .NET SDK 6.0.100 or later, with a .NET 6 compatible version of Rider [2021.3,).

See Roslyn compatibility: https://github.com/dotnet/roslyn/blob/main/docs/wiki/NuGet-packages.md

 

Let me know if this solves your problem.

0
Comment actions Permalink

Hello Michael Hochriegl,

What OS do you use, Windows/MacOS?

0
Comment actions Permalink

My bad! I had an earlier version of the EAP installed (EAP 2 I think) that I was accidentally running instead. I opened EAP 6 from the JetBrains Toolbox and now it works fine.

---

I have the exact same problem. I have a partial class that I'm generating some additional fields for using a source generator. It generates fine, and Rider recognizes the generated file, but I get a build error saying:

MyClass.cs(9, 22): [CS0103] The name 'myField' does not exist in the current context

Here's a MVCE:

namespace MyNamespace
{
public partial class MyClass
{
public void DoSomething()
{
Console.WriteLine(myField);
}
}
}
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace SourceGenerators
{
[Generator]
public class EntitySystemComponentMapperGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
BeginBlock("namespace MyNamespace");
{
BeginBlock("public partial class MyClass");
{
IndentedLn("private readonly string myField = \"Cats!!\";");
}
EndBlock();
}
EndBlock();
context.AddSource("MyClass.g.cs", SourceText.From(sb.ToString(), Encoding.UTF8));
}

public void Initialize(GeneratorInitializationContext context)
{
sb = new StringBuilder();
indentation = 0;
}

private StringBuilder sb;
private int indentation;

private void Indent()
{
indentation++;
}

private void Dedent()
{
indentation--;
}

private void BeginBlock(string statement = "")
{
if (statement.Length != 0)
IndentedLn(statement);
IndentedLn("{");
Indent();
}

private void EndBlock()
{
Dedent();
IndentedLn("}");
}

private void Raw(string text) => sb.Append(text);

private void Indented(string code)
{
for (var i = 0; i < indentation; i++)
Raw("\t");
Raw(code);
}

private void IndentedLn(string code) => Indented(code + "\n");
}
}

This gives the same error that I posted above. This is my environment:

IDE: JetBrains Rider 2022.2 EAP 6 (Doesn't work on latest non-EAP version either)
Main project:
- Target framework: net5.0
- Language version: C# 9
Generator project:
- Target framework: netstandard2.0
- Language version: C# 9
0
Comment actions Permalink

Charanor1

The root cause of the issue is that we run SourceGenerator on every change and keep the instance of the Generator in memory, but once you run Build we create the new instance of the generator. I'd recommend adding sb.Clear() at the beginning for the Execute() method.

0

Please sign in to leave a comment.