Building Typed Languages with Turnstile Stephen Chang Racket
Building Typed Languages with Turnstile Stephen Chang Racket Summer School 2018 (Thursday afternoon)
Where are we in the schedule? • Monday, Tuesday, Wednesday: • Tools for building languages with Racket • Thursday: • How to build typed languages • Thursday and Friday: We are still here But we are also here • Let’s look at some example languages built with Racket
The language of type rules … is a language
A Macro-based Language in Racket UNTYPED-LANG #lang RACKET (provide-as [new-app #%app] [new-λ λ]) (def-stx (new-app e 1 e 2) ; . . (#%app e 1 e 2)) (def-stx (new-λ x e) ; . . (λ x e)) UNTYPED-PROG #lang UNTYPED-LANG ; uses: new-app, new-λ
IDEA: A Typed Macro-based Language UNTYPED-LANG #lang RACKET (provide-as [new-app #%app] [new-λ λ]) #lang RACKET (provide-as [typed-app #%app] [typed-λ λ]) (def-stx (new-app e 1 e 2) ; . . (host-app e 1 e 2)) (def-stx (typed-app e 1 e 2) ; do typechecking (host-app e 1 e 2)) (def-stx (new-λ x e) ; . . (host-λ x e)) (def-stx (typed-λ [x : τ] e) ; do typechecking (host-λ x e)) TYPED-PROG UNTYPED-PROG #lang UNTYPED-LANG #lang TYPED-LANG ; uses: new-app, new-λ ; uses: typed-app, typed-λ
“do typechecking” = expand + stx props (define-syntax (typed-app stx) (syntax-parse stx [(_ e 1 e 2) #: with e 3 (local-expand #’e 1) #: with (→ τin τ) (stx-prop #’e 3‘ty) #: with e 4 (local-expand #’e 2) #: with τarg (stx-prop #’e 4 ‘ty) #: fail-unless (stx= #’τarg #’τin) (stx-prop #’(#%app e 3 e 4) ‘ty #’τ)])) Compute type Check type Assign type Types checked when macro expands
Leverage Domain-specific Syntax Compute type [T-App] Check type Assign type
TURNSTILE: Type and Rewrite Rules Conclusion: inputs (def-typed-stx (typed-app e 1 e 2) » [Ͱ e 1 » e 1’ ⇒ (→ τin τout)] [Ͱ e 2 » e 2’ ⇐ τin] ---------------[Ͱ (#%app e 1’ e 2’) ⇒ τout]) Conclusion: outputs
TURNSTILE: Type and Rewrite Rules Expands to (def-typed-stx (typed-app e 1 e 2) » [Ͱ e 1 » e 1’ ⇒ (→ τin τout)] [Ͱ e 2 » e 2’ ⇐ τin] ---------------(def-typed-stx (typed-app e 1 e 2) » [Ͱ e 1’(→ e 2’)τ ⇒τ τout [Ͱ (#%app e » e ’⇒ )] ]) 1 (def-stx (typed-app e 1 e 2) #: with e 1’ (expand e 1) #: with (→ τin τout) (detach e 1’) #: with e 2’ (expand e 2) #: with τarg (detach e 2’) #: fail-unless (stx= τarg τin) (attach (#%app e 1’ e 2’) τout) 1 in out [Ͱ e 2 » e 2’ ⇐ τin] ---------------[Ͱ (#%app e 1’ e 2’) ⇒ τout])
Surface code Reader / Lexer / Parser AST (e. g. , syntax objects) Expand Type Checked, expanded AST Rest of compiler Core code / bytecode / machine code
- Slides: 10