hutnparser.py 39 KB

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