Debian Codegraph @

lib/mllpt-lib/ml-lpt/common/expand-file.sml

raw
1 (* expand-file.sml
2 *
3 * COPYRIGHT (c) 2016 The Fellowship of SML/NJ (http://www.smlnj.org)
4 * All rights reserved.
5 *
6 * Copy a template file to an output file while expanding placeholders.
7 * Placeholders are denoted by @id@ on a line by themselves.
8 *)
9
10 structure ExpandFile :> sig
11
12 type hook = TextIO.outstream -> unit
13
14 type template
15
16 val mkTemplateFromFile : string -> template
17 val mkTemplateFromList : string list -> template
18
19 val expandTemplate : {
20 src : template,
21 dst : string, (* file name *)
22 hooks : (string * hook) list
23 } -> unit
24
25 end = struct
26
27 structure TIO = TextIO
28 structure SS = Substring
29 structure RE = RegExpFn (
30 structure P = AwkSyntax
31 structure E = BackTrackEngine)
32 structure M = MatchTree
33
34 type hook = TextIO.outstream -> unit
35 type template = string list
36
37 fun mkTemplateFromFile fname = let
38 val file = TIO.openIn fname
39 fun done () = TIO.closeIn file
40 fun read () = (case TIO.inputLine file
41 of NONE => []
42 | SOME line => line::read()
43 (* end case *))
44 in
45 read() handle ex => (done(); raise ex)
46 before done()
47 end
48
49 fun mkTemplateFromList l = l
50
51 val placeholderRE = RE.compileString "[\\t ]*@([a-zA-Z][-a-zA-Z0-9_]*)@[\\t ]*"
52 val prefixPlaceholder = RE.prefix placeholderRE SS.getc
53
54 fun findPlaceholder s = (case prefixPlaceholder(SS.full s)
55 of SOME(M.Match(_, [M.Match({pos, len}, _)]), _) =>
56 SOME(SS.string(SS.slice(pos, 0, SOME len)))
57 | _ => NONE
58 (* end case *))
59
60 (* copy from inStrm to outStrm expanding placeholders *)
61 fun copy (inStrm, outStrm, hooks) = let
62 fun lp [] = ()
63 | lp (s::ss) = (
64 case findPlaceholder s
65 of NONE => TIO.output (outStrm, s)
66 | (SOME id) => (
67 case (List.find (fn (id', h) => id = id') hooks)
68 of (SOME(_, h)) => h outStrm
69 | NONE => raise Fail(concat["bogus placeholder '", id, "'"])
70 (* end case *))
71 (* end case *);
72 lp(ss))
73 in
74 lp(inStrm)
75 end
76
77 exception OpenOut
78
79 fun expandTemplate {src, dst, hooks} = (let
80 val dstStrm = TIO.openOut dst
81 handle ex => (
82 TIO.output(TIO.stdErr, concat[
83 "Error: unable to open output file \"",
84 dst, "\"\n"
85 ]);
86 raise OpenOut)
87 fun done () = (TIO.closeOut dstStrm)
88 in
89 copy (src, dstStrm, hooks) handle ex => (done(); raise ex);
90 done()
91 end
92 handle OpenOut => ())
93
94 end