-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSemanticChecker.cs
More file actions
530 lines (443 loc) · 20.4 KB
/
Copy pathSemanticChecker.cs
File metadata and controls
530 lines (443 loc) · 20.4 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
using HydraScript.Application.StaticAnalysis.Exceptions;
using HydraScript.Domain.Constants;
using HydraScript.Domain.FrontEnd.Parser;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Declarations;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Declarations.AfterTypesAreLoaded;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Expressions;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Expressions.AccessExpressions;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Expressions.ComplexLiterals;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Expressions.PrimaryExpressions;
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Statements;
using HydraScript.Domain.IR.Impl.Symbols;
using HydraScript.Domain.IR.Impl.Symbols.Ids;
using HydraScript.Domain.IR.Types;
using ZLinq;
namespace HydraScript.Application.StaticAnalysis.Visitors;
internal class SemanticChecker : VisitorBase<IAbstractSyntaxTreeNode, Type>,
IVisitor<ScriptBody, Type>,
IVisitor<WhileStatement, Type>,
IVisitor<IfStatement, Type>,
IVisitor<InsideStatementJump, Type>,
IVisitor<ReturnStatement, Type>,
IVisitor<ExpressionStatement, Type>,
IVisitor<IdentifierReference, Type>,
IVisitor<EnvVarReference, Type>,
IVisitor<Literal, Type>,
IVisitor<ImplicitLiteral, Type>,
IVisitor<ArrayLiteral, ArrayType>,
IVisitor<ObjectLiteral, ObjectType>,
IVisitor<ConditionalExpression, Type>,
IVisitor<BinaryExpression, Type>,
IVisitor<UnaryExpression, Type>,
IVisitor<LexicalDeclaration, Type>,
IVisitor<AssignmentExpression, Type>,
IVisitor<MemberExpression, Type>,
IVisitor<IndexAccess, Type>,
IVisitor<DotAccess, Type>,
IVisitor<CastAsExpression, Type>,
IVisitor<WithExpression, ObjectType>,
IVisitor<CallExpression, Type>,
IVisitor<FunctionDeclaration, Type>,
IVisitor<BlockStatement, Type>,
IVisitor<OutputStatement, Type>,
IVisitor<InputStatement, Type>
{
private readonly IHydraScriptTypesService _typesService;
private readonly IFunctionWithUndefinedReturnStorage _functionStorage;
private readonly IMethodStorage _methodStorage;
private readonly ISymbolTableStorage _symbolTables;
private readonly IAmbiguousInvocationStorage _ambiguousInvocations;
private readonly IVisitor<TypeValue, Type> _typeBuilder;
public SemanticChecker(
IHydraScriptTypesService typesService,
IFunctionWithUndefinedReturnStorage functionStorage,
IMethodStorage methodStorage,
ISymbolTableStorage symbolTables,
IAmbiguousInvocationStorage ambiguousInvocations,
IVisitor<TypeValue, Type> typeBuilder)
{
_typesService = typesService;
_functionStorage = functionStorage;
_methodStorage = methodStorage;
_symbolTables = symbolTables;
_ambiguousInvocations = ambiguousInvocations;
_typeBuilder = typeBuilder;
}
public override Type Visit(IAbstractSyntaxTreeNode visitable) => _typesService.Undefined;
public Type Visit(ScriptBody visitable)
{
for (var i = 0; i < visitable.Count; i++)
visitable[i].Accept(This);
foreach (var funcDecl in _functionStorage.Flush())
funcDecl.Accept(This);
_methodStorage.Clear();
_symbolTables.Clear();
_ambiguousInvocations.Clear();
return _typesService.Undefined;
}
public Type Visit(WhileStatement visitable)
{
var condType = visitable.Condition.Accept(This);
if (!condType.Equals(_typesService.Boolean))
throw new NotBooleanTestExpression(visitable.Segment, condType);
visitable.Statement.Accept(This);
return _typesService.Undefined;
}
public Type Visit(IfStatement visitable)
{
var testType = visitable.Test.Accept(This);
if (!testType.Equals(_typesService.Boolean))
throw new NotBooleanTestExpression(visitable.Segment, testType);
visitable.Then.Accept(This);
visitable.Else?.Accept(This);
return _typesService.Undefined;
}
public Type Visit(InsideStatementJump visitable)
{
switch (visitable.Keyword)
{
case InsideStatementJumpKeyword.Break:
if (!(visitable.ChildOf<IfStatement>() || visitable.ChildOf<WhileStatement>()))
throw new OutsideOfStatement(
visitable.Segment,
visitable.Keyword,
statement: "if|while");
break;
case InsideStatementJumpKeyword.Continue:
if (!visitable.ChildOf<WhileStatement>())
throw new OutsideOfStatement(
visitable.Segment,
visitable.Keyword,
statement: "while");
break;
}
return _typesService.Undefined;
}
public Type Visit(ReturnStatement visitable)
{
if (!visitable.ChildOf<FunctionDeclaration>())
throw new ReturnOutsideFunction(visitable.Segment);
return visitable.Expression?.Accept(This) ?? _typesService.Void;
}
public Type Visit(ExpressionStatement visitable) =>
visitable.Expression.Accept(This);
public Type Visit(IdentifierReference visitable)
{
var symbol = _symbolTables[visitable.Scope].FindSymbol(new VariableSymbolId(visitable.Name));
if (symbol is { Initialized: false })
throw new AccessBeforeInitialization(visitable);
return symbol?.Type ?? throw new UnknownIdentifierReference(visitable);
}
public Type Visit(EnvVarReference visitable) => _typesService.String;
public Type Visit(Literal visitable) =>
visitable.Type.Accept(_typeBuilder);
public Type Visit(ImplicitLiteral visitable)
{
var type = visitable.Type.Accept(_typeBuilder);
if (!visitable.IsDefined)
{
var definedValue = _typesService.GetDefaultValueForType(type);
visitable.SetValue(definedValue);
}
return type;
}
public ArrayType Visit(ArrayLiteral visitable)
{
if (visitable.Expressions.Count == 0)
return new ArrayType(new Any());
var type = visitable[0].Accept(This);
if (visitable.Expressions.All(e => e.Accept(This).Equals(type)))
return new ArrayType(type);
throw new WrongArrayLiteralDeclaration(visitable.Segment, type);
}
public ObjectType Visit(ObjectLiteral visitable)
{
var properties = visitable.Properties.AsValueEnumerable().Select(prop =>
{
var propType = prop.Expression.Accept(This);
if (propType is NullType &&
(visitable.ChildOf<AssignmentExpression>(
x => x.ChildOf<LexicalDeclaration>() && x.DestinationType is null) ||
visitable.ChildOf<ReturnStatement>(x => x.ChildOf<FunctionDeclaration>(
decl => decl.ReturnTypeValue is TypeIdentValue { TypeId.Name: "undefined" }))))
throw new CannotAssignNullWhenUndefined(prop.Segment);
var propSymbol = propType switch
{
ObjectType objectType => new ObjectSymbol(prop.Id, objectType),
_ => new VariableSymbol(prop.Id, propType)
};
propSymbol.Initialize();
_symbolTables[visitable.Scope].AddSymbol(propSymbol);
return new PropertyType(prop.Id, propType);
}).OrderBy(x => x.Id).ToDictionary(
x => x.Id,
x => x.Type);
var objectLiteralType = new ObjectType(properties);
return objectLiteralType;
}
public Type Visit(ConditionalExpression visitable)
{
var tType = visitable.Test.Accept(This);
if (!tType.Equals(_typesService.Boolean))
throw new NotBooleanTestExpression(visitable.Test.Segment, tType);
var cType = visitable.Consequent.Accept(This);
var aType = visitable.Alternate.Accept(This);
if (cType.Equals(aType))
return cType;
throw new WrongConditionalTypes(
segment: visitable.Segment,
cSegment: visitable.Consequent.Segment,
cType,
aSegment: visitable.Alternate.Segment,
aType);
}
public Type Visit(BinaryExpression visitable)
{
var lType = visitable.Left.Accept(This);
var rType = visitable.Right.Accept(This);
if (!lType.TryGetOperator(visitable.Operator, out var @operator))
throw new UnsupportedOperation(visitable.Segment, lType, visitable.Operator);
var operation = new OperationDescriptor(visitable.Operator, OperandTypes: [lType, rType]);
if (!@operator.TryGetResultType(operation, out var resultType))
throw new IncompatibleTypesOfOperands(
visitable.Segment,
left: lType,
right: rType);
if (resultType.Equals(_typesService.Undefined))
throw new CannotDefineType(visitable.Segment);
return resultType;
}
public Type Visit(UnaryExpression visitable)
{
var eType = visitable.Expression.Accept(This);
if (!eType.TryGetOperator(visitable.Operator, out var @operator))
throw new UnsupportedOperation(visitable.Segment, eType, visitable.Operator);
var operation = new OperationDescriptor(visitable.Operator, OperandTypes: [eType]);
if (!@operator.TryGetResultType(operation, out var resultType))
throw new UnsupportedOperation(visitable.Segment, eType, visitable.Operator);
if (resultType.Equals(_typesService.Undefined))
throw new CannotDefineType(visitable.Segment);
return resultType;
}
public Type Visit(LexicalDeclaration visitable)
{
for (var i = 0; i < visitable.Assignments.Count; i++)
{
var assignment = visitable.Assignments[i];
var registeredSymbol = _symbolTables[visitable.Scope].FindSymbol(new VariableSymbolId(assignment.Destination.Id))!;
var sourceType = assignment.Source.Accept(This);
if (sourceType.Equals(_typesService.Undefined))
throw new CannotDefineType(assignment.Source.Segment);
if (sourceType.Equals(_typesService.Void))
throw new CannotAssignVoid(assignment.Source.Segment);
if (!registeredSymbol.Type.Equals(_typesService.Undefined) &&
!default(CommutativeTypeEqualityComparer).Equals(registeredSymbol.Type, sourceType))
throw new IncompatibleTypesOfOperands(
assignment.Segment,
left: registeredSymbol.Type,
right: sourceType);
if (sourceType is NullType && registeredSymbol.Type.Equals(_typesService.Undefined))
throw new CannotAssignNullWhenUndefined(assignment.Segment);
var actualType = registeredSymbol.Type.Equals(_typesService.Undefined)
? sourceType
: registeredSymbol.Type;
var actualSymbol = actualType switch
{
ObjectType objectType => new ObjectSymbol(registeredSymbol.Name, objectType, visitable.ReadOnly),
_ => new VariableSymbol(registeredSymbol.Name, actualType, visitable.ReadOnly)
};
actualSymbol.Initialize();
_symbolTables[visitable.Scope].AddSymbol(actualSymbol);
}
return _typesService.Undefined;
}
public Type Visit(AssignmentExpression visitable)
{
var typeComparer = default(CommutativeTypeEqualityComparer);
var sourceType = visitable.Source.Accept(This);
if (!visitable.Destination.Empty())
{
var destinationType = visitable.Destination.Accept(This);
if (!typeComparer.Equals(destinationType, sourceType))
throw new IncompatibleTypesOfOperands(
visitable.Segment,
left: destinationType,
right: sourceType);
return destinationType;
}
// здесь может быть переменная программы, а может быть переменная среды
var symbol = visitable.Destination.Id.ToValueDto().Type is ValueDtoType.Name
? _symbolTables[visitable.Scope].FindSymbol(new VariableSymbolId(visitable.Destination.Id)) ??
throw new UnknownIdentifierReference(visitable.Destination.Id)
: new VariableSymbol(visitable.Destination.Id, _typesService.String);
if (symbol.ReadOnly)
throw new AssignmentToConst(visitable.Destination.Id);
if (!typeComparer.Equals(sourceType, symbol.Type))
throw new IncompatibleTypesOfOperands(
visitable.Segment,
left: symbol.Type,
right: sourceType);
return symbol.Type;
}
public Type Visit(MemberExpression visitable)
{
IAbstractSyntaxTreeNode id = visitable.Id;
return visitable.Empty()
? id.Accept(This)
: visitable.AccessChain.Last?.Value.Accept(This) ?? _typesService.Undefined;
}
public Type Visit(IndexAccess visitable)
{
var prevType =
visitable.Prev?.Accept(This) ??
(visitable.Parent is MemberExpression { Id: IAbstractSyntaxTreeNode id }
? id.Accept(This)
: _typesService.Undefined);
if (!prevType.TryGetOperator("[]", out var indexOperator))
throw new NonAccessibleType(prevType);
var indexType = visitable.Index.Accept(This);
var indexAccessDescriptor = new OperationDescriptor("[]", [prevType, indexType]);
if (!indexOperator.TryGetResultType(indexAccessDescriptor, out var elemType))
throw new ArrayAccessException(visitable.Segment, indexType);
return elemType;
}
public Type Visit(DotAccess visitable)
{
var prevType =
visitable.Prev?.Accept(This) ??
(visitable.Parent is MemberExpression { Id: IAbstractSyntaxTreeNode id }
? id.Accept(This)
: _typesService.Undefined);
if (prevType is not ObjectType objectType)
throw new NonAccessibleType(prevType);
var fieldType = objectType[visitable.Property];
var hasMethod = objectType.HasMethod(visitable.Property);
if (fieldType is null)
return hasMethod
? objectType
: throw new ObjectAccessException(visitable.Segment, objectType, visitable.Property);
return fieldType;
}
public ObjectType Visit(WithExpression visitable)
{
var exprType = visitable.Expression.Accept(This);
if (exprType is not ObjectType supersetObjectType)
throw new UnsupportedOperation(visitable.Segment, exprType, "with");
IVisitor<ObjectLiteral, ObjectType> objectLiteralVisitor = this;
var subsetObjectType = visitable.ObjectLiteral.Accept(objectLiteralVisitor);
if (!supersetObjectType.IsSubsetOf(subsetObjectType))
throw new IncompatibleTypesOfOperands(
visitable.Segment,
left: supersetObjectType,
right: subsetObjectType);
visitable.ComputedCopiedProperties = supersetObjectType.CalculateDifference(subsetObjectType);
return supersetObjectType;
}
public Type Visit(CastAsExpression visitable)
{
var from = visitable.Expression.Accept(This);
if (from.Equals(_typesService.Undefined))
throw new CannotDefineType(visitable.Expression.Segment);
var to = visitable.Cast.Accept(_typeBuilder);
visitable.ToType = to switch
{
_ when to.Equals(_typesService.String) => CastAsExpression.DestinationType.String,
_ when to.Equals(_typesService.Number) => CastAsExpression.DestinationType.Number,
_ when to.Equals(_typesService.Boolean) => CastAsExpression.DestinationType.Boolean,
_ => CastAsExpression.DestinationType.Undefined
};
return _typesService.IsExplicitCastAllowed(from, to)
? to
: throw new ExplicitCastNotSupported(visitable, from, to);
}
public Type Visit(CallExpression visitable)
{
var parameters = visitable.Parameters.Select(expr => expr.Accept(This)).ToList();
FunctionSymbol functionSymbol;
var methodCall = !visitable.Member.Empty();
if (methodCall)
{
var objectType = (ObjectType)visitable.Member.Accept(This);
var availableMethods = _methodStorage.GetAvailableMethods(objectType);
var methodKey = new FunctionSymbolId(objectType.LastAccessedMethodName, [objectType, ..parameters]);
_ambiguousInvocations.CheckCandidatesAndThrow(visitable.Segment, methodKey);
functionSymbol =
availableMethods.GetValueOrDefault(methodKey)
?? throw new UnknownFunctionOverload(visitable.Id, methodKey);
}
else
{
var functionKey = new FunctionSymbolId(visitable.Id, parameters);
_ambiguousInvocations.CheckCandidatesAndThrow(visitable.Segment, functionKey);
functionSymbol =
_symbolTables[visitable.Scope].FindSymbol(functionKey)
?? throw new UnknownFunctionOverload(visitable.Id, functionKey);
}
visitable.ComputedFunctionAddress = functionSymbol.Id.ToString();
visitable.IsEmptyCall = functionSymbol.IsEmpty;
var functionReturnType = functionSymbol.Type;
visitable.Parameters.AsValueEnumerable()
.Zip(parameters).Zip(functionSymbol.Parameters.AsValueEnumerable().Skip(methodCall ? 1 : 0))
.ToList().ForEach(pair =>
{
var ((expr, actualType), expectedType) = pair;
if (!actualType.Equals(expectedType))
throw new WrongTypeOfArgument(expr.Segment, expectedType, actualType);
});
if (functionSymbol.Type.Equals(_typesService.Undefined))
{
var declaration = _functionStorage.Get(functionSymbol);
functionReturnType = declaration.Accept(This);
}
if (!functionReturnType.Equals(_typesService.Void))
visitable.HasReturnValue = true;
return functionReturnType;
}
public Type Visit(FunctionDeclaration visitable)
{
var parameters = visitable.Arguments.Select(x => x.TypeValue.Accept(_typeBuilder)).ToList();
var symbol = _symbolTables[visitable.Scope].FindSymbol(new FunctionSymbolId(visitable.Name, parameters))!;
_functionStorage.RemoveIfPresent(symbol);
visitable.Statements.Accept(This);
HashSet<Type> returnTypes = [];
for (var i = 0; i < visitable.ReturnStatements.Count; i++)
{
var returnStatementType = visitable.ReturnStatements[i].Accept(This);
returnTypes.Add(returnStatementType);
if (returnTypes.Count > 1 && symbol.Type.Equals(_typesService.Undefined))
throw new CannotDefineType(visitable.Segment);
if (!symbol.Type.Equals(_typesService.Undefined) && !symbol.Type.Equals(returnStatementType))
throw new WrongReturnType(
visitable.ReturnStatements[i].Segment,
expected: symbol.Type,
actual: returnStatementType);
}
if (symbol.Type.Equals(_typesService.Undefined))
symbol.DefineReturnType(returnTypes.Single());
if (!symbol.Type.Equals(_typesService.Void) && !visitable.AllCodePathsEndedWithReturn)
throw new FunctionWithoutReturnStatement(visitable.Segment);
if (symbol.Type is NullType)
throw new CannotAssignNullWhenUndefined(visitable.Segment);
return symbol.Type;
}
public Type Visit(BlockStatement visitable)
{
for (var i = 0; i < visitable.Count; i++)
visitable[i].Accept(This);
return _typesService.Undefined;
}
public Type Visit(OutputStatement visitable)
{
visitable.Expression.Accept(This);
return _typesService.Undefined;
}
public Type Visit(InputStatement visitable)
{
IAbstractSyntaxTreeNode id = visitable.Destination;
var idType = id.Accept(This);
if (!idType.Equals(_typesService.String))
throw new UnsupportedOperation(visitable.Segment, idType, "<<<");
return _typesService.Undefined;
}
}