emdash / udlang

A practical, functional language for stream processing.
GNU Lesser General Public License v3.0
1 stars 0 forks source link

Simple Protocol for Formatted Text #22

Open emdash opened 3 years ago

emdash commented 3 years ago

Problem Statement

Allow uDLang to do formatting and pretty-printing of plain-text output by providing implementation support for the writer pattern, whose structure will become clear from the following:

// lib/writer.ud
type Output: "endl" 
  | "indent" 
  | "outdent" 
  | "flush" 
  | "reset"
  | ["set_tab_stop", n:Int] 
  | ["write", s:Str];

The library could then provide primitives like: wrap or join, written in terms of these operations.

The final piece is to mandate implementation support for this protocol in the uDLang CLI tool, perhaps under a flag like --output writer, which would automatically interpret the result. But a short python script which interprets this protocol is provided here below as a poof of concept. Let it be known that, despite the brevity of this example, it took a few tries to get it right. Mutable state is evil.

import sys
import json

def reset():
  global indent, tab_stop, cur_line
  indent = 0
  tab_stop = 4
  cur_line = ""

reset()

for line in sys.stdin:
    command = json.loads(line.strip())
    if command == "endl":
        sys.stdout.write(' ' * indent)
        sys.stdout.write(cur_line)
        sys.stdout.write('\n')
        cur_line = ""
    elif command == "indent":
        indent = indent + tab_stop
    elif command == "outdent":
        indent = indent - tab_stop
    elif command == "flush":
        sys.stdout.flush()
    elif command == "reset":
        reset()
        flush()
    elif command[0] == "set_tab_stop":
        tab_stop = command[1]
    elif command[0] == "write":
        cur_line += command[1]

    assert(indent >= 0)