This repository was archived by the owner on Apr 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathFunctionAnalysisUnit.cs
More file actions
270 lines (231 loc) · 11.3 KB
/
FunctionAnalysisUnit.cs
File metadata and controls
270 lines (231 loc) · 11.3 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Python.Core;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
using Microsoft.Python.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Analyzer {
class FunctionAnalysisUnit : AnalysisUnit {
public readonly FunctionInfo Function;
internal readonly AnalysisUnit _declUnit;
private readonly bool _concreteParameters;
private readonly Dictionary<Node, Expression> _decoratorCalls;
internal FunctionAnalysisUnit(
FunctionInfo function,
AnalysisUnit declUnit,
InterpreterScope declScope,
IPythonProjectEntry declEntry,
bool concreteParameters
)
: base(function.FunctionDefinition, null) {
_declUnit = declUnit;
Function = function;
_concreteParameters = concreteParameters;
_decoratorCalls = new Dictionary<Node, Expression>();
var scope = new FunctionScope(Function, Function.FunctionDefinition, declScope, declEntry);
_scope = scope;
if (GetType() == typeof(FunctionAnalysisUnit)) {
AnalysisLog.NewUnit(this);
}
}
internal virtual void EnsureParameters() {
((FunctionScope)Scope).EnsureParameters(this, usePlaceholders: !_concreteParameters);
}
internal virtual void EnsureParameterZero() {
((FunctionScope)Scope).EnsureParameterZero(this);
}
internal virtual bool UpdateParameters(ArgumentSet callArgs, bool enqueue = true) {
return ((FunctionScope)Scope).UpdateParameters(this, callArgs, enqueue, null, usePlaceholders: !_concreteParameters);
}
internal void AddNamedParameterReferences(AnalysisUnit caller, NameExpression[] names) {
((FunctionScope)Scope).AddParameterReferences(caller, names);
}
internal override ModuleInfo GetDeclaringModule() {
return base.GetDeclaringModule() ?? _declUnit.DeclaringModule;
}
internal override void AnalyzeWorker(DDG ddg, CancellationToken cancel) {
// Resolve default parameters and decorators in the outer scope but
// continue to associate changes with this unit.
ddg.Scope = _declUnit.InterpreterScope;
AnalyzeDefaultParameters(ddg);
var funcType = ProcessFunctionDecorators(ddg);
EnsureParameterZero();
_declUnit.InterpreterScope.AddLocatedVariable(Ast.Name, Ast.NameExpression, this);
// Set the scope to within the function
ddg.Scope = InterpreterScope;
Ast.Body.Walk(ddg);
_declUnit.InterpreterScope.AssignVariable(Ast.Name, Ast.NameExpression, this, funcType);
}
public new FunctionDefinition Ast => (FunctionDefinition)base.Ast;
public VariableDef ReturnValue => (VariableDef)((FunctionScope)Scope).ReturnValue;
private bool ProcessAbstractDecorators(IAnalysisSet decorator) {
var res = false;
// Only handle these if they are specialized
foreach (var d in decorator.OfType<SpecializedCallable>()) {
if (d.DeclaringModule != null
&& d.DeclaringModule.ModuleName != "abc") {
continue;
}
switch (d.Name) {
case "abstractmethod":
res = true;
Function.IsAbstract = true;
break;
case "abstractstaticmethod":
Function.IsStatic = true;
Function.IsAbstract = true;
res = true;
break;
case "abstractclassmethod":
Function.IsClassMethod = true;
Function.IsAbstract = true;
res = true;
break;
case "abstractproperty":
Function.IsProperty = true;
Function.IsAbstract = true;
res = true;
break;
}
}
return res;
}
internal IAnalysisSet ProcessFunctionDecorators(DDG ddg) {
var types = Function.SelfSet;
if (Ast.Decorators != null) {
Expression expr = Ast.NameExpression;
foreach (var d in Ast.Decorators.Decorators.ExcludeDefault()) {
var decorator = ddg._eval.Evaluate(d);
if (decorator.Contains(State.ClassInfos[BuiltinTypeId.Property])) {
Function.IsProperty = true;
} else if (decorator.Contains(State.ClassInfos[BuiltinTypeId.StaticMethod])) {
// TODO: Warn if IsClassMethod is set
Function.IsStatic = true;
} else if (decorator.Contains(State.ClassInfos[BuiltinTypeId.ClassMethod])) {
// TODO: Warn if IsStatic is set
Function.IsClassMethod = true;
} else if (ProcessAbstractDecorators(decorator)) {
// No-op
} else {
Expression nextExpr;
if (!_decoratorCalls.TryGetValue(d, out nextExpr)) {
nextExpr = _decoratorCalls[d] = new CallExpression(d, new[] { new Arg(expr) });
nextExpr.SetLoc(d.IndexSpan);
}
expr = nextExpr;
var decorated = AnalysisSet.Empty;
var anyResults = false;
foreach (var ns in decorator) {
var fd = ns as FunctionInfo;
if (fd != null && InterpreterScope.EnumerateTowardsGlobal.Any(s => s.AnalysisValue == fd)) {
continue;
}
decorated = decorated.Union(ns.Call(expr, this, new[] { types }, ExpressionEvaluator.EmptyNames));
anyResults = true;
}
// If processing decorators, update the current
// function type. Otherwise, we are acting as if
// each decorator returns the function unmodified.
if (ddg.ProjectState.Limits.ProcessCustomDecorators && anyResults) {
types = decorated;
}
}
}
}
return types;
}
internal void AnalyzeDefaultParameters(DDG ddg) {
IVariableDefinition param;
var scope = (FunctionScope)Scope;
for (var i = 0; i < Ast.Parameters.Length; ++i) {
var p = Ast.Parameters[i];
if (p.Annotation != null) {
var val = ddg._eval.EvaluateAnnotation(p.Annotation);
if (val?.Any() == true && Scope.TryGetVariable(p.Name, out param)) {
param.AddTypes(this, val, false);
var vd = scope.GetParameter(p.Name);
if (vd != null && vd != param) {
vd.AddTypes(this, val, false);
}
}
}
if (p.DefaultValue != null && p.Kind != ParameterKind.List && p.Kind != ParameterKind.Dictionary &&
Scope.TryGetVariable(p.Name, out param)) {
var val = ddg._eval.Evaluate(p.DefaultValue);
if (val != null) {
param.AddTypes(this, val, false);
var vd = scope.GetParameter(p.Name);
if (vd != null && vd != param) {
vd.AddTypes(this, val, false);
}
}
}
}
if (Ast.ReturnAnnotation != null) {
var ann = ddg._eval.EvaluateAnnotation(Ast.ReturnAnnotation);
var resType = ann;
if (Ast.IsGenerator) {
if (ann.Split<ProtocolInfo>(out var gens, out resType)) {
var gen = ((FunctionScope)Scope).Generator;
foreach (var g in gens.SelectMany(p => p.GetProtocols<GeneratorProtocol>())) {
gen.Yields.AddTypes(ProjectEntry, g.Yielded);
gen.Sends.AddTypes(ProjectEntry, g.Sent);
gen.Returns.AddTypes(ProjectEntry, g.Returned);
}
}
} else {
((FunctionScope)Scope).AddReturnTypes(
Ast.ReturnAnnotation,
ddg._unit,
resType
);
}
}
}
public override string ToString() {
return "{0}{1}({2})->{3}".FormatInvariant(
base.ToString(),
" def:",
string.Join(", ", Ast.Parameters.Select(p => InterpreterScope.TryGetVariable(p.Name, out var v) ? v.Types.ToString() : "{}")),
((FunctionScope)Scope).ReturnValue.Types.ToString()
);
}
}
class FunctionClosureAnalysisUnit : FunctionAnalysisUnit {
private readonly FunctionAnalysisUnit _originalUnit;
private readonly IVersioned _agg;
internal FunctionClosureAnalysisUnit(IVersioned agg, FunctionAnalysisUnit originalUnit, CallChain callChain) :
base(originalUnit.Function, originalUnit._declUnit, originalUnit._declUnit.InterpreterScope, originalUnit.ProjectEntry, true) {
_originalUnit = originalUnit;
_agg = agg;
CallChain = callChain;
_originalUnit.InterpreterScope.AddLinkedScope(InterpreterScope);
var node = originalUnit.Function.FunctionDefinition;
node.Body.Walk(new OverviewWalker(originalUnit.ProjectEntry, this, originalUnit.Tree));
AnalysisLog.NewUnit(this);
}
public override IVersioned DependencyProject => _agg;
public FunctionAnalysisUnit OriginalUnit => _originalUnit;
internal override ILocationResolver AlternateResolver => _originalUnit;
public CallChain CallChain { get; }
public override string ToString() {
return base.ToString() + " " + CallChain.ToString();
}
}
}