AgentSkillsCN

closure-converter

将闭包转换为显式环境。在以下场景中使用此功能:(1) 实现函数式语言;(2) 构建编译器;(3) 理解闭包。

SKILL.md
--- frontmatter
name: closure-converter
description: 'Transforms closures to explicit environments. Use when: (1) Implementing
  functional languages, (2) Building compilers, (3) Understanding closures.'
version: 1.0.0
tags:
- compiler
- closures
- code-generation
- functional
difficulty: intermediate
languages:
- python
- ocaml
- rust
dependencies:
- lambda-calculus-interpreter

Closure Converter

Transforms closures to explicit environment passing.

When to Use

  • Implementing functional language compilers
  • Building interpreters
  • Understanding closure semantics
  • Transforming functional to imperative

What This Skill Does

  1. Analyzes free variables - Determines captured variables
  2. Creates closures - Transforms lambdas
  3. Passes environments - Explicit env parameter
  4. Optimizes - Avoids unnecessary captures

Key Concepts

ConceptDescription
Free variablesVariables used but not defined
ClosureFunction + captured environment
EnvironmentMapping from variables to values
Lambda liftingMove functions to top level

Techniques

  • Flat environments
  • Shared closures
  • Lambda lifting
  • Representation analysis

Tips

  • Track free variables precisely
  • Consider environment representation
  • Handle recursive functions
  • Optimize shared closures

Related Skills

  • lambda-calculus-interpreter - Lambda calculus
  • jit-compiler-builder - VM design
  • lambda-calculus-interpreter - Bytecode

Research Tools & Artifacts

Real-world closure conversion implementations to study:

ArtifactWhy It Matters
GHC's closure analysisSophisticated info table and closure representation
OCaml's closure conversionProduction-quality, optimized for performance
Scala 2 lambda encodingAnonymous function representation
LuaJIT's closure IRTrace-based closure optimization
PyPy's closure conversionTracing JIT with efficient closures
V8's closure representationHidden class and context optimization

Key Compiler Implementations

  • GHC via STG: Top-level thunks, updatable frames
  • Clean: Graph rewriting with unique nodes
  • Clean: I/o requirements and uniqueness types

Research Frontiers

Current active research in closure conversion:

DirectionKey PapersChallenge
Zero-cost closures"Zero-cost Closures" (2018)No heap allocation for non-escaping
In-place updates"Thunks revisited" (2008)Update-in-place vs copying
Unboxed representations"Unboxed tuples" (GHC)Avoiding heap allocation
Escape analysis"Escape Analysis" (1994)Static lifetime detection
Lambda lifting"Lambda dropping" (2001)When to lift, what to capture

Hot Topics

  1. Swift's escaping closures: Distinguishing escaping vs non-escaping
  2. Rust's closure traits: Fn, FnMut, FnOnce with capture semantics
  3. Wasm GC proposal: First-class function references

Implementation Pitfalls

Common bugs in production closure conversion:

PitfallReal ExamplePrevention
Wrong free variable setEarly Scala lost captured varsCompute FV with bound variable hygiene
Space leaksGHC's CAFs holding closuresAnalyze thunk vs value carefully
Lambda lift too earlyLost sharing opportunitiesLift after inlining
Wrong environment orderVariable capture bugsVerify env layout matches usage
Closure escapeJavaScript hidden class changesTrack escape precisely
Mutable captureClosure capturing mutref unsoundnessTrack mutability separately

The "Mutable Capture" Bug

In languages with mutability:

scala
// Unsound if closure captures mutable ref
val x = Ref(0)
val f = () => { x := 1; x() }

Solution: Mark closures that capture mutable references, restrict their usage.

Lambda Lifting Tradeoffs

Lambda lifting too early loses optimization opportunities:

  • Lift after inlining to see usage patterns
  • Consider partial application patterns
  • Don't lift if closure escapes current scope