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 116<br />
let hasArgAttr : attributes → bool = hasAttribute argStr<br />
let hasAssertAttr : attributes → bool = hasAttribute assertStr<br />
let hasMandatoryAttr : attributes → bool = hasAttribute mandatoryStr<br />
The functions isArgType, and isMandatoryType return true when their argument types have the<br />
indicated attributes.<br />
let isArgType (t : typ) : bool = t | > typeAttrs | > hasArgAttr<br />
let isMandatoryType (t : typ) : bool = t | > typeAttrs | > hasMandatoryAttr<br />
The function getAssertAttr returns the attribute parameter when the type has a "ciltut assert"<br />
attribute, and otherwise throws an exception.<br />
let getAssertAttr (t : typ) : attrparam =<br />
match filterAttributes assertStr (typeAttrs t) with<br />
| [Attr( , [ap])] → ap<br />
| → E.s (E.error "Malformed %s attribute: %a" assertStr d type t)<br />
The function string <strong>of</strong> exp extracts a string literal from an expression and returns it as an OCaml<br />
string. If the expression is NULL, it returns the empty string. If the expression is not a string, it<br />
raises an exception. We'll use it to extract structure elds for the argument type.<br />
let rec string <strong>of</strong> exp (e : exp) : string =<br />
match e with<br />
| Const(CStr s) → s<br />
| z when z = zero → ""<br />
| CastE( , e) → string <strong>of</strong> exp e<br />
| → E.s (E.error "Expected string literal: %a" d exp e)<br />
The function name <strong>of</strong> argname extracts the name <strong>of</strong> the argument from the name <strong>of</strong> the instance<br />
<strong>of</strong> the argument description structure.<br />
let name <strong>of</strong> argname (s : string) : string =<br />
if S.length s < 8 then<br />
E.s (E.error "Invalid argument name: %s" s);<br />
S.sub s 8 (S.length s − 8)<br />
Since we're using attributes to express the assertions about arguments, we'll need a few functions<br />
from Chapter 8 that we'll use to compile the attribute parameters. The function req <strong>of</strong> exp<br />
extracts the attrparam for an argument assertion from a CastE expression, and compiles it using<br />
T.exp <strong>of</strong> ap. The context c holds all <strong>of</strong> the global variables, so the assertion can also refer to other<br />
command line arguments.