-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract.py
2439 lines (2136 loc) · 128 KB
/
extract.py
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
import glob
import logging
# Third-party
from z3 import *
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from antlr4.tree.Tree import TerminalNode
from neomodel import config
from condition_data_structure import LocalVariable, OrExpression, ComparisonExpression
# Grammar generates by Antlr
from grammar.CMakeListener import CMakeListener
# Our own library
from datastructs import TestNode, LiteralNode, OptionNode, Directory, DirectoryNode
from commands import *
from typing import Dict, List
logging.basicConfig(filename='cmakeInspector.log', level=logging.DEBUG)
config.DATABASE_URL = 'bolt://neo4j:123@localhost:7687'
project_dir = "."
extension_type = "ECM"
no_op_commands = ['cmake_policy', 'enable_testing', 'fltk_wrap_ui', 'install', 'mark_as_advanced', 'message',
'qt_wrap_cpp',
'source_group', 'variable_watch', 'include_guard', 'install_icon']
find_package_lookup_directories = ['cmake', 'CMake', ':name', ':name/cmake', ':name/CMake', 'lib/cmake/:name',
'share/cmake/:name', 'share/cmake-:version/:name', 'lib/:name', 'share/:name',
'lib/:name/cmake', 'lib/:name/CMake',
'share/:name/cmake', 'share/:name/CMake', ':name/lib/cmake/:name',
':name/share/cmake/:name', ':name/lib/:name', ':name/share/:name',
':name/lib/:name/cmake', ':name/lib/:name/CMake', ':name/share/:name/cmake',
'share/:name/modules', 'bin', 'lib/x86_64-linux-gnu/cmake/:name'
':name/share/:name/CMake',
'lib/x86_64-linux-gnu/cmake/:name',
'/opt/homebrew/Cellar/extra-cmake-modules/5.83.0/share/ECM/cmake',
'/opt/homebrew/Cellar/extra-cmake-modules/5.83.0/share/ECM/modules',
'/opt/homebrew/Cellar/extra-cmake-modules/5.83.0/share/ECM/kde-modules'
'/opt/homebrew/Cellar/qt@5/5.15.2/bin',
'/Applications/CMake.app/Contents/share/cmake-3.20/Modules',
'/opt/homebrew/Cellar/cmake/3.20.4/share/cmake/Modules/',
'share/cmake-:version/:name', 'share/cmake-:version/Modules',
'/usr/share/kde4/apps/cmake/modules',
'/opt/homebrew/Cellar/qt@5/5.15.2/lib/cmake/Qt5']
find_package_prefixes = ['/usr', '']
architecture = 'x86_64-linux-gnu'
includes_paths = ['/Applications/CMake.app/Contents/share/cmake-3.20/Modules']
# Handle max recursion
currentFunction = None
prevFunction = []
maxRecursionDepth = 100
currentRecursionDepth = 0
#
foreachCommandStack = []
foreachNodeStack = []
# noinspection PyGlobalUndefined
def initialize(inputText, path, shouldUseInput=False):
global vmodel, lookupTable, directoryTree, project_dir
vmodel = VModel.getInstance()
lookupTable = Lookup.getInstance()
directoryTree = Directory.getInstance()
project_dir = path
getIncludePaths()
# Initializing the important variables
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_SOURCE_DIR', LiteralNode(project_dir, project_dir))
util_create_and_add_refNode_for_variable('CMAKE_SOURCE_DIR', LiteralNode(project_dir, project_dir))
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_LIST_DIR', LiteralNode(project_dir, project_dir))
util_create_and_add_refNode_for_variable('CMAKE_VERSION', LiteralNode('cmakeVersion', '3.16'))
util_create_and_add_refNode_for_variable('CMAKE_MODULE_PATH', ConcatNode('cmakeVersion'))
# TODO: get these from the environment variables
util_create_and_add_refNode_for_variable('CMAKE_PROJECT_VERSION_MAJOR', LiteralNode('VERSION_MAJOR', 3))
util_create_and_add_refNode_for_variable('CMAKE_PROJECT_VERSION_MINOR', LiteralNode('VERSION_MINOR', 20))
util_create_and_add_refNode_for_variable('CMAKE_PROJECT_VERSION_PATCH', LiteralNode('VERSOIN_PATCH', 0))
util_create_and_add_refNode_for_variable('CMAKE_PROJECT_VERSION_TWAEK', LiteralNode('VERSION_TWEAK', 0))
util_create_and_add_refNode_for_variable('HUPNP_VERSION_MAJOR', LiteralNode('HUPNP_VERSION_MAJOR', 1))
util_create_and_add_refNode_for_variable('HUPNP_VERSION_MINOR', LiteralNode('VERSION_TWEAK', 1))
util_create_and_add_refNode_for_variable('HUPNP_VERSION_PATCH', LiteralNode('VERSION_TWEAK', 1))
if not shouldUseInput:
parseFile(os.path.join(project_dir, 'CMakeLists.txt'),True)
else:
parseFile(inputText, False)
class CMakeExtractorListener(CMakeListener):
rule: Optional[Rule] = None
insideLoop = False;
logicalExpressionStack: List[LogicalExpression] = []
foreachVariable: List[String] = []
def __init__(self):
global vmodel
global lookupTable
global directoryTree
vmodel = VModel.getInstance()
lookupTable = Lookup.getInstance()
directoryTree = Directory.getInstance()
directoryTree.setRoot(project_dir)
self.rule = None
self.logicalExpressionStack = []
def exitLogicalExpressionAnd(self, ctx: CMakeParser.LogicalExpressionAndContext):
# Popping order matters
rightLogicalExpression = self.logicalExpressionStack.pop()
leftLogicalExpression = self.logicalExpressionStack.pop()
andLogic = AndExpression(leftLogicalExpression, rightLogicalExpression)
self.logicalExpressionStack.append(andLogic)
def exitConstantValue(self, ctx: CMakeParser.ConstantValueContext):
constant = ConstantExpression(ctx.getText())
self.logicalExpressionStack.append(constant)
def exitLogicalExpressionNot(self, ctx: CMakeParser.LogicalExpressionNotContext):
logicalExpression = self.logicalExpressionStack.pop()
notLogic = NotExpression(logicalExpression)
self.logicalExpressionStack.append(notLogic)
def exitLogicalExpressionOr(self, ctx: CMakeParser.LogicalExpressionOrContext):
rightLogicalExpression = self.logicalExpressionStack.pop()
leftLogicalExpression = self.logicalExpressionStack.pop()
orLogic = OrExpression(leftLogicalExpression, rightLogicalExpression)
self.logicalExpressionStack.append(orLogic)
def exitLogicalEntity(self, ctx: CMakeParser.LogicalEntityContext):
if len(ctx.getText()) and ctx.getText()[0] == "$":
variableLookedUp = lookupTable.getKey(f'${ctx.getText()}')
else:
variableLookedUp = lookupTable.getKey(f'${{{ctx.getText()}}}')
localVariable = LocalVariable(ctx.getText())
if variableLookedUp:
try:
# Wherever we create a LocalVariable, we should flat the corresponding variable
self.flattenVariableInConditionExpression(localVariable, variableLookedUp)
except Z3Exception as e:
logging.error("[exitLogicalEntity] {}".format(localVariable))
raise e
else:
# We create an empty RefNode, perhaps it's a env variable
variable_name = "${{{}}}".format(ctx.getText())
variableNode = RefNode("{}".format(variable_name), None)
lookupTable.setKey(variable_name, variableNode)
self.logicalExpressionStack.append(localVariable)
def exitIfStatement(self, ctx: CMakeParser.IfStatementContext):
self.rule.setCondition(self.logicalExpressionStack.pop())
assert len(self.logicalExpressionStack) == 0
def exitComparisonExpression(self, ctx: CMakeParser.ComparisonExpressionContext):
ctx_left_get_text: str = ctx.left.getText()
ctx_right_get_text: str = ctx.right.getText()
if ctx_left_get_text[0] == "$":
leftVariableLookedUp = lookupTable.getKey(f'{ctx_left_get_text}')
else:
leftVariableLookedUp = lookupTable.getKey(f'${{{ctx_left_get_text}}}')
if ctx_right_get_text[0] == "$":
rightVariableLookedUp = lookupTable.getKey(f'{ctx_right_get_text}')
else:
rightVariableLookedUp = lookupTable.getKey(f'${{{ctx_right_get_text}}}')
operator = ctx.operator.getText().upper()
localVariableType = 'string' if operator in ('STRLESS', 'STREQUAL', 'STRGREATER', 'MATCHES', "VERSION_LESS",
"VERSION_GREATER", "VERSION_GREATER_EQUAL",
"VERSION_EQUAL") else 'int'
constantExpressionType = ConstantExpression.Z3_STR if operator in ('STRLESS', 'STREQUAL',
'STRGREATER', 'MATCHES', "VERSION_LESS",
"VERSION_GREATER", "VERSION_GREATER_EQUAL",
"VERSION_EQUAL") \
else ConstantExpression.PYTHON_STR
if leftVariableLookedUp:
leftExpression = LocalVariable(ctx_left_get_text, localVariableType)
self.flattenVariableInConditionExpression(leftExpression, leftVariableLookedUp)
else:
realVar = ctx_left_get_text.strip('"').lstrip('${').rstrip('}')
if realVar.upper().startswith('CMAKE_') or realVar.upper().startswith('${CMAKE_'):
# Reserved variable for CMake
variable_name = "${{{}}}".format(realVar)
variableNode = RefNode("{}".format(variable_name), None)
lookupTable.setKey(variable_name, variableNode)
leftExpression = LocalVariable(realVar, localVariableType)
else:
leftExpression = ConstantExpression(realVar, constantExpressionType)
if rightVariableLookedUp:
rightExpression = LocalVariable(ctx_right_get_text, localVariableType)
self.flattenVariableInConditionExpression(rightExpression, rightVariableLookedUp)
else:
realVar = ctx_right_get_text.strip('"').lstrip('${').rstrip('}')
if realVar.upper().startswith('CMAKE_'):
# Reserved variable for CMake
variable_name = "${{{}}}".format(realVar)
variableNode = RefNode("{}".format(variable_name), None)
lookupTable.setKey(variable_name, variableNode)
rightExpression = LocalVariable(realVar, localVariableType)
else:
rightExpression = ConstantExpression(realVar, constantExpressionType)
self.logicalExpressionStack.append(
ComparisonExpression(leftExpression, rightExpression, operator)
)
def flattenVariableInConditionExpression(self, expression: LocalVariable, variable: Node):
# Flattening the variable used inside the condition, like [(True, {bar}), (False, {Not bar, john > 2})]
flattened = flattenAlgorithmWithConditions(variable, ignoreSymbols=True) or []
# We need to add an assertion to the solver, like {bar, foo == True} and {Not bar, john > 2, foo == False}
temp_result = []
for item in flattened:
for condition in self.rule.flattenedResult:
s = Solver()
if isinstance(expression.getAssertions(), SeqRef):
assertion = condition.union(item[1].union({expression.getAssertions() == StringVal(item[0])}))
else:
try:
rightHandSide = item[0]
if isinstance(expression.getAssertions(), BoolRef):
# To convert float (3.14) to (314) and also support ("3.14")
if item[0].replace('.', '', 1).replace('"', '').isdigit():
rightHandSide = bool(int(item[0].replace('.', '', 1).replace('"', '')))
if rightHandSide == '""':
rightHandSide = False
elif not isinstance(rightHandSide, bool):
# TODO: needs more investigation, I think we are missing some problems
# Like 'INSTALL_DEFAULT_BASEDIR' in ET: Legacy project
rightHandSide = bool(rightHandSide)
if isinstance(expression.getAssertions(), ArithRef) and isinstance(rightHandSide, str):
cleanedRighthandSide = item[0].replace('.', '', 1).replace('"', '')
if (cleanedRighthandSide.isdigit()):
rightHandSide = int(cleanedRighthandSide)
else:
rightHandSide = Int(cleanedRighthandSide)
assertion = condition.union(item[1].union({expression.getAssertions() == rightHandSide}))
except Exception as e:
print(f"Variable name: {expression.variableName} and item[0]: {item[0]}")
raise e
s.add(assertion)
if s.check() == sat:
temp_result.append(assertion)
if not temp_result:
temp_result.append(set())
self.rule.flattenedResult = temp_result
def exitElseIfStatement(self, ctx: CMakeParser.ElseIfStatementContext):
# Logical expression for the elseif itself
rightLogic = self.logicalExpressionStack.pop()
# For the else if, to be evaluated as true, all the previous conditions should be evaluated as false
# Using bellow algorithm, we need to check the latest condition only.
logic, prevConditionFlattened = util_getNegativeOfPrevLogics()
andLogic = AndExpression(logic, rightLogic)
assert len(self.logicalExpressionStack) == 0
self.rule.setCondition(andLogic)
self.rule.flattenedResult = list(prevConditionFlattened)
vmodel.pushSystemState(self.rule)
def enterIfCommand(self, ctx: CMakeParser.IfCommandContext):
# Make sure that the logical expression stack is empty every time we enter an if statement
assert len(self.logicalExpressionStack) == 0
self.rule = Rule()
vmodel.setInsideIf()
vmodel.pushCurrentLookupTable()
vmodel.ifLevel += 1
self.rule.setType('if')
self.rule.setLevel(vmodel.ifLevel)
vmodel.pushSystemState(self.rule)
def enterElseIfStatement(self, ctx: CMakeParser.ElseIfStatementContext):
# Make sure that the logical expression stack is empty every time we enter an else if statement
assert len(self.logicalExpressionStack) == 0
self.rule = Rule()
vmodel.popLookupTable()
vmodel.pushCurrentLookupTable()
self.rule.setType('elseif')
self.rule.setLevel(vmodel.ifLevel)
def enterElseStatement(self, ctx: CMakeParser.ElseStatementContext):
# Make sure that the logical expression stack is empty every time we enter an else statement
assert len(self.logicalExpressionStack) == 0
self.rule = Rule()
# Else statement is true when all the previous conditions are false
# Same as elseif, we only need to check the previous state
logic, prevConditionFlattened = util_getNegativeOfPrevLogics()
while True:
systemStateObject = vmodel.getCurrentSystemState()
state = systemStateObject.getType()
if state != 'if':
vmodel.popSystemState()
else:
break
vmodel.popLookupTable()
vmodel.pushCurrentLookupTable()
self.rule.setType('elseif')
self.rule.setLevel(vmodel.ifLevel)
self.rule.setCondition(logic)
self.rule.flattenedResult = list(prevConditionFlattened)
vmodel.pushSystemState(self.rule)
def exitIfCommand(self, ctx: CMakeParser.IfCommandContext):
vmodel.setOutsideIf()
vmodel.popLookupTable()
vmodel.ifLevel -= 1
# In case of an if statement without else command, the state of the if itself and multiple else ifs
# still exists. We should keep popping until we reach to the if
while True:
systemStateObject = vmodel.popSystemState()
state = systemStateObject.type
if state == 'if':
break
def enterOptionCommand(self, ctx: CMakeParser.OptionCommandContext):
arguments = [child.getText() for child in ctx.argument().getChildren() if not isinstance(child, TerminalNode)]
optionName = arguments.pop(0)
optionInitialValue = False
if len(arguments) > 1:
arguments.pop(0) # Remove description from the option command
optionInitialValue = arguments.pop(0)
vmodel.addOption(optionName, optionInitialValue)
optionNode = OptionNode(optionName)
optionNode.default = optionInitialValue
util_create_and_add_refNode_for_variable(optionName, optionNode)
def exitForeachOptions(self, ctx: CMakeParser.WhileCommandContext):
ctx.left.getText()
self.foreachVariable.append()
def enterForeachCommand(self, ctx: CMakeParser.WhileCommandContext):
assert len(self.foreachVariable) == 0
self.insideLoop = True
def enterForeachInputs(self, ctx: CMakeParser.WhileStatementContext):
global foreachCommandStack
ctx_var = ctx.getText();
if ctx_var[0] == "$":
foreachVariableRawName = f'{ctx_var}'
else:
foreachVariableRawName = f'${{{ctx_var}}}'
foreachCommandStack.append(foreachVariableRawName)
def exitForeachStatement(self, ctx: CMakeParser.WhileStatementContext):
global foreachCommandStack, foreachNodeStack
# # self.rule.setType('foreach')
# assert len(self.logicalExpressionStack) == 0
# foreachCommand(self.rule)
foreachNodeStack.append(foreachCommandStack)
foreachCommandStack = []
foreachCommand();
def exitForeachCommand(self, ctx: CMakeParser.WhileCommandContext):
global foreachCommandStack
endForeachCommand(foreachNodeStack.pop())
self.insideLoop = False
def enterWhileCommand(self, ctx: CMakeParser.WhileCommandContext):
assert len(self.logicalExpressionStack) == 0
self.rule = Rule()
self.rule.setType('while')
def exitWhileStatement(self, ctx: CMakeParser.WhileStatementContext):
self.rule.setCondition(self.logicalExpressionStack.pop())
assert len(self.logicalExpressionStack) == 0
whileCommand(self.rule)
def exitWhileCommand(self, ctx: CMakeParser.WhileCommandContext):
endwhileCommand()
def enterFunctionCommand(self, ctx: CMakeParser.FunctionCommandContext):
startIdx = ctx.functionBody().start.start
endIdx = ctx.functionBody().stop.stop
inputStream = ctx.start.getInputStream()
bodyText = inputStream.getText(startIdx, endIdx)
isMacro = ctx.functionStatement().children[0].getText().lower() == 'macro'
arguments = [child.getText() for child in ctx.functionStatement().argument().getChildren() if
not isinstance(child, TerminalNode)]
functionName = arguments.pop(0)
vmodel.functions[functionName] = {'arguments': arguments, 'commands': bodyText, 'isMacro': isMacro}
def includeCommand(self, arguments):
commandNode = CustomCommandNode("include")
if 'RESULT_VARIABLE' in arguments:
varIndex = arguments.index('RESULT_VARIABLE')
arguments.pop(varIndex) # This is RESULT_VAR
util_create_and_add_refNode_for_variable(arguments.pop(varIndex), commandNode,
relatedProperty='RESULT_VARIABLE')
args = vmodel.expand(arguments)
include_possibilities = flattenAlgorithmWithConditions(args)
commandNode.depends.append(args)
if self.insideLoop:
print("[warning] include inside loop neglected")
return;
currentPath = flattenAlgorithmWithConditions(vmodel.expand(['${CMAKE_CURRENT_LIST_DIR}']))
if len(currentPath):
currentPath = currentPath[0][0];
else:
currentPath = '';
for include_possibility in include_possibilities:
argsVal = include_possibility[0]
includedFile = os.path.join(project_dir, argsVal)
# clean the include path
while includedFile.find('//') != -1:
includedFile = includedFile.replace('//', '/')
# We execute the command if we can find the CMake file and there is no condition to execute it
if os.path.isfile(includedFile):
parseFile(includedFile, True)
# for item in vmodel.nodes:
# if item not in prevNodeStack:
# commandNode.commands.append(item)
elif os.path.isdir(includedFile):
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_LIST_DIR',
LiteralNode(f"include_{includedFile}", includedFile))
parseFile(os.path.join(includedFile, 'CMakeLists.txt'), True)
else:
cmake_module_paths = flattenAlgorithmWithConditions(vmodel.expand(["${CMAKE_MODULE_PATH}"]))
for cmake_module_path in cmake_module_paths:
if os.path.exists(os.path.join(cmake_module_path[0], f'{argsVal}.cmake').replace('//', '/')):
includePath = os.path.join(cmake_module_path[0], f'{argsVal}.cmake').replace('//', '/')
if os.path.isfile(includePath):
pathDir = os.path.dirname(includePath)
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_LIST_DIR',
LiteralNode(f"include_{includedFile}", pathDir));
parseFile(includePath, True)
break
# assert len(cmake_module_path[1]) == 0 # check if we have multiple conditions
if not (len(cmake_module_path[1]) == 0):
logging.warning('Something might go wrong, conditional module path exist!')
else:
paths = [os.path.join(path, argsVal).replace('//', '/') + '.cmake' for path in includes_paths]
paths += [os.path.join(path, argsVal).replace('//', '/') for path in includes_paths]
foundModule = False
for path in paths:
if os.path.isfile(path):
pathDir = os.path.dirname(path)
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_LIST_DIR',
LiteralNode(f"include_{includedFile}", pathDir));
parseFile(path, True)
foundModule = True
if not foundModule:
print("[error][enterCommand_invocation] Cannot Find : {} to include, conditions {}".format(
arguments, include_possibility[1]))
vmodel.nodes.append(util_handleConditions(commandNode, commandNode.getName()))
# now we turn the current list dir back
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_SOURCE_DIR',
LiteralNode(f"parse_{currentPath}", currentPath))
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_LIST_DIR',
LiteralNode(f"original_{currentPath}", currentPath))
# now we turn the current list dir back
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_SOURCE_DIR',
LiteralNode(f"parse_{currentPath}", currentPath))
util_create_and_add_refNode_for_variable('CMAKE_CURRENT_LIST_DIR',
LiteralNode(f"original_{currentPath}", currentPath))
def find_Module(self, packageName, findPackageNode):
global vmodel
global project_dir
flattened_packageName = flattenAlgorithmWithConditions(packageName)
for possible_include in flattened_packageName:
includePath = None
# First we check CMAKE_MODULE_PATH
cmake_module_paths = flattenAlgorithmWithConditions(vmodel.expand(["${CMAKE_MODULE_PATH}"]))
for cmake_module_path in cmake_module_paths:
if os.path.exists(os.path.join(cmake_module_path[0], f'Find{possible_include[0]}.cmake')):
includePath = os.path.abspath(
os.path.join(cmake_module_path[0], f'Find{possible_include[0]}.cmake'))
break
if not (len(cmake_module_path[1]) == 0 and len(possible_include[1]) == 0):
print("something might go wrong, conditional module path exist!")
# assert len(cmake_module_path[1]) == 0 and len(possible_include[1]) == 0 # check if we have multiple conditions
else:
# If not found, then, we search in default directories
for find_package_prefix in find_package_prefixes:
for index, path in enumerate(find_package_lookup_directories):
if os.path.exists(os.path.join(find_package_prefix, path.replace(':name', possible_include[0]),
f'Find{possible_include[0]}.cmake')):
includePath = os.path.abspath(
os.path.join(find_package_prefix, path.replace(':name', possible_include[0]),
f'Find{possible_include[0]}.cmake'))
break
if includePath:
break
if includePath:
util_create_and_add_refNode_for_variable(packageName.getValue() + "_Module",
LiteralNode(includePath, includePath))
util_create_and_add_refNode_for_variable('PACKAGE_FIND_NAME',
LiteralNode(f"name_{packageName.getValue()}",
packageName.getValue()))
util_create_and_add_refNode_for_variable('PACKAGE_FIND_VERSION',
LiteralNode('VERSION_MINOR', 20))
if len(possible_include[1]):
vmodel = VModel.getInstance()
prior_condition = possible_include[1]
logicalExpression = DummyExpression(prior_condition)
rule = Rule()
if len(vmodel.systemState):
rule.setLevel(vmodel.systemState[-1].level)
else:
rule.setLevel(1)
rule.setType('if')
rule.setCondition(logicalExpression)
vmodel.pushSystemState(rule)
vmodel.pushCurrentLookupTable()
vmodel.nodeStack.append(list(vmodel.nodes))
tempProjectDir = project_dir
project_dir = os.path.dirname(includePath)
setCommand(['CMAKE_CURRENT_LIST_DIR', project_dir])
self.includeCommand([includePath])
project_dir = tempProjectDir
rule = vmodel.popSystemState()
prevNodeStack = vmodel.nodeStack.pop()
for item in vmodel.nodes:
if item not in prevNodeStack:
findPackageNode.pointTo.append(item)
else:
tempProjectDir = project_dir
project_dir = os.path.dirname(includePath)
setCommand(['CMAKE_CURRENT_LIST_DIR', project_dir])
self.includeCommand([includePath])
project_dir = tempProjectDir
return True
return False
def enterCommand_invocation(self, ctx: CMakeParser.Command_invocationContext):
global project_dir
global extension_type
global vmodel
global lookupTable
commandId = ctx.Identifier().getText().lower()
arguments = [child.getText() for child in ctx.argument().getChildren() if not isinstance(child, TerminalNode)]
# a hacky fix for consecutive double quotes
regex = r"^\"\"(.*?)\"\"$"
for idx, argument in enumerate(arguments):
arguments[idx] = argument.replace(regex, "")
if vmodel.currentFunctionCommand is not None and commandId not in ('endfunction', 'endmacro'):
vmodel.currentFunctionCommand.append((commandId, arguments))
return
if commandId == 'set':
if vmodel.currentFunctionCommand is not None:
vmodel.currentFunctionCommand.append(('set', arguments))
else:
setCommand(arguments)
# add_definitions(-DFOO -DBAR ...)
elif commandId == 'add_definitions':
handleCompileDefinitionCommand(arguments, command='add', specific=False, project_dir=project_dir)
# remove_definitions(-DFOO -DBAR ...)
elif commandId == 'remove_definitions':
handleCompileDefinitionCommand(arguments, command='remove', specific=False, project_dir=project_dir)
# load_cache(pathToCacheFile READ_WITH_PREFIX
# prefix entry1...)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# load_cache(pathToCacheFile [EXCLUDE entry1...]
# [INCLUDE_INTERNALS entry1...])
elif commandId == 'load_cache':
cacheNode = CustomCommandNode('load_cache_{}'.format(vmodel.getNextCounter()))
if 'READ_WITH_PREFIX' in arguments:
argIndex = arguments.index('READ_WITH_PREFIX')
arguments.pop(argIndex) # This is always 'READ_WITH_PREFIX'
prefix = arguments.pop(argIndex)
while len(arguments) > argIndex:
varname = arguments.pop(argIndex)
util_create_and_add_refNode_for_variable("{}{}".format(prefix, varname), cacheNode)
cacheNode.commands.append(vmodel.expand(arguments))
# find_library (<VAR> name1 [path1 path2 ...])
# +++++++++++++++++++++++++++++++++++++++++++++++++++++
# find_path (<VAR> name1 [path1 path2 ...])
elif commandId in ('find_library', 'find_path', 'find_program'):
varFound = arguments.pop(0)
varNotFound = varFound + '-NOTFOUND'
findLibraryNode = CustomCommandNode("{}_{}".format(commandId, vmodel.getNextCounter()))
findLibraryNode.commands.append(vmodel.expand(arguments))
util_create_and_add_refNode_for_variable(varFound, findLibraryNode, relatedProperty='FOUND')
util_create_and_add_refNode_for_variable(varNotFound, findLibraryNode, relatedProperty='NOTFOUND')
# find_package( < package > [version][EXACT][QUIET][MODULE]
# [REQUIRED][[COMPONENTS][components...]]
# [OPTIONAL_COMPONENTS
# components...]
# [NO_POLICY_SCOPE])
elif commandId == 'find_package':
# XXX versioning is not considered in this version
packageName = vmodel.expand([arguments[0]])
findPackageNode = CustomCommandNode("find_package_{}".format(vmodel.getNextCounter()))
findPackageNode.commands.append(vmodel.expand(arguments))
util_create_and_add_refNode_for_variable(packageName.getValue() + "_FOUND", findPackageNode)
capitalArguments = [x.upper() for x in arguments]
if 'REQUIRED' in capitalArguments:
requiredIndex = capitalArguments.index('REQUIRED')
else:
requiredIndex = -1
isModule = False
if 'MODULE' in capitalArguments:
isModule = True
requiredPackage = False
if requiredIndex != -1:
requiredPackage = True
flattened_packageName = flattenAlgorithmWithConditions(packageName)
version = ''
if self.find_Module(packageName, findPackageNode):
return True;
elif not isModule:
for possible_include in flattened_packageName:
includePath = None
# First we check CMAKE_MODULE_PATH
cmake_module_paths = flattenAlgorithmWithConditions(vmodel.expand(["${CMAKE_MODULE_PATH}"]))
for cmake_module_path in cmake_module_paths:
if os.path.exists(os.path.join(cmake_module_path[0], f'{possible_include[0]}Config.cmake')):
includePath = os.path.join(cmake_module_path[0], f'{possible_include[0]}Config.cmake')
version = os.path.join(cmake_module_path[0], f'{possible_include[0]}ConfigVersion.cmake')
break
if os.path.exists(os.path.join(cmake_module_path[0], f'{possible_include[0]}-config.cmake')):
includePath = os.path.exists(
os.path.join(cmake_module_path[0], f'{possible_include[0]}-config.cmake'))
version = os.path.join(cmake_module_path[0], f'{possible_include[0]}-config-version.cmake')
break
if not (len(cmake_module_path[1]) == 0 and len(possible_include[1]) == 0):
print("something might go wrong, conditional module path exist!")
# assert len(cmake_module_path[1]) == 0 and len(possible_include[1]) == 0 # check if we have multiple conditions
else:
# If not found, then, we search in default directories
for find_package_prefix in find_package_prefixes:
for index, path in enumerate(find_package_lookup_directories):
if os.path.exists(
os.path.join(find_package_prefix, path.replace(':name', possible_include[0]),
f'{possible_include[0]}Config.cmake')):
includePath = os.path.join(find_package_prefix,
path.replace(':name', possible_include[0]),
f'{possible_include[0]}Config.cmake')
version = os.path.join(find_package_prefix,
path.replace(':name', possible_include[0]),
f'{possible_include[0]}ConfigVersion.cmake')
break
if os.path.exists(
os.path.join(find_package_prefix, path.replace(':name', possible_include[0]),
f'{possible_include[0].lower()}-config.cmake')):
includePath = os.path.join(find_package_prefix,
path.replace(':name', possible_include[0]),
f'{possible_include[0].lower()}-config.cmake')
version = os.path.join(find_package_prefix,
path.replace(':name', possible_include[0]),
f'{possible_include[0].lower()}-config-version.cmake')
break
if includePath:
break
if includePath:
util_create_and_add_refNode_for_variable(packageName.getValue() + "_CONFIG",
LiteralNode(includePath, includePath))
util_create_and_add_refNode_for_variable('PACKAGE_FIND_NAME',
LiteralNode(f"name_{packageName.getValue()}",
packageName.getValue()))
if len(possible_include[1]):
vmodel = VModel.getInstance()
prior_condition = possible_include[1]
logicalExpression = DummyExpression(prior_condition)
rule = Rule()
if len(vmodel.systemState):
rule.setLevel(vmodel.systemState[-1].level)
else:
rule.setLevel(1)
rule.setType('if')
rule.setCondition(logicalExpression)
vmodel.pushSystemState(rule)
vmodel.pushCurrentLookupTable()
vmodel.nodeStack.append(list(vmodel.nodes))
tempProjectDir = project_dir
project_dir = os.path.dirname(includePath)
# load_version
if (os.path.exists(version)):
self.includeCommand([version])
package_version = flattenAlgorithmWithConditions(vmodel.expand(['PACKAGE_VERSION']))
if len(package_version):
setCommand([f"{packageName.getValue()}_FIND_VERSION", package_version[0][0]]);
# end load version
setCommand(['CMAKE_CURRENT_LIST_DIR', project_dir])
self.includeCommand([includePath])
project_dir = tempProjectDir
rule = vmodel.popSystemState()
prevNodeStack = vmodel.nodeStack.pop()
for item in vmodel.nodes:
if item not in prevNodeStack:
findPackageNode.pointTo.append(item)
else:
tempProjectDir = project_dir
project_dir = os.path.dirname(includePath)
# load_version
if (os.path.exists(version)):
self.includeCommand([version])
package_version = flattenAlgorithmWithConditions(vmodel.expand(['PACKAGE_VERSION']))
if len(package_version):
setCommand([f"{packageName.getValue()}_FIND_VERSION", package_version[0][0]]);
# end load version
setCommand(['CMAKE_CURRENT_LIST_DIR', project_dir])
self.includeCommand([includePath])
project_dir = tempProjectDir
elif requiredPackage:
logging.error("Required package not found: {}".format(packageName.getValue()))
# raise Exception("Required package not found: {}".format(packageName.getValue()))
print("[Bug or Error]Required package not found: {}".format(packageName.getValue()))
elif requiredPackage:
logging.error("Required module not found: {}".format(packageName.getValue()))
raise Exception("Required package not found: {}".format(packageName.getValue()))
# print("Required module not found: {}".format(packageName.getValue()))
# capitalArguments = [x.upper() for x in arguments]
# projectVersion = None
# projectDescription = None
# if 'DESCRIPTION' in capitalArguments:
# descriptionIndex = arguments.index('DESCRIPTION')
# projectDescription = arguments[descriptionIndex+1]
# include( < file | module > [OPTIONAL][RESULT_VARIABLE < VAR >]
# [NO_POLICY_SCOPE])
elif commandId in ('include'):
self.includeCommand(arguments)
elif commandId == 'find_file':
variableName = arguments.pop(0)
fileNode = CustomCommandNode('find_file_{}'.format(vmodel.getNextCounter()))
fileNode.pointTo.append(vmodel.expand(arguments))
foundRefNode = RefNode("{}_{}".format(variableName, vmodel.getNextCounter()), fileNode)
notFoundRefNode = RefNode("{}-NOTFOUND_{}".format(variableName, vmodel.getNextCounter()), fileNode)
lookupTable.setKey("${{{}}}".format(variableName), foundRefNode)
lookupTable.setKey("${{{}}}".format(variableName + "-NOTFOUND"), notFoundRefNode)
vmodel.nodes.append(foundRefNode)
vmodel.nodes.append(notFoundRefNode)
elif commandId == 'math':
# Throw first argument away, it is always "EXPR" according to the document
arguments.pop(0)
varName = arguments.pop(0)
mathNode = CustomCommandNode("{}_{}".format('MATH', vmodel.getNextCounter()))
mathNode.pointTo.append(vmodel.expand(arguments))
refNode = RefNode("{}_{}".format(varName, vmodel.getNextCounter()), mathNode)
lookupTable.setKey("${{{}}}".format(varName), refNode)
vmodel.nodes.append(refNode)
# TODO: We should keep the outputs in lookup table
# We cannot handle scenario given in : https://gist.github.com/socantre/7ee63133a0a3a08f3990
# This is a very common use of this command, but we don't have solution for that
# add_custom_command(OUTPUT output1 [output2 ...]
# COMMAND command1 [ARGS] [args1...]
# [COMMAND command2 [ARGS] [args2...] ...]
# [MAIN_DEPENDENCY depend]
# [DEPENDS [depends...]]
# [IMPLICIT_DEPENDS <lang1> depend1
# [<lang2> depend2] ...]
# [WORKING_DIRECTORY dir]
# [COMMENT comment] [VERBATIM] [APPEND])
# -----------------------------------------------------
# add_custom_command(TARGET target
# PRE_BUILD | PRE_LINK | POST_BUILD
# COMMAND command1 [ARGS] [args1...]
# [COMMAND command2 [ARGS] [args2...] ...]
# [WORKING_DIRECTORY dir]
# [COMMENT comment] [VERBATIM])
elif commandId == 'add_custom_command':
OPTIONS = ['OUTPUT', 'COMMAND', 'MAIN_DEPENDENCY', 'DEPENDS', 'IMPLICIT_DEPENDS',
'WORKING_DIRECTORY', 'COMMENT', 'VERBATIM', 'APPEND']
customCommand = CustomCommandNode("custom_command")
depends = []
commandSig = arguments.pop(0)
if commandSig == 'TARGET':
targetName = arguments.pop(0)
target = lookupTable.getKey("t:{}".format(targetName))
commandType = arguments.pop(0)
if commandType == 'POST_BUILD':
depends.append(targetName)
vmodel.nodes.append(customCommand)
else:
target.addLinkLibrary(customCommand)
else:
while arguments[0] not in OPTIONS:
outName = arguments.pop(0)
if lookupTable.getKey(outName):
variable = lookupTable.getKey(outName)
if isinstance(variable.getPointTo(), ConcatNode):
variable.pointTo.addToBeginning(customCommand)
else:
variable.pointTo = customCommand
else:
refNode = RefNode(outName, customCommand)
vmodel.nodes.append(refNode)
while 'COMMAND' in arguments:
# From that index until the next command we parse the commands
commands = []
commandStartingIndex = arguments.index('COMMAND')
# pop 'COMMAND'
arguments.pop(commandStartingIndex)
while len(arguments) > commandStartingIndex and arguments[commandStartingIndex] not in OPTIONS:
commands.append(arguments.pop(commandStartingIndex))
customCommand.commands.append(vmodel.expand(commands))
if 'MAIN_DEPENDENCY' in arguments:
mdIndex = arguments.index('MAIN_DEPENDENCY')
# pop 'MAIN_DEPENDENCY'
arguments.pop(mdIndex)
depends.append(arguments.pop(mdIndex))
if 'DEPENDS' in arguments:
dIndex = arguments.index('DEPENDS')
# pop 'DEPENDS'
arguments.pop(dIndex)
while len(arguments) > dIndex and arguments[dIndex] not in OPTIONS:
depends.append(arguments.pop(dIndex))
if depends:
customCommand.depends.append(vmodel.expand(depends))
# add_test(NAME <name> COMMAND <command> [<arg>...]
# [CONFIGURATIONS <config>...]
# [WORKING_DIRECTORY <dir>])
# --------------------------------------------------
# add_test(<name> <command> [<arg>...])
elif commandId == 'add_test':
# Check if we should proceed with first signature or the second one
if arguments[0] == 'NAME':
arguments.pop(0) # NAME
testName = arguments.pop(0)
testNode = TestNode(testName)
arguments.pop(0) # COMMAND
if 'CONFIGURATIONS' in arguments:
cIndex = arguments.index('CONFIGURATIONS')
arguments.pop(cIndex) # 'CONFIGURATIONS'
configArgs = []
while cIndex < len(arguments) and arguments[cIndex] not in ['COMMAND', 'WORKING_DIRECTORY']:
configArgs.append(arguments.pop(cIndex))
testNode.configurations = vmodel.expand(configArgs)
if 'WORKING_DIRECTORY' in arguments:
wdIndex = arguments.index('WORKING_DIRECTORY')
arguments.pop(wdIndex) # WORKING_DIRECTORY
testNode.working_directory = vmodel.expand([arguments.pop(wdIndex)])
testNode.command = vmodel.expand(arguments)
else:
# We go with the second sig
testName = arguments.pop(0)
testNode = TestNode(testName)
testNode.command = vmodel.expand(arguments)
vmodel.nodes.append(testNode)
# cmake_host_system_information(RESULT <variable> QUERY <key> ...)
elif commandId == 'cmake_host_system_information':
arguments.pop(0) # First argument is RESULT
variableName = arguments.pop(0)
arguments.pop(0) # This one is always QUERY
commandNode = CustomCommandNode("cmake_host_system_information_{}".format(vmodel.getNextCounter()))
commandNode.commands.append(vmodel.expand(arguments))
refNode = RefNode("{}_{}".format(variableName, vmodel.getNextCounter()), commandNode)
lookupTable.setKey("${{{}}}".format(variableName), refNode)
vmodel.nodes.append(refNode)
# TODO: It may be a good idea to list commands and files under a different list
# We should create a new class for this command to separate command and sources and etc ...
# This new class should inherit TargetNode
elif commandId == 'add_custom_target':
targetName = arguments.pop(0)
dependedElement: List[TargetNode] = []
defaultBuildTarget = False
# Check for some keywords in the command
if 'ALL' in arguments:
allIndex = arguments.index('ALL')
arguments.pop(allIndex)
defaultBuildTarget = True
# Check if we have depend command
if 'DEPENDS' in arguments:
dependsIndex = arguments.index('DEPENDS')
# Trying to find the next argument after DEPENDS. Anything in between is the one that this command
# should depends on
nextArgIndex = len(arguments)
for otherArg in ['ALL', 'COMMAND', 'WORKING_DIRECTORY', 'COMMENT', 'VERBATIM', 'SOURCES']:
if otherArg not in arguments:
continue
otherArgIndex = arguments.index(otherArg)
if otherArgIndex > dependsIndex:
nextArgIndex = min(nextArgIndex, otherArgIndex)
for i in range(dependsIndex + 1, nextArgIndex):
# TODO: There is a bug here. As we add a number to the end of nodes, vmodel.findNode may not be
# be able to find the node based on name
targetElement = lookupTable.getKey("t:{}".format(arguments[i])) \
or vmodel.findNode(arguments[i])
if targetElement is None:
targetElement = RefNode(arguments[i], None)
lookupTable.setKey(arguments[i], targetElement)
# raise Exception("There is a problem in finding dependency for {}".format(targetName))
dependedElement.append(targetElement)
# Now we have to pop these arguments:
for i in range(dependsIndex, nextArgIndex):
arguments.pop(dependsIndex)
targetNode = TargetNode("{}".format(targetName), vmodel.expand(arguments))
targetNode.isCustomTarget = True
targetNode.defaultBuildTarget = defaultBuildTarget
targetNode.sources.listOfNodes += dependedElement
lookupTable.setKey("t:{}".format(targetName), targetNode)
vmodel.nodes.append(targetNode)
# get_filename_component(<var> <FileName> <mode> [CACHE])
# -------------------------------------------------------
# get_filename_component(<var> <FileName> <mode> [BASE_DIR <dir>] [CACHE])
# -------------------------------------------------------
# get_filename_component(<var> <FileName> PROGRAM [PROGRAM_ARGS <arg_var>] [CACHE])
# TODO: WE do not support ABSOLUTE at this point
elif commandId == 'get_filename_component':
varName = arguments.pop(0)
# currentPath = flattenAlgorithmWithConditions(vmodel.expand(['${CMAKE_CURRENT_LIST_DIR}']))
# if len(currentPath):
# currentPath = currentPath[0][0];
# else:
# currentPath = '';
commandNode = CustomCommandNode("get_filename_component_{}".format(vmodel.getNextCounter()))
otherArgs = vmodel.expand(arguments)
commandNode.commands.append(otherArgs)
pathVariable = vmodel.expand([arguments[0]])
tmp = flattenAlgorithmWithConditions(pathVariable)
# TODO: We need to support multiple file conditions here!
if tmp:
pathValue = tmp[0][0].rstrip('/')
else:
pathValue = pathVariable
# TODO: investigate these options in more detail!
if not isinstance(pathValue, str):
return;
capitalArguments = [x.upper() for x in arguments]
if 'BASE_DIR' in capitalArguments:
if not len(pathValue) or pathValue[0] != '/':
base_dir_idx = capitalArguments.index('BASE_DIR') + 1
baseAddr = vmodel.expand([arguments[base_dir_idx]]).getValue()
pathValue = os.path.join(baseAddr, pathValue).rstrip('/')
if isinstance(pathValue, RefNode):
pathValue = flattenAlgorithmWithConditions(pathValue)
if 'DIRECTORY' in capitalArguments or 'PATH' in capitalArguments:
pathValue = os.path.dirname(pathValue)