From a720b9ffd8c347c7bda56eb752c62b1588e9b614 Mon Sep 17 00:00:00 2001 From: sebastianselander Date: Fri, 5 May 2023 15:09:51 +0200 Subject: [PATCH] Peano --- src/Codegen/Emits.hs | 5 +++-- src/Main.hs | 4 ++++ test_program.crf | 37 ++++++++++++++++++++++++++----------- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/src/Codegen/Emits.hs b/src/Codegen/Emits.hs index 5ab9801..bc19f87 100644 --- a/src/Codegen/Emits.hs +++ b/src/Codegen/Emits.hs @@ -325,6 +325,7 @@ emitApp rt e1 e2 = appEmitter e1 e2 [] let call = case name of TIR.Ident ('l' : 't' : '$' : _) -> Icmp LLSlt I64 (snd (head args')) (snd (args' !! 1)) + TIR.Ident ('$' : 'm' : 'i' : 'n' : 'u' : 's' : '$' : '$' : _) -> Sub I64 (snd (head args')) (snd (args' !! 1)) _ -> Call FastCC (type2LlvmType rt) visibility name args' emit $ Comment $ show rt emit $ SetVariable vs call @@ -359,8 +360,8 @@ exprToValue = \case (MIR.ELit i, _t) -> pure $ case i of (MIR.LInt i) -> VInteger i (MIR.LChar i) -> VChar $ ord i - (MIR.EVar (TIR.Ident "True"), _t) -> pure $ VInteger 1 - (MIR.EVar (TIR.Ident "False"), _t) -> pure $ VInteger 0 + (MIR.EVar (TIR.Ident "True$Bool"), _t) -> pure $ VInteger 1 + (MIR.EVar (TIR.Ident "False$Bool"), _t) -> pure $ VInteger 0 (MIR.EVar name, t) -> do funcs <- gets functions cons <- gets constructors diff --git a/src/Main.hs b/src/Main.hs index b70a80c..ea6103a 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -187,4 +187,8 @@ prelude = , " _ => True" , " _ => False" , "\n" + , -- The function body of - is replaced during code gen. It exists here for type checking purposes. + ".- : Int -> Int -> Int" + , ".- x y = 0" + , "\n" ] diff --git a/test_program.crf b/test_program.crf index 5f35a1d..6e528dc 100644 --- a/test_program.crf +++ b/test_program.crf @@ -1,15 +1,30 @@ -data List a where - Cons : a -> List a -> List a - Nil : List a +-- Peano naturals +data Nat where + Zero : Nat + Succ : Nat -> Nat -.++ xs ys = case xs of - Nil => ys - Cons z zs => Cons z (zs ++ ys) +toInt : Nat -> Int +toInt a = case a of + Succ n => 1 + toInt n + Zero => 0 -length xs = case xs of - Cons x xs => 1 + length xs +fromInt a = case a of + 0 => Zero + n => Succ (fromInt (a - 1)) -main = length (list1 ++ list2) +-- Peano arithmetic -- -list1 = Cons 0 (Cons 1 (Cons 2 (Cons 3 Nil))) -list2 = Cons 4 (Cons 5 (Cons 6 (Cons 7 Nil))) +-- Peano addition +add : Nat -> Nat -> Nat +add left right = case left of + Zero => right + Succ n => Succ (add n right) + +-- Peano multiplication +mul : Nat -> Nat -> Nat +mul left right = case right of + Zero => Zero + Succ n => add left (mul left n) + +-- Returns 10_000 +main = toInt (mul (fromInt 100) (fromInt 100))