|
| 1 | +from ..ir import IR |
| 2 | +from ..types import FunctionType |
| 3 | + |
| 4 | +text_stack = [] |
| 5 | + |
| 6 | +def head(): |
| 7 | + return text_stack[-1] |
| 8 | + |
| 9 | +def compile_text(text): |
| 10 | + import json |
| 11 | + data = json.dumps(text, separators=(',', ':')) |
| 12 | + return IR.Asm((('CMD tellraw @s ' + data, None, None),)) |
| 13 | + |
| 14 | +def begin(visitor, expr): |
| 15 | + text_stack.append({}) |
| 16 | + |
| 17 | +def set_text(visitor, expr): |
| 18 | + text = visitor.visit_expression(expr.args[0]) |
| 19 | + assert isinstance(text, IR.LiteralString) |
| 20 | + head()['text'] = text.val |
| 21 | + |
| 22 | +def set_color(visitor, expr): |
| 23 | + color = visitor.visit_expression(expr.args[0]) |
| 24 | + assert isinstance(color, IR.LiteralString) |
| 25 | + head()['color'] = color.val |
| 26 | + |
| 27 | +def set_click_run(visitor, expr): |
| 28 | + func = visitor.visit_expression(expr.args[0]) |
| 29 | + assert isinstance(func.type, FunctionType) |
| 30 | + name = expr.args[0].val |
| 31 | + head()['clickEvent'] = { |
| 32 | + 'action': 'run_command', |
| 33 | + 'value': '/function $func:%s$' % name |
| 34 | + } |
| 35 | + |
| 36 | +def set_click_url(visitor, expr): |
| 37 | + url = visitor.visit_expression(expr.args[0]) |
| 38 | + assert isinstance(url, IR.LiteralString) |
| 39 | + head()['clickEvent'] = { |
| 40 | + 'action': 'open_url', |
| 41 | + 'value': url.val |
| 42 | + } |
| 43 | + |
| 44 | +def end(visitor, expr): |
| 45 | + action = visitor.visit_expression(expr.args[0]) |
| 46 | + assert isinstance(action, IR.LiteralInt) |
| 47 | + action = action.val |
| 48 | + text = text_stack.pop() |
| 49 | + if text.keys() == set(['extra']): |
| 50 | + # if extra is only present, convert to array |
| 51 | + text = text['extra'] |
| 52 | + else: |
| 53 | + assert 'text' in text, "Must have text component" |
| 54 | + if action == 1: |
| 55 | + h = head() |
| 56 | + if 'extra' not in h: |
| 57 | + h['extra'] = [] |
| 58 | + h['extra'].append(text) |
| 59 | + elif action == 2: |
| 60 | + visitor.emit(compile_text(text)) |
| 61 | + else: |
| 62 | + assert False |
| 63 | + |
| 64 | + |
| 65 | +def exports(): |
| 66 | + return { |
| 67 | + 'text_begin': begin, |
| 68 | + 'text_set_text': set_text, |
| 69 | + 'text_set_color': set_color, |
| 70 | + 'text_set_click_run': set_click_run, |
| 71 | + 'text_set_click_url': set_click_url, |
| 72 | + 'text_end': end, |
| 73 | + } |
0 commit comments