-
Notifications
You must be signed in to change notification settings - Fork 25
/
CrossChecker.cs
1850 lines (1635 loc) · 90.4 KB
/
CrossChecker.cs
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using JetBrains.Annotations;
using TypeCobol.Compiler.CodeElements;
using TypeCobol.Compiler.CodeElements.Expressions;
using TypeCobol.Compiler.CodeModel;
using TypeCobol.Compiler.Nodes;
using TypeCobol.Compiler.Parser;
using Antlr4.Runtime;
using TypeCobol.Compiler.Directives;
using TypeCobol.Compiler.Scanner;
using TypeCobol.Compiler.Symbols;
using System.Diagnostics;
namespace TypeCobol.Compiler.Diagnostics
{
public class CrossCompleteChecker : AbstractAstVisitor
{
public CrossCompleteChecker([NotNull]TypeCobolOptions compilerOptions)
{
_compilerOptions = compilerOptions;
_searchTables = new Dictionary<Search, List<DataDefinition>>();
}
private readonly TypeCobolOptions _compilerOptions;
/// <summary>
/// For each encountered Search statement, stores target table and its parent table definitions.
/// If the target table could not be resolved or if it's actually not a table, no entry is added.
/// Every entry is either null (if table is part of a TC typedef) or not empty (the searched table itself is always part of the list).
/// </summary>
private readonly Dictionary<Search, List<DataDefinition>> _searchTables;
//Holds a reference to the last section node visited as to know in which current section we are
private Section _currentSection;
private Node CurrentNode { get; set; }
public override bool BeginNode(Node node)
{
CurrentNode = node;
//Build node StorageAreaWritesDataDefinition and StorageAreaReadsDataDefinition dictionaries
//from CodeElement StorageAreaReads and StorageAreaWrites
CodeElement codeElement = node.CodeElement;
if (codeElement?.StorageAreaReads != null)
{
foreach (var storageAreaRead in codeElement.StorageAreaReads)
{
CheckVariable(node, storageAreaRead, true);
}
}
if (codeElement?.StorageAreaWrites != null)
{
foreach (var storageAreaWrite in codeElement.StorageAreaWrites)
{
CheckVariable(node, storageAreaWrite.StorageArea, false);
}
}
//Build node StorageAreaWritesDataDefinition and StorageAreaReadsDataDefinition dictionaries
//for Corresponding instruction from StorageAreaGroupsCorrespondingImpact
if (codeElement?.StorageAreaGroupsCorrespondingImpact != null)
{
CheckVariable(node, codeElement.StorageAreaGroupsCorrespondingImpact.SendingGroupItem, true);
CheckVariable(node, codeElement.StorageAreaGroupsCorrespondingImpact.ReceivingGroupItem, false);
}
return true;
}
public override bool Visit(GlobalStorageSection globalStorageSection)
{
GlobalStorageSectionChecker.OnNode(globalStorageSection);
return true;
}
public override bool BeginCodeElement(CodeElement codeElement)
{
//This checker is only for Node after the full AST has been created
return false;
}
public override bool Visit(FunctionDeclaration functionDeclaration)
{
FunctionDeclarationChecker.OnNode(functionDeclaration);
FormalizedCommentsChecker.CheckFunctionComments(functionDeclaration);
return true;
}
public override bool Visit(DataRedefines dataRedefines)
{
RedefinesChecker.OnNode(dataRedefines);
return true;
}
public override bool Visit(DataRenames dataRenames)
{
RenamesChecker.OnNode(dataRenames);
return true;
}
public override bool Visit(ProcedureStyleCall call)
{
FunctionCallChecker.OnNode(call);
return true;
}
public override bool Visit(PerformProcedure performProcedureNode)
{
var performCE = performProcedureNode.CodeElement;
(performProcedureNode.ProcedureParagraphSymbol, performProcedureNode.ProcedureSectionSymbol) = SectionOrParagraphUsageChecker.ResolveParagraphOrSection(performProcedureNode, performCE.Procedure, _currentSection);
(performProcedureNode.ThroughProcedureParagraphSymbol, performProcedureNode.ThroughProcedureSectionSymbol) = SectionOrParagraphUsageChecker.ResolveParagraphOrSection(performProcedureNode, performCE.ThroughProcedure, _currentSection);
return true;
}
public override bool Visit(Sort sort)
{
//TODO Check subscripts !
// Check nature of SORT target
var sortStatement = sort.CodeElement;
DataDefinition sortTarget = null;
if (sort.StorageAreaReadsDataDefinition != null &&
sort.StorageAreaReadsDataDefinition.TryGetValue(sortStatement.FileNameOrTableName, out sortTarget))
{
// SORT target has been resolved, compute SORT nature from its target's CodeElementType
Debug.Assert(sortTarget.CodeElement != null);
sort.Nature = sortTarget.CodeElement.Type == CodeElementType.FileDescriptionEntry ? SortNature.FileSort : SortNature.TableSort;
}
// Check format based on nature of target
switch (sort.Nature)
{
case SortNature.FileSort:
CheckFileSort();
break;
case SortNature.TableSort:
CheckTableSort();
break;
}
// Resolve input and output procedures
(sort.InputProcedureParagraphSymbol, sort.InputProcedureSectionSymbol) = SectionOrParagraphUsageChecker.ResolveParagraphOrSection(sort, sortStatement.InputProcedure, _currentSection);
(sort.InputThroughProcedureParagraphSymbol, sort.InputThroughProcedureSectionSymbol) = SectionOrParagraphUsageChecker.ResolveParagraphOrSection(sort, sortStatement.ThroughInputProcedure, _currentSection);
(sort.OutputProcedureParagraphSymbol, sort.OutputProcedureSectionSymbol) = SectionOrParagraphUsageChecker.ResolveParagraphOrSection(sort, sortStatement.OutputProcedure, _currentSection);
(sort.OutputThroughProcedureParagraphSymbol, sort.OutputThroughProcedureSectionSymbol) = SectionOrParagraphUsageChecker.ResolveParagraphOrSection(sort, sortStatement.ThroughOutputProcedure, _currentSection);
return true;
void CheckFileSort()
{
// File SORT must have at least one sorting KEY (ASCENDING or DESCENDING)
if (sortStatement.SortingKeys == null || sortStatement.SortingKeys.Count == 0)
{
DiagnosticUtils.AddError(sort, "SORT file statement requires at least one sorting KEY.", sortStatement);
}
// Requires an INPUT (PROCEDURE or USING file)
if ((sortStatement.InputFiles == null || sortStatement.InputFiles.Length == 0) && sortStatement.InputProcedure == null)
{
DiagnosticUtils.AddError(sort, "Missing input definition in SORT file statement: either add INPUT PROCEDURE phrase or USING file phrase to define required input.", sortStatement);
}
// Requires an OUTPUT (PROCEDURE or GIVING file)
if ((sortStatement.OutputFiles == null || sortStatement.OutputFiles.Length == 0) && sortStatement.OutputProcedure == null)
{
DiagnosticUtils.AddError(sort, "Missing output definition in SORT file statement: either add OUTPUT PROCEDURE phrase or GIVING file phrase to define required output.", sortStatement);
}
}
void CheckTableSort()
{
// No input or output allowed on SORT table statement
if ((sortStatement.InputFiles != null && sortStatement.InputFiles.Length > 0) || sortStatement.InputProcedure != null)
{
DiagnosticUtils.AddError(sort, "SORT table statement does not allow input definition.", sortStatement);
}
if ((sortStatement.OutputFiles != null && sortStatement.OutputFiles.Length > 0) || sortStatement.OutputProcedure != null)
{
DiagnosticUtils.AddError(sort, "SORT table statement does not allow output definition.", sortStatement);
}
// The KEY must be defined on SORT if no key is already defined on target
if (sortStatement.SortingKeys == null || sortStatement.SortingKeys.Count == 0)
{
Debug.Assert(sortTarget != null);
var tableSortingKeys = sortTarget.GetTableSortingKeys();
if (tableSortingKeys == null || tableSortingKeys.Length == 0)
{
DiagnosticUtils.AddError(sort, $"SORT table statement has no sorting KEY and the sorted table '{sortTarget.Name}' does not define any KEY clause.", sortStatement);
}
}
}
}
public override bool Visit(Paragraph paragraph)
{
SectionOrParagraphUsageChecker.CheckParagraph(paragraph);
return true;
}
public override bool Visit(ProcedureDivision procedureDivision)
{
LibraryChecker.CheckLibrary(procedureDivision);
//initializing the current section to null
_currentSection = null;
return true;
}
public override bool Visit(Section section)
{
//Save current scope node for paragraph resolution
_currentSection = section;
SectionOrParagraphUsageChecker.CheckSection(section);
return true;
}
public override bool Visit(Set set)
{
if (set.StorageAreaWritesDataDefinition != null && set.CodeElement is SetStatementForConditions setConditions && setConditions.IsSendingValueFalse)
{
// Statement is a SET TO FALSE: we need to check that all conditions have been defined with a clause WHEN SET TO FALSE
foreach (var condition in setConditions.Conditions)
{
if (condition.StorageArea != null && set.StorageAreaWritesDataDefinition.TryGetValue(condition.StorageArea, out var dataCondition))
{
if (dataCondition?.CodeElement is DataConditionEntry dataConditionEntry && dataConditionEntry.FalseConditionValue == null)
{
DiagnosticUtils.AddError(set, $"A condition-name was specified in a \"SET TO FALSE\" statement, but no \"WHEN FALSE\" value was defined for \"{dataCondition.Name}\".", setConditions);
}
}
}
}
SetStatementChecker.CheckStatement(set);
return true;
}
public override bool Visit(Move move)
{
var moveCorresponding = move?.CodeElement as MoveCorrespondingStatement;
var moveSimple = move?.CodeElement as MoveSimpleStatement;
if (moveCorresponding != null)
{
DataDefinition fromVariable = null;
DataDefinition toVariable = null;
//For MoveCorrespondingStatement check children compatibility
fromVariable = move.GetDataDefinitionFromStorageAreaDictionary(moveCorresponding.FromGroupItem, true);
toVariable = move.GetDataDefinitionFromStorageAreaDictionary(moveCorresponding.ToGroupItem, false);
if (fromVariable == null || toVariable == null)
{
return
true; //Do not continue, the variables hasn't been found. An error will be raised later by CheckVariable()
}
var fromVariableChildren = fromVariable.Children.Where(c => c?.Name != null);
var toVariableChildren = toVariable.Children.Where(c => c?.Name != null);
var matchingChildrenNames = fromVariableChildren.Select(c => c.Name.ToLowerInvariant())
.Intersect(toVariableChildren.Select(c => c.Name.ToLowerInvariant()));
foreach (var matchingChildName in matchingChildrenNames)
{
var retrievedChildrenFrom =
fromVariableChildren.Where(c => c.Name.ToLowerInvariant() == matchingChildName);
var retrievedChildrenTo =
toVariableChildren.Where(c => c.Name.ToLowerInvariant() == matchingChildName);
if (retrievedChildrenFrom.Count() != 1 || retrievedChildrenTo.Count() != 1)
DiagnosticUtils.AddError(move,
string.Format("Multiple symbol \"{0}\" detected in MOVE CORR", matchingChildName));
var retrievedChildFrom = (retrievedChildrenFrom.First() as DataDefinition);
var retrievedChildTo = (retrievedChildrenTo.First() as DataDefinition);
if (retrievedChildFrom == null || retrievedChildTo == null)
continue; //Doesn't have to happen but in case...
var fromDataType = retrievedChildFrom.DataType;
var toDataType = retrievedChildTo.DataType;
if (fromDataType != toDataType && fromDataType.CobolLanguageLevel > CobolLanguageLevel.Cobol85 &&
toDataType.CobolLanguageLevel > CobolLanguageLevel.Cobol85) //Check DataType matching
DiagnosticUtils.AddError(move,
string.Format("Symbol {0} of type {1} do not match symbol {2} of type {3}",
retrievedChildFrom.VisualQualifiedName, fromDataType,
retrievedChildTo.VisualQualifiedName, toDataType));
}
}
else
{
if (moveSimple?.StorageAreaWrites == null)
{
return true;
}
var senderIsAlphanumeric = false;
DataDefinition senderDataDefinition = null;
if (moveSimple.SendingVariable?.StorageArea?.Kind == StorageAreaKind.DataOrCondition
&& move.StorageAreaReadsDataDefinition?.TryGetValue(moveSimple.SendingVariable.StorageArea, out senderDataDefinition) == true)
{
senderIsAlphanumeric = senderDataDefinition.DataType == DataType.Alphanumeric;
}
foreach (var area in moveSimple.StorageAreaWrites)
{
var receiver = area.StorageArea;
if (receiver == null) continue;
if (receiver.Kind == StorageAreaKind.FunctionCallResult)
{
DiagnosticUtils.AddError(move, "MOVE: illegal <function call> after TO");
}
else if (senderIsAlphanumeric
&& receiver.Kind == StorageAreaKind.DataOrCondition
&& move.StorageAreaWritesDataDefinition != null
&& move.StorageAreaWritesDataDefinition.TryGetValue(receiver, out var receiverDataDefinition))
{
if (receiverDataDefinition.DataType == DataType.Numeric || receiverDataDefinition.DataType == DataType.NumericEdited)
{
if (receiverDataDefinition.Usage != null && receiverDataDefinition.Usage != DataUsage.None)
{
DiagnosticUtils.AddError(move, $"Moving alphanumeric '{senderDataDefinition.Name}' to numeric '{receiverDataDefinition.Name}' declared with an USAGE may lead to unexpected results.", code: MessageCode.Warning);
}
}
}
}
}
return true;
}
public override bool Visit(Search search)
{
int whenSearchCount = 0;
bool onAtEndFound = false;
int index = 0;
foreach (var child in search.Children)
{
if (child is OnAtEnd)
{
if (onAtEndFound)
{
DiagnosticUtils.AddError(child, "ON AT END clause must be unique.");
}
else
{
onAtEndFound = true;
if (index > 0)
{
DiagnosticUtils.AddError(child, "ON AT END clause must appear before WHEN.");
}
}
}
else if (child is When whenSearch)
{
whenSearchCount++;
if (whenSearchCount > 1 && search.CodeElement.StatementType == StatementType.SearchBinaryStatement)
{
DiagnosticUtils.AddError(whenSearch,
"Invalid WHEN clause, binary SEARCH only allows a single WHEN clause");
}
}
index++;
}
if (whenSearchCount == 0)
{
DiagnosticUtils.AddError(search, "Search statement must have at least one when element.");
}
var tableToSearch = search.CodeElement.TableToSearch?.StorageArea;
if (tableToSearch != null)
{
var searchedTable = search.GetDataDefinitionFromStorageAreaDictionary(tableToSearch);
if (searchedTable != null)
{
if (searchedTable.IsTableOccurence)
{
var parentTableDefinitions = searchedTable.GetParentTableDefinitions();
_searchTables.Add(search, parentTableDefinitions);
//Check keys and indexes for binary search
if (search.CodeElement.StatementType == StatementType.SearchBinaryStatement)
{
//Searched table must have at least one KEY
var keys = searchedTable.GetTableSortingKeys();
if (keys == null || keys.Length == 0)
{
DiagnosticUtils.AddError(search, $"Cannot use binary SEARCH on '{searchedTable.Name}' because it has no KEY.");
}
//Main table and all parent tables must have at least one index
if (parentTableDefinitions != null)
{
foreach (var table in parentTableDefinitions)
{
var indexes = table.GetIndexes();
if (indexes == null || indexes.Length == 0)
{
var message = table == searchedTable
? $"Cannot use binary SEARCH on '{searchedTable.Name}' because it is not indexed."
: $"Cannot use binary SEARCH on '{searchedTable.Name}' because parent table '{table.Name}' is not indexed.";
DiagnosticUtils.AddError(search, message);
}
}
}
//else TC not supported
}
}
else
{
//Not a table
DiagnosticUtils.AddError(search, $"Cannot SEARCH in '{searchedTable.Name}', data item is not a table.");
}
}
//else undefined reference
}
//else it's a syntax error
return true;
}
public override bool Visit(When whenSearch)
{
if (!(whenSearch.Parent is Search search)) return true; //EVALUATE statement, not our concern here.
if (whenSearch.ChildrenCount == 0)
{
var messageCode = search.CodeElement.StatementType == StatementType.SearchSerialStatement ? MessageCode.SyntaxErrorInParser : MessageCode.Warning;
DiagnosticUtils.AddError(whenSearch, "Missing statement in \"when\" clause", messageCode);
}
if (search.CodeElement.StatementType == StatementType.SearchBinaryStatement && _searchTables.TryGetValue(search, out var tableDefinitions))
{
//TC not supported
if (tableDefinitions == null) return true;
//Main table
System.Diagnostics.Debug.Assert(tableDefinitions.Count > 0);
var searchedTable = tableDefinitions[0];
//Init a dictionary of used keys
Dictionary<string, bool> usedKeys = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
var keys = searchedTable.GetTableSortingKeys();
if (keys != null)
{
foreach (var key in keys)
{
if (key.SortDirection != null && key.SortDirection.Value != SortDirection.None)
{
usedKeys.Add(key.SortKey.Name, false);//Set initial status of the key to 'not used'
}
}
}
//Collect every first index of searched table and its parent tables (multidimensional search)
//Reverse order because parent tables are from child to parent but subscripts are from parent to child
var expectedIndexes = tableDefinitions.Select(table => table.GetIndexes()?.FirstOrDefault()).Reverse().ToArray();
//WHEN condition must use keys and first index of the table
if (!CheckCondition(whenSearch.CodeElement.Condition))
{
return true;
}
//Check all keys are properly used
bool expectKeyUsed = true;
foreach (var isKeyUsed in usedKeys.Values)
{
if (isKeyUsed)
{
if (expectKeyUsed) continue; //OK
//KO all keys from first to "highest" used must be used
DiagnosticUtils.AddError(whenSearch, "All the table keys that precede a referenced key must be used.");
break;
}
if (expectKeyUsed)
{
//First time we see an unused key, so all following keys must not be used
expectKeyUsed = false;
}
}
//Check syntax of a whenSearchCondition (in a binary search)
bool CheckCondition(ConditionalExpression whenSearchCondition)
{
switch (whenSearchCondition)
{
case ConditionNameConditionOrSwitchStatusCondition conditionInstance:
DataOrConditionStorageArea dataOrConditionStorageArea = conditionInstance.ConditionReference;
if (dataOrConditionStorageArea.Subscripts.Length > 0)
{
return CheckDataOrConditionStorageArea(dataOrConditionStorageArea);
}
return true;
case RelationCondition relationCondition:
if (relationCondition.Operator?.SemanticOperator != RelationalOperatorSymbol.EqualTo)
{
DiagnosticUtils.AddError(whenSearch, "Invalid relational operator in WHEN SEARCH condition, EqualTo operator expected.");
return false;
}
return CheckOperand(relationCondition.LeftOperand);
case LogicalOperation logicalOperation:
if (logicalOperation.Operator.Value != LogicalOperator.AND)
{
DiagnosticUtils.AddError(whenSearch, "Invalid logical operator in WHEN SEARCH condition, AND operator expected.");
}
return CheckCondition(logicalOperation.LeftOperand) && CheckCondition(logicalOperation.RightOperand);
default:
DiagnosticUtils.AddError(whenSearch, "Invalid condition in WHEN SEARCH, only condition-names and key to value comparison are allowed.");
return false;
}
}
bool CheckOperand(ConditionOperand operand)
{
if (operand.ArithmeticExpression is NumericVariableOperand numericVariableOperand
&& numericVariableOperand.NumericVariable?.StorageArea is DataOrConditionStorageArea dataOrConditionStorageArea
&& dataOrConditionStorageArea.Subscripts.Length > 0)
{
return CheckDataOrConditionStorageArea(dataOrConditionStorageArea);
}
DiagnosticUtils.AddError(whenSearch, "Left side operand of a WHEN condition must use first index of the table and at least one of declared keys.");
return false;
}
bool CheckDataOrConditionStorageArea(DataOrConditionStorageArea dataOrConditionStorageArea)
{
//Check indexes for every dimension
if (dataOrConditionStorageArea.Subscripts.Length == expectedIndexes.Length)
{
for (int i = 0; i < dataOrConditionStorageArea.Subscripts.Length; i++)
{
var expectedIndex = expectedIndexes[i];
var subscript = dataOrConditionStorageArea.Subscripts[i];
//Check use of first table index for the current dimension
var usedIndexStorageArea = ((NumericVariableOperand)subscript.NumericExpression).IntegerVariable.StorageArea;
var usedIndex = whenSearch.GetDataDefinitionFromStorageAreaDictionary(usedIndexStorageArea);
if (usedIndex != null && (expectedIndex == null || !expectedIndex.Name.Equals(usedIndex.Name, StringComparison.OrdinalIgnoreCase)))
{
//Not the first index (or no index defined for the table)
DiagnosticUtils.AddError(whenSearch, "When subscripting, only first index declared for the table is allowed.");
return false;
}
}
}
//else invalid subscript count, this is already checked by CheckSubscripts. No need to report more errors on this condition.
//Collect used key
var usedKey = whenSearch.GetDataDefinitionFromStorageAreaDictionary(dataOrConditionStorageArea, true);
if (usedKey != null)
{
if (usedKeys.ContainsKey(usedKey.Name))
{
//Valid key, set key status to 'used'
usedKeys[usedKey.Name] = true;
}
else
{
//Special check for 88 level definitions that are children of a selected used key.
if (usedKey.CodeElement?.Type == CodeElementType.DataConditionEntry &&
usedKey.Parent is DataDefinition parentUsedKey &&
usedKeys.ContainsKey(parentUsedKey.Name))
{
usedKeys[parentUsedKey.Name] = true;
}
else
{
//Not a key
DiagnosticUtils.AddError(whenSearch, $"'{usedKey.Name}' is not a sorting key of table '{searchedTable.Name}'.");
return false;
}
}
}
//else undefined reference
return true;
}
}
return true;
}
public override bool Visit(Evaluate evaluate)
{
bool whenOtherSeen = false;
//Start to loop on children from the end because:
//- Grammar enforce that there is 0 to 1 "whenOther" and that it's the last element of an "evaluate"
//- Invalid empty "when" can only be the last "when"
for (int i = evaluate.ChildrenCount - 1; i >= 0; i--)
{
if (evaluate.Children[i] is WhenOther)
{
whenOtherSeen = true;
}
else if (evaluate.Children[i] is Then then)
{
if (then.ChildrenCount == 0)
{
// i is the Then node
// i-1 is the When group
var whenGroup = then.Parent.Children[i - 1];
System.Diagnostics.Debug.Assert(whenGroup.ChildrenCount > 0);
//Get the last When of the WhenGroup. This is the invalid empty When
var whenNode = whenGroup.Children[whenGroup.ChildrenCount - 1];
System.Diagnostics.Debug.Assert(whenNode.CodeElement?.Type == CodeElementType.WhenCondition);
//Syntax error.
DiagnosticUtils.AddError(whenNode, "Missing statement in \"when\" clause");
}
break; //Previous "when" are allowed to have no instructions (#1593)
}
}
if (!whenOtherSeen)
{
DiagnosticUtils.AddError(evaluate, "\"when other\" is missing", MessageCode.Warning);
}
return true;
}
public override bool Visit(If ifNode)
{
#region Temporary debug code for #2266
if (ifNode.Children.Count == 0)
{
var debugData = Logging.LoggingSystemExtensions.CreateDebugData(ifNode);
Logging.LoggingSystem.LogMessage(Logging.LogLevel.Error, "CrossCompleteChecker.Visit, found invalid IF node", debugData);
}
#endregion
if (!(ifNode.Children.Last() is End))
{
DiagnosticUtils.AddError(ifNode,
"\"end-if\" is missing", MessageCode.Warning);
}
return true;
}
public override bool Visit(Then thenNode)
{
//This check only applies to THEN nodes coming from IF statements.
if (thenNode.ChildrenCount == 0 && thenNode.Parent.CodeElement?.Type == CodeElementType.IfStatement)
{
//THEN has no CodeElement, report on Parent IF.
DiagnosticUtils.AddError(thenNode.Parent, "Missing statement or NEXT SENTENCE after IF condition.");
}
return true;
}
public override bool Visit(Else elseNode)
{
if (elseNode.ChildrenCount == 0)
{
DiagnosticUtils.AddError(elseNode, "Missing statement or NEXT SENTENCE after ELSE keyword.");
}
return true;
}
public override bool Visit(TypeDefinition typeDefinition)
{
//Cobol 2002 rule
//TODO need to clarify if we have 1 visitor per LanguageLevel
//For performance reason it seems better to have only one here
TypeDefinitionChecker.CheckTypeDefinition(typeDefinition);
FormalizedCommentsChecker.CheckTypeComments(typeDefinition);
return true;
}
public override bool Visit(Program program)
{
// Check that program has a closing end
CheckEndProgram(program);
if (program.IsNested)
{
NestedProgram nestedProgram = (NestedProgram)program;
if (nestedProgram.ContainingProgram.CodeElement.IsRecursive)
{
DiagnosticUtils.AddError(program, "A Nested Program cannot be declared in a RECURSIVE program.");
}
if (program.CodeElement.IsRecursive)
{
DiagnosticUtils.AddError(program, "A Nested Program cannot have a RECURSIVE attribute.");
}
}
else if (program.CodeElement.IsCommon)
{
DiagnosticUtils.AddError(program, "A Root Program cannot have a COMMON attribute.");
}
FormalizedCommentsChecker.CheckProgramComments(program);
return true;
}
public override bool Visit(ConfigurationSection configurationSection)
{
Program program = configurationSection.GetProgramNode();
if (program != null && program.IsNested)
{
DiagnosticUtils.AddError(configurationSection, "A Nested Program cannot have a CONFIGURATION SECTION.");
}
return true;
}
public override bool VisitVariableWriter(VariableWriter variableWriter)
{
WriteTypeConsistencyChecker.OnNode(variableWriter, CurrentNode);
ReadOnlyPropertiesChecker.OnNode(variableWriter, CurrentNode);
return true;
}
public override bool Visit(DataDefinition dataDefinition)
{
TypedDeclarationChecker.OnNode(dataDefinition);
DataDefinitionEntry dataDefinitionEntry = dataDefinition.CodeElement;
if (dataDefinitionEntry == null) return true;
var commonDataDataDefinitionCodeElement = dataDefinitionEntry as CommonDataDescriptionAndDataRedefines;
var levelNumber = dataDefinitionEntry.LevelNumber;
if (levelNumber != null)
{
var dataDefinitionParent = (dataDefinition.Parent as DataDefinition);
var codeElementType = dataDefinitionEntry.Type;
if (dataDefinitionParent != null)
{
//Check if DataDefinition is level 88 and declared under a Type BOOL variable
//Perf note: first compare CodeElementType because it's faster than DataType
if (codeElementType == CodeElementType.DataConditionEntry && dataDefinitionParent.DataType == DataType.Boolean)
{
DiagnosticUtils.AddError(dataDefinition,
"The Level 88 symbol '" + dataDefinition.Name +
"' cannot be declared under a BOOL typed symbol");
}
}
else
{
//Parent is not a DataDefinition so it's a top level data definition under a section (eg working-storage)
//These top level DataDefinition can only be level 01 or 77
var levelNumberValue = levelNumber.Value;
if (!(levelNumberValue == 01 || levelNumberValue == 77))
{
DiagnosticUtils.AddError(dataDefinition,
"The variable '" + dataDefinition.Name + "' can only be of level 01 or 77",
dataDefinitionEntry);
}
}
//Level 88 and 66 cannot have Children.
if ((codeElementType == CodeElementType.DataConditionEntry || codeElementType == CodeElementType.DataRenamesEntry))
{
if (dataDefinition.ChildrenCount != 0)
{
DiagnosticUtils.AddError(dataDefinition,
"The variable '" + dataDefinition.Name + "' with level 88 and 66 cannot be group item.",
dataDefinitionEntry);
}
if (dataDefinition.Usage != null)
{
DiagnosticUtils.AddError(dataDefinition,
"The variable '" + dataDefinition.Name + "' with level 88 and 66 cannot have USAGE.",
dataDefinitionEntry);
}
}
}
if (dataDefinition.SemanticData != null)
{
//Check if Strict Typedef declaration uses Sync clause
if (dataDefinition.SemanticData.HasFlag(Symbol.Flags.InsideTypedef) &&
dataDefinition.SemanticData.HasFlag(Symbol.Flags.Sync))
{
//Typedef instruction => check if it's marked Strict
if (dataDefinition.SemanticData.Kind == Symbol.Kinds.Typedef && dataDefinition.SemanticData.HasFlag(Symbol.Flags.Strict))
{
DiagnosticUtils.AddError(dataDefinition, $"Cannot declare Type definition {dataDefinition.Name} with Sync clause because it is Strict.");
}
//Variable inside Typedef => check if parent typedef is marked Strict
else if (dataDefinition.SemanticData.NearestParent(Symbol.Kinds.Typedef).HasFlag(Symbol.Flags.Strict))
{
DiagnosticUtils.AddError(dataDefinition, $"{dataDefinition.Name} is part of a declaration using Sync clause in Strict Type definition {dataDefinition.ParentTypeDefinition?.Name}.");
}
}
//Check if variable of user defined Strict Type is declared or has a parent declared with Sync clause (flag is inherited so no need to iterate through parents)
else if (dataDefinition.SemanticData.HasFlag(Symbol.Flags.HasATypedefType) &&
dataDefinition.TypeDefinition?.RestrictionLevel == RestrictionLevel.STRICT &&
dataDefinition.SemanticData.HasFlag(Symbol.Flags.Sync))
{
DiagnosticUtils.AddError(dataDefinition, $"{dataDefinition.Name} cannot be declared or have a parent declared with Sync clause because its Type definition {dataDefinition.DataType.Name} is Strict.");
}
}
if (HasChildrenThatDeclareData(dataDefinition))//Check if group is valid
{
if (dataDefinition.Picture != null)
{
DiagnosticUtils.AddError(dataDefinition,
"Group item " + dataDefinition.Name + " cannot have a \"PICTURE\"", dataDefinitionEntry);
}
if (commonDataDataDefinitionCodeElement?.UserDefinedDataType != null)
{
DiagnosticUtils.AddError(dataDefinition,
"Group item " + dataDefinition.Name + " cannot have a \"TYPE\"", dataDefinitionEntry);
}
if (commonDataDataDefinitionCodeElement?.IsBlankWhenZero?.Value == true)
{
DiagnosticUtils.AddError(dataDefinition,
"Group item " + dataDefinition.Name + " cannot have \"Blank when zero\" clause",
dataDefinitionEntry);
}
}
else if (commonDataDataDefinitionCodeElement != null)
{
//This is an elementary item. It must have a picture, type or a valid usage
var levelNumberValue = levelNumber?.Value;
if ((levelNumberValue < 50 || levelNumberValue == 77)
&& dataDefinition.Picture == null
//commonDataDataDefinitionCodeElement.UserDefinedDataType is the type as written in the code. dataDefinition.TypeDefinition is the resolved type which can be null if the type cannot be found
&& commonDataDataDefinitionCodeElement.UserDefinedDataType == null
&& (!dataDefinition.Usage.HasValue || !IsUsageStandalone(dataDefinition.Usage.Value)))
{
DiagnosticUtils.AddError(dataDefinition, "A group item cannot be empty. Add children, picture or valid usage (INDEX, COMP-1, COMP-2, POINTER, POINTER-32, PROCEDURE-POINTER or FUNCTION-POINTER).", commonDataDataDefinitionCodeElement);
//Detect copy included at wrong level (because there is already the same level in the copy)
CheckCopyAtWrongLevel(dataDefinition, commonDataDataDefinitionCodeElement);
}
}
var usage = commonDataDataDefinitionCodeElement?.Usage;
if (usage != null && IsUsageStandalone(usage.Value) && commonDataDataDefinitionCodeElement.Picture != null)
{
DiagnosticUtils.AddError(dataDefinition,
"Variable with usage COMP-1, COMP-2, INDEX, POINTER, POINTER-32, PROCEDURE-POINTER and FUNCTION-POINTER cannot have a PICTURE", commonDataDataDefinitionCodeElement);
}
return true;
// Return true for usages which cannot have a PICTURE, false for usages requiring a PICTURE
static bool IsUsageStandalone(DataUsage usage)
{
switch (usage)
{
case DataUsage.Index:
case DataUsage.FloatingPoint:
case DataUsage.LongFloatingPoint:
case DataUsage.Pointer:
case DataUsage.Pointer32:
case DataUsage.ProcedurePointer:
case DataUsage.FunctionPointer:
return true;
default:
// None is not allowed
return false;
}
}
static void CheckCopyAtWrongLevel(DataDefinition dataDefinition, CommonDataDescriptionAndDataRedefines commonDataDescriptionAndDataRedefines)
{
//Get current node index
var nodeIndex = dataDefinition.Parent.IndexOf(dataDefinition);
//Get sibling nodes
var siblingNodes = dataDefinition.Parent.Children;
//Get immediately following DataDefinition
var nextData = siblingNodes.Skip(nodeIndex + 1).OfType<DataDefinition>().FirstOrDefault();
if (nextData != null && nextData.IsInsideCopy())
{
DiagnosticUtils.AddError(dataDefinition, $"Cannot include copy {nextData.CodeElement.FirstCopyDirective.TextName} " +
$"under level {commonDataDescriptionAndDataRedefines.LevelNumber} " +
$"because copy starts at level {nextData.CodeElement.LevelNumber}.", commonDataDescriptionAndDataRedefines);
}
}
}
public override bool Visit(Sentence sentence)
{
// Check for missing end
bool hasEnd = false;
if (sentence.ChildrenCount > 0)
{
hasEnd = sentence.Children[sentence.ChildrenCount - 1].CodeElement?.Type == CodeElementType.SentenceEnd;
}
if (!hasEnd)
{
// Report missing end on node coming right after
var nextNode = sentence.GetNextNode();
DiagnosticUtils.AddError(nextNode, "Sentence is not correctly ended: a period was required.");
}
return true;
}
public override bool Visit(End end)
{
// Check if PROGRAM END is orphan
if (_compilerOptions.CheckEndProgram.IsActive)
{
if (end.CodeElement.Type == CodeElementType.ProgramEnd && !(end.Parent is Program))
{
DiagnosticUtils.AddError(end, "Unexpected orphan \"PROGRAM END\".", _compilerOptions.CheckEndProgram.GetMessageCode());
}
}
// Check end statement is aligned with the matching opening statement
if (_compilerOptions.CheckEndAlignment.IsActive && end.CodeElement.Type != CodeElementType.SentenceEnd)
{
CodeElement parentCodeElement = end.Parent.CodeElement; ;
if (parentCodeElement?.IsInsideCopy() == false && end.IsInsideCopy() == false)
{
CheckEndNode(parentCodeElement, end);
}
}
return true;
}
public override bool Visit(FunctionEnd functionEnd)
{
// Check end statement is aligned with the matching opening statement
if (_compilerOptions.CheckEndAlignment.IsActive)
{
CodeElement parentCodeElement = functionEnd.Parent.CodeElement;
if (parentCodeElement?.IsInsideCopy() == false && functionEnd.IsInsideCopy() == false)
{
Token openingDeclareToken = parentCodeElement.ConsumedTokens.FirstOrDefault(t => t.TokenType == TokenType.DECLARE);
CheckEndNode(openingDeclareToken, functionEnd);
}
}
return true;
}
/// <summary>
/// Test if the received DataDefinition has other children than DataConditionEntry or DataRenamesEntry
/// </summary>
/// <param name="dataDefinition">Item to check</param>
/// <returns>True if there are only DataConditionEntry or DataRenamesEntry children</returns>
private static bool HasChildrenThatDeclareData([NotNull] DataDefinition dataDefinition)
{
//We only need to check the last children:
//DataConditionEntry is a level 88, DataRenamesEntry is level 66 and they cannot have children
//DataDescription and DataRedefines are level between 1 and 49 inclusive.
//As the level number drives the positioning of Node inside the Children:
//- DataConditionEntry will always be positioned before other dataDescription
//- DataRenamesEntry will always be positioned after other dataDescription
if (dataDefinition.ChildrenCount > 0)
{
var lastChild = dataDefinition.Children[dataDefinition.ChildrenCount - 1];
if (lastChild.CodeElement == null)
{
Debug.Assert(lastChild is IndexDefinition);
//Last child is an Index in an OCCURS: it is not a declaration
return false;
}
if (lastChild.CodeElement.Type == CodeElementType.DataRenamesEntry)
{
//Last child is a DataRenamesEntry: we need to loop on the other children to find a possible DataDescription before
return dataDefinition.Children.Any(c => c is DataDescription);
}
return lastChild.CodeElement.Type != CodeElementType.DataConditionEntry;
}
return false;
}
public override bool Visit(IndexDefinition indexDefinition)
{
var found =
indexDefinition.SymbolTable.GetVariablesExplicit(new URI(indexDefinition.Name))
.Where(i => i.ParentTypeDefinition == null)
.ToList();
if (indexDefinition.ParentTypeDefinition != null) return true;
if (found.Count > 1) //If multiple index with same name found, display a warning.
{
DiagnosticUtils.AddError(indexDefinition.Parent,
"An index named '" + indexDefinition.Name + "' is already defined.", MessageCode.Warning);
}
return true;
}