Skip to content

Commit 47119ab

Browse files
committed
Unmarshal Lua strings as literal Doc values
1 parent 2222796 commit 47119ab

2 files changed

Lines changed: 32 additions & 5 deletions

File tree

src/Foreign/Lua/Module/DocLayout.hs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{-# LANGUAGE FlexibleInstances #-}
2+
{-# LANGUAGE LambdaCase #-}
23
{-# OPTIONS_GHC -fno-warn-orphans #-}
34
{-|
45
Module : Foreign.Lua.Module.DocLayout
@@ -20,11 +21,16 @@ module Foreign.Lua.Module.DocLayout (
2021

2122
-- * Functions
2223
, render
24+
25+
-- * Marshaling
26+
, peekDoc
27+
, pushDoc
2328
)
2429
where
2530

2631
import Data.Text (Text)
27-
import Foreign.Lua (Lua, NumResults (..), Optional, Peekable, Pushable)
32+
import Foreign.Lua (Lua, NumResults (..), Optional,
33+
Peekable, Pushable, StackIndex)
2834
import Text.DocLayout (Doc)
2935

3036
import qualified Foreign.Lua as Lua
@@ -48,13 +54,28 @@ preloadModule :: String -> Lua ()
4854
preloadModule = flip Lua.preloadhs pushModule
4955

5056
-- | Render a @'Doc'@. The text is reflowed on breakable spaces
51-
-- to match the line length if a line length is provided. Text is
52-
-- not reflowed if the parameter is omitted or nil.
57+
-- to match the given line length. Text is not reflowed if the
58+
-- line length parameter is omitted or nil.
5359
render :: Doc Text -> Optional Int -> Lua Text
5460
render doc optLength = return $ Doc.render (Lua.fromOptional optLength) doc
5561

62+
--
63+
-- Marshaling
64+
--
65+
66+
-- | Retrieve a @Doc Text@ value from the Lua stack. Strings are
67+
-- converted to plain @'Doc'@ values.
68+
peekDoc :: StackIndex -> Lua (Doc Text)
69+
peekDoc idx = Lua.ltype idx >>= \case
70+
Lua.TypeString -> Doc.literal <$> Lua.peek idx
71+
_ -> Lua.peekAny idx
72+
5673
instance Peekable (Doc Text) where
57-
peek = Lua.peekAny
74+
peek = peekDoc
75+
76+
-- | Push a @Doc Text@ value to the Lua stack.
77+
pushDoc :: Doc Text -> Lua ()
78+
pushDoc = Lua.pushAny
5879

5980
instance Pushable (Doc Text) where
60-
push = Lua.pushAny
81+
push = pushDoc

test/test-doclayout.lua

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,11 @@ return {
2222
assert.are_equal(doclayout.render(doclayout.empty_doc), '')
2323
end)
2424
}
25+
},
26+
27+
group 'Doc type' {
28+
test('strings can be used as Doc values', function ()
29+
assert.are_equal(doclayout.render('hello world'), 'hello world')
30+
end)
2531
}
2632
}

0 commit comments

Comments
 (0)