| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Computing free variable annotations on reflected syntax. |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
{-# OPTIONS --safe --with-K #-} |
| 8 |
|
| 9 |
module Reflection.AnnotatedAST.Free where |
| 10 |
|
| 11 |
open import Data.Bool.Base using (if_then_else_) |
| 12 |
open import Data.Nat.Base using (ℕ; _∸_; compare; _<ᵇ_; less; equal; greater) |
| 13 |
open import Data.List.Base using (List; []; _∷_; [_]; concatMap; length) |
| 14 |
open import Data.List.Relation.Unary.All using (_∷_) |
| 15 |
open import Data.Product.Base using (_×_; _,_; proj₁; proj₂) |
| 16 |
open import Data.String.Base using (String) |
| 17 |
open import Reflection.AST.Universe |
| 18 |
using (⟨term⟩; ⟨pat⟩; ⟨clause⟩; ⟨abs⟩; ⟨tel⟩; ⟦_⟧) |
| 19 |
open import Reflection.AnnotatedAST |
| 20 |
using (Annotated; AnnotationFun; annotate; defaultAnn; ⟨_⟩_; var; absurd |
| 21 |
; clause; absurd-clause; abs) |
| 22 |
|
| 23 |
------------------------------------------------------------------------ |
| 24 |
-- Free variable sets as lists of natural numbers |
| 25 |
|
| 26 |
FVs : Set |
| 27 |
FVs = List ℕ -- ordered, no duplicates |
| 28 |
|
| 29 |
private |
| 30 |
|
| 31 |
infixr 3 _∪_ |
| 32 |
|
| 33 |
_∪_ : FVs → FVs → FVs |
| 34 |
[] ∪ ys = ys |
| 35 |
xs ∪ [] = xs |
| 36 |
x ∷ xs ∪ y ∷ ys with compare x y | x ∷ xs ∪ ys |
| 37 |
... | less x _ | _ = x ∷ (xs ∪ y ∷ ys) |
| 38 |
... | equal x | _ = x ∷ (xs ∪ ys) |
| 39 |
... | greater y _ | rec = y ∷ rec |
| 40 |
|
| 41 |
insert : ℕ → FVs → FVs |
| 42 |
insert x [] = x ∷ [] |
| 43 |
insert x (y ∷ xs) with compare x y |
| 44 |
... | less x k = x ∷ y ∷ xs |
| 45 |
... | equal x = y ∷ xs |
| 46 |
... | greater y k = y ∷ insert x xs |
| 47 |
|
| 48 |
close : ℕ → FVs → FVs |
| 49 |
close k = concatMap λ x → if x <ᵇ k then [] else [ x ∸ k ] |
| 50 |
|
| 51 |
|
| 52 |
------------------------------------------------------------------------ |
| 53 |
-- Annotation function computing free variables |
| 54 |
|
| 55 |
freeVars : AnnotationFun (λ _ → FVs) |
| 56 |
freeVars ⟨term⟩ (var x (⟨ fv ⟩ _)) = insert x fv |
| 57 |
freeVars ⟨pat⟩ (var x) = x ∷ [] |
| 58 |
freeVars ⟨pat⟩ (absurd x) = x ∷ [] |
| 59 |
-- Note: variables are bound in the clause telescope, so we treat pattern variables as free |
| 60 |
freeVars ⟨clause⟩ (clause {tel = Γ} (⟨ fvΓ ⟩ _) (⟨ fvps ⟩ _) (⟨ fvt ⟩ _)) = fvΓ ∪ close (length Γ) (fvps ∪ fvt) |
| 61 |
freeVars ⟨clause⟩ (absurd-clause {tel = Γ} (⟨ fvΓ ⟩ _) (⟨ fvps ⟩ _)) = fvΓ ∪ close (length Γ) fvps |
| 62 |
freeVars (⟨abs⟩ u) (abs _ (⟨ fv ⟩ _)) = close 1 fv |
| 63 |
freeVars ⟨tel⟩ (⟨ fv ⟩ _ ∷ xs) = fv ∪ close 1 (freeVars _ xs) |
| 64 |
freeVars u t = defaultAnn [] _∪_ u t |
| 65 |
|
| 66 |
annotateFVs : ∀ {u} → (t : ⟦ u ⟧) → Annotated (λ _ → FVs) t |
| 67 |
annotateFVs = annotate freeVars |