hutnparser.py 40 KB

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