hutnparser.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. """
  2. Author: Bruno Barroca
  3. Date: October 2014
  4. Description: A top down parser
  5. Modifications by Daniel Riegelhaupt:
  6. *removed test input
  7. *changed pos to startpos because in my humble opinion it makes more sense to have a tupple (startpos, endpos) than (pos, endpos)
  8. *aded parameters to init: tab_size, line_position, hide_implicit
  9. - see init comments for more info on all otions
  10. - line_postion will change startpos and end Pos to instance of class Postion. (changed december 2014)
  11. *Added anonymous terminals: tokens do not have to be defined as tokens but can be typed directly in rules
  12. *changed interleave function to be deep, and start on START
  13. *changed position returned in tree to be relative to line numbers instead of the absolute one
  14. - Did the same for partialresults returned on syntax error change this is error results too
  15. - TODO check efficiency on the previous point checking the whole text for every position might be slow
  16. *Changed usage , instead of Parser(input, grammar).pars() it is now Parser(grammar).parse(input)
  17. - Added a self.reset() method for fields that need to be initializes again when parsing a new input
  18. *Changed findFailure and generateErrorReports:
  19. * i need the the rule/token name as well not only the error text
  20. * hidden elements (like for example comments and newline ) are not included in error reports if hide_implicit is set to true
  21. * same for the interleave rule
  22. """
  23. import re
  24. from copy import deepcopy
  25. from position import Position
  26. class Tree(object):
  27. def __init__(self, head, tail, startpos, endpos):
  28. self.head = head
  29. self.tail = tail
  30. self.startpos = startpos
  31. self.endpos = endpos
  32. self._tail = None
  33. self.inputfile = ""
  34. # IMPORTANT: self.replaced: replace_child defines self.replaced
  35. def is_rule(self):
  36. return self.head.islower()
  37. def is_token(self):
  38. return not self.is_rule()
  39. def get_tail(self):
  40. if self.is_rule():
  41. if not self._tail:
  42. self._tail = [t for t in self.get_raw_tail()
  43. if not t.head.startswith("implicit_autogenerated_")]
  44. return self._tail
  45. else:
  46. return self.get_raw_tail()
  47. def get_raw_tail(self):
  48. return self.tail
  49. def get_text(self, with_implicit=False):
  50. parts = []
  51. if with_implicit:
  52. tail = Tree.get_raw_tail
  53. else:
  54. tail = Tree.get_tail
  55. def post_order(tree):
  56. for child in tail(tree):
  57. if hasattr(child, "replaced"):
  58. child = child.replaced
  59. if isinstance(child, Tree):
  60. post_order(child)
  61. else:
  62. parts.append(child)
  63. post_order(self)
  64. return ''.join(parts)
  65. def get_child(self, name):
  66. for child in self.get_tail():
  67. if child.head == name:
  68. return child
  69. return None
  70. def get_children(self, name):
  71. children = []
  72. for child in self.get_tail():
  73. if child.head == name:
  74. children.append(child)
  75. return children
  76. def replace_child(self, old_child, new_child):
  77. new_child.replaced = old_child
  78. i = self.get_raw_tail().index(old_child)
  79. self.get_raw_tail()[i] = new_child
  80. i = self.get_tail().index(old_child)
  81. self.get_tail()[i] = new_child
  82. def get_tail_without(self, names):
  83. if self.is_rule():
  84. return [t for t in self.get_tail() if not t.head in names]
  85. else:
  86. return self.get_raw_tail()
  87. def __str__(self):
  88. return "(%s, %s) [%s]" % (
  89. self.head, str((self.startpos, self.endpos)),
  90. ", ".join([str(i) for i in self.get_raw_tail()]))
  91. class Parser(object):
  92. class Constants(object):
  93. Token = 'token'
  94. Production = 'prod'
  95. Success = 'success'
  96. Failure = 'failure'
  97. class LR(object):
  98. def __init__(self, seed, rulename, head, nextlr):
  99. self.seed = seed
  100. self.rule = rulename
  101. self.head = head
  102. self.next = nextlr
  103. def copy(self):
  104. return Parser.LR(self.seed, self.rule, self.head, self.next)
  105. class Head(object):
  106. def __init__(self, rulename, involved, evaluation):
  107. self.rule = rulename
  108. self.involved = involved
  109. self.evaluation = evaluation
  110. def __init__(self, grammar, **options):
  111. """
  112. creates a Parser for the given grammar
  113. :param grammar: An instance of the Grammar class
  114. :param options: the following options are supported:
  115. tab_size: default 1. sets the character size of a tab character
  116. hide_implicit: default False. when true implicit tokens are hidden from the returned parse tree and error message.
  117. Note that this this option will not override rules or tokens where the hidden variable has already been set manually in the Grammar class
  118. line_position: default False. when true we use line, column Position object instead of absolute position integer in the parse tree for startpos and endpos
  119. """
  120. #changed by Daniel: members that need to be initialized each time parse is a called have been put in def reset()
  121. #that method is called when the parse() method is called
  122. self.rules = deepcopy(grammar.rules)
  123. self.tokens = deepcopy(grammar.tokens)
  124. self.implicitList = [] #added by Daniel, set in hideImplict so that we can review the implicit list in case of error messages
  125. self.implictRuleName = ""
  126. #options Added by Daniel
  127. self.tabsize = int(options.pop('tab_size', 1)) #the character size of a tab
  128. self.hideImplicit = bool(options.pop('hide_implicit', False))
  129. #whether to hide implicit tokens and rules from the returned parse tree
  130. #Important note: this option will not override rules or tokens where the hidden variable has already been set manually
  131. self.linePosition = bool(options.pop('line_position', False))
  132. #if true the position of the returned parse tree will consist of a line and a column instead of the position in the string array
  133. #preprocess must happen after options, (after hideImplicit has been set)
  134. self.preprocess()
  135. def reset(self):
  136. self.input = ""
  137. self.memotable = {}
  138. self.failure = {}
  139. self.lrstack = None
  140. self.heads = {}
  141. self.countcard = {}
  142. def preprocess(self):
  143. #for elem in self.rules.keys(): #Changed by Daniel: we only check start because it's global
  144. elem = 'start'
  145. if elem in self.rules.keys():
  146. if ('interleave' in self.rules[elem]):
  147. ilist = self.rules[elem]['interleave']
  148. self.setHideImplicit(ilist, self.hideImplicit)
  149. self.interleave(self.rules[elem], ilist)
  150. def setHideImplicit(self, ilist, bool= False):
  151. if ilist:
  152. #ilist = ['?', '@rulename']
  153. rulename= ilist[1][1:]
  154. self.implictRuleName = rulename #used to hide later error reports later
  155. self.rules[rulename]['hidden'] = bool
  156. if rulename in self.rules:
  157. body = self.rules[rulename]['body']
  158. #body = [*, [| ,,,,]]
  159. elems= body[1][1:]
  160. self.implicitList = elems
  161. for elem in elems:
  162. l = None
  163. error = ''
  164. if elem[0] == '@':
  165. l = self.rules
  166. error = ' rule not found in grammar rules.'
  167. elif elem[0]== '$':
  168. l = self.tokens
  169. error = ' token not found in grammar rules.'
  170. #else: in this case it is an anonymous token,
  171. if l:
  172. name = elem[1:]
  173. if name in l:
  174. if not l[name].has_key('hidden'):
  175. #this method will not override anything the user has explicitly specified in the structure
  176. #if there is already a hidden value there it will be kept even if it is not the same one
  177. #an examples use case is whitespaces vs comments:
  178. #both can appear anywhere in the text and so are implicit in the grammar.
  179. #however we dont want spaces in the tree but we do want the comments
  180. l[name]['hidden'] = bool
  181. else:
  182. raise Exception(name + error)
  183. #else: Anon token can't be ignored for the moment unless we create an ignore list for it or something like that.
  184. else:
  185. raise Exception(rulename + ' rule not found in grammar rules.')
  186. def interleave(self, elem, ilist):
  187. #quick and simple interleaving method, will probably contain double interleaving
  188. #but this is as simple as i could make it without taking into account each and every case
  189. def quickInterLeave(lst, inter):
  190. newL = []
  191. newL.append(lst[0])
  192. isSeq = self.isSequence(lst[0])
  193. for item in lst[1:]:
  194. if (isinstance(item, list)):#a sublist
  195. newL.append(quickInterLeave(item,inter))
  196. else:
  197. if(item[0] == '@'): #rule
  198. rulename = item [1:]
  199. if rulename in self.rules:
  200. rule = self.rules[rulename]
  201. if not rule.has_key('visited') or rule['visited'] == False:
  202. self.interleave(rule, inter)
  203. else:
  204. raise Exception(rulename + ' rule not found in grammar rules.')
  205. """
  206. Else:
  207. pass
  208. in this case it is a token or anon token we dont need to do anything special,
  209. just add it to the list interleaved
  210. """
  211. if isSeq: # no need to complicate the data structure if the list is a sequence
  212. if not newL[-1] == inter:
  213. newL.append(inter)
  214. newL.append(item)
  215. newL.append(inter)
  216. else:
  217. newL.append(['.', inter,item ,inter])
  218. """
  219. This way in case the list is not a sequence this doesnt change the meaning of the list:
  220. example: t1, t2 are tokens, i is an optional whitespace being intereleaved
  221. [., t1, t2] -> [., i ,t1, i, t2]
  222. the meaning stays the same:
  223. t1 and t2 both have ot be found for the rule to apply regardless of the ws
  224. [|, t1, t2] -> [|, i ,t1, i, t2]
  225. the meaning changed: if i is encountered the or is satisfied:
  226. so instead we do -> [|, [., i ,t1, i,], [., i ,t2, i,]]
  227. note that while inter has been added to the data stricture 4 times it will only match
  228. for one option so it is not really duplicate.
  229. another way of writing this can be [., inter [|, t1, t2], inter ] but this is easier said than
  230. done especially for big (complex) data structures
  231. """
  232. return newL
  233. #the first thing we do is say that the item has been visited this will avoid infinite loop due to recursion
  234. elem['visited'] = True
  235. if (not 'body' in elem):
  236. return
  237. ls = elem['body']
  238. newbody = quickInterLeave(ls,ilist)
  239. elem['body'] = newbody
  240. def parse(self, text):
  241. self.reset() #Changed by Daniel receive text as param. instead of once at init so first we reset the fields
  242. self.input = text
  243. results = self.applyrule('@start', 0)
  244. if (results == [] or results[0]['endpos'] < len(self.input)):
  245. result = self.generateErrorReport()
  246. for elem in result['partialresults']: #Added by Daniel there was no post processing on partial results. I need it
  247. if elem['tree']: #with partial results the tree can be None
  248. elem['tree'] = IgnorePostProcessor(self.rules, self.tokens).visit(elem['tree'])
  249. if self.linePosition:
  250. # elem['tree'].startpos = 0
  251. # elem['tree'].endpos = 0
  252. elem['tree'] = Parser.PositionPostProcessor(self.convertToLineColumn).visit(elem['tree']) #Added by Daniel
  253. else:
  254. result = results[0]
  255. result.update({'status': Parser.Constants.Success})
  256. if result['tree'].head != 'start':
  257. result['tree'] = Tree('start', [result['tree']], result['tree'].startpos, result['tree'].endpos)
  258. result['tree'] = IgnorePostProcessor(self.rules, self.tokens).visit(result['tree'])
  259. if self.linePosition: #Added by Daniel
  260. result['tree'] = Parser.PositionPostProcessor(self.convertToLineColumn).visit(result['tree'])
  261. return result
  262. def convertToLineColumn(self, pos):
  263. line = 1
  264. column = 0
  265. l = len(self.input)
  266. for i in range(0, l):
  267. if (i > pos):
  268. break
  269. if self.input[i] == '\n':
  270. line += 1
  271. column = 0
  272. elif self.input[i] == '\t':
  273. column += self.tabsize #changed by Daniel: this used to be 4
  274. else:
  275. column += 1
  276. if pos >= l: #the end of the text
  277. """
  278. added by Daniel: needed for the case of the last word/character.
  279. Assume a text on one word 'foo'
  280. in absolute position the tree says word is from 1 to 4 (as always 'to' means not included)
  281. in this method we only count until the range so we would return line 1 col 1 to line 1 col 3
  282. but we need col 4
  283. we could just says pos == l but i think its better to say any position bigger than the text is simply the end of the text
  284. """
  285. column += 1
  286. return {'line': line, 'column': column}
  287. def findlargerresultat(self, pos):
  288. endpos = pos
  289. result = None
  290. for key in self.memotable.keys():
  291. elem = self.memotable[key]
  292. if (elem == []):
  293. continue
  294. if (elem[0]['startpos'] == pos and endpos < elem[0]['endpos']):
  295. endpos = elem[0]['endpos']
  296. result = elem[0]
  297. return result
  298. def generateErrorReport(self):
  299. # consult the memotable and collect contiguities until endpos
  300. endpos = len(self.input) - 1
  301. pos = 0
  302. elems = []
  303. while pos <= endpos:
  304. elem = self.findlargerresultat(pos)
  305. if (not elem or (elem and elem['endpos'] == pos)):
  306. break
  307. pos = elem['endpos']
  308. elems.append(elem)
  309. if (pos <= endpos):
  310. elems.append({'tree': None, 'startpos': pos, 'endpos': endpos})
  311. elem = self.getFirstBiggestSpan(elems)
  312. if elem is None:
  313. return {'status': Parser.Constants.Failure, 'line': 0, 'column': 0, 'text': "Empty input file", 'partialresults': [], 'grammarelements': None}
  314. reasons = self.findFailure(elem['startpos'], elem['endpos'])
  315. if (reasons == []):
  316. pos -= 1
  317. else:
  318. pos = reasons[0]['startpos']
  319. read = self.input[pos:pos + 1]
  320. linecolumn = self.convertToLineColumn(pos)
  321. message = 'Syntax error at line ' + str(linecolumn['line']) + ' and column ' + str(linecolumn['column']) + '. '
  322. keys = []
  323. if (not reasons == []):
  324. first = True
  325. for reason in reasons:
  326. if (first):
  327. message += 'Expected ' + reason['text']
  328. first = False
  329. else:
  330. message += ' or ' + reason['text']
  331. keys.append(reason['key'])
  332. message += '. Instead read: ' + repr(read) + '.'
  333. else:
  334. message += 'Read: \'' + read + '\'.'
  335. return {'status': Parser.Constants.Failure, 'line': linecolumn['line'], 'column': linecolumn['column'],
  336. 'text': message, 'partialresults': elems, 'grammarelements': keys}
  337. def getFirstBiggestSpan(self, elems):
  338. biggestspan = 0
  339. result = None
  340. for elem in elems:
  341. span = elem['endpos'] - elem['startpos']
  342. if (biggestspan < span):
  343. result = elem
  344. span = biggestspan
  345. return result
  346. def findFailure(self, pos, endpos):
  347. posreasons = []
  348. endposreasons = []
  349. #changed by Daniel:
  350. #* i need the key as well for autocomplete so in stead of appending elem i return a new dictionary with elem and the key inside
  351. #* checks both condition for posreasons and endposreasons in one for loop instead of 2
  352. #* do not cosider keys that are hidden
  353. for key in self.failure.keys():
  354. #keys are given starting either with $ for tokens or @ for rules
  355. #howver with the the given metagrammar Tokens are all caps and rules are all in small letters so there cant be an overlapp
  356. #and we can safely test both
  357. if self.hideImplicit and\
  358. (('$' + key in self.implicitList) or ('@' + key in self.implicitList) or (key == self.implictRuleName)):
  359. continue
  360. else:
  361. elem = self.failure[key]
  362. if (elem['startpos'] == pos and not elem['text'] == ''):
  363. posreasons.append({'key': key, 'startpos': elem['startpos'] , 'text': elem['text'] })
  364. if (elem['startpos'] == endpos and not elem['text'] == ''):
  365. endposreasons.append({'key': key, 'startpos': elem['startpos'] , 'text': elem['text'] })
  366. if (len(endposreasons) < len(posreasons)):
  367. return posreasons
  368. else:
  369. return endposreasons
  370. def setupLR(self, rule, elem):
  371. if (elem.head == None):
  372. elem.head = Parser.Head(rule, [], [])
  373. s = self.lrstack
  374. while s and not s.rule == elem.head.rule:
  375. s.head = elem.head
  376. if (not s.rule in elem.head.involved):
  377. elem.head.involved.append(s.rule)
  378. s = s.next
  379. def recall(self, rule, j):
  380. newresults = []
  381. if ((rule, j) in self.memotable):
  382. newresults = self.memotable[(rule, j)]
  383. h = None
  384. if (j in self.heads):
  385. h = self.heads[j]
  386. if (not h):
  387. return newresults
  388. if (newresults == [] and not rule in (h.involved + [h.rule])):
  389. return [] # [{'tree': [], 'startpos': j, 'endpos': j}]
  390. if (rule in h.evaluation):
  391. h.evaluation.remove(rule)
  392. newresults = self.eval(rule, j)
  393. self.memotable.update({(rule, j): newresults})
  394. return newresults
  395. def applyrule(self, rule, j):
  396. overallresults = []
  397. newresults = self.recall(rule, j)
  398. if (not newresults == []):
  399. memoresults = []
  400. for elem in newresults:
  401. if (isinstance(elem['tree'], Parser.LR)):
  402. self.setupLR(rule, elem['tree'])
  403. memoresults += elem['tree'].seed
  404. else:
  405. overallresults.append(elem)
  406. if (not memoresults == []):
  407. self.memotable.update({(rule, j): memoresults})
  408. return memoresults
  409. return overallresults
  410. else:
  411. #lr = Parser.LR([], rule, None, deepcopy(self.lrstack))
  412. lr = Parser.LR([], rule, None, None if not self.lrstack else self.lrstack.copy())
  413. self.lrstack = lr
  414. self.memotable.update({(rule, j): [{'tree': lr, 'startpos': j, 'endpos': j}]})
  415. newresults = self.eval(rule, j)
  416. self.lrstack = self.lrstack.next
  417. memoresults = []
  418. if ((rule, j) in self.memotable):
  419. memoresults = self.memotable[(rule, j)]
  420. for melem in memoresults:
  421. if (isinstance(melem['tree'], Parser.LR) and melem['tree'].head):
  422. melem['tree'].seed = newresults
  423. r = self.lr_answer(rule, j, melem)
  424. if (not r == []):
  425. overallresults += r
  426. if (overallresults != []): # prefer grown results
  427. return overallresults
  428. self.memotable.update({(rule, j): newresults})
  429. return newresults
  430. def lr_answer(self, rule, pos, melem):
  431. h = melem['tree'].head
  432. if (not h.rule == rule):
  433. return melem['tree'].seed
  434. else:
  435. melems = melem['tree'].seed
  436. result = []
  437. for melem_i in melems:
  438. if (not melem_i['tree'] == None):
  439. result.append(melem_i)
  440. if (result == []):
  441. return []
  442. else:
  443. newresult = []
  444. for melem_i in result:
  445. newresult.append(self.growLR(rule, pos, melem_i, h))
  446. return newresult
  447. def growLR(self, rule, pos, melem, head=None):
  448. self.heads.update({pos: head})
  449. while (True):
  450. overallresults = []
  451. head.evaluation = deepcopy(head.involved)
  452. newresults = self.eval(rule, pos)
  453. for elem in newresults:
  454. if (elem['endpos'] > melem['endpos']):
  455. melem = elem
  456. overallresults.append(elem)
  457. if (overallresults == []):
  458. self.heads.update({pos: None})
  459. return melem
  460. self.memotable.update({(rule, pos): overallresults})
  461. def eval(self, rulename, j):
  462. # Returns [{'tree':Tree(head=rulename, tail=[...], startpos=j, endpos=x), 'startpos':j, 'endpos':x}]
  463. # Raises Exception if there is no such token/rule
  464. if (rulename[0] == '@'):
  465. rulename = rulename[1:]
  466. if (not rulename in self.rules):
  467. raise Exception(rulename + ' rule not found in grammar rules.')
  468. rule = self.rules[rulename]
  469. elif (rulename[0] == '$'):
  470. rulename = rulename[1:]
  471. if (not rulename in self.tokens):
  472. raise Exception(rulename + ' token not found in grammar tokens.')
  473. rule = self.tokens[rulename]
  474. else:
  475. # raise Exception('Plain terminals not allowed inside grammar rules: ' + str(rulename))
  476. # we create an anonymous token rule
  477. # we can write whatever we want as fake type as long as it is not equal to the type of the prodcution rule
  478. # or to that of the token
  479. rule = {'type': 'anonymous_token'}
  480. if (self.isType(rule, Parser.Constants.Production)):
  481. newresults = []
  482. results = self.eval_body(rulename, rule['body'], j)
  483. for r in results:
  484. if (r['tree']):
  485. head = r['tree'].head
  486. if(head == '*' or head == '+' or head == '?' or head == '|' or head == '.'):
  487. newr = {'tree': Tree(rulename, [r['tree']], r['startpos'], r['endpos']), 'startpos': r['startpos'],
  488. 'endpos': r['endpos']}
  489. r = newr
  490. newresults.append(r)
  491. elif (self.isType(rule, Parser.Constants.Token)):
  492. newresults = self.term(rulename, j)
  493. else: ##Changed by Daniel: if not a production rule or defined token we try an anonymous token:
  494. newresults = self.anonTerm(rulename, j)
  495. return newresults
  496. def eval_body(self, rulename, ls, j):
  497. # Delegates the task to sub-functions: alt, seq, opt, many, more, card
  498. # Returns
  499. # Raises Exception if the first element in the body is not in {'|', '.', '?', '*', '+', '#'}
  500. if (self.isAlternative(ls[0])):
  501. return self.alt(rulename, ls[1:], j)
  502. elif (self.isSequence(ls[0])):
  503. return self.seq(rulename, ls[1:], j)
  504. elif (self.isOptional(ls[0])):
  505. return self.opt(rulename, ls[1:], j)
  506. elif (self.isMany(ls[0])):
  507. return self.many(rulename, ls[1:], j)
  508. elif (self.isMore(ls[0])):
  509. return self.more(rulename, ls[1:], j)
  510. elif (self.isCard(ls[0])):
  511. return self.card(rulename, ls[0][1:], ls[1:], j)
  512. raise Exception('Unrecognized grammar expression: ' + str(ls[0]))
  513. def isSequence(self, operator):
  514. return operator == '.'
  515. def isAlternative(self, operator):
  516. return operator == '|'
  517. def isMany(self, operator):
  518. return operator == '*'
  519. def isCard(self, operator):
  520. return operator.startswith('#')
  521. def isMore(self, operator):
  522. return operator == '+'
  523. def isOptional(self, operator):
  524. return operator == '?'
  525. def isType(self, rule, oftype):
  526. if (rule['type'] == oftype):
  527. return True
  528. def term(self, rulename, j):
  529. if (j >= len(self.input)):
  530. errortext = ''
  531. if (rulename in self.tokens and 'errortext' in self.tokens[rulename]):
  532. errortext = self.tokens[rulename]['errortext']
  533. self.failure.update({rulename: {'startpos': j, 'text': errortext}})
  534. return []
  535. rule = self.tokens[rulename]
  536. mobj = re.match(rule['reg'], self.input[j:])
  537. #Changed by daniel instead of re.match(reg) did re.match(re.compile(reg).patern)
  538. #this is to avoid problems with \ before i did this i had the match the character \ by doing [\\\\]
  539. # because to write only two slashes it would have to be r'[\\]' which cant be done directly in hte grammar so it had to be in string form
  540. #this way reading [\\] will be interpreted correctly instead of giving an error like it used to
  541. if (not mobj):
  542. # this is a failure! nice to register!
  543. self.failure.update({rulename: {'startpos': j, 'text': self.tokens[rulename]['errortext']}})
  544. return []
  545. return [{'tree': Tree(rulename, [mobj.group()], j, j + mobj.end()), 'startpos': j, 'endpos': j + mobj.end()}]
  546. def anonTerm(self, term, j):
  547. """
  548. #Changed by Daniel: added this whole method.
  549. Anonymous term to allow for direct terminals in rules
  550. (write 'Foo' directly instead of having to deine a FOO token)
  551. """
  552. qt = '\''
  553. name = qt + term + qt
  554. if (j >= len(self.input)):
  555. self.failure.update({ name : {'startpos': j, 'text': name}})
  556. return []
  557. mobj = re.match(term, self.input[j:])
  558. if (not mobj):
  559. # this is a failure! nice to register!
  560. self.failure.update({ name : {'startpos': j, 'text': name }})
  561. return []
  562. return [{'tree': Tree(name , [mobj.group()], j, j + mobj.end()), 'startpos': j, 'endpos': j + mobj.end()}]
  563. def many(self, rulename, ls, j):
  564. rule_i = ls[0]
  565. if (isinstance(rule_i, list)):
  566. results = self.eval_body('*', rule_i, j)
  567. else:
  568. results = self.applyrule(rule_i, j)
  569. if (results == []):
  570. return [{'tree': None, 'startpos': j, 'endpos': j}]
  571. seq = ['.'] + ls + [['*'] + ls]
  572. results = self.eval_body('*', seq, j)
  573. overall_results = []
  574. for r in results:
  575. if (r['tree']):
  576. if (len(r['tree'].tail) > 1):
  577. left = r['tree'].tail[0]
  578. right = r['tree'].tail[1].tail
  579. r['tree'].tail = [left] + right
  580. overall_results.append(r)
  581. return overall_results
  582. def more(self, rulename, ls, j):
  583. rule_i = ls[0]
  584. if (isinstance(rule_i, list)):
  585. results = self.eval_body('+', rule_i, j)
  586. else:
  587. results = self.applyrule(rule_i, j)
  588. if (results == []):
  589. return []
  590. seq = ['.'] + ls + [['*'] + ls]
  591. results = self.eval_body('+', seq, j)
  592. overall_results = []
  593. for r in results:
  594. if (r['tree']):
  595. if (len(r['tree'].tail) > 1):
  596. left = r['tree'].tail[0]
  597. right = r['tree'].tail[1].tail
  598. r['tree'].tail = [left] + right
  599. overall_results.append(r)
  600. return overall_results
  601. def opt(self, rulename, ls, j):
  602. if (j >= len(self.input)):
  603. errortext = ''
  604. if (rulename in self.rules and 'errortext' in self.rules[rulename]):
  605. errortext = self.rules[rulename]['errortext']
  606. else:
  607. for item in ls:
  608. if ((not isinstance(item[1:], list)) and item[1:] in self.rules):
  609. errortext = self.rules[item[1:]]['errortext']
  610. self.failure.update({rulename: {'startpos': j, 'text': errortext}})
  611. return [{'tree': None, 'startpos': j, 'endpos': j}]
  612. results = []
  613. rule_i = ls[0]
  614. if (isinstance(rule_i, list)):
  615. results = self.eval_body('?', rule_i, j)
  616. else:
  617. results = self.applyrule(rule_i, j)
  618. if (not results == []):
  619. return results
  620. # empty case
  621. return [{'tree': None, 'startpos': j, 'endpos': j}]
  622. def card(self, rulename, cardrule, ls, j):
  623. count = 0
  624. delta = 1
  625. # a# a#(-1) #indent, #(-1)indent
  626. group = re.match('\((?P<delta>[-+]?\d+)\)(?P<rule>\S+)',cardrule)
  627. if(group):
  628. cardrule = group.group('rule')
  629. delta = int(group.group('delta'))
  630. if (not cardrule in self.countcard):
  631. count = delta
  632. self.countcard.update({cardrule: {j: count}})
  633. else:
  634. if not j in self.countcard[cardrule]: # # if we already know the count for j, then ignore..
  635. d = self.countcard[cardrule]
  636. lastcount = 0
  637. for i in range(0, j):
  638. if i in d:
  639. lastcount = d[i]
  640. count = lastcount + delta
  641. d.update({j: count})
  642. else:
  643. count = self.countcard[cardrule][j]
  644. results = []
  645. rule_i = '@' + cardrule
  646. if(count == 0):
  647. results = [{'tree': None, 'startpos': j, 'endpos': j}]
  648. else:
  649. for i in range(0, count):
  650. if (results == []):
  651. if (isinstance(rule_i, list)):
  652. newresults = self.eval_body(rulename, rule_i, j)
  653. else:
  654. newresults = self.applyrule(rule_i, j)
  655. if (newresults == []):
  656. del self.countcard[cardrule][j]
  657. return []
  658. newresults = self.merge(rulename, newresults, {'startpos': j, 'endpos': j})
  659. else:
  660. for elem_p in results:
  661. if (isinstance(rule_i, list)):
  662. newresults = self.eval_body(rulename, rule_i, elem_p['endpos'])
  663. else:
  664. newresults = self.applyrule(rule_i, elem_p['endpos'])
  665. if (newresults == []):
  666. del self.countcard[cardrule][j]
  667. return []
  668. newresults = self.merge(rulename, newresults, elem_p)
  669. results = newresults
  670. for rule_i in ls:
  671. for elem_p in results:
  672. if (isinstance(rule_i, list)):
  673. newresults = self.eval_body(rulename, rule_i, elem_p['endpos'])
  674. else:
  675. newresults = self.applyrule(rule_i, elem_p['endpos'])
  676. if (newresults == []):
  677. del self.countcard[cardrule][j]
  678. return []
  679. newresults = self.merge(rulename, newresults, elem_p)
  680. results = newresults
  681. del self.countcard[cardrule][j]
  682. return results
  683. def seq(self, rulename, ls, j):
  684. #
  685. results = []
  686. for rule_i in ls:
  687. if (results == []):
  688. if (isinstance(rule_i, list)):
  689. newresults = self.eval_body('.', rule_i, j)
  690. else:
  691. newresults = self.applyrule(rule_i, j)
  692. if (newresults == []):
  693. return []
  694. newresults = self.merge('.', newresults, {'startpos': j, 'endpos': j})
  695. else:
  696. for elem_p in results:
  697. if (isinstance(rule_i, list)):
  698. newresults = self.eval_body('.', rule_i, elem_p['endpos'])
  699. else:
  700. newresults = self.applyrule(rule_i, elem_p['endpos'])
  701. if (newresults == []):
  702. return []
  703. newresults = self.merge('.', newresults, elem_p)
  704. results = newresults
  705. return results
  706. def merge(self, rulename, newres, elem_p):
  707. # Brief: tail of each new tree needs to be prepended with tail of the previous tree
  708. # rulename: becomes the head of each tree in the returned list
  709. # newres: may have more than one tree in case of alt operator: 'x' ('a' | 'b') 'y'
  710. # tail of each new tree needs to be prepended with tail of previous tree
  711. # Returns same list as eval: [{'tree':Tree(head=rulename, tail=[...], startpos=j, endpos=x), 'startpos':j, 'endpos':x}]
  712. results = []
  713. for elem_n in newres:
  714. tail = []
  715. if ('tree' in elem_p and elem_p['tree']):
  716. tail += elem_p['tree'].tail
  717. if ('tree' in elem_n and elem_n['tree']):
  718. tail.append(elem_n['tree'])
  719. value = {'tree': Tree(rulename, tail, elem_p['startpos'], elem_n['endpos']), 'startpos': elem_p['startpos'],
  720. 'endpos': elem_n['endpos']}
  721. results += [value]
  722. return results
  723. def alt(self, rulename, ls, j):
  724. # Evaluates all alternatives using eval_body or applyrule
  725. # Returns same list as eval: [{'tree':Tree(head=rulename, tail=[...], startpos=j, endpos=x), 'startpos':j, 'endpos':x}]
  726. overall_results = []
  727. results = [] # TODO: remove this variable as it's never used
  728. for rule_i in ls:
  729. if (isinstance(rule_i, list)):
  730. newresults = self.eval_body('|', rule_i, j)
  731. else:
  732. newresults = self.applyrule(rule_i, j)
  733. overall_results += newresults
  734. return overall_results
  735. class PositionPostProcessor(object):
  736. """
  737. This post processor changes absolute position (place in the parsed string )to a line, column position
  738. added by Daniel
  739. """
  740. """
  741. efficiency note:
  742. how effective is this. this might be slowing things down quit a bit having to calculate that for everything
  743. 1) an alternative would be use the method only for the leaves, and that traverse the tree bottom up to create
  744. the interval using the left most and right most children of each subtree. but since tat involves extra tree
  745. traversal that might not help that much.
  746. 2) another thing that might improve efficiency is to create change the position calculating method:
  747. create one that doesnt scan the whole text for new line each time we calculate a position,
  748. but creates a table of them the first time.
  749. we can calculate the line by returning the index in the table of the the new line the closest to the given
  750. position and the column is the difference between the position of that newline and the column (maybe + or - 1,
  751. check that)
  752. in case this method doesn't slow things down too much ignore this
  753. """
  754. def __init__(self, method):
  755. self.calcPosMethod = method
  756. def inner_visit(self,tree):
  757. startDic = self.calcPosMethod(tree.startpos)
  758. endDic = self.calcPosMethod(tree.endpos)
  759. tree.startpos = Position(startDic["line"], startDic["column"])
  760. tree.endpos = Position(endDic["line"], endDic["column"])
  761. for item in tree.tail:
  762. if (isinstance(item, Tree)):
  763. self.inner_visit(item)
  764. def visit(self, tree):
  765. if tree:
  766. self.inner_visit(tree)
  767. return tree
  768. class DefaultPrinter(object):
  769. def __init__(self, output='console'):
  770. self.outputStream = ''
  771. self.output = output
  772. def inner_visit(self, tree):
  773. for item in tree.tail:
  774. if (isinstance(item, Tree)):
  775. self.inner_visit(item)
  776. else:
  777. self.outputStream += item
  778. def visit(self, tree):
  779. self.inner_visit(tree)
  780. if (self.output == 'console'):
  781. print self.outputStream
  782. class PrettyPrinter(object):
  783. def __init__(self, output='console'):
  784. self.outputStream = ''
  785. self.output = output
  786. self.tabcount = -1
  787. def tab(self):
  788. tabspace = ''
  789. for i in range(0, self.tabcount):
  790. tabspace += ' '
  791. return tabspace
  792. def inner_visit(self, tree):
  793. self.tabcount += 1
  794. self.outputStream += self.tab()
  795. self.outputStream += 'node ' + tree.head + ':\n'
  796. for item in tree.tail:
  797. if (isinstance(item, Tree)):
  798. self.inner_visit(item)
  799. else:
  800. self.tabcount += 1
  801. self.outputStream += self.tab() + item + ' @' + str(tree.startpos) + ' to ' + str(
  802. tree.endpos) + ' \n'
  803. self.tabcount -= 1
  804. self.tabcount -= 1
  805. def visit(self, tree):
  806. self.inner_visit(tree)
  807. if (self.output == 'console'):
  808. print self.outputStream
  809. class IgnorePostProcessor(object):
  810. def __init__(self, rules, tokens):
  811. self.rules = rules
  812. self.tokens = tokens
  813. def inner_visit(self, tree):
  814. results = []
  815. if (isinstance(tree, Tree)):
  816. if (self.isHidden(tree.head)):
  817. for item in tree.tail:
  818. ivlist = []
  819. ivresult = self.inner_visit(item)
  820. for elem in ivresult:
  821. if (isinstance(elem, Tree)):
  822. ivlist += [elem]
  823. results += ivlist
  824. else:
  825. tlist = []
  826. for item in tree.tail:
  827. tlist += self.inner_visit(item)
  828. tree.tail = tlist
  829. results += [tree]
  830. return results
  831. return [tree]
  832. def visit(self, tree):
  833. # start cannot be hidden
  834. tlist = []
  835. for item in tree.tail:
  836. tlist += self.inner_visit(item)
  837. tree.tail = tlist
  838. return tree
  839. def isHidden(self, head):
  840. if (head == '*' or head == '+' or head == '?' or head == '|' or head == '.'):
  841. return True
  842. if (head in self.rules):
  843. return 'hidden' in self.rules[head] and self.rules[head]['hidden']
  844. elif (head in self.tokens): #Changed by Daniel: added elif condition and return false otherwise, need for anon tokens
  845. return 'hidden' in self.tokens[head] and self.tokens[head]['hidden']
  846. else:
  847. return False