hutnparser.py 40 KB

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