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 118<br />
a.argName ← name <strong>of</strong> argname vi.vname;<br />
a.argGot ← makeGlobalVar (a.argName¢"got") intType;<br />
a.argOpt ← ¬(isMandatoryType vi.vtype);<br />
iterCompound £implicit :false £doinit : (handle field c loc a)<br />
£ct : vi.vtype £initl : ini;<br />
[a]<br />
end<br />
| → [ ]<br />
Now that we can extract an argument specication from an arbitrary global, we can just iterate<br />
over all the globals to collect a list <strong>of</strong> all the arguments. The function gatherArguments performs<br />
this iteration and returns the list <strong>of</strong> found argument specications.<br />
let gatherArguments (f : file) : argument list =<br />
let c = T.context for globals f in<br />
f.globals<br />
|> L.map (argument <strong>of</strong> global c)<br />
|> L.concat<br />
14.1.2 Code Generation<br />
With the argument specications successfully gathered, we can now generate the code that actually<br />
parses the command line. As mentioned above, we'll use the getopt long function from the C<br />
Library. This process will involve three steps. First, we'll generate assignments to initialize the<br />
global variables for the options to any default values given by the programmer. Second, we'll<br />
generate a loop that calls getopt long and interprets its results. Finally, we'll generate checks to<br />
make sure that the arguments are consistent with any assertions that the programmer gave.<br />
Initializing the global varialbes and checking the programmer provided assertions is reletively<br />
easy, but initializing the option strucutres and generating the loop for getopt long is more involved.<br />
First, we'll need a few utility functions:<br />
The function field <strong>of</strong> option gives us the <strong>CIL</strong> lval for the eld n <strong>of</strong> the i'th option structure<br />
in the array <strong>of</strong> options based at o. We'll use it in generating Set instructions that initialize the<br />
array <strong>of</strong> options needed for getopt long.<br />
let field <strong>of</strong> option (o : varinfo) (ot : typ) (i : int) (n : string) : lval =<br />
(Var o),<br />
Index(integer i, Field(fieldinfo <strong>of</strong> name ot n, NoOffset))<br />
The functions has arg <strong>of</strong> argument and int code <strong>of</strong> argument transform bits <strong>of</strong> the argument<br />
specication into <strong>CIL</strong> expressions that we'll use to initialize elds <strong>of</strong> the option structures.