A CIL Tutorial - Department of Computer Science - ETH Zürich
A CIL Tutorial - Department of Computer Science - ETH Zürich
A CIL Tutorial - Department of Computer Science - ETH Zürich
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
CHAPTER 14. IMPLEMENTING A SIMPLE DSL 119<br />
let has arg <strong>of</strong> argument (a : argument) : exp =<br />
if a.argOption then one else zero<br />
let int code <strong>of</strong> argument (a : argument) : exp =<br />
a.argShort.[0] | > int <strong>of</strong> char | > integer<br />
The function initialize options takes a function for generating an lval, (e.g. field <strong>of</strong> option),<br />
an index, a eld name, and an argument. Using the argument it generates instructions for initializing<br />
the elds.<br />
let initialize options (foo : int → string → lval)<br />
(i : int) (a : argument)<br />
: instr list<br />
=<br />
[Set(foo i "name", mkString a.argName, locUnknown);<br />
Set(foo i "has arg", has arg <strong>of</strong> argument a, locUnknown);<br />
Set(foo i "val", int code <strong>of</strong> argument a, locUnknown)]<br />
The function create long options generates code that allocates an option array, and lls it in.<br />
It returns the varinfo for the array, the call to malloc, and the assignments for the initializations.<br />
let create long options (f : file) (main : fundec) (al : argument list)<br />
: varinfo × instr × instr list<br />
=<br />
let malloc = findOrCreateFunc f "malloc" (mallocType f) in<br />
let ot = findType f.globals "option" in<br />
let o = makeTempVar main (TPtr(ot, [ ])) in<br />
let foo = field <strong>of</strong> option o ot in<br />
let size = integer((L.length al + 1) × ((bitsSizeOf ot)/8)) in<br />
let mcall = Call(Some(var o), v2e malloc, [size], locUnknown) in<br />
let inits = al | > A.<strong>of</strong> list<br />
|> A.mapi (initialize options foo)<br />
|> A.to list<br />
|> L.concat<br />
in<br />
o, mcall, inits<br />
With an array <strong>of</strong> options allocated and initialized, we can now generate the code for the loop that<br />
calls getopt long. Since generating this code using type-constructors would be tedious and dicult<br />
to read, we'll use <strong>CIL</strong>'s interpreted constructors instead. To do this, we need to build a string to<br />
pass to Formatcil.cStmts.<br />
Before doing that, though, we'll dene a few utility functions for obtaining expressions that will<br />
be parameters to the interpreted constructor. The function create short options generates an<br />
expression for the string to be used as the parameter to getopt long that denes the short versions<br />
<strong>of</strong> the arguments.