80 likes | 215 Views
CS 341 Programming Language Design and Implementation. Administrative HW 3 released ― due next Wed, 1/29 @ start of class Need to install Windows and Visual Studio? See Sean… Compilers, part 2 What they can (and should) do…. Control Flow Graph and Dataflow analysis…. // C:
E N D
CS 341 Programming Language Design and Implementation • Administrative • HW 3 released ― due next Wed, 1/29 @ start of class • Need to install Windows and Visual Studio? See Sean… • Compilers, part 2 • What they can (and should) do… CS 341 -- 24 Jan 2013
Control Flow Graph and Dataflow analysis… // C: #include <stdio.h> . . . inti, j; scanf("%d", &i); if (i> 0) j = i- 1; else printf("negative"); printf("%d", j); CS 341 -- 24 Jan 2013
Semantic errors in C: • C language does not require detection, so compilers don't… • But you *CAN* detect error, you just have to use the right tool… • lint main.c • gcc -Wall -O main.c • Visual Studio: • Analyze menu • Run Code Analysis // C: #include <stdio.h> . . . inti, j; scanf("%d", &i); if (i> 0) j = i- 1; else printf("negative"); printf("%d", j); No error reported by default… CS 341 -- 24 Jan 2013
How about uninitialized pointer? Array out of bounds? // C: #include <stdio.h> #include <stdlib.h> . . . inti, j; int *A; scanf("%d", &i); if (i> 0) j = i- 1; else A = malloc(100 * sizeof(int)); A[0] = 123; A[100] = 456; Tools will catch error (A uninitialized)… Tools will not catch out of boundsat compile time; can generate code to detect at run-time if you ask… CS 341 -- 24 Jan 2013
How about NULL pointer? Depends… // C: inti, j; int *A = NULL; scanf("%d", &i); if (i> 0) j = i- 1; else A = malloc(100 * sizeof(int)); A[0] = 123; Visual Studio will catch possible NULL pointer, gcc –Wall –O does not… CS 341 -- 24 Jan 2013
Limitations of compile-time analysis… • Most compilers perform intra-procedural analysis • This means within procedures, not across procedures // C: int *AllocArray(int N) { return NULL; } int main() { int *A = AllocArray(N); A[0] = 123; Tools will not detect A is NULL… CS 341 -- 24 Jan 2013
Semantics errors in Java? C#? • These languages require compiler to detect common semantic errors… // Java: class Program { public static void Main() { inti, j; i = 10; if (i > 0) j = i - 1; else System.out.println("negative!"); System.out.println(j); } } javac Program.java Compiler detects that j is uninitialized! CS 341 -- 24 Jan 2013
What else can compilers do? • One of my favorites is type inference • When you declare a variable, compiler can infer type • Available in C#, and the latest version of C++ ("C++11") infer variable type • autosum = 0; // this is C++11 • auto r = sqrt(9.0); • auto A = new int[100]; • vector<int> vec; • ... • for(autoitr = vec.begin(); itr != vec.end(); itr++) • cout << *itr << endl; vector<int>::iterator CS 341 -- 24 Jan 2013