-
Notifications
You must be signed in to change notification settings - Fork 0
/
MethodModel.cpp
1012 lines (848 loc) · 39.4 KB
/
MethodModel.cpp
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
// SPDX-License-Identifier: GPL-3.0-only
/**
* @file MethodModel.cpp
*
* @copyright Copyright (C) 2021-2024 srcML, LLC. (www.srcML.org)
*
* This file is part of the Stereocode application.
*/
#include "MethodModel.hpp"
extern primitiveTypes PRIMITIVES;
extern ignorableCalls IGNORED_CALLS;
extern XPathBuilder XPATH_TRANSFORMATION;
methodModel::methodModel(srcml_archive* archive, srcml_unit* unit, const std::string& methodXpath,
const std::string& unitLang, const std::string& propertyReturnType, int unitNum) :
unitLanguage(unitLang), xpath(methodXpath), unitNumber(unitNum) {
srcML = srcml_unit_get_srcml(unit);
isConstructorDestructor(archive, unit);
isStatic(archive, unit);
findMethodName(archive, unit);
findParameterList(archive, unit);
if (unitLanguage == "C++") isConst(archive, unit);
// Method could be inside a property (C# only), so return type is collected separately
// returnType = "" if the unitLanguage is not C#
returnType = propertyReturnType;
// Name signature needed for call analysis
std::string paramList = parametersList;
std::string methName = name;
removeBetweenComma(paramList, false);
removeNamespace(methName, true, unitLanguage);
nameSignature = methName + paramList;
trimWhitespace(nameSignature);
}
void methodModel::findMethodData(std::unordered_map<std::string, variable>& attributes,
const std::unordered_set<std::string>& classMethods,
const std::unordered_set<std::string>& inheritedClassMethods,
const std::string& classNamePar) {
classNameParsed = classNamePar;
if (!constructorDestructorUsed) {
srcml_archive* archive = srcml_archive_create();
srcml_archive_read_open_memory(archive, srcML.c_str(), srcML.size());
srcml_unit* unit = srcml_archive_read_unit(archive);
findMethodReturnType(archive, unit);
findParameterName(archive, unit);
findParameterType(archive, unit);
findLocalVariableName(archive, unit);
findLocalVariableType(archive, unit);
findReturnExpression(archive, unit);
findCallName(archive, unit);
findCallArgument(archive, unit);
findNewAssign(archive, unit);
isIgnorableCall(methodCalls);
isIgnorableCall(functionCalls);
isIgnorableCall(constructorCalls);
// Must only be called before isCallOnAttribute()
isAttributeUsedInCallArgument(archive, unit, attributes);
// Must only be called after isIgnorableCall()
isCallOnAttribute(attributes, classMethods, inheritedClassMethods);
// Must only be called after findNewAssign()
isVariableReturned(attributes, false);
isVariableUsedInExpression(archive, unit, attributes, false);
isVariableModified(archive, unit, attributes, false);
isEmpty(archive, unit);
isFactory();
srcml_unit_free(unit);
srcml_archive_close(archive);
srcml_archive_free(archive);
}
}
void methodModel::findFreeFunctionData() {
if (!constructorDestructorUsed) {
srcml_archive* archive = srcml_archive_create();
srcml_archive_read_open_memory(archive, srcML.c_str(), srcML.size());
srcml_unit* unit = srcml_archive_read_unit(archive);
findMethodReturnType(archive, unit);
findLocalVariableName(archive, unit);
findLocalVariableType(archive, unit);
findParameterName(archive, unit);
findParameterType(archive, unit);
findReturnExpression(archive, unit);
findCallName(archive, unit);
findCallArgument(archive, unit);
findNewAssign(archive, unit);
isIgnorableCall(methodCalls);
isIgnorableCall(functionCalls);
isCallOnParameter();
isVariableReturned(parameters, true);
isVariableUsedInExpression(archive, unit, parameters, true);
isVariableModified(archive, unit, parameters, true);
isEmpty(archive, unit);
srcml_unit_free(unit);
srcml_archive_close(archive);
srcml_archive_free(archive);
}
}
// Gets the method name
//
void methodModel::findMethodName(srcml_archive* archive, srcml_unit* unit) {
if (constructorDestructorUsed)
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"constructor_destructor_name").c_str());
else
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"method_name").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
// n > 0 instead of n == 1 because there is an issue with srcML and C# not closing the function block properly,
// so it keeps reading other random names
if (n > 0) {
srcml_unit* resultUnit = srcml_transform_get_unit(result, 0);
char* unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
name = unparsed;
trimWhitespace(name);
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Gets the method parameter list
//
void methodModel::findParameterList(srcml_archive* archive, srcml_unit* unit) {
if (constructorDestructorUsed)
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"constructor_destructor_parameter_list").c_str());
else
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"method_parameter_list").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
if (n == 1) {
srcml_unit* resultUnit = srcml_transform_get_unit(result, 0);
char* unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
parametersList = unparsed;
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Gets the method return type
//
void methodModel::findMethodReturnType(srcml_archive* archive, srcml_unit* unit) {
if (returnType == "") { // If method was a property (C#), type is found in previous steps
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"method_return_type").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
for (int i = 0; i < n; i++) {
srcml_unit* resultUnit = srcml_transform_get_unit(result, i);
std::string unparsed = srcml_unit_get_srcml(resultUnit);
returnType += srcml_unit_get_srcml(resultUnit);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
variable temp;
if (isNonPrimitiveType(returnType, temp, unitLanguage, classNameParsed))
nonPrimitiveReturnType = true;
nonPrimitiveReturnTypeExternal = temp.getNonPrimitiveExternal();
returnTypeParsed = returnType;
removeTypeTokens(returnTypeParsed, unitLanguage);
trimWhitespace(returnType);
trimWhitespace(returnTypeParsed);
}
// Collects the names of local variables
//
void methodModel::findLocalVariableName(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"local_variable_name").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; i++) {
resultUnit = srcml_transform_get_unit(result, i);
char * unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string localName = unparsed;
// Chop off [] for arrays
if (unitLanguage == "C++") {
size_t start_position = localName.find("[");
if (start_position != std::string::npos){
localName = localName.substr(0, start_position);
Rtrim(localName);
}
}
localsOrdered.push_back(variable());
localsOrdered.back().setName(localName);
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Collects the types of local variables
//
void methodModel::findLocalVariableType(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"local_variable_type").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
std::string prev = "";
for (int i = 0; i < n; i++) {
resultUnit = srcml_transform_get_unit(result, i);
std::string type = srcml_unit_get_srcml(resultUnit);
char* unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
if (type == "<type ref=\"prev\"/>") {
type = prev;
}
else {
type = unparsed;
prev = type;
}
localsOrdered[i].setType(type);
isNonPrimitiveType(type, localsOrdered[i], unitLanguage, classNameParsed);
locals.insert({localsOrdered[i].getName(), localsOrdered[i]});
nonPrimitiveLocalExternal = localsOrdered[i].getNonPrimitiveExternal();
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Collects the names of parameters in each method
//
void methodModel::findParameterName(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"parameter_name").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; ++i) {
resultUnit = srcml_transform_get_unit(result, i);
char * unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string parameterName = unparsed;
// Chop off [] for arrays
if (unitLanguage == "C++") {
size_t start_position = parameterName.find("[");
if (start_position != std::string::npos){
parameterName = parameterName.substr(0, start_position);
Rtrim(parameterName);
}
}
parametersOrdered.push_back(variable());
parametersOrdered.back().setName(parameterName);
parametersOrdered.back().setPos(i);
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Collects the types of parameters
// In C++, parameters could have a type but no name (for backward compatibility),
// Only collect the type if there is a name
//
void methodModel::findParameterType(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"parameter_type").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; ++i) {
resultUnit = srcml_transform_get_unit(result, i);
char * unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string type = unparsed;
parametersOrdered[i].setType(type);
isNonPrimitiveType(type, parametersOrdered[i], unitLanguage, classNameParsed);
parameters.insert({parametersOrdered[i].getName(), parametersOrdered[i]});
nonPrimitiveParamaterExternal = parametersOrdered[i].getNonPrimitiveExternal();
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Collects all return expressions
//
void methodModel::findReturnExpression(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"return_expression").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; ++i) {
resultUnit = srcml_transform_get_unit(result, i);
char *unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string expr = unparsed;
free(unparsed);
returnExpressions.push_back(expr);
std::string newOperator = expr.substr(0,3);
if (newOperator == "new")
newReturned = true;
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Collects names of calls including function, method, and constructor calls
//
void methodModel::findCallName(srcml_archive* archive, srcml_unit* unit) {
std::vector<std::string> callType = {"function", "method", "constructor"};
for (const std::string& c : callType) {
if (c == "function")
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"function_call_name").c_str());
else if (c == "method")
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"method_call_name").c_str());
else if (c == "constructor")
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"constructor_call_name").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; ++i) {
resultUnit = srcml_transform_get_unit(result, i);
char* unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
calls call;
call.setName(unparsed);
if (c == "function")
functionCalls.push_back(call);
else if (c == "method")
methodCalls.push_back(call);
else if (c == "constructor")
constructorCalls.push_back(call);
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
}
// Collects arguments of calls including function, method, and constructor calls
//
void methodModel::findCallArgument(srcml_archive* archive, srcml_unit* unit) {
std::vector<std::string> callType = {"function", "method", "constructor"};
for (const std::string& c : callType) {
if (c == "function")
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"function_call_arglist").c_str());
else if (c == "method")
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"method_call_arglist").c_str());
else if (c == "constructor")
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"constructor_call_arglist").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; ++i) {
resultUnit = srcml_transform_get_unit(result, i);
callsArguments += srcml_unit_get_srcml(resultUnit);
char * unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string arguList = unparsed;
if (c == "function") {
functionCalls[i].setArgumentList(arguList);
removeBetweenComma(arguList, false);
std::string funcCallName = functionCalls[i].getName();
removeNamespace(funcCallName, true, unitLanguage);
std::string funcCallParsed = funcCallName + arguList;
trimWhitespace(funcCallParsed);
functionCalls[i].setSignature(funcCallParsed);
}
else if (c == "method")
methodCalls[i].setArgumentList(arguList);
else if (c == "constructor")
constructorCalls[i].setArgumentList(arguList);
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
}
// Finds all variables that are declared/initialized with the "new" operator
//
void methodModel::findNewAssign(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"new_operator_assign").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; ++i) {
resultUnit = srcml_transform_get_unit(result, i);
char *unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string varName = unparsed;
free(unparsed);
trimWhitespace(varName);
variablesCreatedWithNew.insert(varName);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Determines if method is empty
//
void methodModel::isEmpty(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"empty").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
empty = (n==0);
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
void methodModel::isFactory() {
if (!constructorDestructorUsed) {
if (nonPrimitiveReturnType && (newReturned || numOfVariablesReturnedCreatedWithNew > 0)) {
factory = true;
if (numOfVariablesReturnedCreatedWithNew == (int)(returnExpressions.size()))
strictFactory = true;
}
}
}
// Determines if method is const
//
void methodModel::isConst(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"const").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
if (n == 1) constMethod = true;
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Check if method is a constructor or a destructor
//
void methodModel::isConstructorDestructor(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"constructor_or_destructor").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
if (n == 1) constructorDestructorUsed = true;
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Check if method is static
//
void methodModel::isStatic(srcml_archive* archive, srcml_unit* unit) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"static").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
if (n == 1) staticMethod = true;
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// In C#, non-primitive parameters are passed by value and the value is a reference to the object,
// this means that if you re-assign the parameters itself (e.g., a = value), then the original object won't change
// So, C# need to use the ref, out, *(unsafe context), or [] to pass by reference and be able to re-assign the parameters
// But, if you use a attribute inside the parameter (a.b = value) the change will persist and affect the original object
// In Java, the (a.b = value) is the only way to change a parameter and keep the changes outside
// C++ can use *, [], or & to pass by reference
// No need to check for 'const' since this function is only called when there is a modification to the parameter
//
void methodModel::isParameterRefChanged(std::string para, bool propertyCheck) {
std::string type = parameters[para].getType();
if (unitLanguage == "C++" || unitLanguage == "C#"){
// C# could use * in unsafe contexts
bool referencePointer = type.find("*") != std::string::npos;
if (unitLanguage == "C++"){
std::string parName = parameters[para].getName();
bool reference = type.find("&") != std::string::npos;
trimWhitespace(parName);
bool referenceArray = parName.find("[]") != std::string::npos;
if (reference || referencePointer || referenceArray)
parameterRefChanged = true;
}
else if (unitLanguage == "C#"){
bool nonPrimitive = !isPrimitiveType(type, unitLanguage);
bool referenceOut = type.find("out") != std::string::npos ||
type.find("ref") != std::string::npos;
trimWhitespace(type);
bool referenceArray = type.find("[]") != std::string::npos;
if (referenceOut || referenceArray || referencePointer)
parameterRefChanged = true;
else if (nonPrimitive && propertyCheck) {
// For C# and Java, only check if a parameter's property is modified
// For example, parameter.b = value --> check
// parameter = value --> don't check
parameterRefChanged = true;
}
}
}
else if (unitLanguage == "Java"){
bool nonPrimitive = !isPrimitiveType(type, unitLanguage);
trimWhitespace(type);
bool referenceArray = type.find("[]") != std::string::npos;
if (referenceArray || (nonPrimitive && propertyCheck))
parameterRefChanged = true;
}
}
// Determines if a return expression returns a variable (parameter or an attribute)
// Both simple returns (e.g., return variable;) and
// complex returns (e.g., return variable + 5; or e.g., return 5 + 5;) are found
//
void methodModel::isVariableReturned(std::unordered_map<std::string, variable>& variables, bool isParamaterCheck) {
for (const std::string& expr : returnExpressions) {
if (isParamaterCheck) {
if (!isVariableUsed(variables, expr, true, false, false, isParamaterCheck, false))
parameterNotReturned = true; // Complex return
}
else {
if (isVariableUsed(variables, expr, true, false, false, false, false))
attributeReturned = true; // Simple return
else
attributeNotReturned = true; // Complex return
}
}
}
// Determines if a variable (parameter or an attribute) is used in an expression
//
void methodModel::isVariableUsedInExpression(srcml_archive* archive, srcml_unit* unit,
std::unordered_map<std::string, variable>& variables, bool isParameterCheck) {
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"expression_name").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int i = 0; i < n; i++) {
resultUnit = srcml_transform_get_unit(result, i);
char *unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
if (isParameterCheck)
isVariableUsed(variables, unparsed, false, false, false, true, false);
else
isVariableUsed(variables, unparsed, false, false, false, false, false);
free(unparsed);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Finds if an attribute is changed or
// if a parameter that is passed by reference is changed
//
void methodModel::isVariableModified(srcml_archive* archive, srcml_unit* unit,
std::unordered_map<std::string, variable>& variables, bool isParameterCheck) {
int changed = 0;
// An attribute that is changed multiple times should only be considered as 1 change
std::unordered_set<std::string> checked;
srcml_append_transform_xpath(archive, XPATH_TRANSFORMATION.getXpath(unitLanguage,"expression_assignment").c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int j = 0; j < n; ++j) {
resultUnit = srcml_transform_get_unit(result, j);
char *unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string possibleVariable = unparsed;
free(unparsed);
if (isParameterCheck)
isVariableUsed(variables, possibleVariable, false, true, false, true, false);
else if (isVariableUsed(variables, possibleVariable, false, true, true, false, false)
&& checked.find(possibleVariable) == checked.end()) {
changed++;
checked.insert(possibleVariable);
}
}
numOfAttributesModified = changed;
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Ignores calls from analysis
// For example, if call to ignore is 'foo',
// then some of the matched cases are foo<>() or bar::foo() or a->b.foo()
void methodModel::isIgnorableCall(std::vector<calls>& calls) {
for (auto it = calls.begin(); it != calls.end();) {
std::string callName = it->getName();
size_t listOpen = callName.find("<");
if (listOpen != std::string::npos)
callName = callName.substr(0, listOpen);
// Try to match the whole call
if (IGNORED_CALLS.isIgnored(callName, unitLanguage)) {
it = calls.erase(it);
}
else {
size_t split = callName.rfind("::");
if (split != std::string::npos)
callName = callName.substr(split + 2);
else {
split = callName.rfind("->");
if (split != std::string::npos)
callName = callName.substr(split + 2);
else {
split = callName.rfind(".");
if (split != std::string::npos)
callName = callName.substr(split + 1);
}
}
if (IGNORED_CALLS.isIgnored(callName, unitLanguage))
it = calls.erase(it);
else ++it;
}
}
}
void methodModel::isAttributeUsedInCallArgument(srcml_archive* archive, srcml_unit* unit, std::unordered_map<std::string, variable>& attributes) {
if (methodCalls.size() == 0 && functionCalls.size() == 0 && constructorCalls.size() == 0)
return;
std::string xpathArg = "//src:expr/src:name[ancestor::src:call[1][";
for (size_t i = 0; i < methodCalls.size(); ++i) {
xpathArg += "./src:name='" + methodCalls[i].getName() + "'";
if (i != methodCalls.size() - 1)
xpathArg += " or ";
}
if (methodCalls.size() != 0 && (functionCalls.size() != 0 || constructorCalls.size() != 0))
xpathArg += " or ";
for (size_t i = 0; i < functionCalls.size(); ++i) {
xpathArg += "./src:name='" + functionCalls[i].getName() + "'";
if (i != functionCalls.size() - 1)
xpathArg += " or ";
}
if (functionCalls.size() != 0 && constructorCalls.size() != 0)
xpathArg += " or ";
for (size_t i = 0; i < constructorCalls.size(); ++i) {
xpathArg += "./src:name='" + constructorCalls[i].getName() + "'";
if (i != constructorCalls.size() - 1)
xpathArg += " or ";
}
xpathArg += "]]";
srcml_append_transform_xpath(archive, xpathArg.c_str());
srcml_transform_result* result = nullptr;
srcml_unit_apply_transforms(archive, unit, &result);
int n = srcml_transform_get_unit_size(result);
srcml_unit* resultUnit = nullptr;
for (int j = 0; j < n; ++j) {
resultUnit = srcml_transform_get_unit(result, j);
char *unparsed = nullptr;
size_t size = 0;
srcml_unit_unparse_memory(resultUnit, &unparsed, &size);
std::string possibleAttribute = unparsed;
free(unparsed);
isVariableUsed(attributes, possibleAttribute, false, true, true, false, false);
}
srcml_clear_transforms(archive);
srcml_transform_free(result);
}
// Function calls: --> foo() bar::foo()
// Checks if a function call is made to a method in the class, else it is removed and considered as external function call
//
// So, static calls and free function calls are considered as external function calls
//
// Method Calls: --> bar.foo() where 'bar' could be a variable or a classname or a namespace
// Checks if there is a method call on an attribute
// For example, a.foo() where a is an attribute, else it is removed and considered as external method call
//
// In C# or Java, a class name can be used with the dot operator to invoke static methods
// For example, className.staticMethodName();
// These are removed and considered as external function calls
//
// base, and super can only be used to invoke non-static methods in the current class (this) or parent class (base or super)
// For example, this.methodName();
// So these should be also treated as function calls and not method calls
//
void methodModel::isCallOnAttribute(std::unordered_map<std::string, variable>& attributes,
const std::unordered_set<std::string>& classMethods,
const std::unordered_set<std::string>& inheritedClassMethods) {
// Check on function calls (Should be done before checking on method calls)
for (auto it = functionCalls.begin(); it != functionCalls.end();) {
if (classMethods.find(it->getSignature()) == classMethods.end() &&
inheritedClassMethods.find(it->getSignature()) == inheritedClassMethods.end()) {
it = functionCalls.erase(it);
++numOfExternalFunctionCalls;
}
else ++it;
}
// Check on method calls
for (auto it = methodCalls.begin(); it != methodCalls.end();) {
// Could be a normal method call on an attribute
if (!isVariableUsed(attributes,it->getName(), false, false, false, false, false)) { // Checks if call is on attribute
if (unitLanguage != "C++") {
// These should be function calls
if (matchSubstring(it->getName(), "base") || matchSubstring(it->getName(), "this") ||
matchSubstring(it->getName(), "super"))
functionCalls.push_back(*it);
// Could be a call on a local or a parameter
else if (isVariableUsed(attributes, it->getName(), false, false, false, true, true))
++numOfExternalMethodCalls;
// It is a static call
else
++numOfExternalFunctionCalls;
it = methodCalls.erase(it);
}
else {
++numOfExternalMethodCalls;
it = methodCalls.erase(it);
}
}
else ++it;
}
}
void methodModel::isCallOnParameter() {
for (auto& m : methodCalls)
isVariableUsed(parameters, m.getName(), false, false, false, true, false);
}
// Checks if an expression uses an attribute, local, or a parameter --> call them variable
// Possible cases:
// C++: this->a; (*this).a; Foo::a; this->a.b; (*this).a.b; Foo::a.b; a.b; a
// Java: super.a; this.a; Foo.a; super.a.b; this.a.b; Foo.a.b; a.b; a
// C#: base.a; this.a; Foo.a; base.a.b; this.a.b; Foo.a.b; a.b; a
// Where 'a' is a variable and Foo is class itself if the variable is an attribute
// Can match with complex uses of variables (e.g., this->a.b.c or a[]->b or (*a).b.c)
//
bool methodModel::isVariableUsed(std::unordered_map<std::string, variable>& variables,
const std::string& expression, bool returnCheck,
bool parameterModifiedCheck, bool localModifiedCheck,
bool isParamaterCheck, bool isLocalCheck) {
std::string expr = expression;
trimWhitespace(expr);
// Remove brakcets. For example, a [3]
size_t openingBracket = expr.find("[");
if (openingBracket != std::string::npos)
expr = expr.substr(0, openingBracket);
// Removing () and {} on the outside of expression
// Might remove } and ) for calls but that doesn't affect the analysis
if (unitLanguage == "C++") {
while (!expr.empty() && (expr.front() == '{' || expr.front() == '(')) {
if (expr.size() > 6 && expr.substr(1, 5) == "(*this)")
break;
expr.erase(0, 1);
}
while (!expr.empty() && (expr.back() == '}' || expr.back() == ')')) expr.pop_back();
}
else {
while (!expr.empty() && expr.front() == '(') expr.erase(0, 1);
while (!expr.empty() && expr.back() == ')') expr.pop_back();
}
// In C# the null-conditional operator is represented by ? and it allows you to check if an object
// is null before accessing its members. For example, testString?.Length;
if (unitLanguage == "C#") {
size_t nullConditionOperator = expr.find("?");
while (nullConditionOperator != std::string::npos) {
expr.erase(nullConditionOperator, 1);
nullConditionOperator = expr.find("?"); // For chaining
}
}
// Remove pointers. For example, *a
if (unitLanguage != "Java")
while (!expr.empty() && expr.front() == '*') expr.erase(0, 1);
if (expr.empty()) return false;
// ^ indicates that we should only match from the beginning
// We only care about the first two variables. For example, in a.b.c() the a.b is sufficient to
// determine what "a" is
// base and super point to the parent class (not interfaces)
bool isMatched = false;
std::smatch match;
std::string pattern;
if (!returnCheck) {
if (unitLanguage == "C++")
pattern = R"(^(?:\(\*this\)\.|this->|([^.->]*)(?:::|\.|->))([^.->]*))";
else if (unitLanguage == "Java")
pattern = R"(^(?:super|this|([^.]*))\.([^.]*))";
else if (unitLanguage == "C#")
pattern = R"(^(?:base|this|([^.->]*))(?:\.|->)([^.->]*))";
}
else {
// $ Used to match end of line. For example, return this.a; matches but return this.a.b; doesn't
if (unitLanguage == "C++")
pattern = R"(^(?:\(\*this\)\.|this->|([^.->]*)(?:::|\.|->))([^.->\(\){}]*)$)";
else if (unitLanguage == "Java")
pattern = R"(^(?:super|this|([^.]*))\.([^.\(\)]*)$)";
else if (unitLanguage == "C#")
pattern = R"(^(?:base|this|([^.->]*))(?:\.|->)([^.->\(\)]*)$)";
}
const std::regex regexPattern(pattern);
isMatched = std::regex_search(expr, match, regexPattern);
int count = isMatched ? 2 : 1;
bool overShadow = true;
std::string possibleVar = expr; // For some reason, this fixes an issues dealing with invalid read memory
for (int i = 0; i < count; i++) {
if (isMatched && i == 0) {
if (match[1] == "") {
possibleVar = match[2]; // Case of base, super, and this
// Needed in cases such as this.data = data where this.data is an attribute and data is a local or a parameter
overShadow = false;
}
else
possibleVar = match[1]; // Perhaps variable itself (e.g., a or a.foo())
}
else if (isMatched && match[1] != "") // Case of class or parent class
possibleVar = match[2];
if (overShadow) {
// Checked first in case of overshadowing if variables = attributes
// Case of variables = locals
if (locals.find(possibleVar) != locals.end()) {
if (localModifiedCheck && locals.at(possibleVar).getNonPrimitive())
nonPrimitiveLocalOrParameterChanged = true;
if (returnCheck) {
if (variablesCreatedWithNew.find(possibleVar) != variablesCreatedWithNew.end())
++numOfVariablesReturnedCreatedWithNew;
}
if (isLocalCheck)
return true;
else
return false;
}
// Case of variables = parameters
else if (parameters.find(possibleVar) != parameters.end()) {
parameterUsed = true;
if (parameterModifiedCheck) {
if (parameters.at(possibleVar).getNonPrimitive()) nonPrimitiveLocalOrParameterChanged = true;
isParameterRefChanged(possibleVar, isMatched);
}
if (returnCheck) {
if (variablesCreatedWithNew.find(possibleVar) != variablesCreatedWithNew.end())
++numOfVariablesReturnedCreatedWithNew;
}
if (isParamaterCheck)
return true;
else
return false;
}
}
// Case of variables = attributes
if (variables.find(possibleVar) != variables.end()) {
attributeUsed = true;
if (possibleVar != "this") {
nonPrimitiveAttributeExternal = variables.at(possibleVar).getNonPrimitiveExternal();
if (returnCheck) {
attributeReturned = true; // Simple return
if (variablesCreatedWithNew.find(possibleVar) != variablesCreatedWithNew.end())
++numOfVariablesReturnedCreatedWithNew;
}
}
return true;
}
}
if(parameterModifiedCheck)
globalOrStaticChanged = true;
return false;
}
void methodModel::setStereotype(const std::string& s) {
stereotype.push_back(s);
}