Advertisement
Merxlc

lexer.py

May 25th, 2021
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. mapping = {
  2. 0: 'POINTER_LEFT',
  3. 1: 'POINTER_RIGHT',
  4. 2: 'VALUE_INCREASE',
  5. 3: 'VALUE_DECREASE',
  6. 4: 'OPEN_BRACKET',
  7. 5: 'CLOSE_BRACKET',
  8. 6: 'OUTPUT_CHARACTER',
  9. 7: 'INPUT_CHARACTER',
  10. 8: 'OUTPUT_INTEGER'
  11. }
  12.  
  13. def lex(content):
  14. glyphs = [char for char in content]
  15. lines = [len([char for char in line]) for line in ''.join(glyphs).split('\n')]
  16. return {i: mapping[line] for i, line in enumerate(lines)}
  17.  
  18. brain_mapping = {
  19. 'POINTER_LEFT': '<',
  20. 'POINTER_RIGHT': '>',
  21. 'VALUE_INCREASE': '+',
  22. 'VALUE_DECREASE': '-',
  23. 'OPEN_BRACKET': '[',
  24. 'CLOSE_BRACKET': ']',
  25. 'OUTPUT_INTEGER': '!',
  26. 'INPUT_CHARACTER': ',',
  27. 'OUTPUT_CHARACTER': '.'
  28. }
  29.  
  30. def match(target):
  31. for key in brain_mapping:
  32. if brain_mapping[key] == target:
  33. return key
  34.  
  35. def match_spaces(target):
  36. for key in mapping:
  37. if mapping[key] == target:
  38. return key
  39.  
  40. def to_brain(lines):
  41. final = ''
  42. for line in lines:
  43. final += brain_mapping[lines[line]]
  44. return final
  45.  
  46. def from_brain(code):
  47. final = []
  48. for char in code:
  49. final.append(match_spaces(match(char)))
  50. final = [item for item in final if item != None]
  51. finalstr = ''
  52. for kc in final:
  53. finalstr += ' '*kc
  54. finalstr += '\n'
  55. return finalstr
  56.  
  57. def sprint(astro):
  58. lines = astro.split('\n')
  59. for line in lines:
  60. print(f'|{line}|')
  61.  
  62. def read(file_name):
  63. with open(file_name, 'r') as file:
  64. return file.read()
  65.  
  66. def lex_all(file_name):
  67. cont = read(file_name)
  68. lexed = lex(cont)
  69. return to_brain(lexed)
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement