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 123<br />
let makeArgChecks (f : file) (al : argument list) : stmt =<br />
let got arg a = if a.argOpt then one else v2e a.argGot in<br />
let bexp, mexp =<br />
L.fold left (fun b a → BinOp(LAnd, b, a.argReq, intType)) one al,<br />
L.fold left (fun b a → BinOp(LAnd, b, (got arg a), intType)) one al<br />
in<br />
mkStmt (If(BinOp(LOr, UnOp(LNot, mexp, intType), UnOp(LNot, bexp, intType), intType),<br />
mkBlock (printHelp f al), mkBlock[ ],<br />
locUnknown))<br />
If we have found the main function, then the function processFunction inserts the code for processing<br />
command line arguments at the top <strong>of</strong> the function.<br />
let processFunction (f : file) (al : argument list)<br />
(fd : fundec) (loc : location) : unit =<br />
if fd.svar.vname = "main" then<br />
fd.sbody.bstmts ← (initArgs al) @<br />
(makeArgStmts f fd al) @<br />
[makeArgChecks f al] @<br />
fd.sbody.bstmts<br />
Finally, the function tut14 gathers the argument specications using gatherArguments before calling<br />
processFunction, which generates the argument parsing code.<br />
let tut14 (f : file) : unit =<br />
f | > gatherArguments<br />
|> processFunction f<br />
|> onlyFunctions<br />
|> iterGlobals f;<br />
eraseAttrs f<br />
14.2 test/tut14.c<br />
This C code demonstrates the language extension we wrote for generating code to process command<br />
line arguments. It will accept one argument called boolarg, and another called intarg.<br />
../test/tut14.c<br />
# include <br />
# include <br />
# include // This is where the argument macro is #define'd<br />
The boolarg argument can be passed with --boolarg or -b, and its value can be accessed in the<br />
program through the global variable boolarg <strong>of</strong> type int. When not given, the default value is 0<br />
or false.