rfc:dbc

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
rfc:dbc [2015/02/06 18:01] francoisrfc:dbc [2018/03/01 23:19] (current) – Typo "Under Discussion" carusogabriel
Line 1: Line 1:
-====== PHP RFC: Native Design by Contract support ====== +====== PHP RFC: Implementing Design by Contract ====== 
-  * Version: 0.1 +  * Version: 0.4 
-  * Date: 2015-02-04 +  * Date: 2015-02-09 
-  * Author: Yasuo Ohgaki <yohgaki@ohgaki.net>, François Laupretre <francois@php.net> +  * Author: François Laupretre <francois@php.net> 
-  * Status: Draft+  * Status: Under Discussion
   * First Published at: http://wiki.php.net/rfc/dbc   * First Published at: http://wiki.php.net/rfc/dbc
 +
 +  This RFC is waiting for the decisions that will be made about scalar
 +  type hinting. The reason is that the design and syntax
 +  decisions that will be made about scalar type hinting heavily impact the
 +  contents of this RFC. Proposal is subject to be changed according scalar type 
 +  hinting implementation.
 +
 +===== Preamble =====
 +
 +This RFC is part of "Design by Contract Introduction" RFC
 +
 +  * https://wiki.php.net/rfc/introduce_design_by_contract
 +
 +There is alternative implementation proposal by "Definition"
 +
 +  * https://wiki.php.net/rfc/dbc2
 +
 +
 +The original idea of introducing DbC in PHP comes from Yasuo Ohgaki
 +<yohgaki@ohgaki.net>.
 +
 +Then, I offered to write an RFC where I propose to include DbC constraints in
 +doc comments. This is the present document.
 +
 +While we agree on the concept, Yasuo is preferring a D-like syntax, which he's proposing in [[https://wiki.php.net/rfc/dbc2|another RFC]].
 +IMO, adopting the D syntax would be fine if we designed the language from scratch, but is not the
 +best way to include the concept in PHP (more details below).
  
 ===== Introduction ===== ===== Introduction =====
  
-For more than 10 years (roughly since PHP 5 was released), the PHP core community has+For more than 10 years (since PHP 5 was released), the PHP core community has
 seen a lot of discussions about strict vs loose typing, type hinting and seen a lot of discussions about strict vs loose typing, type hinting and
-related features.+related features. Through these discussions, developers are actually searching for a way to help reduce coding errors by detecting 
 +them as early as possible. Strictifying types is an approach but, unfortunately, it does not fit 
 +so well with PHP as a loose-typed language.
  
-To summarize years of flame warsdevelopers argue that strict typing and type hinting +This RFC proposes an alternative approachalready present in several 
-will make their source code cleaner and easier to debug. On the other sidethese +languagesnamed 'Design by Contract' (reduced to 'DbC' in the rest of the document).
-features must remain optional and compatible with 'basicloose-typed PHP syntax. +
-And the debate generally dies in endless discussions about the concept of +
-'number', 'int', 'float'... :).+
  
-With this RFCwe propose an alternative approach, already present in several +Here is the definition of a contractaccording to the D language documentation :
-languages, named 'design by contract' (reduced to 'DbC' in the rest of the document).+
  
-We won't detail the concept of DbC hereas we provide links in +  The idea of a contract is simple - it's just an expression that must evaluate 
-the reference section belowJust note that DbC is way to define constraints on +  to true. If it does not, the contract is broken, and by definition, the program 
-function argumentsreturn valuesand class propertiesThe key +  has a bug in itContracts form part of the specification for program, moving 
-point is that DbC checks are performed during the development/validation +  it from the documentation to the code itself. And as every programmer knows, 
-phase only. In production phase, DbC checks are turned off.+  documentation tends to be incompleteout of datewrong, or non-existent
 +  Moving the contracts into the code makes them verifiable against the program.
  
-So, the most important points are :+For more info on the DbC theoryuse the links in the 'reference' section below.
  
