hutnparser.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. print("Results: " + str(len(results)))
  253. if len(results) > 1:
  254. # Handle ambiguity
  255. from prettyprint_visitor import PrettyPrintVisitor
  256. for p in results:
  257. print("===================================")
  258. print("VISIT RESULT")
  259. print("===================================")
  260. visitor = PrettyPrintVisitor([])
  261. visitor.visit(p["tree"])
  262. print(visitor.dump())
  263. result = self.generateErrorReport()
  264. elif (results == [] or results[0]['endpos'] < len(self.input)):
  265. result = self.generateErrorReport()
  266. for elem in result['partialresults']: #Added by Daniel there was no post processing on partial results. I need it
  267. if elem['tree']: #with partial results the tree can be None
  268. elem['tree'] = IgnorePostProcessor(self.rules, self.tokens).visit(elem['tree'])
  269. if self.linePosition:
  270. # elem['tree'].startpos = 0
  271. # elem['tree'].endpos = 0
  272. elem['tree'] = Parser.PositionPostProcessor(self.convertToLineColumn).visit(elem['tree']) #Added by Daniel
  273. elif len(results) == 1:
  274. result = results[0]
  275. result.update({'status': Parser.Constants.Success})
  276. if result['tree'].head != 'start':
  277. result['tree'] = Tree('start', [result['tree']], result['tree'].startpos, result['tree'].endpos)
  278. result['tree'] = IgnorePostProcessor(self.rules, self.tokens).visit(result['tree'])
  279. if self.linePosition: #Added by Daniel
  280. result['tree'] = Parser.PositionPostProcessor(self.convertToLineColumn).visit(result['tree'])
  281. return result
  282. def convertToLineColumn(self, pos):
  283. line = 1
  284. column = 0
  285. l = len(self.input)
  286. for i in range(0, l):
  287. if (i > pos):
  288. break
  289. if self.input[i] == '\n':
  290. line += 1
  291. column = 0
  292. elif self.input[i] == '\t':
  293. column += self.tabsize #changed by Daniel: this used to be 4
  294. else:
  295. column += 1
  296. if pos >= l: #the end of the text
  297. """
  298. added by Daniel: needed for the case of the last word/character.
  299. Assume a text on one word 'foo'
  300. in absolute position the tree says word is from 1 to 4 (as always 'to' means not included)
  301. in this method we only count until the range so we would return line 1 col 1 to line 1 col 3
  302. but we need col 4
  303. 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
  304. """
  305. column += 1
  306. return {'line': line, 'column': column}
  307. def findlargerresultat(self, pos):
  308. endpos = pos
  309. result = None
  310. for key in self.memotable.keys():
  311. elem = self.memotable[key]
  312. if (elem == []):
  313. continue
  314. if (elem[0]['startpos'] == pos and endpos < elem[0]['endpos']):
  315. endpos = elem[0]['endpos']
  316. result = elem[0]
  317. return result
  318. def generateErrorReport(self):
  319. # consult the memotable and collect contiguities until endpos
  320. endpos = len(self.input) - 1
  321. pos = 0
  322. elems = []
  323. while pos <= endpos:
  324. elem = self.findlargerresultat(pos)
  325. if (not elem or (elem and elem['endpos'] == pos)):
  326. break
  327. pos = elem['endpos']
  328. elems.append(elem)
  329. if (pos <= endpos):
  330. elems.append({'tree': None, 'startpos': pos, 'endpos': endpos})
  331. elem = self.getFirstBiggestSpan(elems)
  332. if elem is None:
  333. return {'status': Parser.Constants.Failure, 'line': 0, 'column': 0, 'text': "Empty input file", 'partialresults': [], 'grammarelements': None}
  334. reasons = self.findFailure(elem['startpos'], elem['endpos'])
  335. if (reasons == []):
  336. pos -= 1
  337. else:
  338. pos = reasons[0]['startpos']
  339. read = self.input[pos:pos + 1]
  340. linecolumn = self.convertToLineColumn(pos)
  341. message = 'Syntax error at line ' + str(linecolumn['line']) + ' and column ' + str(linecolumn['column']) + '. '
  342. keys = []
  343. if (not reasons == []):
  344. first = True
  345. for reason in reasons:
  346. if (first):
  347. message += 'Expected ' + reason['text']
  348. first = False
  349. else:
  350. message += ' or ' + reason['text']
  351. keys.append(reason['key'])
  352. message += '. Instead read: ' + repr(read) + '.'
  353. else:
  354. message += 'Read: \'' + read + '\'.'
  355. return {'status': Parser.Constants.Failure, 'line': linecolumn['line'], 'column': linecolumn['column'],
  356. 'text': message, 'partialresults': elems, 'grammarelements': keys}
  357. def getFirstBiggestSpan(self, elems):
  358. biggestspan = 0
  359. result = None
  360. for elem in elems:
  361. span = elem['endpos'] - elem['startpos']
  362. if (biggestspan < span):
  363. result = elem
  364. span = biggestspan
  365. return result
  366. def findFailure(self, pos, endpos):
  367. posreasons = []
  368. endposreasons = []
  369. #changed by Daniel:
  370. #* 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
  371. #* checks both condition for posreasons and endposreasons in one for loop instead of 2
  372. #* do not cosider keys that are hidden
  373. for key in self.failure.keys():
  374. #keys are given starting either with $ for tokens or @ for rules
  375. #howver with the the given metagrammar Tokens are all caps and rules are all in small letters so there cant be an overlapp
  376. #and we can safely test both
  377. if self.hideImplicit and\
  378. (('$' + key in self.implicitList) or ('@' + key in self.implicitList) or (key == self.implictRuleName)):
  379. continue
  380. else:
  381. elem = self.failure[key]
  382. if (elem['startpos'] == pos and not elem['text'] == ''):
  383. posreasons.append({'key': key, 'startpos': elem['startpos'] , 'text': elem['text'] })
  384. if (elem['startpos'] == endpos and not elem['text'] == ''):
  385. endposreasons.append({'key': key, 'startpos': elem['startpos'] , 'text': elem['text'] })
  386. if (len(endposreasons) < len(posreasons)):
  387. return posreasons
  388. else:
  389. return endposreasons
  390. def setupLR(self, rule, elem):
  391. if (elem.head == None):
  392. elem.head = Parser.Head(rule, [], [])
  393. s = self.lrstack
  394. while s and not s.rule == elem.head.rule:
  395. s.head = elem.head
  396. if (not s.rule in elem.head.involved):
  397. elem.head.involved.append(s.rule)
  398. s = s.next
  399. def recall(self, rule, j):
  400. newresults = []
  401. if ((rule, j) in self.memotable):
  402. newresults = self.memotable[(rule, j)]
  403. h = None
  404. if (j in self.heads):
  405. h = self.heads[j]
  406. if (not h):
  407. return newresults
  408. if (newresults == [] and not rule in (h.involved + [h.rule])):
  409. return [] # [{'tree': [], 'startpos': j, 'endpos': j}]
  410. if (rule in h.evaluation):
  411. h.evaluation.remove(rule)
  412. newresults = self.eval(rule, j)
  413. self.memotable.update({(rule, j): newresults})
  414. return newresults
  415. def applyrule(self, rule, j):
  416. overallresults = []
  417. newresults = self.recall(rule, j)
  418. if (not newresults == []):
  419. memoresults = []
  420. for elem in newresults:
  421. if (isinstance(elem['tree'], Parser.LR)):
  422. self.setupLR(rule, elem['tree'])
  423. memoresults += elem['tree'].seed
  424. else:
  425. overallresults.append(elem)
  426. if (not memoresults == []):
  427. self.memotable.update({(rule, j): memoresults})
  428. return memoresults
  429. return overallresults
  430. else:
  431. #lr = Parser.LR([], rule, None, deepcopy(self.lrstack))
  432. lr = Parser.LR([], rule, None, None if not self.lrstack else self.lrstack.copy())
  433. self.lrstack = lr
  434. self.memotable.update({(rule, j): [{'tree': lr, 'startpos': j, 'endpos': j}]})
  435. newresults = self.eval(rule, j)
  436. self.lrstack = self.lrstack.next
  437. memoresults = []
  438. if ((rule, j) in self.memotable):
  439. memoresults = self.memotable[(rule, j)]
  440. for melem in memoresults:
  441. if (isinstance(melem['tree'], Parser.LR) and melem['tree'].head):
  442. melem['tree'].seed = newresults
  443. r = self.lr_answer(rule, j, melem)
  444. if (not r == []):
  445. overallresults += r
  446. if (overallresults != []): # prefer grown results
  447. return overallresults
  448. self.memotable.update({(rule, j): newresults})
  449. return newresults
  450. def lr_answer(self, rule, pos, melem):
  451. h = melem['tree'].head
  452. if (not h.rule == rule):
  453. return melem['tree'].seed
  454. else:
  455. melems = melem['tree'].seed
  456. result = []
  457. for melem_i in melems:
  458. if (not melem_i['tree'] == None):
  459. result.append(melem_i)
  460. if (result == []):
  461. return []
  462. else:
  463. newresult = []
  464. for melem_i in result:
  465. newresult.append(self.growLR(rule, pos, melem_i, h))
  466. return newresult
  467. def growLR(self, rule, pos, melem, head=None):
  468. self.heads.update({pos: head})
  469. while (True):
  470. overallresults = []
  471. head.evaluation = deepcopy(head.involved)
  472. newresults = self.eval(rule, pos)
  473. for elem in newresults:
  474. if (elem['endpos'] > melem['endpos']):
  475. melem = elem
  476. overallresults.append(elem)
  477. if (overallresults == []):
  478. self.heads.update({pos: None})
  479. return melem
  480. self.memotable.update({(rule, pos): overallresults})
  481. def eval(self, rulename, j):
  482. # Returns [{'tree':Tree(head=rulename, tail=[...], startpos=j, endpos=x), 'startpos':j, 'endpos':x}]
  483. # Raises Exception if there is no such token/rule
  484. if (rulename[0] == '@'):
  485. rulename = rulename[1:]
  486. if (not rulename in self.rules):
  487. raise Exception(rulename + ' rule not found in grammar rules.')
  488. rule = self.rules[rulename]
  489. elif (rulename[0] == '$'):
  490. rulename = rulename[1:]
  491. if (not rulename in self.tokens):
  492. raise Exception(rulename + ' token not found in grammar tokens.')
  493. rule = self.tokens[rulename]
  494. else:
  495. # raise Exception('Plain terminals not allowed inside grammar rules: ' + str(rulename))
  496. # we create an anonymous token rule
  497. # we can write whatever we want as fake type as long as it is not equal to the type of the prodcution rule
  498. # or to that of the token
  499. rule = {'type': 'anonymous_token'}
  500. if (self.isType(rule, Parser.Constants.Production)):
  501. newresults = []
  502. results = self.eval_body(rulename, rule['body'], j)
  503. for r in results:
  504. if (r['tree']):
  505. head = r['tree'].head
  506. if(head == '*' or head == '+' or head == '?' or head == '|' or head == '.'):
  507. newr = {'tree': Tree(rulename, [r['tree']], r['startpos'], r['endpos']), 'startpos': r['startpos'],
  508. 'endpos': r['endpos']}
  509. r = newr
  510. newresults.append(r)
  511. elif (self.isType(rule, Parser.Constants.Token)):
  512. newresults = self.term(rulename, j)
  513. else: ##Changed by Daniel: if not a production rule or defined token we try an anonymous token:
  514. newresults = self.anonTerm(rulename, j)
  515. return newresults
  516. def eval_body(self, rulename, ls, j):
  517. # Delegates the task to sub-functions: alt, seq, opt, many, more, card
  518. # Returns
  519. # Raises Exception if the first element in the body is not in {'|', '.', '?', '*', '+', '#'}
  520. if (self.isAlternative(ls[0])):
  521. return self.alt(rulename, ls[1:], j)
  522. elif (self.isSequence(ls[0])):
  523. return self.seq(rulename, ls[1:], j)
  524. elif (self.isOptional(ls[0])):
  525. return self.opt(rulename, ls[1:], j)
  526. elif (self.isMany(ls[0])):
  527. return self.many(rulename, ls[1:], j)
  528. elif (self.isMore(ls[0])):
  529. return self.more(rulename, ls[1:], j)
  530. elif (self.isCard(ls[0])):
  531. return self.card(rulename, ls[0][1:], ls[1:], j)
  532. raise Exception('Unrecognized grammar expression: ' + str(ls[0]))
  533. def isSequence(self, operator):
  534. return operator == '.'
  535. def isAlternative(self, operator):
  536. return operator == '|'
  537. def isMany(self, operator):
  538. return operator == '*'
  539. def isCard(self, operator):
  540. return operator.startswith('#')
  541. def isMore(self, operator):
  542. return operator == '+'
  543. def isOptional(self, operator):
  544. return operator == '?'
  545. def isType(self, rule, oftype):
  546. if (rule['type'] == oftype):
  547. return True
  548. def term(self, rulename, j):
  549. if (j >= len(self.input)):
  550. errortext = ''
  551. if (rulename in self.tokens and 'errortext' in self.tokens[rulename]):
  552. errortext = self.tokens[rulename]['errortext']
  553. self.failure.update({rulename: {'startpos': j, 'text': errortext}})
  554. return []
  555. rule = self.tokens[rulename]
  556. mobj = re.match(rule['reg'], self.input[j:])
  557. #Changed by daniel instead of re.match(reg) did re.match(re.compile(reg).patern)
  558. #this is to avoid problems with \ before i did this i had the match the character \ by doing [\\\\]
  559. # 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
  560. #this way reading [\\] will be interpreted correctly instead of giving an error like it used to
  561. if (not mobj):
  562. # this is a failure! nice to register!
  563. self.failure.update({rulename: {'startpos': j, 'text': self.tokens[rulename]['errortext']}})
  564. return []
  565. return [{'tree': Tree(rulename, [mobj.group()], j, j + mobj.end()), 'startpos': j, 'endpos': j + mobj.end()}]
  566. def anonTerm(self, term, j):
  567. """
  568. #Changed by Daniel: added this whole method.
  569. Anonymous term to allow for direct terminals in rules
  570. (write 'Foo' directly instead of having to deine a FOO token)
  571. """
  572. qt = '\''
  573. name = qt + term + qt
  574. if (j >= len(self.input)):
  575. self.failure.update({ name : {'startpos': j, 'text': name}})
  576. return []
  577. mobj = re.match(term, self.input[j:])
  578. if (not mobj):
  579. # this is a failure! nice to register!
  580. self.failure.update({ name : {'startpos': j, 'text': name }})
  581. return []
  582. return [{'tree': Tree(name , [mobj.group()], j, j + mobj.end()), 'startpos': j, 'endpos': j + mobj.end()}]
  583. def many(self, rulename, ls, j):
  584. rule_i = ls[0]
  585. if (isinstance(rule_i, list)):
  586. results = self.eval_body('*', rule_i, j)
  587. else:
  588. results = self.applyrule(rule_i, j)
  589. if (results == []):
  590. return [{'tree': None, 'startpos': j, 'endpos': j}]
  591. seq = ['.'] + ls + [['*'] + ls]
  592. results = self.eval_body('*', seq, j)
  593. overall_results = []
  594. for r in results:
  595. if (r['tree']):
  596. if (len(r['tree'].tail) > 1):
  597. left = r['tree'].tail[0]
  598. right = r['tree'].tail[1].tail
  599. r['tree'].tail = [left] + right
  600. overall_results.append(r)
  601. return overall_results
  602. def more(self, rulename, ls, j):
  603. rule_i = ls[0]
  604. if (isinstance(rule_i, list)):
  605. results = self.eval_body('+', rule_i, j)
  606. else:
  607. results = self.applyrule(rule_i, j)
  608. if (results == []):
  609. return []
  610. seq = ['.'] + ls + [['*'] + ls]
  611. results = self.eval_body('+', seq, j)
  612. overall_results = []
  613. for r in results:
  614. if (r['tree']):
  615. if (len(r['tree'].tail) > 1):
  616. left = r['tree'].tail[0]
  617. right = r['tree'].tail[1].tail
  618. r['tree'].tail = [left] + right
  619. overall_results.append(r)
  620. return overall_results
  621. def opt(self, rulename, ls, j):
  622. if (j >= len(self.input)):
  623. errortext = ''
  624. if (rulename in self.rules and 'errortext' in self.rules[rulename]):
  625. errortext = self.rules[rulename]['errortext']
  626. else:
  627. for item in ls:
  628. if ((not isinstance(item[1:], list)) and item[1:] in self.rules):
  629. errortext = self.rules[item[1:]]['errortext']
  630. self.failure.update({rulename: {'startpos': j, 'text': errortext}})
  631. return [{'tree': None, 'startpos': j, 'endpos': j}]
  632. results = []
  633. rule_i = ls[0]
  634. if (isinstance(rule_i, list)):
  635. results = self.eval_body('?', rule_i, j)
  636. else:
  637. results = self.applyrule(rule_i, j)
  638. if (not results == []):
  639. return results
  640. # empty case
  641. return [{'tree': None, 'startpos': j, 'endpos': j}]
  642. def card(self, rulename, cardrule, ls, j):
  643. count = 0
  644. delta = 1
  645. # a# a#(-1) #indent, #(-1)indent
  646. group = re.match('\((?P<delta>[-+]?\d+)\)(?P<rule>\S+)',cardrule)
  647. if(group):
  648. cardrule = group.group('rule')
  649. delta = int(group.group('delta'))
  650. if (not cardrule in self.countcard):
  651. count = delta
  652. self.countcard.update({cardrule: {j: count}})
  653. else:
  654. if not j in self.countcard[cardrule]: # # if we already know the count for j, then ignore..
  655. d = self.countcard[cardrule]
  656. lastcount = 0
  657. for i in range(0, j):
  658. if i in d:
  659. lastcount = d[i]
  660. count = lastcount + delta
  661. d.update({j: count})
  662. else:
  663. count = self.countcard[cardrule][j]
  664. results = []
  665. rule_i = '@' + cardrule
  666. if(count == 0):
  667. results = [{'tree': None, 'startpos': j, 'endpos': j}]
  668. else:
  669. for i in range(0, count):
  670. if (results == []):
  671. if (isinstance(rule_i, list)):
  672. newresults = self.eval_body(rulename, rule_i, j)
  673. else:
  674. newresults = self.applyrule(rule_i, j)
  675. if (newresults == []):
  676. del self.countcard[cardrule][j]
  677. return []
  678. newresults = self.merge(rulename, newresults, {'startpos': j, 'endpos': j})
  679. else:
  680. for elem_p in results:
  681. if (isinstance(rule_i, list)):
  682. newresults = self.eval_body(rulename, rule_i, elem_p['endpos'])
  683. else:
  684. newresults = self.applyrule(rule_i, elem_p['endpos'])
  685. if (newresults == []):
  686. del self.countcard[cardrule][j]
  687. return []
  688. newresults = self.merge(rulename, newresults, elem_p)
  689. results = newresults
  690. for rule_i in ls:
  691. for elem_p in results:
  692. if (isinstance(rule_i, list)):
  693. newresults = self.eval_body(rulename, rule_i, elem_p['endpos'])
  694. else:
  695. newresults = self.applyrule(rule_i, elem_p['endpos'])
  696. if (newresults == []):
  697. del self.countcard[cardrule][j]
  698. return []
  699. newresults = self.merge(rulename, newresults, elem_p)
  700. results = newresults
  701. del self.countcard[cardrule][j]
  702. return results
  703. def seq(self, rulename, ls, j):
  704. #
  705. results = []
  706. for rule_i in ls:
  707. if (results == []):
  708. if (isinstance(rule_i, list)):
  709. newresults = self.eval_body('.', rule_i, j)
  710. else:
  711. newresults = self.applyrule(rule_i, j)
  712. if (newresults == []):
  713. return []
  714. newresults = self.merge('.', newresults, {'startpos': j, 'endpos': j})
  715. else:
  716. r = []
  717. for elem_p in results:
  718. if (isinstance(rule_i, list)):
  719. newresults = self.eval_body('.', rule_i, elem_p['endpos'])
  720. else:
  721. newresults = self.applyrule(rule_i, elem_p['endpos'])
  722. if (newresults == []):
  723. return []
  724. newresults = self.merge('.', newresults, elem_p)
  725. results = newresults
  726. return results
  727. def merge(self, rulename, newres, elem_p):
  728. # Brief: tail of each new tree needs to be prepended with tail of the previous tree
  729. # rulename: becomes the head of each tree in the returned list
  730. # newres: may have more than one tree in case of alt operator: 'x' ('a' | 'b') 'y'
  731. # tail of each new tree needs to be prepended with tail of previous tree
  732. # Returns same list as eval: [{'tree':Tree(head=rulename, tail=[...], startpos=j, endpos=x), 'startpos':j, 'endpos':x}]
  733. results = []
  734. for elem_n in newres:
  735. tail = []
  736. if ('tree' in elem_p and elem_p['tree']):
  737. tail += elem_p['tree'].tail
  738. if ('tree' in elem_n and elem_n['tree']):
  739. tail.append(elem_n['tree'])
  740. value = {'tree': Tree(rulename, tail, elem_p['startpos'], elem_n['endpos']), 'startpos': elem_p['startpos'],
  741. 'endpos': elem_n['endpos']}
  742. results += [value]
  743. return results
  744. def alt(self, rulename, ls, j):
  745. # Evaluates all alternatives using eval_body or applyrule
  746. # Returns same list as eval: [{'tree':Tree(head=rulename, tail=[...], startpos=j, endpos=x), 'startpos':j, 'endpos':x}]
  747. overall_results = []
  748. results = [] # TODO: remove this variable as it's never used
  749. for rule_i in ls:
  750. if (isinstance(rule_i, list)):
  751. newresults = self.eval_body('|', rule_i, j)
  752. else:
  753. newresults = self.applyrule(rule_i, j)
  754. overall_results += newresults
  755. return overall_results
  756. class PositionPostProcessor(object):
  757. """
  758. This post processor changes absolute position (place in the parsed string )to a line, column position
  759. added by Daniel
  760. """
  761. """
  762. efficiency note:
  763. how effective is this. this might be slowing things down quit a bit having to calculate that for everything
  764. 1) an alternative would be use the method only for the leaves, and that traverse the tree bottom up to create
  765. the interval using the left most and right most children of each subtree. but since tat involves extra tree
  766. traversal that might not help that much.
  767. 2) another thing that might improve efficiency is to create change the position calculating method:
  768. create one that doesnt scan the whole text for new line each time we calculate a position,
  769. but creates a table of them the first time.
  770. we can calculate the line by returning the index in the table of the the new line the closest to the given
  771. position and the column is the difference between the position of that newline and the column (maybe + or - 1,
  772. check that)
  773. in case this method doesn't slow things down too much ignore this
  774. """
  775. def __init__(self, method):
  776. self.calcPosMethod = method
  777. def inner_visit(self,tree):
  778. startDic = self.calcPosMethod(tree.startpos)
  779. endDic = self.calcPosMethod(tree.endpos)
  780. tree.startpos = Position(startDic["line"], startDic["column"])
  781. tree.endpos = Position(endDic["line"], endDic["column"])
  782. for item in tree.tail:
  783. if (isinstance(item, Tree)):
  784. self.inner_visit(item)
  785. def visit(self, tree):
  786. if tree:
  787. self.inner_visit(tree)
  788. return tree
  789. class DefaultPrinter(object):
  790. def __init__(self, output='console'):
  791. self.outputStream = ''
  792. self.output = output
  793. def inner_visit(self, tree):
  794. for item in tree.tail:
  795. if (isinstance(item, Tree)):
  796. self.inner_visit(item)
  797. else:
  798. self.outputStream += item
  799. def visit(self, tree):
  800. self.inner_visit(tree)
  801. if (self.output == 'console'):
  802. print self.outputStream
  803. class PrettyPrinter(object):
  804. def __init__(self, output='console'):
  805. self.outputStream = ''
  806. self.output = output
  807. self.tabcount = -1
  808. def tab(self):
  809. tabspace = ''
  810. for i in range(0, self.tabcount):
  811. tabspace += ' '
  812. return tabspace
  813. def inner_visit(self, tree):
  814. self.tabcount += 1
  815. self.outputStream += self.tab()
  816. self.outputStream += 'node ' + tree.head + ':\n'
  817. for item in tree.tail:
  818. if (isinstance(item, Tree)):
  819. self.inner_visit(item)
  820. else:
  821. self.tabcount += 1
  822. self.outputStream += self.tab() + item + ' @' + str(tree.startpos) + ' to ' + str(
  823. tree.endpos) + ' \n'
  824. self.tabcount -= 1
  825. self.tabcount -= 1
  826. def visit(self, tree):
  827. self.inner_visit(tree)
  828. if (self.output == 'console'):
  829. print self.outputStream
  830. class IgnorePostProcessor(object):
  831. def __init__(self, rules, tokens):
  832. self.rules = rules
  833. self.tokens = tokens
  834. def inner_visit(self, tree):
  835. results = []
  836. if (isinstance(tree, Tree)):
  837. if (self.isHidden(tree.head)):
  838. for item in tree.tail:
  839. ivlist = []
  840. ivresult = self.inner_visit(item)
  841. for elem in ivresult:
  842. if (isinstance(elem, Tree)):
  843. ivlist += [elem]
  844. results += ivlist
  845. else:
  846. tlist = []
  847. for item in tree.tail:
  848. tlist += self.inner_visit(item)
  849. tree.tail = tlist
  850. results += [tree]
  851. return results
  852. return [tree]
  853. def visit(self, tree):
  854. # start cannot be hidden
  855. tlist = []
  856. for item in tree.tail:
  857. tlist += self.inner_visit(item)
  858. tree.tail = tlist
  859. return tree
  860. def isHidden(self, head):
  861. if (head == '*' or head == '+' or head == '?' or head == '|' or head == '.'):
  862. return True
  863. if (head in self.rules):
  864. return 'hidden' in self.rules[head] and self.rules[head]['hidden']
  865. elif (head in self.tokens): #Changed by Daniel: added elif condition and return false otherwise, need for anon tokens
  866. return 'hidden' in self.tokens[head] and self.tokens[head]['hidden']
  867. else:
  868. return False