Com S 641 meeting -*- Outline -*- * declaration blocks (4.4) This is like ML's "local" declaration form ** syntax and examples ------------------------------------------ DECLARATION BLOCKS AND INFORMATION-HIDING (4.4) Syntax: D ::= ... | begin D1 in D2 end Example: module GLOBALSTACK(N:int) = begin var CTR: newint, var STACK: array[1..N] of newint in proc PUSH(X:int exp) = if @CTR=N then skip else CTR := @CTR+1; STACK[@CTR] := X fi, proc POP = if @CTR = 0 then skip else CTR := @CTR -1 fi proc TOP = if @CTR = 0 then error else @(STACK[@CTR]) fi proc INIT = CTR := 0 end ------------------------------------------ The meaning is that declarations in D1 are local to this block, and the environment produced is only that of D2. This effectively hides the declarations D1, since they can only be seen by D2, as in the example, CTR and STACK are hidden. use: import GLOBALSTACK(641) in call INIT; call PUSH(0); ... Q: How does this guarantee information hiding? ------------------------------------------ STATIC VARIABLES As in C and C++ int timescalled() { static int i = 0; i++; return i; } main() { return timescalled() + timescalled(); } ------------------------------------------ Q: How could you do this using local declarations? begin var i: newint in fun timescalled = (i := i + 1; i) end in timescalled + timescalled (have to imagine we have an expression language for a moment...) ** semantics ------------------------------------------ SEMANTICS OF LOCAL DECLARATIONS Typing rule: Semantics: ------------------------------------------ Q: What's the typing rule that's appropriate for this? Q: Do we deallocate the storage at the end of a declaration block? no, that's only in command blocks... [[pi |- begin D1 in D2 end: pi2 dec]] e s = [[pi `unionMinus` pi1 |- D2: pi2 dec]] (e `unionMinus` e1) s1 where (e1, s1) = [[pi |- D1: pi1 dec]] e s ** problems with the direct model In direct-model languages (Ada, Modula-2), one has a problem in that hidden type structures can't be used by clients, So global-module examples work, but not object-like examples ------------------------------------------ USING HIDDEN TYPE STRUCTURES Example of the problem: module RATIONAL = begin class RAT = record var NUM: newint, var DEN: newint end in proc INITRAT(N:int exp, D: int exp, M:RAT) = (M.NUM := N; M.DEN := D), proc MULTRAT(M:RAT, N: RAT, P: RAT) = (P.NUM := @M.NUM * @N.NUM; P.DEN := @M.DEN * @N.DEN) ... end Can clients use RAT in declarations? ------------------------------------------ ... no in Modula-2, have definition modules, that allow RAT to be used as a type structure with unknown properties (by-name) definition module RATIONAL = { class RAT, proc INITRAT(N:int exp, D: int exp, M:RAT); proc MULTRAT(M:RAT, N: RAT, P: RAT); ... } Q: Is this a problem in the indirect model too? no. Why not?