-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsyncLoweringVisitor.cs
More file actions
156 lines (116 loc) · 5.17 KB
/
AsyncLoweringVisitor.cs
File metadata and controls
156 lines (116 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using System.Linq.Expressions;
using Hyperbee.Collections;
using Hyperbee.Expressions.CompilerServices.Transitions;
using Hyperbee.Expressions.Visitors;
namespace Hyperbee.Expressions.CompilerServices.Lowering;
internal class AsyncLoweringVisitor : BaseLoweringVisitor<AsyncLoweringInfo>
{
private ParameterExpression _finalResultVariable;
private bool _hasFinalResultVariable;
private int _awaitCount;
public bool Optimize { get; init; } = true;
public override AsyncLoweringInfo Transform(
Type resultType,
ParameterExpression[] localVariables,
Expression[] expressions,
LinkedDictionary<ParameterExpression, ParameterExpression> scopedVariables = null )
{
ArgumentNullException.ThrowIfNull( expressions, nameof( expressions ) );
ArgumentOutOfRangeException.ThrowIfZero( expressions.Length, nameof( expressions ) );
ExpressionMatcher = new ExpressionMatcher( expr => expr is AwaitExpression or AsyncBlockExpression );
VariableResolver = new VariableResolver( localVariables, scopedVariables, States );
_finalResultVariable = CreateFinalResultVariable( resultType, VariableResolver );
VisitExpressions( expressions );
if ( Optimize )
StateOptimizer.Optimize( States );
ThrowIfInvalid();
return new AsyncLoweringInfo
{
Scopes = States.Scopes,
HasFinalResultVariable = _hasFinalResultVariable,
AwaitCount = _awaitCount,
ScopedVariables = scopedVariables
};
// helpers
void ThrowIfInvalid()
{
if ( States.Scopes[0].States.Count == 0 )
throw new LoweringException(
$"Evaluation of the {nameof( expressions )} parameter resulted in empty states." );
if ( _awaitCount == 0 )
throw new LoweringException(
$"The {nameof( expressions )} parameter must contain at least one awaitable." );
}
static ParameterExpression CreateFinalResultVariable( Type resultType, VariableResolver resolver )
{
var finalResultType = resultType == typeof( void )
? typeof( IVoidResult )
: resultType;
return resolver.GetFinalResult( finalResultType );
}
}
// Visit methods
protected override void VisitExpressions( IEnumerable<Expression> expressions )
{
base.VisitExpressions( expressions );
// update the final state
if ( !_hasFinalResultVariable )
{
// assign the final result variable if not already assigned for state-machine builder.
// this is the case when the last expression is not a return statement.
// this will ensure that the state-machine builder will have a final result field.
States.TailState.Result.Variable = _finalResultVariable;
}
}
protected override Expression VisitGoto( GotoExpression node )
{
var updateNode = base.VisitGoto( node );
if ( updateNode is not GotoExpression { Kind: GotoExpressionKind.Return } gotoExpression )
return updateNode;
_hasFinalResultVariable = true;
return Expression.Assign( _finalResultVariable, gotoExpression.Value! );
}
// Override method for extension expression types
protected override Expression VisitExtension( Expression node )
{
return node switch
{
AwaitExpression awaitExpression => VisitAwaitExtension( awaitExpression ),
// Nested async blocks should be visited by their own visitor,
// but nested variables must be replaced
AsyncBlockExpression => VariableResolver.Resolve( node ),
// Lowering visitor shouldn't be used by extensions directly
// since it changes the shape of the code
_ => base.Visit( node.Reduce() )
};
}
protected Expression VisitAwaitExtension( AwaitExpression node )
{
var updatedNode = Visit( node.Target );
var joinState = States.EnterState( out var sourceState );
var resultVariable = VariableResolver.GetResultVariable( node, sourceState.StateId );
_awaitCount++;
var awaitBinder = node.GetAwaitBinder();
var awaiterVariable = VariableResolver.GetAwaiterVariable(
awaitBinder.GetAwaiterMethod.ReturnType,
sourceState.StateId
);
var resumeLabel = Expression.Label( $"{sourceState.NodeLabel.Name}_RESUME" );
var awaitTransition = new AwaitTransition
{
Target = updatedNode,
StateId = sourceState.StateId,
ResumeLabel = resumeLabel,
TargetNode = joinState,
AwaiterVariable = awaiterVariable,
ResultVariable = resultVariable,
AwaitBinder = awaitBinder,
ConfigureAwait = node.ConfigureAwait
};
States.AddJumpCase( resumeLabel, sourceState.StateId );
sourceState.Result.Variable = resultVariable;
joinState.Result.Value = resultVariable;
States.ExitState( sourceState, awaitTransition );
return ConvertToExpression( sourceState );
}
}