common.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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):
  6. if type_name == "ActionCode":
  7. if '\n' in val:
  8. return '```\n'+indent(val, indentation+4)+'\n'+' '*indentation+'```'
  9. else:
  10. return '`'+val+'`'
  11. elif type_name == "String":
  12. return '"'+val+'"'
  13. elif type_name == "Integer" or type_name == "Boolean":
  14. return str(val)
  15. else:
  16. raise Exception("don't know how to display value" + type_name)
  17. # internal use only
  18. # just a dumb wrapper to distinguish between code and string
  19. class _Code:
  20. def __init__(self, code):
  21. self.code = code
  22. class TBase(Transformer):
  23. def IDENTIFIER(self, token):
  24. return str(token)
  25. def INT(self, token):
  26. return int(token)
  27. def BOOL(self, token):
  28. return token == "True"
  29. def STR(self, token):
  30. return str(token[1:-1]) # strip the "" or ''
  31. def CODE(self, token):
  32. return _Code(str(token[1:-1])) # strip the ``
  33. def INDENTED_CODE(self, token):
  34. skip = 4 # strip the ``` and the following newline character
  35. space_count = 0
  36. while token[skip+space_count] == " ":
  37. space_count += 1
  38. lines = token.split('\n')[1:-1]
  39. for line in lines:
  40. if len(line) >= space_count and line[0:space_count] != ' '*space_count:
  41. raise Exception("wrong indentation of INDENTED_CODE")
  42. unindented_lines = [l[space_count:] for l in lines]
  43. return _Code('\n'.join(unindented_lines))
  44. def literal(self, el):
  45. return el[0]