Add some extra outline to the Hardware Description chapter.
[matthijs/master-project/report.git] / pret-lam.lua
1 -- filename : type-lam.lua
2 -- comment  : Pretty printing of (extended) lambda calculus
3 -- author   : Matthijs Kooijman, Universiteit Twente, NL
4 -- copyright: Matthijs Kooijman
5 -- license  : None
6
7 local utf = unicode.utf8
8
9 local vis = buffers.newvisualizer("lam")
10
11 local colors = {
12     "prettytwo",
13     "prettyone",
14     "prettythree",
15     "prettyfour"
16 }
17
18 -- Symbols that should have a different representation
19 local symbols = {
20     [' '] = {repr = '\\obs '},
21     ['_'] = {repr = '\\_'},
22     ['->'] = {repr = '\\rightarrow'},
23     -- The default * sits very high above the baseline, \ast (u+2217) looks
24     -- better.
25     ['*'] = {repr = '\\ast'},
26     ['~'] = {repr = '\\HDLine[width=.20 * \\the\\textwidth]'},
27     ['|'] = {repr = '\\char' .. utf.byte('|')},
28 }
29
30 -- Keywords that should be bold
31 local keywords = {
32     ['case'] = {},
33     ['of'] = {},
34     ['let'] = {},
35     ['letrec'] = {},
36     ['letnonrec'] = {},
37     ['in'] = {},
38     ['DEFAULT'] = {},
39 }
40
41 local in_block = 0
42 local submatches = {}
43 local bases = {}
44 -- Store the last line for each indent level
45 local indentlines = {}
46
47 -- See if str starts with a symbol, and return the remaining string and that
48 -- symbol. If no symbol from the table is matched, just returns the first
49 -- character.  We can do a lookup directly, since symbols can be different in
50 -- length, so we just loop over all symbols, trying them in turn.
51 local function take_symbol(str)
52     for symbol,props in pairs(symbols) do
53         -- Try to remove symbol from the start of str 
54         symbol, newstr = utf.match(str, "^(" .. symbol .. ")(.*)")
55         if symbol then
56             -- Return this tokens repr, or just the token if it has no
57             -- repr.
58             res = props.repr or symbol
59             -- Enclose the token in {\style .. }
60             if props.style then
61                 res = "{\\" .. props.style ..  " " .. res ..  "}"
62             end
63             return res, newstr
64         end
65     end
66     -- No symbol found, just return the first character
67     return utf.match(str, "^(.)(.*)")
68 end
69
70 -- Take a single word from str, if posible. Returns the rest of the string and
71 -- the word taken.
72 local function take_word(str)
73         -- A word must always start with a-z (in particular, λ is not a valid
74         -- start of a word).
75         res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]+)(.*)")
76         return res, newstr or str
77 end
78
79 -- Tries to match each of the patterns and returns the captures of the first
80 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
81 -- matches.
82 local function match_mul(str, patterns)
83     for i, pat in ipairs(patterns) do
84         a, b, c, d, e = utf.match(str, pat)
85         if a then
86             return a, b, c, d, e
87         end
88     end
89     return nil
90 end
91
92 -- Find any subscripts in the given word and typeset them
93 local function do_subscripts(word)
94     base, sub = match_mul(res, submatches)
95     if sub then
96         word = base .. "\\low{" .. sub .. "}"
97         -- After a word has been used as a base, allow subscripts
98         -- without _, even for non-numbers.
99         if not bases[base] then
100             -- Register that we've added this base
101             bases[base] = true
102             -- Add a patterns for this base. First, the base with a single
103             -- letter or number subscript.
104             submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
105             -- Seconde, the base with a longer prefix that includes at least
106             -- one of +-, (to catch things like ri+1, but not return).
107             submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+%,]+[%a%d%-%+%,]*)$"
108         end
109     end
110     return word
111 end
112
113 -- Do proper aligning for subsequent lines. For example, in 
114 --   foo = bar
115 --       | baz
116 -- We replace the spaces in the second line with a skip with the same with as
117 -- "foo ", to align the | with the =.
118 -- For this, we keep a table "indentlines", which contains all previous lines
119 -- with smaller indent levels that are still "in scope" (e.g., have not yet
120 -- been followed by a line with a smaller indent level). For example:
121 --   line1
122 --     line2
123 --       line3
124 --     line4
125 --       line5
126 -- After the last line, the table will contain:
127 --   { 0 = "line1", 2 = "  line4", 4 = "    line5"}
128 --   In other words, line3 is no longer in scope since it is "hidden" by
129 --   line4, and line is no longer in scope since it is replaced by line4.
130 local function do_indent(line)
131     newind, rest = utf.match(line, '^(%s*)(.*)')
132     prev = -1
133     -- Loop all the previous lines
134     for indent, unused in pairs(indentlines) do
135         if indent > #newind then
136             -- Remove any lines with a larger indent
137             indentlines[indent] = nil
138         elseif indent < #newind and indent > prev then
139             -- Find the last line (e.g, with the highest indent) with an
140             -- indent smaller than the new indent. This is the line from which
141             -- we need to copy the indent.
142             prev = indent
143         end
144     end
145     
146     -- Always store this line, possibly overwriting a previous line with the
147     -- same indent
148     indentlines[#newind] = line
149
150     if prev ~= -1 then
151         -- If there is a previous line with a smaller indent, make sure we
152         -- align with it. We do this by taking a prefix from that previous
153         -- line just as long as our indent. This gives us a bunch of
154         -- whitespace, with a few non-whitespace characters. We find out the
155         -- width of this prefix, and put whitespace just as wide as that
156         -- prefix before the current line, instead of the whitespace
157         -- characters that were there.
158         -- Doing this is slightly risky, since the prefix might contain
159         -- unfinished markup (e.g., \foo{bar without the closing }). We might
160         -- need to solve this later.
161         copyind = utf.sub(indentlines[prev], 1, #newind)
162         setwidth = "\\setwidthof{" .. copyind .. "}\\to\\pretlamalignwidth"
163         hskip = "\\hskip\\pretlamalignwidth"
164         return "{" .. setwidth .. hskip .. "}" .. rest
165     end
166         -- No previous line? Just return the unmodified line then
167         return line
168 end
169
170
171 -- Mark the begin of a block of lambda formatted buffers or expressions. This
172 -- means that, until you call end_of_block again, the subscript bases are
173 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
174 -- single block, the yn will properly get subscripted. Be sure to call
175 -- end_of_block again!
176 --
177 -- Blocks can be partially nested, meaning that the block
178 -- won't be closed until end_of_block was called exactly as often as
179 -- begin_of_block. However, subscripts from the inner block can still
180 -- influence subscripts in the outer block.
181 function vis.begin_of_block()
182     vis.begin_of_display()
183     in_block = in_block + 1
184 end
185
186 -- Ends the current block
187 function vis.end_of_block()
188     in_block = in_block - 1
189 end
190
191 function vis.begin_of_display()
192     if in_block == 0 then
193         -- Initially allow subscripts using _ or just appending a number (later,
194         -- we will add extra patterns here.
195         submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)([%d,]+)$"}
196         -- This stores all the bases we've encountered so far (to prevent
197         -- duplicates). For each of them there will be a pattern in submatches
198         -- above.
199         bases = {}
200     end
201     indentlines = {}
202 end
203     
204
205 -- Make things work for inline typeing (e.g., \type{}) as well.
206 vis.begin_of_inline = vis.begin_of_display
207 vis.end_of_inline = vis.end_of_display
208
209 function vis.flush_line(str,nested)
210     local result, state = { }, 0
211     local finish, change = buffers.finish_state, buffers.change_state
212     str = do_indent(str)
213     -- Set the colorscheme, which is used by finish_state and change_state
214     buffers.currentcolors = colors
215     while str ~= "" do
216         local found = false
217         local word, symbol
218         -- See if the next token is a word
219         word, str = take_word(str)
220         if word then
221             if keywords[res] then
222                 -- Make all keywords bold
223                 word = "{\\bold " .. word ..  "}"
224             else
225                 -- Process any subscripts in the word
226                 word = do_subscripts(word)
227             end
228         else
229             -- The next token is not a word, it must be a symbol
230             symbol, str = take_symbol(str)
231         end
232
233         -- Append the resulting token
234         result[#result+1] = word or symbol
235     end
236     
237     state = finish(state, result)
238     buffers.flush_result(result,nested)
239 end
240
241 -- vim: set sw=4 sts=4 expandtab ai: