-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_PF.py
203 lines (155 loc) · 5.55 KB
/
generate_PF.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
import argparse
import glob
import logging
import os
import pickle
import random
import re
import shutil
import numpy as np
import torch
import json
try:
from torch.utils.tensorboard import SummaryWriter
except:
from tensorboardX import SummaryWriter
from tqdm import tqdm, trange
import multiprocessing
logger = logging.getLogger(__name__)
import sctokenizer
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
asst_operators = ["=", "+=", "-=", "*=", "/=", "<<=", ">>="]
def readData(file_path):
with open(file_path) as f:
for line in tqdm(f):
#print(line)
js=json.loads(line.strip())
code = js["code"]
#print(code)
#f = open("temp_1.cpp", "w")
#f.write(code)
#f.close()
#print(js["code"])
newTokens = []
tokenTypes = []
tokens = sctokenizer.tokenize_file(filepath='temp_1.cpp', lang='cpp')
#print("Length of tokens ", len(tokens))
#print("Adj matrix", adj_matrix)
for token in tokens:
out = (str(token)[1:-1])
tup = tuple(map(str, out.split(', ')))
#print(tup[0])
newTokens.append(tup[0])
tokenTypes.append(tup[1])
#break
#print(newTokens)
# Convert to string and add a break
codeStr = " ".join(newTokens)
#print(codeStr)
return codeStr, tokenTypes
break
def getNextToken(tokens, tokenType, index):
for i in range(index + 1, len(tokens)):
#print(tokens[i], tokenType[i])
if tokenType[i] == 'TokenType.IDENTIFIER' or tokenType[i] == 'TokenType.KEYWORD':
return tokens[i], i
def getPrevToken(tokens, tokenType, index):
#for i in range(0, index - 1):
i = index - 1
while i >= 0:
if tokenType[i] == 'TokenType.IDENTIFIER' or tokenType[i] == 'TokenType.KEYWORD':
return tokens[i], i
i -= 1
def isFunctionDecl(tokens, tokenType, index):
#print(tokens[index], tokens[index + 1])
if tokenType[index] == 'TokenType.IDENTIFIER' and tokens[index + 1] == "(":
prevToken, prevIndex = getPrevToken(tokens, tokenType, index)
#if tokenType[prevIndex] == 'TokenType.KEYWORD':
if tokens[prevIndex] in ["void", "float", "int", "doble", "char"]:
return True
else:
return False
return False
def isAPICall(tokens, tokenType, index):
#print("....",tokens[index], tokens[index + 1])
if tokenType[index] == 'TokenType.IDENTIFIER' and tokens[index + 1] == "(":
prevToken, prevIndex = getPrevToken(tokens, tokenType, index)
#print(prevToken, tokenType[prevIndex])
if tokens[prevIndex] not in ["void", "float", "int", "doble", "char"]:
return True
else:
return False
return False
def getFuncParams(tokens, tokenType, index):
i = index + 1
params = []
if tokens[i] == "(" and tokens[i + 1] == ")":
return params
while True:
nextToken, nextIndex = getNextToken(tokens, tokenType, i)
params.append((nextToken, nextIndex))
i = nextIndex
if tokens[i + 1] == ")":
break
return params
"""
code, tokenType = readData("../FQ_validating.jsonl")
print(code)
print(tokenType)
print("-----------------------------------------------------------------")
print("Next token ...", getNextToken(code.split(" "), tokenType, 9))
print("Previous token ...", getPrevToken(code.split(" "), tokenType, 1))
print("Is FunctionDecl", isFunctionDecl(code.split(" "), tokenType, 3))
#isAPICall(code.split(" "), tokenType, 33)
print("Is isAPICall", isAPICall(code.split(" "), tokenType, 33)) # 33, 40
print("Is getFuncParams", getFuncParams(code.split(" "), tokenType, 40))
"""
def generatePFEdges(tokens, tokenType):
asst_operators = ["=", "+=", "-=", "*=", "/=", "<<=", ">>="]
execute_apis = ["exec", "system"]
rows = cols = len(tokens)
adj_matrix = [[0]*cols]*rows
scope = {}
token_pair = []
try:
for i in range(len(tokens)):
if tokens[i] in asst_operators:
left, leftIndex = getPrevToken(tokens, tokenType, i)
right, rightIndex = getNextToken(tokens, tokenType, i)
adj_matrix[leftIndex][rightIndex] = 1
token_pair.append((leftIndex, rightIndex))
elif isAPICall(tokens, tokenType, i):
params = getFuncParams(tokens, tokenType, i)
for item in params:
adj_matrix[i][item[1]]
token_pair.append((i, item[1]))
elif tokens[i] in execute_apis:
params = getFuncParams(tokens, tokenType, i)
for item in params:
adj_matrix[i][item[1]]
token_pair.append((i, item[1]))
elif tokens[i] == "free":
indexFree = tokens.index("free")
adj_matrix[i][indexFree] = 1
token_pair.append((i, indexFree))
except:
pass
return token_pair #,adj_matrix
"""
newTokens = []
tokenTypes = []
tokens = sctokenizer.tokenize_file(filepath='temp.cpp', lang='cpp')
for token in tokens:
out = (str(token)[1:-1])
tup = tuple(map(str, out.split(', ')))
#print(tup[0])
newTokens.append(tup[0])
tokenTypes.append(tup[1])
#break
print(newTokens)
print("------------------------------------------------")
print(tokenTypes)
"""