Initial commit.

This commit is contained in:
Phil Gilmore 2025-03-05 08:06:37 -07:00
commit 03b7002d4b
9 changed files with 625 additions and 0 deletions

34
.editorconfig Normal file
View File

@ -0,0 +1,34 @@
root=true
[{*, *.*}]
resharper_tabs_are_disallowed_highlighting=none
[*.cs]
tab_width = 4
indent_size = 4
indent_style = tab
[{*.vb, *.bas}]
tab_width = 4
indent_size = 4
indent_style = tab
[*.xml]
tab_width = 4
indent_size = 4
indent_style = tab
[*.py]
tab_width = 4
indent_size = 4
indent_style = tab
[{*.yml, *.yaml}]
tab_width = 2
indent_size = 2
indent_style = space
[*.pas]
tab_width = 2
indent_size = 2
indent_style = space

398
.gitignore vendored Normal file
View File

@ -0,0 +1,398 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

View File

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GeneratorLib\GeneratorLib.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"/>
</ItemGroup>
</Project>

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35506.116 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneratorConsole", "GeneratorConsole.csproj", "{C65515FB-4DA0-459C-94B6-542B26D25886}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneratorLib", "..\GeneratorLib\GeneratorLib.csproj", "{B3522DFA-0DDF-49A0-871F-40571B5A51DB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C65515FB-4DA0-459C-94B6-542B26D25886}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C65515FB-4DA0-459C-94B6-542B26D25886}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C65515FB-4DA0-459C-94B6-542B26D25886}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C65515FB-4DA0-459C-94B6-542B26D25886}.Release|Any CPU.Build.0 = Release|Any CPU
{B3522DFA-0DDF-49A0-871F-40571B5A51DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3522DFA-0DDF-49A0-871F-40571B5A51DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3522DFA-0DDF-49A0-871F-40571B5A51DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3522DFA-0DDF-49A0-871F-40571B5A51DB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,11 @@
namespace GeneratorConsole;
internal class Program
{
private static void Main(string[] args)
{
// This line produces error "CS0103: The name 'HelloNamespace' does not exist in the current context", but it still builds and works!
// I had to delete the .vs directory to clean it up.
HelloNamespace.HelloWorld.SayHello();
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<langVersion>12</langVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
<IncludeBuildOutput>false</IncludeBuildOutput>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<!--<CompilerGeneratedFilesOutputPath>.\GeneratedFiles</CompilerGeneratedFilesOutputPath>-->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,41 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Immutable;
using System.Text;
namespace GeneratorLib;
[Generator(LanguageNames.CSharp)]
public class HelloWorldGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var provider = context.SyntaxProvider.CreateSyntaxProvider(
static (syntaxNode, _) => syntaxNode is ClassDeclarationSyntax,
static (generatorSyntaxContext, _) => (ClassDeclarationSyntax)generatorSyntaxContext.Node)
.Where(static node => node != null);
var compilation = context.CompilationProvider.Combine(provider.Collect());
context.RegisterSourceOutput(compilation, ExecuteHelloWorldGeneration);
}
private static void ExecuteHelloWorldGeneration(SourceProductionContext context, (Compilation compilation, ImmutableArray<ClassDeclarationSyntax> classDeclarationSyntax) compilationProvider)
{
const string hintName = "HelloWorld.g.cs";
string sourceText = new StringBuilder()
.AppendLine("namespace HelloNamespace")
.AppendLine("{")
.AppendLine("\tpublic class HelloWorld")
.AppendLine("\t{")
.AppendLine("\t\tpublic static void SayHello()")
.AppendLine("\t\t{")
.AppendLine("\t\t\tConsole.WriteLine(\"Hello, World!\");")
.AppendLine("\t\t}")
.AppendLine("\t}")
.AppendLine("}")
.ToString();
context.AddSource(hintName, sourceText);
}
}

21
license.txt Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

51
readme.md Normal file
View File

@ -0,0 +1,51 @@
# Source Generator Demo
This is an attempt at a bare-bones minimal source generator in an attemp to evolve to a project template or other boilerplate approach to creating source generators.
## GeneratorConsole and HelloWorldGenerator
The HelloWorldGenerator should produce a static class with a single static method that can easily by called by any project that properly references the analyzer project, GeneratorLib. It should be called like this:
```
HelloWorldNamespace.HelloWorld.SayHello();
```
## How to Greate a Source Generator
* Create a new class library for the generators.
* Change the class library target framework to "netstandard2.0", even if there is a newer version. This is a "plugin" for the analyzer system and must match its version.
* Manually add appropriate attributes to the .csproj file as listed below.
* Add appropriate NuGet references listed below.
Appropriate attributes for the generator .csproj project file:
* `<langVersion>12</langVersion>` OR `<langVersion>latest</langVersion>`
* `<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>`
* `<IsRoslynComponent>true</IsRoslynComponent>`
* `<IncludeBuildOutput>false</IncludeBuildOutput>`
* `<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>`
Probably not needed attributes:
* `<CompilerGeneratedFilesOutputPath>.\GeneratedFiles</CompilerGeneratedFilesOutputPath>`
Required NuGet references for generators:
* `Microsoft.CodeAnalysis.Analyzers`
* `Microsoft.CodeAnalysis.CSharp`
Gen-1 analyzers also needed (Gen-2 probably does not and sometimes gives you a warning to remove it):
* `Microsoft.CodeAnalysis.CSharp.Workspaces`
## How to Consume a Source Generator
Create a new application of any kind or a new shared class library. Add a reference to the source generator library. This can be a NuGet reference. While under development, it will probably be a project reference. If it is a project reference, you will need to manually modify the reference in the consumer project's .csproj file manually to tell it that the assembly is an analyzer. It will need the `OutputItemType` attribute at least. Example:
```
<ItemGroup>
<ProjectReference Include="..\GeneratorLib\GeneratorLib.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"/>
</ItemGroup>
```
## Issues
- When you get the warning "2>CSC : warning CS9057: The analyzer assembly 'mygeneratorproject.dll' references version '4.13.0.0' of the compiler, which is newer than the currently running version '4.12.0.0'.", it will NOT generate the sources! You must adjust the version of the Microsoft.Analyzers.CSharp Nuget package!
- The `CompilerGeneratedFilesOutputPath` generator project setting causes the build process to create the specified output folder (not under bin/ or obj/, however). But the sources never show up in there. There is also a "generated" folder under the obj/ folder, but nothing shows up there either. I don't know how to control the generated source output. If I debug and step into generated code, then do a SAVE-AS, it shows me that it's in the `C:\Users\Phil.Gilmore\AppData\Local\Temp folder`.
- References to the generated code DO work and the program DOES build and the program DOES run and the running program DOES work. However, the IDE editor and the ERRORS toolwindow show errors in the code that refernces generated types. As if it didn't build. VERY frustrating!