scope(success) lowered to try-catch ?

Steven Schveighoffer schveiguy at yahoo.com
Sun Jun 17 12:34:14 UTC 2018


On 6/17/18 8:24 AM, Timoses wrote:
> On Sunday, 17 June 2018 at 10:58:29 UTC, Cauterite wrote:
>> Hello,
>> I'm not sure whether I'm missing something obvious here, but is there 
>> a reason for scope(success) being lowered to a try-catch statement?
>> I would have expected only scope(exit) and scope(failure) to actually 
>> interact with exception handling, while scope(success) simply places 
>> code on the path of normal control flow.
>>
>> Example (windows x32):
>>
>> ---
>>
>> // main.d
>> void main() {
>>     scope(success) {}
>> }
>>
>>> dmd -betterC main.d
>> Error: Cannot use try-catch statements with -betterC
>>
>> ---
>>
>> Regardless of whether -betterC is used, you can see in the disassembly 
>> that having a scope(success) anywhere in the function causes the SEH 
>> prologue to be emitted in the code.
>>
>> Is there a reason scope(success) needs to set up for exception handling?
>> Or is this a bug / potential enhancement ?
> 
> In Andrei's book 'The D Programming Language' the following is written:
> 
> {
>      <statement1>
>      scope(success) <statement2>
>      <statement3>
> }
> is lowered to
> {
>      <statement1>
>      bool __succeeded = true;
>      try {
>          <statement3>
>      } catch(Exception e) {
>          __succeeded = false;
>          throw e;
>      } finally {
>          if (__succeeded) <statement2> // vice-versa for scope(failure): 
> `if (!__succeeded) ...`
>      }
> }
> 
> If it weren't and it would simply be integrated one would have to write
> 
>      potentiallyThrowingFunc();
>      scope(success) {...};
> 
> I suppose? And this seems like breaking how scope works with failure and 
> exit?
I think the request isn't to integrate the code immediately, but to do:

{
<statement 1>
<statement 3>

<statement 2>
}

and be just fine. I think the reason the scope(failure) is done that way 
is likely for proper exception chaining in case one of the scope 
statements throws.

-Steve


More information about the Digitalmars-d-learn mailing list