Download presentation
Presentation is loading. Please wait.
Published byJoshua Walters Modified over 9 years ago
1
Expanding Predefined Types Karl Schnaitter November 30, 2004
2
Inspiration In the C standard I/O library, there is a function called fgetc fgetc takes a file stream as input, and returns the next character in the stream What if there are no characters left? return a “signal” called EOF fgetc has a dual behavior : –Can return any byte –Can also return EOF
3
C implementation of fgetc Pseudocode outline: #define EOF -1 int fgetc(stream) if (stream is empty) return EOF; else return next character;
4
C implementation of fgetc Pseudocode outline: #define EOF -1 int fgetc(stream) if (stream is empty) return EOF; else return next character; The int return type is awkward
5
C implementation of fgetc Pseudocode outline: #define EOF -1 int fgetc(stream) if (stream is empty) return EOF; else return next character; The int return type is awkward There’s no difference between EOF and -1
6
C implementation of fgetc Pseudocode outline: #define EOF -1 expand char with EOF; int fgetc(stream) if (stream is empty) return EOF; else return next character; The int return type is awkward There’s no difference between EOF and -1
7
C implementation of fgetc Pseudocode outline: #define EOF -1 expand char with EOF; char int fgetc(stream) if (stream is empty) return EOF; else return next character; The int return type is awkward There’s no difference between EOF and -1
8
Type Expansion Sample type expansion code: expand bool with MAYBE This assigns MAYBE to a unique value (neither true nor false) The type of MAYBE is bool MAYBE is constant, i.e. it cannot be assigned
9
Accomplishments Successfully designed a language supporting type expansion, based partially on IMP Also added function declarations Defined small step semantics and type system The type system might be sound –A big challenge and a major focus in my project –Just a conjecture: there are 67 semantic rules to check Implemented an interpreter and type checker in OCaml Tested some applications
10
Operations on expanded values What should happen here? expand int with foo; x := foo + 2 There is a predefined value NaN, which is an expanded int The default bahavior in this case is to use expanded addition, defined as follows
11
Redefining basic operators We can also write our own version of + expand int with OVERFLOW;; function +(m : int, n : int) : int local (sum : int, ans : int, testA : bool, testB : bool) bodysum := m + n; testA := (sum < 0) || (9 < sum); testB := (m = OVERFLOW) || (n = OVERFLOW); if testA || testB then ans := OVERFLOW else ans := sum return ans Recursive calls are prevented: This is default addition
12
Applying Redefined Addition Here are some examples after redefining + 1 + 1 5 + 5 (5 + 5) + (-5) (OVERFLOW – 5) + 5 → 2→ 2 → OVERFLOW → OVERFLOW + (-5) → OVERFLOW → NaN + 5 → NaN
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.