Перейти к содержанию
Skillpedia
Код в целом40k · #7406

roslyn-analyzers

Что он делает

Этот инструмент помогает разработчикам создавать и улучшать автоматические проверки кода (анализаторы Roslyn) и генераторы кода. Он следит за тем, чтобы код соответствовал определенным правилам, и помогает находить ошибки.

Когда использовать

  • ✓Когда нужно создать новые проверки для поиска распространенных ошибок в коде.
  • ✓Когда нужно исправить проблемы, которые уже нашли анализаторы.
  • ✓Когда нужно оптимизировать автоматическую генерацию кода.

Ссылка на скилл

https://github.com/github/awesome-copilot/blob/main/skills/roslyn-analyzers/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/github/awesome-copilot/blob/main/skills/roslyn-analyzers/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Как создать анализатор, который проверяет, что все переменные имеют понятные имена?”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Инструмент работает, анализируя код по мере его написания или компиляции. Он использует правила, чтобы понимать структуру кода и символы, и находит шаблоны, которые требуют внимания или исправления.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Roslyn Analyzers and Source Generators

Use this workflow when adding or changing a Roslyn analyzer, code fix, source generator, tests, dependencies, or package layout. First inspect the repository's target frameworks, central package management, test framework, analyzer and generator conventions, diagnostic ID allocation, localization, and packaging. Preserve established conventions unless they conflict with the compatibility rules below.

Non-negotiable design rules

  • Prefer IOperation-based analysis wherever possible. Register the narrowest applicable OperationKind and inspect typed operations such as IInvocationOperation, IAwaitOperation, or IObjectCreationOperation. This usually supports C# and VB with one analyzer and gives direct access to symbols and conversions.
  • Use syntax analysis only for inherently syntactic rules or syntax not represented adequately by IOperation. A syntax-node callback already has a SemanticModel; do not call Compilation.GetSemanticModel or fetch another semantic model from it. Repeated semantic-model creation is expensive and often indicates that an operation or symbol action is the better abstraction.
  • Every analyzer must support C#. VB.NET support is optional until requested or established repository precedent requires it. A language-neutral operation analyzer may declare both languages. If VB support is promised, include equivalent C# and VB snippets in tests; do not infer VB correctness from shared implementation alone.
  • Keep analyzer and code-fix providers in distinct assemblies. The analyzer project must never reference Roslyn Workspaces packages. Workspaces dependencies belong only in the code-fix and test projects.
  • Analyzer callbacks must be stateless or concurrency-safe. Call EnableConcurrentExecution(). Make an explicit generated-code choice with ConfigureGeneratedCodeAnalysis(...); follow repository policy rather than silently accepting the default.
  • Respect cancellation where APIs expose a token. Do not retain compilations, operations, syntax trees, symbols, or semantic models in static state.
  • Avoid InternalsVisibleTo. Test analyzers through their public DiagnosticAnalyzer and CodeFixProvider APIs and the Roslyn test harness. A small analyzer helper may be public when direct testing is genuinely useful, but most behavior should be tested end to end.
  • Centralize metadata names and member names instead of propagating magic strings. Use one shared static catalog for fully qualified type names, namespaces, and API member names.
  • Never identify a symbol, including an attribute class, by calling ToDisplayString() and comparing the result with a string literal. Resolve an expected named type from the Compilation once by metadata name. To resolve a method, property, field, or event, first resolve its containing type, then select the expected member by name and signature. Compare encountered symbols with SymbolEqualityComparer.Default.Equals(actual, expected). When generic substitutions are irrelevant, compare named types, properties, fields, and events by OriginalDefinition; compare methods after replacing a reduced extension method with ReducedFrom ?? method and then taking OriginalDefinition. Normalize both expected and encountered symbols, and inspect type arguments separately when they are part of the match. Display strings are for presentation, not identity, and can vary with formatting, aliases, qualification, nullability, and other context.
  • Document every diagnostic ID. When the repository uses Docfx, put analyzer documentation under its Docfx tree, typically docfx/analyzers, and include each page in the relevant table of contents.
  • Set every analyzer assembly's version precisely enough that each commit produces a unique assembly version. When using Nerdbank.GitVersioning, give each analyzer project its own version.json with assemblyVersion.precision set to revision and ensure that repository-wide MSBuild properties do not prevent that file from being discovered.
  • Source generators must implement IIncrementalGenerator, not ISourceGenerator. Design the provider graph so unchanged inputs remain cached and do not regenerate output.
  • Source generators must use a small SourceWriter abstraction for deterministic newlines, indentation, encoding, and balanced output. Start from SourceWriter.cs and tailor its namespace and target-framework details to the receiving repository.

…

Частые вопросы

Что такое анализаторы Roslyn?

Это инструменты, которые анализируют ваш код на C# или VB.NET, находят потенциальные проблемы, предлагают улучшения или даже исправляют их автоматически.

Что такое генераторы кода?

Это программы, которые автоматически создают код на основе других частей проекта. Это экономит время и снижает количество ошибок, допущенных вручную.

Нужно ли много знать о программировании, чтобы использовать этот инструмент?

Инструмент предназначен для разработчиков, которые уже пишут код. Он помогает сделать их код лучше и эффективнее.

Подробности

Оригинальное описание автора

Build, review, debug, package, and test Roslyn diagnostic analyzers, code fix providers, and incremental source generators. Use for DiagnosticAnalyzer, CodeFixProvider, IIncrementalGenerator, IOperation analysis, Microsoft.CodeAnalysis dependency pinning, Roslyn test harnesses, C#/VB tests, and analyzer NuGet packaging.

repo: github/awesome-copilot

Популярность

Звёзды на GitHub
40k
Место в рейтинге
#7406
Лицензия
MIT
Обновлён
15.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы