common.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from lark import Transformer
  2. def indent(multiline_string, how_much):
  3. lines = multiline_string.split('\n')
  4. return '\n'.join([' '*how_much+l for l in lines])
  5. def display_value(val: any, type_name: str, indentation=0, newline_character='\n'):
  6. if type_name == "ActionCode":
  7. if '\n' in val:
  8. orig = '```\n'+indent(val, indentation+4)+'\n'+' '*indentation+'```'
  9. escaped = orig.replace('\n', newline_character)
  10. return escaped
  11. else:
  12. return '`'+val+'`'
  13. elif type_name == "String":
  14. return '"'+val+'"'.replace('\n', newline_character)
  15. elif type_name == "Integer" or type_name == "Boolean":
  16. return str(val)
  17. else:
  18. raise Exception("don't know how to display value" + type_name)
  19. def display_name(raw_name: str) -> str:
  20. if raw_name[0:2] == "__":
  21. return "" # hide names that start with '__', they are anonymous (by convention)
  22. else:
  23. return raw_name
  24. # internal use only
  25. # just a dumb wrapper to distinguish between code and string
  26. class _Code:
  27. def __init__(self, code):
  28. self.code = code
  29. class TBase(Transformer):
  30. def IDENTIFIER(self, token):
  31. return str(token)
  32. def INT(self, token):
  33. return int(token)
  34. def BOOL(self, token):
  35. return token == "True"
  36. def STR(self, token):
  37. return str(token[1:-1]) # strip the "" or ''
  38. def CODE(self, token):
  39. return _Code(str(token[1:-1])) # strip the ``
  40. def INDENTED_CODE(self, token):
  41. skip = 4 # strip the ``` and the following newline character
  42. space_count = 0
  43. while token[skip+space_count] == " ":
  44. space_count += 1
  45. lines = token.split('\n')[1:-1]
  46. for line in lines:
  47. if len(line) >= space_count and line[0:space_count] != ' '*space_count:
  48. raise Exception("wrong indentation of INDENTED_CODE")
  49. unindented_lines = [l[space_count:] for l in lines]
  50. return _Code('\n'.join(unindented_lines))
  51. def literal(self, el):
  52. return el[0]