-  * DbC constraints can be extremely detailed as performance is not a problem+An important point in DbC theory is that contracts are checked during the development/debugging phase only
-  DbC checks cannot handle checks that must always run, even in production. Validating user input, for instance, must remain out of DbC constraints. +A global switch allows to turn DbC checks off when the software goes to production.
-  * The DbC and 'Test Driven Development' concepts are closely related, as DbC heavily relies on the quality of test coverage.+
  
-===== Example =====+So, what we need to retain :
  
-First, an example of a function defining input, inline and output constraints +  * DbC constraints can be highly sophisticated as we don't care about performance. 
-('$>' means 'return value'):+  * As they are checked at runtime, DbC constraints can check types AND values. 
 +  * DbC checks must not handle checks that must always run, even in production. Validating user input, for instance, must remain out of DbC constraints. 
 +  * DbC and 'Test Driven Development' concepts are closely related, as DbC heavily relies on the quality of test coverage. 
 + 
 +===== Examples ===== 
 + 
 +First, an example of a function defining input and output constraints 
 +('$>' means 'return value'). This example is adapted from the [[http://ddili.org/ders/d.en/invariant.html|D language]].
  
 <code php> <code php>
Line 45: Line 77:
 * This function computes the area of a triangle using Heron's formula. * This function computes the area of a triangle using Heron's formula.
 * *
-* @param float $a Length of 1st side +* @param number $a Length of 1st side 
-* @assert.in ($a >= 0) +* @requires ($a >= 0) 
-* @param float $b Length of 2nd side +* @param number $b Length of 2nd side 
-* @assert.in ($b >= 0) +* @requires ($b >= 0) 
-* @param float $c Length of 3rd side +* @param number $c Length of 3rd side 
-* @assert.in ($c >= 0) +* @requires ($c >= 0) 
-* @assert.in ($a <= ($b+$c)) +* @requires ($a <= ($b+$c)) 
-* @assert.in ($b <= ($a+$c)) +* @requires ($b <= ($a+$c)) 
-* @assert.in ($c <= ($a+$b))+* @requires ($c <= ($a+$b))
 * *
-* @return float The triangle area +* @return number The triangle area 
-* @assert.out ($> >= 0)+* @ensures ($> >= 0)
 */ */
  
Line 62: Line 94:
 { {
 $halfPerimeter = ($a + $b + $c) / 2; $halfPerimeter = ($a + $b + $c) / 2;
- 
-// @assert ($halfPerimeter >= 0) 
  
 return sqrt($halfPerimeter return sqrt($halfPerimeter
Line 72: Line 102:
 </code> </code>
  
-Another example with a clone of str_replace() :+Then : 
 + 
 +<code php> 
 +$area=triangleArea(4,2,3); 
 + -> OK 
 + 
 +$area=triangleArea('foo',2,3); 
 + -> PHP Fatal error: triangleArea: DbC input type mismatch - $a should match 'number' (string(3) "foo") in xxx on line nn 
 + 
 +$area=triangleArea(10,2,3); 
 + -> PHP Fatal error: triangleArea: DbC pre-condition violation ($a <= ($b+$c)) in xxx on line nn 
 +</code> 
 + 
 +Another example with a PHP clone of str_replace() :
  
 <code php> <code php>
Line 86: Line 129:
 * @param string|array(string) $subject The string or array being searched and replaced on * @param string|array(string) $subject The string or array being searched and replaced on
 * @param.out int $count The number of replacements performed * @param.out int $count The number of replacements performed
-* @assert.out ($count >= 0)+* @ensures ($count >= 0)
 * @return string|array(string) A string or an array with the replaced values * @return string|array(string) A string or an array with the replaced values
 * *
 * Ensure that returned value is the same type as input subject : * Ensure that returned value is the same type as input subject :
-* @assert.out (is_array($>)===is_array($subject))+* @ensures (is_array($>)===is_array($subject))
 */ */
  
Line 100: Line 143:
 Note that we didn't provide any constraint on $count input, as this Note that we didn't provide any constraint on $count input, as this
 parameter is used for output only. parameter is used for output only.
 +
 +Finally, we rewrite the first example as a class :
 +
 +<code php>
 +<?php
 +/**
 +* @invariant ($this->a >= 0) && ($this->a <= ($this->b+$this->c))
 +* @invariant ($this->b >= 0) && ($this->b <= ($this->a+$this->c))
 +* @invariant ($this->c >= 0) && ($this->c <= ($this->b+$this->a))
 +*/
 +
 +class triangle
 +{
 +/*-- Properties */
 +
 +/** @var number Side lengths */
 +
 +private $a,$b,$c;
 +
 +//---------
 +/**
 +* @param number $a Length of 1st side
 +* @param number $b Length of 2nd side
 +* @param number $c Length of 3rd side
 +*
 +* No need to repeat constraints on values as they are checked by class invariants.
 +*/
 +
 +public function __construct($a,$b,$c)
 +{
 +$this->a=$a;
 +$this->b=$b;
 +$this->c=$c;
 +}
 +
 +//---------
 +/**
 +* Compute area of a triangle
 +*
 +* This function computes the area of a triangle using Heron's formula.
 +*
 +* @return number The triangle area
 +* @ensures ($> >= 0)
 +*/
 +
 +public function area()
 +{
 +$halfPerimeter = ($this->a + $this->b + $this->c) / 2;
 +
 +return sqrt($halfPerimeter
 + * ($halfPerimeter - $this->a)
 + * ($halfPerimeter - $this->b)
 + * ($halfPerimeter - $this->c));
 +}
 +</code>
 +
 +and check DbC constraints :
 +
 +<code php>
 +$t= new triangle(4,2,3);
 + -> OK
 +
 +$t=new triangle('foo',2,3);
 + -> PHP Fatal error: triangle::__construct: DbC input type mismatch - $a should match 'number' (string(3) "foo") in xxx on line nn
 +
 +$area=triangleArea(10,2,3);
 + -> PHP Fatal error: triangle: DbC invariant violation (($this->a >= 0) && ($this->a <= ($this->b+$this->c)) in xxx on line nn
 +</code>
  
 ===== Proposal ===== ===== Proposal =====
  
-DbC typically defines three constraint types :+DbC defines three constraint types :
  
   * pre-conditions: checked when entering a function/method. Generally check that passed arguments are valid.   * pre-conditions: checked when entering a function/method. Generally check that passed arguments are valid.
   * post-conditions: checked when a function/method exits. Used to check the return type/value and the returned type/value of arguments passed by reference.   * post-conditions: checked when a function/method exits. Used to check the return type/value and the returned type/value of arguments passed by reference.
-  * class invariants: Constraints on class properties. In PHPtwo subtypes exist : constraints on static properties and constraint on dynamic (instance) properties.+  * class invariants: Constraints on class properties. 
 + 
 +In this documentwe propose a mechanism to implement these constraints in the PHP world.
  
 ==== Syntax ==== ==== Syntax ====
  
-We propose to include the DbC directives in PHP comments. The function/method/class-related +We propose to include the DbC directives in phpdoc blocks. Here are the 
-constraints will be included in phpdoc blocks (extending the phpdoc syntax)while +main reasons, that make itin my opinion, a better choice than every other syntaxes 
-inline assertions will be included in plain comments.+proposed so far :
  
-The benefits are :+  * it allows to keep the source code executable on previous PHP interpreters. 
 +  * Phpdoc comments, while not perfect, have always played the role of annotations in PHP. 'Real' annotations would be probably better but the don't exist yet. And they won't be approved in the near future. That's why everyone needing annotations so far has extended the phpdoc syntax. 
 +  * DbC can use a great part of the already-written phpdoc informations (@param and @return types, @throws information too). So, unchanged code could already benefit of DbC.
  
-  * As directives are exclusively contained in PHP comments, the source code remains executable on every past and future PHP interpreter (no compatibility break). +Note: Some people on the mailing list are religiously opposed to including information 
-  * phpdoc blocks already contain arguments and return types. DbC will use this informationSo, unchanged code will already benefit from DbC. +in phpdoc blocksdespite the fact that thousands of people already use them 
-  * phpDocumentor will easily take advantage of the extensions DbC is bringing to the phpdoc syntax and will easily generate a more detailed documentationThere is no BC break here aseven using the current version of phpDocumentorDbC-specific keywords are ignored and the documentation is correctly generated+for this purposeThe reason is that the parser cannot handle thatI agreebut 
-  * PHP IDEs already use phpdoc blocks. So, it will be easier for them to understand DbC constraints.+that's not a task for the parserthat's a task for an external tool. We just need 
 +the hooks
 +  
 +==== Side effects ====
  
-==== Pre-conditions ====+As DbC, by nature, can be turned on and off, DbC checks must not modify 
 +anything in the environment.
  
-These conditions are checked at the beginning of a function or methodafter +While enforcing this is partially possible in theorythis implementation will leave it to 
-arguments have been receivedbut before starting executing the function body.+the developer's responsibilityas most languages do.
  
-The pre-conditions are expressed in two forms : argument types, and explicit assertions. +==== DbC types ====
-Argument types are used first and explicit assertions supplement argument types +
-with additional conditions (like conditions between arguments).+
  
-Argument types are checked before explicit assertions, meaning that +DbC types are an extension and formalization of the pre-existing phpdoc 
-explicit assertions can assume correct types.+argument/return types.
  
-=== Argument types ===+DbC types are not present in original DbC syntax (like Eiffel or D implementation), which are based on conditions only. 
 +This is a PHP-specific addition to enhance simplicity and readability. DbC types can be 
 +seen as built-in conditions.
  
-Argument type syntax is an extension and formalization of pre-existing phpdoc +Here are the main benefits of defining a set of DbC types :
-argument types. phpdoc accepts almost any string as argument type. DbC applies +
-a real meaning on these types, reusing the types commonly used in phpdoc blocks.+
  
-Argument types are not present in original DbC syntax (like Eiffel or D implementation). +  * PHP is_xxx() functions are not as intuitive as they may seem, as they are based on zval types (an equivalent of strict type checks). They are not appropriate for people who just want to accept a limited set of type juggling (accepting a numeric string from a DB, for instance). Unfortunately, checking that a given value is an integer or string containing an integer is a common need, but is quite complex to write in PHP
-This is a PHP-specific addition to enhance simplicity and readabilityArgument types +  * As it was already said, tons of source code already contains argument return/types in phpdoc. DbC types are designed to match as much as possible of this pre-existing information. 
-are just shortcuts as they could be replaced by explicit assertions.+  * Readability is a key point too: just compare a type like 'string|array(string|integer)' with the PHP code to check the same ! 
 +  * DbC types allow static analysis, which is practically impossible with conditions. 
 +  * A lot of other analyzis/debugging/profiling tools can use this information.
  
-Readability is the key point here: just compare a type like 'string|array(string|integer)' with +DbC types are used to check :
-the PHP code to check the same ! +
- +
-Argument types are used to check :+
  
   * arguments sent to a function   * arguments sent to a function
-  * arguments passed by ref returned by the function+  * arguments passed by ref returned by function
   * the function's return value   * the function's return value
 +  * the type of class properties
  
-== Syntax ==+=== Syntax ===
  
-Argument types cannot contain whitespaces.+DbC types don'contain whitespaces.
  
-Here is a pseudo-grammar of argument types :+Here is a pseudo-grammar of DbC types :
  
 <code> <code>
-phpdoc-line "*", "@param", compound-type, $<argument-name> [, free-text]+dbc-type = compound-type
  
 compound-type = type, { "|", type } compound-type = type, { "|", type }
  
 type = "integer" type = "integer"
- | "float"+ | "integer!" 
 + | "number" 
 + | "float!"
  | "string"  | "string"
 + | "string!"
  | array-type  | array-type
  | "callable"  | "callable"
Line 175: Line 295:
  | "mixed"  | "mixed"
  | "boolean"  | "boolean"
 + | "boolean!"
  
 array-type = "array" array-type = "array"
Line 186: Line 307:
 </code> </code>
  
-Every types are detailed below.+=== DbC types vs zval types ===
  
-== DbC types vs zval types ==+DbC types follow specific rules to match PHP zvals. These rules are less permissive than 
 +PHP API type juggling and previously-proposed scalar 'weak' typing, but more than previously-proposed strict typing. Actually, 
 +these types try to be a more intuitive compromise between both.
  
-Before detailing DbC types, here is a table showing the matches between zval +Strict typing is sometimes required. That's why DbC types also include a set of 
-types and DbC types:+strict types. 
 + 
 +Note that the benefit of DbC, hereis that we can match depending on zval values, as 
 +we don't care about performance.
  
 ^            ^  Zval type  ^^^^^^^^ ^            ^  Zval type  ^^^^^^^^
 ^  DbC type  ^ IS_NULL ^ IS_LONG ^ IS_DOUBLE ^ IS_BOOL(1) ^ IS_ARRAY ^ IS_OBJECT ^ IS_STRING ^ IS_RESOURCE ^ ^  DbC type  ^ IS_NULL ^ IS_LONG ^ IS_DOUBLE ^ IS_BOOL(1) ^ IS_ARRAY ^ IS_OBJECT ^ IS_STRING ^ IS_RESOURCE ^
 ^ integer    |  No      Yes    |  (2)      |  No        |  No      |  No        (3)      |  No         | ^ integer    |  No      Yes    |  (2)      |  No        |  No      |  No        (3)      |  No         |
-float       No      Yes    |  Yes      |  No        |  No      |  No        (4)      |  No         |+integer!    No      Yes    |  No        No        |  No      |  No        No        No         | 
 +^ number     |  No      Yes    |  Yes      |  No        |  No      |  No        (4)      |  No         | 
 +^ float!      No      No      Yes      |  No        |  No      |  No        No       |  No         |
 ^ string      No      Yes    |  Yes      |  No        |  No      |  (6)      |  Yes      |  No         | ^ string      No      Yes    |  Yes      |  No        |  No      |  (6)      |  Yes      |  No         |
 +^ string!    |  No      No      No        No        |  No      |  (6)      |  Yes      |  No         |
 ^ array      |  No      No      No        No        |  Yes      No        No        No         | ^ array      |  No      No      No        No        |  Yes      No        No        No         |
-^ callable    No      No      No        No        |  (5)     |  No       |  (5)      |  No         |+^ callable    No      No      No        No        |  (5)     |  (5)      |  (5)      |  No         |
 ^ object      No      No      No        No        |  No      |  Yes      |  No        No         | ^ object      No      No      No        No        |  No      |  Yes      |  No        No         |
 ^ resource    No      No      No        No        |  No      |  No        No        Yes        | ^ resource    No      No      No        No        |  No      |  No        No        Yes        |
Line 205: Line 334:
 ^ null        Yes    |  No      No        No        |  No      |  No        No        No         | ^ null        Yes    |  No      No        No        |  No      |  No        No        No         |
 ^ mixed      |  Yes    |  Yes    |  Yes      |  Yes        Yes      Yes      |  Yes      |  Yes        | ^ mixed      |  Yes    |  Yes    |  Yes      |  Yes        Yes      Yes      |  Yes      |  Yes        |
-^ boolean    |  No      No      No        Yes        No      |  No        No        No         |+^ boolean    |  No      (7)    |  (7)      |  Yes        No      |  No        No        No         | 
 +^ boolean!   |  No      No      No        Yes        No      |  No        No        No         |
  
-(1) IS_TRUE/IS_FALSE in PHP 7\\ +  * (1) IS_TRUE/IS_FALSE in PHP 7\\ 
-(2) only if decimal part is null\\ +  (2) only if decimal part is null\\ 
-(3) only is_numeric(string) returns true and decimal part is null\\ +  (3) only if is_numeric(string) returns true and decimal part is null\\ 
-(4) only is_numeric(string) returns true\\ +  (4) only if is_numeric(string) returns true\\ 
-(5) See below for conditions to match 'callable'\\ +  (5) only if is_callable(arg,true) returns true\\ 
-(6) only if class defines a \_\_toString() method+  (6) only if class defines a %%__%%toString() method\\ 
 +  * (7) O is false, 1 is true. Other values don't match (to be discussed)
  
-You may note that this much more restrictive that PHP native type juggling.+=== DbC types ===
  
 == integer == == integer ==
Line 225: Line 356:
 Synonyms: 'int' Synonyms: 'int'
  
-== float ==+== integer! == 
 + 
 +A zval-type-based integer value, positive or negative. 
 + 
 +Note: This type is equivalent to is_int($arg). 
 + 
 +Synonyms: 'int!' 
 + 
 +== number ==
  
 Any value that returns true through is_numeric(). Any value that returns true through is_numeric().
Line 231: Line 370:
 Equivalent to 'is_numeric($arg)'. Equivalent to 'is_numeric($arg)'.
  
-Synonyms: 'numeric', 'num'+Synonyms: 'numeric', 'float' 
 + 
 +== float! == 
 + 
 +A zval-type-based float value. 
 + 
 +Note: This type is equivalent to is_float($arg).
  
 == string == == string ==
  
 An entity that can be represented by a string. Numeric values are accepted as strings, An entity that can be represented by a string. Numeric values are accepted as strings,
-like objects whose class defines a __toString() method.+as well as objects whose class defines a __toString() method. 
 + 
 +== string! == 
 + 
 +Accepts IS_STRING zvals and objects whose class defines a __toString() method.
  
 == array == == array ==
  
 A PHP array. A PHP array.
- 
-Synonyms: 'arr' 
  
 Complements: Can be followed by a 'compound-type', enclosed in parentheses. Complements: Can be followed by a 'compound-type', enclosed in parentheses.
Line 257: Line 404:
 == callable == == callable ==
  
-A string or array considered as 'callable'. For more information, refer to the +A string, object or array returning true through 'is_callable($arg,true)'.
-documentation of the 'is_callable() PHP function.+
  
-Equivalent to 'is_callable($arg,true)'.+Please consult the [[http://php.net/manual/en/function.is-callable.php|is_callable() documentation]] for more details.
  
 == object == == object ==
Line 302: Line 448:
 == scalar == == scalar ==
  
-Shortcut for 'integer|float|boolean|string'.+Shortcut for 'numeric|boolean|string'.
  
 Equivalent to 'is_scalar()'. Equivalent to 'is_scalar()'.
Line 326: Line 472:
 == mixed == == mixed ==
  
-Accepts every zval type & value (catch-all).+Accepts any zval type & value (catch-all).
  
 Synonyms: 'any' Synonyms: 'any'
- 
-Complements: None 
  
 == boolean == == boolean ==
Line 342: Line 486:
 Synonyms: 'bool' Synonyms: 'bool'
  
-ComplementsNone+== boolean! == 
 + 
 +Accepts IS_BOOL zvals only (IS_TRUE/IS_FALSE on PHP 7). 
 + 
 +Synonyms'bool!' 
 + 
 +==== Pre-conditions ==== 
 + 
 +These conditions are checked at the beginning of a function or method, after 
 +arguments have been received, but before starting executing the function body. 
 + 
 +Pre-conditions are expressed in two forms : argument types, and explicit assertions. 
 +Argument types are used first and explicit assertions supplement argument types 
 +with additional conditions (like conditions between arguments). 
 + 
 +Argument types are checked before explicit assertions, meaning that 
 +explicit assertions can assume correct types.
  
 === Optional arguments === === Optional arguments ===
  
-When an optional argument is not set by the caller, its input/output types are not+When an optional argument is not set by the caller, its input (and possibly outputtypes are not
 checked. This allows to set a default value which does not match the argument's checked. This allows to set a default value which does not match the argument's
 declared input type. declared input type.
Line 368: Line 528:
  
 === Input assertions === === Input assertions ===
 +
 +These conditions supplement argument types for more complex conditions. They
 +are executed in the function scope before executing the function's body.
 +
 +Syntax :
  
 <code> <code>
-line = "*", "@assert.in", php-condition+/** 
 +* ... 
 +* @requires <php-condition
 +* ...
 </code> </code>
 +
 +where <php-condition> is a PHP expression whose evaluation returns true or false.
 +
 +These assertions can appear anywhere in the phpdoc block. They are executed in
 +the same order as they appear in the doc block.
  
 === Inheritance === === Inheritance ===
 +
 +The DbC theory, in accordance with the [[http://en.wikipedia.org/wiki/Liskov_substitution_principle|LSP]],
 +states that a subclass can override pre-conditions only if it loosens them.
 +
 +The logic we implement is in the spirit of the way PHP handles class constructors/destructors :
 +
 +  * Function pre-conditions are checked. If the function does not define any pre-condition, no check is performed, even if a parent's method defines some.
 +  * A special pre-condition is introduced. The '@parent' pre-condition causes the engine to check the parent method's pre-conditions. No existing parent method or parent method not defining any pre-condition is not considered as an error. In this case, we just have nothing to check.
 +  * The special '@parent' pre-condition can appear anywhere in the list.
  
 ==== Post-conditions ==== ==== Post-conditions ====
 +
 +Post-conditions are checked at function's exit. Like pre-conditions, they are
 +executed in the function scope.
 +
 +They are generally used to check the returned type and value, and arguments
 +returned by ref.
 +
 +When a function exits because an exception was thrown,
 +the function's post-conditions are not checked, but class constraints are
 +checked.
  
 === Returned type === === Returned type ===
  
-line = "*", "@return", compound-type [free-text]+Syntax: 
 + 
 +<code> 
 +* @return <compound-type[free-text] 
 +</code> 
 + 
 +The syntax of <compound-type> is the same as argument types. 
 + 
 +Examples: 
 + 
 +<code> 
 +* @return resource|null 
 + 
 +// For a factory: 
 + 
 +* @return object(MyClass) 
 +</code>
  
 === Argument return type === === Argument return type ===
Line 385: Line 593:
 This is the return type & value of the arguments passed by reference. This is the return type & value of the arguments passed by reference.
  
-@param.out <compound-type> <name> <free-text>+Syntax: 
 + 
 +<code> 
 +@param.out <compound-type> $<arg-name> [free-text
 +</code> 
 + 
 +Note that an argument passed by reference can have a '@param' line to define 
 +its input type and/or a '@param.out' line to define its output type. 
 +In the str_replace() example above, we don't define an input type for $count 
 +because it is undefined.
  
 === Output assertions === === Output assertions ===
  
-@assert.out+Syntax: 
 + 
 +<code> 
 +@ensures <condition> 
 +</code> 
 + 
 +As with input assertions, <condition> is a PHP condition that will be executed 
 +in the function scope. The only addition is that the '$>' string will be 
 +replaced with the function's return value before evaluation. 
 + 
 +As with pre-conditions, output types are checked before output assertions.
  
 === Inheritance === === Inheritance ===
  
-==== Class-wide constraints ====+The inheritance rules are the same as the ones for pre-conditions.
  
-=== Static constraints ===+Unlike the Eiffel or D implementations, parent post-conditions will be checked 
 +only if the child requires it using a '@ensures @parent' directive.
  
-== Syntax ==+==== Class constraints ====
  
-@assert.static+These constraints are called 'invariants' in the DbC litterature. The idea is 
 +that properties must always verify a set of 'invariant' conditions.
  
-== Execution ==+Class constraints take two forms : property types and class assertions.
  
-== Scope ==+Each property type is defined in its own docblock, just before the definition of its property and 
 +class assertions are defined in the class docblock (the block just before the class 
 +definition).
  
-== Inheritance ==+Note that we don't define a specific constraint type for static properties. They 
 +will be checked using the same syntax as dynamic properties.
  
-=== Instance constraints ===+=== Property types ===
  
-@assert.instance+Syntax:
  
-== Execution ==+<code> 
 +/** @var <compound-type> [free-text] */ 
 +</code>
  
-== Scope ==+where <compound-type> follows the same syntax as argument types.
  
-== Inheritance ==+=== Class assertions ===
  
-==== Inline assertions ====+These are defined in class docblocks.
  
-=== Syntax ===+Syntax:
  
 <code> <code>
-// @assert <condition>+@invariant <condition>
 </code> </code>
  
-=== Scope ===+<condition> must use '$this->' to access dynamic properties and 'self::' to access static properties. 
 + 
 +== Execution == 
 + 
 +Property types are checked before class assertions. 
 + 
 +This set of constraints is checked : 
 + 
 +  * after the execution of the constructor, if it exists. 
 +  * before destroying the object, even if no destructor exists. 
 +  * before and after execution of a public dynamic method. 
 + 
 +Class constraints are executed before pre-conditions and/or after post-conditions. 
 + 
 +== Scope == 
 + 
 +These constraints are executed in the class scope ('$this' and 'self' can be used). 
 + 
 +== Inheritance == 
 + 
 +The same mechanism is used as with pre/post-conditions. Parent constraints are 
 +checked only if explicitely called using '@invariant @parent'
 + 
 +==== Nested calls ==== 
 + 
 +When a function or method is called from a DbC condition, its constraints are 
 +not checked.
  
-==== Exception thrown ====+==== Constraint violations ====
  
-ContractException+When a DbC condition fails, an E_ERROR is raised, containing the file and line number of the failing condition.
  
 ===== Backward Incompatible Changes ===== ===== Backward Incompatible Changes =====
Line 437: Line 697:
 ===== Proposed PHP Version(s) ===== ===== Proposed PHP Version(s) =====
  
-PHP 7+As the plan is to implement this in a separate extension, it should be availbale for PHP 5 ans PHP 7.
  
 ===== RFC Impact ===== ===== RFC Impact =====
Line 446: Line 706:
 ==== To Existing Extensions ==== ==== To Existing Extensions ====
  
-Compatibility with Xdebug ? <TODO>+None
  
 ==== To Opcache ==== ==== To Opcache ====
  
-<TODO>+None
  
 ==== New Constants ==== ==== New Constants ====
Line 458: Line 718:
 ==== php.ini Defaults ==== ==== php.ini Defaults ====
  
-dbc.enforce : boolean+boolean whose name is still undefined.
  
   * php.ini-development value: true   * php.ini-development value: true
Line 467: Line 727:
 ===== Unaffected PHP Functionality ===== ===== Unaffected PHP Functionality =====
  
-When DbC is off, there's no change in PHP behavior.+When DbC is turned off, there's no change in PHP behavior.
  
 ===== Future Scope ===== ===== Future Scope =====
  
-  * Exceptions: Using the '@throws' keyword, we can raise an error if the function throws an exception of an undeclared class. +  - Extend DbC to internal functions 
-  * Enforce phpdoc's @var property types. Static and dynamic propertiy checks would be added to invariant checks. +  - Add exception checks (using '@throws') 
-  * Extend type syntax (define a syntax for ranges, enums, etc)+  Extend type syntax (define a syntax for ranges, enums, etc) 
 +  - Implement static-only class constraints (to be called before and after executing a static or dynamic public method) 
 +  - Extend DbC to interfaces and traits
  
 ===== Proposed Voting Choices ===== ===== Proposed Voting Choices =====
  
-Required majority ?+Required majority ? To be defined.
  
 ===== Patches and Tests ===== ===== Patches and Tests =====
  
-Dmitry Stogov volunteered for implementation. +This should be implemented in Zend extension, not in the coreThis would be a perfect addition for XDebug.
- +
-Not sure this should be implemented in the PHP core. A Zend extension would be probably better, +
-if possibleAn additional benefit, in this case, would be to add the feature to PHP 7 and PHP 5. +
- +
-We only need 3 hooks : +
- +
-  * When script file is read, before any parsing starts +
-  * When a function/method starts, after arguments are received, but before executing the function's body. +
-  * When a function returns, before the function scope is deleted. And we need access to the return value. +
- +
-I don't know yet if these hooks are available in the current engine. If implementation does not require +
-any change in the PHP engine, this RFC is useless but getting people's opinion is always valuable. +
- +
-===== Implementation ===== +
- +
-<TODO>+
  
 ===== References ===== ===== References =====
Line 507: Line 753:
 [[http://ddili.org/ders/d.en/contracts.html|Contracts Programming in the D language]] [[http://ddili.org/ders/d.en/contracts.html|Contracts Programming in the D language]]
  
-===== Rejected Features ===== +[[https://wiki.php.net/rfc/dbc2|Alternative RFC]]
- +
rfc/dbc.1423245698.txt.gz · Last modified: 2017/09/22 13:28 (external edit)