Section 3 with Remik (rz33@cornell.edu) Meeting #5 Notes ******************************************************** Administrivia: Evaluate your TAs with www.engineering.cornell.edu/taeval/survey.cfm Check the cs212 website for Assignment #2 errata Review: Type-safety in languages Type checking a program Why Type-Safety? **************************** Types act as an attribute on values. Therefore we can ensure that we use only specific operations defined for certain categories of types. Although this adds security to our code, some argue against this restriction since it may limit the capabilities of a language. If we are interested in ensuring types are used properly, we need to type check our programs. There are 2 ways about it: Static (Compile time): Pascal vs. Dynamic (Run-time): Visual Basic, ML Static checking is typically a pre-processing step for compiling, but it can also been done inline. Languages employing type-checking are called "Strongly Typed", such as Java and Pascal. Those that don't are "Weakly Typed", such as C and LISP. Here is an example that won't compile by Java: int x = 0; ... x = x + true; // mixing addition with boolean; undefined A Simple Type-Checker **************************** Let's write a method to type check this simple language su: EXP ::= INTEXP | BOOL INTEXP ::= (INTEXP + INTEXP) | n BOOL ::= "true" | "false" static final int INTEGER = 0; // types in our language static final int BOOLEAN = 1; bool typeCheck(CS211In f) { try { getType(f); } catch (Exception e) { return false; // type checking failed } return true; // no exception, it passed } int getType(CS211In f) { switch( f.peekAtKind() ) { case f.INTEGER: return INTEGER; case f.WORD: if (f.check("true") || f.check("false")) return BOOLEAN; else throw new Exception("Type error"); case f.OPERATOR: f.check('('); int type1 = getType(f); // use recursion f.check('+'); int type2 = getType(f); if (type1 == INTEGER) { // adding integers? if(type1 == type2) return INTEGER; // yes else throw new Exception("Adding non-integer"); } else throw new Exception("Adding non-integer"); } return 0; // shouldn't be able to get to this line }