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
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
CHAPTER 14. IMPLEMENTING A SIMPLE DSL 121<br />
let create if str (a : argument) : string =<br />
"if (c == "¢(string <strong>of</strong> short arg a)¢") {"¢<br />
"if ("¢(string <strong>of</strong> arg opt a)¢") { if(%e:optarg) {"¢<br />
"%l:scan(%e:optarg,%e:"¢a.argVi.vname¢"fmt,%e:"¢a.argVi.vname¢"addr);"¢<br />
"}}"¢<br />
(create def int string a)¢<br />
"%l:"¢a.argGot.vname¢" = 1;"¢<br />
"}"<br />
The if statements created with create if str from the arguments form the body <strong>of</strong> the loop in<br />
which we repeatedly call getopt long. The function create opt loop str generates the string <strong>of</strong><br />
C code for the loop. It calls getopt long before proceeding into the if statements generated by<br />
create\ if str. If the return <strong>of</strong> getopt long is −1, we break out <strong>of</strong> the loop.<br />
let create opt loop str (al : argument list) : string =<br />
"while(1) {"¢<br />
"int c;"¢<br />
"c = %l:gol(%e:argc, %e:argv, %e:sstr, %e:lopts, (void * )0);"¢<br />
"if (c == -1) break;"¢<br />
(al | > L.map create if str | > S.concat " else ")¢<br />
"}"<br />
Finally, in the function makeArgStmts we can call Formatcil.cStmts to generate the <strong>CIL</strong> statements<br />
for argument processing. The calls to findOrCreateFunc and findGlobalVar retrieve varinfos<br />
from the <strong>CIL</strong> le that we'll need to pass as parameters to the interpreted constructor. Here, we'll<br />
also call the functions that generate the code for allocating and initializing the option array.<br />
let makeArgStmts (f : file) (main : fundec) (al : argument list) : stmt list =<br />
let gol = findOrCreateFunc f "getopt long" intType in<br />
let scan = findOrCreateFunc f "sscanf" intType in<br />
let optarg = findGlobalVar f.globals "optarg" in<br />
let so = create short options al in<br />
let o, m, i = create long options f main al in<br />
let argc, argv = getMainArgs main in<br />
(L.map i2s (m :: i)) @<br />
Formatcil.cStmts (create opt loop str al)<br />
(fun n t → makeTempVar main £name : n t) locUnknown<br />
([("argc", Fe(v2e argc));<br />
("argv", Fe(v2e argv));<br />
("sstr", Fe so);<br />
("lopts", Fe (v2e o));<br />
("gol", Fl(var gol));<br />
("scan", Fl(var scan));<br />
("optarg",Fe(v2e optarg))]@<br />
(L.map (fun a → (a.argVi.vname¢"fmt"), Fe (mkString a.argFmt)) al)@