hutnparser.py 40 KB

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