Roslyn 使用雙層樹結構來平衡效能與易用性
Green Nodes不可變節點:
Red Nodes導航節點:
// 簡化的 Red/Green 概念示例
public abstract class GreenNode // 實際 Roslyn 中的不可變節點
{
public abstract SyntaxKind Kind { get; }
public abstract int FullWidth { get; }
public virtual bool HasTrivia => false;
}
public abstract class SyntaxNode // 實際 Roslyn 中的 Red 節點
{
internal GreenNode Green { get; }
public SyntaxNode? Parent { get; }
public int Position { get; }
// 導航 API
public SyntaxNode? NextSibling() { /* ... */ }
public SyntaxNode? PreviousSibling() { /* ... */ }
public IEnumerable<SyntaxNode> Ancestors() { /* ... */ }
}
Roslyn 支援增量解析,只重新解析變更的部分:
public class Diagnostic
{
public DiagnosticSeverity Severity { get; }
public string Id { get; }
public string Message { get; }
public Location Location { get; }
// 實際使用
// CS0103: The name 'undefined' does not exist in the current context
}
// 診斷產生範例
public void ReportUndefinedVariable(SyntaxToken identifier)
{
var diagnostic = Diagnostic.Create(
DiagnosticDescriptor.CS0103_UndefinedName,
identifier.GetLocation(),
identifier.ValueText
);
_diagnostics.Add(diagnostic);
}