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

29.01.2014 Views

CHAPTER 2. VISITING THE AST 18 Coding Hint: The inx function |> has type (α → (α → β) → β). The code in tut2 is another way of writing iterGlobals f (onlyFunctions (processFunction funvar)) but without all the extra parenthesis. |> is included in the F# standard library, but since it isn't in OCaml's we dene it in Tututil. You can read it as expression on the left is passed to function on right, and we can chain them up like I have in tut2 without writing lots of extra parenthesis. let tut2 (funvar : string × string) (f : file) : unit = funvar | > processFunction | > onlyFunctions | > iterGlobals f 2.2 test/tut2.c In main.ml tut2 in tut2.ml is called with argument ("foo","bar") meaning that assignments to global variables called bar should be removed from functions called foo. Thus, when the code below is compiled with tut2 enabled, the program should print 37 and exit. # include int bar = 37; int foo() { int l; bar = 0; l = bar; return l; } int main() { int r; r = foo(); printf("r = %d\n", r); return 0; } ../test/tut2.c As with test/tut1.c, we can build this le with the following command:

CHAPTER 2. VISITING THE AST 19 $ ciltutcc --enable-tut2 -o tut2 test/tut2.c test/tut2.c:16: Deleted assignment: #line 16 "test/tut2.c" bar = 0; Again, using the E.log function above, ciltutcc informs us that it has removed an assignment to bar on line 16. Now, we can run the resulting program: $ ./tut2 r = 37 As expected, the assignment of 0 to bar has been removed from the function foo, and the program prints the original value. 2.3 Exercises 1. Take a look at the methods available for use in a visitor class. Rewrite this example without using iterGlobals. That is, use only the visitor class to do all the work.

CHAPTER 2. VISITING THE AST 19<br />

$ ciltutcc --enable-tut2 -o tut2 test/tut2.c<br />

test/tut2.c:16: Deleted assignment: #line 16 "test/tut2.c"<br />

bar = 0;<br />

Again, using the E.log function above, ciltutcc informs us that it has removed an assignment<br />

to bar on line 16. Now, we can run the resulting program:<br />

$ ./tut2<br />

r = 37<br />

As expected, the assignment <strong>of</strong> 0 to bar has been removed from the function foo, and the<br />

program prints the original value.<br />

2.3 Exercises<br />

1. Take a look at the methods available for use in a visitor class. Rewrite this example without<br />

using iterGlobals. That is, use only the visitor class to do all the work.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!