-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyLuaTblParser.py
More file actions
586 lines (485 loc) · 21.2 KB
/
PyLuaTblParser.py
File metadata and controls
586 lines (485 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
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
# -*- coding: utf-8 -*-
class InvalidLuaTableError(Exception):
pass
class PyLuaTblParser:
'''
This is a lua table parser
Chi Wang
'''
# string to be parsed
luaString = ''
result = None
otherCharacterSet="~!@#$%^&*()+-={':[,]}|;.</>?"
def __init__(self):
self.result = None
self.luaString = ''
def load(self, myStr):
if len(myStr) == 0:
raise Exception('Empty input Lua Table string')
self.luaString = self.__removeComment(myStr).strip()
self.__checkLuaTbl()
self.result = self.__processString(self.luaString)
def dump(self):
return self.luaString
def loadLuaTable(self, filePath):
try:
luaFile = open(filePath)
except IOError as e:
print 'file reading error:', e.strerror, e.errno
raise Exception('file reading error')
fileStr = luaFile.read()
self.luaString = self.__removeComment(fileStr).strip()
self.__checkLuaTbl()
self.result = self.__processString(self.luaString)
def __checkLuaTbl(self):
# make sure lua table starts and ends with { }
if (self.luaString.find('{') != 0) or (self.luaString.rfind('}') != len(self.luaString) - 1):
raise InvalidLuaTableError('Incorrect input Lua Table: table string does not start and end with { and }.')
# load an external dict, and store in class
def loadDict(self, dict):
if type(dict) == type({}):
newDict = {}
typeSet = [type(2), type(2.3), type('a')]
for k, v in dict.items():
if type(k) in typeSet:
newDict[k] = self.loadDictValue(v)
self.result = newDict
else:
raise Exception('input parameter is not a dict type data')
def loadDictValue(self, dictValue):
if type(dictValue) == type({}):
newDict = {}
typeSet = [type(2), type(2.3), type('a')]
for k, v in dictValue.items():
if type(k) in typeSet:
newDict[k] = self.loadDictValue(v)
return newDict
else:
return dictValue
# export dict data
def dumpDict(self):
if self.result == None and self.luaString != '':
self.result = self.__processString(self.luaString)
return self.result
# the following three functions export python data in Lua table form
def dumpLuaTable(self, filePath):
try:
outputFile = open(filePath, 'w')
outputFile.write('{')
if type(self.result) == type([]):
for s in self.result:
self.writeSingleListData(s, outputFile)
outputFile.write(',')
if type(self.result) == type({}):
self.writeDictData(self.result, outputFile)
outputFile.write('}')
outputFile.close()
except IOError as e:
print e.errno, e.strerror
raise Exception('errors in exporting data')
# write dict data recursively
def writeDictData(self, dictData, outputFileHandle):
# write dict data
for k, v in dictData.items():
if type(k) == type(''):
outputFileHandle.write('"'+str(k) + '"=')
if type(k) == type(1):
outputFileHandle.write('['+str(k) + ']=')
self.writeDictKeyData(v, outputFileHandle)
outputFileHandle.write(',')
# write the key element in dict data
def writeDictKeyData(self, dictKeyData, outputFileHandle):
if type(dictKeyData) == type({}):
# if dictKeyData is still a dict
outputFileHandle.write('{')
self.writeDictData(dictKeyData, outputFileHandle)
outputFileHandle.write('}')
return
if type(dictKeyData) == type([]):
# if dictKeyData is a list
outputFileHandle.write('{')
for y in dictKeyData:
if type(y) == type({}):
self.writeDictData(y, outputFileHandle)
else:
self.writeSingleListData(y, outputFileHandle)
outputFileHandle.write(',')
outputFileHandle.write('}')
else:
# if dictKeyData is a single value
self.writeSingleListData(dictKeyData, outputFileHandle)
# write list data, we need to take care of None, False, and True etc.
def writeSingleListData(self, singleValue, outputFileHandle):
if singleValue != None:
if str(singleValue) == 'False' or str(singleValue) == 'True':
outputFileHandle.write(str(singleValue).lower())
else:
if type(singleValue) == type(''):
outputFileHandle.write('"' + str(singleValue) + '"')
if type(singleValue) == type(1) or type(singleValue) == type(1.1):
outputFileHandle.write(str(singleValue))
else:
outputFileHandle.write('nil')
def __parseKey(self, keyStr):
keyStr = keyStr.strip()
keyStr = keyStr.strip('[')
keyStr = keyStr.strip(']')
key = self.rtnCorrectType(keyStr)
return key
def __parseValue(self, valueStr):
valueStr = valueStr.strip()
value = self.__processString(valueStr)
return value
# core function of lua table string parser
# add a lable of the string here!!!
def __processString(self, myStr):
myStr = myStr.strip()
hasBracket = (myStr.find('{') == 0 and myStr.rfind('}') == len(myStr) - 1)
if hasBracket:
# if string starts with '{' and ends with '}'
newStr = myStr[1:len(myStr) - 1].strip()
# fix {}, {}, {} bugs
allBracket = newStr.split(',')
areAllBracket = True
bracketList = []
for s in allBracket:
if s.strip() == '{}':
bracketList.append([])
else:
areAllBracket = False
break
if areAllBracket:
return bracketList
if (newStr.find('{') == 0 and newStr.rfind('}') == len(newStr) - 1):
tmp = []
tmp.append(self.__processString(newStr))
return tmp
# 按照逗号或分号,将字符串划分成若干子串
partition = self.__stringPartition(newStr)
dictStrList = []
hasDictInTable = False
for s in partition:
dictStr = self.__parseDictStr(s)
dictStrList.append(dictStr)
if type(dictStr) != str:
hasDictInTable = True
if hasDictInTable:
# deal with the string like {1,{1,2,3},a=1}
# return a dict type
tempDict = {}
# turn every one into dict element
index = 1
# record the all the keys
keyList = []
for tmp in dictStrList:
if type(tmp) == str:
if len(tmp) != 0 and tmp.strip().lower() != 'nil':
# if this tmp is not a dict element
# tmp might be like 1 or {1,2,3}
tmp = self.__processString(tmp)
tempDict[index] = tmp
keyList.append(index)
index += 1
else:
key = self.__parseKey(tmp[0])
value = self.__parseValue(tmp[1])
if value != None and (key not in keyList):
# make sure the key is not used
# in case the key is used, discard this pair
tempDict[key] = value
return tempDict
else:
# deal with a list case, like {1, 2, 3}, return a list type data []
tempList = []
for s in partition:
temp = self.__processString(s)
if temp != '' and temp != {}:
tempList.append(temp)
return tempList
else:
# deal with single value data, like '1' or 'abc'
return self.rtnCorrectType(myStr)
def __isNumber(self, myStr):
return self.__isFloat(myStr.strip()) or myStr.strip().isdigit()
def __isFloat(self, myStr):
''' test if a string represent a float number '''
try:
float(myStr)
return True
except:
return False
# tell whether the string is a number(float or int?) or a Boolean value, or a string
# return their corresponding types
def rtnCorrectType(self, myStr):
'''
tell whether the string is a number(float or int?) or a Boolean value, or a string
return the value of their corresponding types
'''
# is Boolean type ?
if myStr.strip().lower() == 'false':
return False
if myStr.strip().lower() == 'true':
return True
if myStr.strip() == 'nil':
return None
# is a int number ?
if myStr.strip().isdigit():
return int(myStr.strip())
if self.__isFloat(myStr.strip()):
return float(myStr.strip())
value = myStr.strip()
# remove quote
if self.__isAStrWithQuote(value):
value = value[1:len(value)-1]
# process escape string
value = value.replace('\\"', '\"')
value = value.replace("\\'", '\'')
value = value.replace('\\a', '\a')
value = value.replace('\\b', '\b')
value = value.replace('\\x08', '\b')
value = value.replace('\\x0c', '\f')
value = value.replace('\\n', '\n')
value = value.replace('\\r', '\r')
value = value.replace('\\t', '\t')
value = value.replace('\\f', '\f')
value = value.replace('\\\\', '\\')
value = value.replace('\\/', '/')
value = value.replace('\\v', '\v')
return value
# split given string with comma at top level
# e.g. input : {'1','2','{3,4}'}
# output: '1,2,{3,4}'R
def __stringPartition(self, myStr):
partition = []
seperatorList = [',', ';']
strBeginPos = 0
seperatorPos = 0
index = 0
length = len(myStr)
inQuote = False
bracketLayer = 0
while index < length:
if myStr[index] == '"' and inQuote == False:
inQuote = True
index += 1
continue
if myStr[index] == '"' and inQuote == True:
inQuote = False
index += 1
continue
if myStr[index] == '\\':
# 进入转义字符状态
index += 2
continue
if inQuote == False and myStr[index] == '{':
bracketLayer += 1
index += 1
continue
if inQuote == False and myStr[index] == '}':
bracketLayer -= 1
index += 1
continue
if inQuote == True and (myStr[index] == '{' or myStr[index] == '}'):
index += 1
continue
if myStr[index] in seperatorList and bracketLayer == 0 and inQuote == False:
# find a partition
partition.append(myStr[strBeginPos: index])
index += 1
strBeginPos = index
continue
index = index + 1
if strBeginPos!= length :
partition.append(myStr[strBeginPos:])
return partition
# find separation index of given string with first ',' or ';'
def findLuaTblSep(self, myStr, index):
sep = [',',';']
pos = []
for s in sep:
pos.append(myStr.find(s,index))
pos = [x for x in sorted(pos) if x > -1]
if len(pos) == 0:
return -1
else:
return pos[0]
def __removeComment(self, myStr):
uncommentedStr = myStr
inQuote = False
index = 0
length = len(myStr)
while index < length:
if myStr[index] == '"' and inQuote == False:
inQuote = True
index += 1
continue
if myStr[index] == '"' and inQuote == True:
inQuote = False
index += 1
continue
if myStr[index] == '\\':
# 转义字符,直接忽略其后面一个字符
index += 2
continue
if myStr[index: index + 2] == '--':
if inQuote == False:
uncommentedStr = self.__processComment(uncommentedStr, index)
break
else:
index += 2
continue
index += 1
if uncommentedStr!=myStr:
return self.__removeComment(uncommentedStr)
else:
return myStr
def __processComment(self, myStr, commentStart):
if self.__isMultiLineComment(myStr, commentStart):
endPos = self.__locateMultiLineComment(myStr, commentStart)
else:
# 否则用 \n 标识注释的结束位置
# 跳过字符中的 \\n
jumpPos = myStr.find('\\n', commentStart + 1)
endPos = myStr.find('\n', commentStart + 1)
while endPos == jumpPos + 1:
jumpPos = myStr.find('\\n', jumpPos + 1)
endPos = myStr.find('\n', endPos + 1)
myStr = myStr[0:commentStart] + myStr[endPos + 1:]
return myStr
def __isMultiLineComment(self,myStr, commentStart):
''' 是否有多行注释'''
newStr = myStr[commentStart+2:].strip()
if newStr.find('[[') == 0:
return True
return False
def __locateMultiLineComment(self,myStr, commentStart):
''' 定位多行注释的结束位置'''
# myStr might be '-- [[ dsa221rfcsdsadd[[]] -- ]]abcd'
end = -1
if myStr.find('[[') != -1:
end = myStr.find(']]')
while end !=-1:
tmp = myStr[:end].strip()
if tmp.rfind('--') == len(tmp) - 2 :
break
else:
end = myStr.find(']]', end + 1)
if end == -1:
raise Exception('invalide lua multi line comment')
return end+2
pass
def __isAStrWithBracket(self, myStr):
myStr = myStr.strip()
return (myStr.find('{') == 0 and myStr.rfind('}') == len(myStr) - 1)
def __parseDictStr(self, inputStr='*Sdsa={13}2easd={231rfs3=P{}}'):
'''
test if a given string represents a dict data
correct lua dict form:
["x"] = 1, [1] = "x" , x = 1, x = {...}
incorrect form:
[ x ] = 1, [1] = x, "xyz" = 1
( 'x' is not valid here, because we are already inside of a string)
如果遇到[],则[]内的字符串可以出现任意字符,包括 =,
如果左侧字符不存在[],则第一个=就是划分的位置, 但是在=右侧出现"" 或者 {} 之前,再次出现=
那么此字符串为invalid expression, 比如 xyz=x=1
返回值,如果不是dict,返回 inputStr
否则,返回 [key,value],其中 key value 为一个字典的划分
'''
stripedStr = inputStr.strip()
if self.__isAStrWithQuote(stripedStr) or self.__isAStrWithBracket(stripedStr) or len(stripedStr) == 0 :
# 如果输入代表一个字符串, 例如"xyz=123",则一定不是dict型数据
return inputStr
if stripedStr.find('=') == -1:
return inputStr
else:
# might be a dict expression
if stripedStr[0] == '[':
# 如果字符串存在[]
# 找到对应 ] 的位置, 其后的第一个 = 为划分位置
leftBracket = inputStr.find('[')
# 从左侧找到[ 之后的第一个"
leftQuote = inputStr.find('"', leftBracket)
if leftQuote != -1:
if self.__isBlankInTwoIndex(inputStr, leftBracket, leftQuote):
# ["abc"] = 1 case
# " ] = 组合 确定了一个字典的划分
rightQuote = inputStr.find('"', leftQuote + 1)
rightBracket = inputStr.find(']', rightQuote + 1)
equalPos = inputStr.find('=',rightBracket + 1)
while (rightQuote < rightBracket < equalPos and self.__isBlankInTwoIndex(inputStr,rightQuote,rightBracket) and self.__isBlankInTwoIndex(inputStr,rightBracket,equalPos)) == False:
rightQuote = inputStr.find('"', rightQuote + 1)
rightBracket = inputStr.find(']', rightQuote + 1)
equalPos = inputStr.find('=', rightBracket + 1)
if rightQuote == -1 or rightBracket == -1 or equalPos == -1:
raise InvalidLuaTableError('invalide lua table express, [ "abx" d] or [" ads case: non-closed bracket for a key string')
else:
#[1] = "x" case
rightBracket = inputStr.find(']', leftBracket)
tmp = inputStr[leftBracket+1: rightBracket].strip()
if self.__isNumber(tmp) == False:
# 处理 不带引号的key 不为数字的异常
#print inputStr
raise InvalidLuaTableError('invalide lua table express, [x]=1 case: unquoted string as key in bracket')
else:
# [1] = 2 case
rightBracket = inputStr.find(']', leftBracket)
tmp = inputStr[leftBracket+1: rightBracket].strip()
if tmp.isdigit() == False:
#print inputStr
raise InvalidLuaTableError('invalide lua table express, [x]=1 case: unquoted string as key in bracket')
pos = inputStr.find('=', rightBracket)
if self.__isBlankInTwoIndex(inputStr, rightBracket, pos) == False:
# 处理 ["x"] abc = 1 的异常
raise InvalidLuaTableError(
'invalide lua table express, [x] abc = 1 case: extra string between ] and = ')
else:
# 如果 myStr不以[开头,则第一个=号,应该就是划分的位置
pos = inputStr.find('=')
# 在此种情况下,key的格式有特殊的要求:
# n ame = 1, 4name = 1 , nam#e = 1 均为错
key = inputStr[:pos].strip()
if key.find(' ') != -1:
#print inputStr, key
raise InvalidLuaTableError('found blank inside of a key string')
if key[0].isdigit():
#print inputStr, key
raise InvalidLuaTableError('found digit at the beginning of a key string')
for s in self.otherCharacterSet:
if key.find(s) != -1:
#print inputStr, key
raise InvalidLuaTableError('found other character in a key string')
# 测试字符串的有效性:不存在多个等号
# 尝试寻找第二个等号
pos2 = inputStr.find('=', pos + 1)
if pos2 != -1:
# 找到 第二个等号 后面的 第一个 " 或者 {
firstQuoteAfterEqual = inputStr.find('"', pos + 1)
firstBracketAfterEqual = inputStr.find('{', pos + 1)
firstSeperator = -1
if self.__isBlankInTwoIndex(inputStr, pos, firstQuoteAfterEqual):
firstSeperator = firstQuoteAfterEqual
if self.__isBlankInTwoIndex(inputStr, pos, firstBracketAfterEqual):
firstSeperator = firstBracketAfterEqual
if firstSeperator == -1:
raise InvalidLuaTableError('invalide lua table express, x==1 case: found two = in string')
# 如果等号在"或者{ 之前,则为错误的输入格式
if pos2 < firstSeperator:
# 如果第二个等号的位置,在左括弧的后面,则返回第一个等号的位置
# 作为划分的位置
raise InvalidLuaTableError('invalide lua table express, x == "123" or x == {123} case: found two = in string')
key = inputStr[:pos]
value = inputStr[pos+1:]
return [key, value]
def __isAStrWithQuote(self,myStr):
# 判断输入字符串是否被" " 包围,如果是,则认为myStr代表一个字符串
if len(myStr) > 1 and myStr[0] == '"' and myStr[len(myStr) - 1] == '"':
return True
else:
return False
def __isBlankInTwoIndex(self, myStr, start, end):
# 测试字符串 start 和 end 之间是否只有空格
tmp = myStr[start+1:end].strip()
if tmp == '':
return True
else:
return False