2
0
Эх сурвалжийг харах

Implicit type narrowing documentation.

Vladislav Folts 11 жил өмнө
parent
commit
352ff33614

+ 33 - 0
doc/wiki/eberon-implicit-type-narrowing.md

@@ -0,0 +1,33 @@
+Original Oberon-07 has no facility for runtime type testing combined with type casting into single operation. It leads to extra code to write (for a person) and extra operations to run (for a computer). Consider following example:
+
+    TYPE
+        Base = RECORD END;
+        PBase = POINTER TO Base;
+        Derived = RECORD (Base) derivedField: INTEGER END;
+        PDerived = POINTER TO Derived;
+    VAR
+        pb: PBase;
+    BEGIN
+        IF pb IS PDerived THEN
+            pb(PDerived).derivedField := 123;
+        END;
+
+        ASSERT(~(pb IS PDerived) OR (pb(PDerived).derivedField = 123));
+    END.
+
+As you can see here there is two separate operations - type test and then type cast. *Implicit type narrowing* is introduced to resolve this problem.
+
+The idea of *implicit type narrowing* is to make the compiler smart enough to comprehend that type testing (using IS) and following IF branch or logical conjunction (&) in expression narrows just tested variable type. The same type narrowing happens in the inverse case: logical not (~) for IS operation and following ELSE branch or logical disjunction (OR). Also compiler should guarantee that tested variable is not modified after type narrowing so there is no loopholes to corrupt type system by chance. That guarantee is easy to reach in case of [In Place Variables](/vladfolts/oberonjs/wiki/eberon-in-place-variables) because their scope is very local and they cannot be modified by local procedures. So if the example will use *pb* variable as *in place* variable then it will be compiled without addition type casts:
+
+    VAR
+        pbVar: PBase;
+    BEGIN
+        pb <- pbVar;
+        IF pb IS PDerived THEN
+            pb.derivedField := 123;
+        END;
+
+        ASSERT(~(pb IS PDerived) OR (pb.derivedField = 123));
+    END.
+
+Type narrowing is also applies for WHILE statement and its ELSIF branches.

+ 1 - 0
doc/wiki/eberon.md

@@ -6,6 +6,7 @@ Eberon extends original Oberon so any valid oberon program is also a valid ebero
 * [Methods](/vladfolts/oberonjs/wiki/eberon-methods)
 * [Strings](/vladfolts/oberonjs/wiki/eberon-strings)
 * [In Place Variables](/vladfolts/oberonjs/wiki/eberon-in-place-variables)
+* [Implicit Type Narrowing](/vladfolts/oberonjs/wiki/eberon-implicit-type-narrowing)
 * [Record fields read-only export](/vladfolts/oberonjs/wiki/eberon-record-fields-read-only-export)
 * [Procedure call result can be denoted](/vladfolts/oberonjs/wiki/eberon-procedure-call-result)
 * Non-scalar variables (arrays and records) can be exported (forbidden in oberon for some unknown reason).