Object Pooling
// Roslyn 大量使用物件池減少 GC 壓力
internal static class SyntaxListPool<T> where T : SyntaxNode
{
private static readonly ObjectPool<List<T>> s_pool =
new DefaultObjectPool<List<T>>(new ListPolicy());
public static List<T> Allocate() => s_pool.Get();
public static void Free(List<T> list) => s_pool.Return(list);
}
表格驅動解析
// 使用預計算表格加速解析決策
private static readonly byte[,] s_precedenceTable = {
// 運算子優先順序表格
// + - * / ( )
/*+*/{ 1, 1, 0, 0, 0, 1 },
/*-*/{ 1, 1, 0, 0, 0, 1 },
/***/{ 1, 1, 1, 1, 0, 1 },
// ...
};
例子
class Program
{
static void Main()
{
string source = "3 + 4 * 2";
// 1. 語法分析
var syntaxTree = MiniParser.Parse(source);
Console.WriteLine($"AST: {syntaxTree}");
// 2. 語意分析
var binder = new Binder();
var semanticModel = binder.Analyze(syntaxTree);
// 3. IL 生成
var ilGen = new ILGenerator();
var il = ilGen.Generate(syntaxTree, semanticModel);
Console.WriteLine("Generated IL:");
Console.WriteLine(il);
// 輸出結果:
// AST: BinaryNode { Op = +, Left = NumberNode { Value = 3 },
// Right = BinaryNode { Op = *, Left = NumberNode { Value = 4 },
// Right = NumberNode { Value = 2 } } }
// Generated IL:
// .assembly extern mscorlib {}
// .assembly Sample {}
// ...
// ldc.i4 3
// ldc.i4 4
// ldc.i4 2
// mul
// add
// call void [mscorlib]System.Console::WriteLine(int32)
// ret
}
}