Skip to content

Commit e78bcde

Browse files
authored
Merge pull request #4333 from ntrel/contract-inheritance
[spec/function] Add contract inheritance examples
2 parents 638d642 + 56cf3fe commit e78bcde

File tree

1 file changed

+60
-3
lines changed

1 file changed

+60
-3
lines changed

spec/function.dd

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,28 @@ $(GNAME OutStatement):
378378
functions then becomes a process of $(I loosening) the preconditions.
379379
)
380380

381+
$(SPEC_RUNNABLE_EXAMPLE_RUN
382+
---
383+
class B
384+
{
385+
int i;
386+
387+
int f() in (i == 5) => 5;
388+
}
389+
class C : B
390+
{
391+
override int f() => i; // no `in` contract, `i` can have any value
392+
}
393+
394+
B b = new B;
395+
assert(b.i == 0);
396+
//b.f(); // AssertError, `i == 5` failed
397+
398+
b = new C;
399+
assert(b.f() == 0); // OK
400+
---
401+
)
402+
381403
$(P A function without preconditions means its precondition is always
382404
satisfied.
383405
Therefore if any
@@ -386,12 +408,47 @@ $(GNAME OutStatement):
386408
effect.
387409
)
388410

389-
$(P Conversely, all of the postconditions of the function and its
390-
overridden functions must to be satisfied.
391-
Adding overriding functions then becomes a processes of $(I tightening) the
411+
$(SPEC_RUNNABLE_EXAMPLE_FAIL
412+
---
413+
class C : Object
414+
{
415+
int x;
416+
417+
override string toString()
418+
in (x > 0) // Error, Object.toString has no `in` contract
419+
{
420+
return "";
421+
}
422+
}
423+
---
424+
)
425+
426+
$(P Conversely, all the postconditions of the function and its
427+
overridden functions must be satisfied.
428+
Overriding functions then becomes a process of $(I tightening) the
392429
postconditions.
393430
)
394431

432+
$(SPEC_RUNNABLE_EXAMPLE_FAIL
433+
---
434+
class B
435+
{
436+
int i;
437+
438+
int f() out (; i > 5) => i;
439+
}
440+
class C : B
441+
{
442+
override int f() out (; i < 10) => i;
443+
}
444+
445+
B b = new C;
446+
b.f(); // AssertError, `i > 5` failed
447+
b.i = 10;
448+
b.f(); // AssertError, `i < 10` failed
449+
---
450+
)
451+
395452

396453
$(H2 $(LNAME2 function-return-values, Function Return Values))
397454

0 commit comments

Comments
 (0)