about summary refs log tree commit diff stats
path: root/trainfuck
blob: 602fc925ca42d33e93e1b80b649dc28f538f2544 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/bin/awk -f
# TRAINFUCK: CHOO CHOO MUTHAFUCKA -*- awk -*-
# Author: Case Duckworth <acdw@acdw.net>
# License: WTFPL
# Version: #9

### Commentary:

# LANGUAGE

# trainfuck is not case-sensitive
# -- except for ALL ABOARD and END OF THE LINE
# ignore everything before ALL ABOARD
# ignore everything after END OF THE LINE
# (this means you can comment between these)
# bf tf
# +  chug
# -  chugga
# >  choo
# <  choo choo
# .  click OR clickety
# ,  clack
# [  tickets please
# ]  your ticket please
# syntax does NOT WRAP across line breaks
# anything else is an error and DERAILS the train

### Code:
BEGIN {
	aboard = 0
	width = 30
	print "["
}

/^ALL ABOARD$/ {
	if (! header) {
		print "]"
	}
	header++
	aboard = 1
	next
}

/^END OF THE LINE$/ {
	aboard = 0
	next
}

aboard {
	gsub(/[[:space:]]/, "", $0)
	buf = buf proc(toupper($0))
}

! aboard {
	printbuf()
	if (header) {
		gsub(/[-+<>.,\[\]]/, "", $0)
	}
	print
	buf = ""
}

END {
	if (DERAIL_ERR) {
		print DERAIL_ERR
		exit 9
	}
	printbuf()
	printf "\n"
}


function derail(err)
{
	print "TRAIN DERAILED at input line", FNR
	DERAIL_ERR = err
	exit
}

function printbuf(newline)
{
	for (ss = 1; ss <= length(buf); ss += width) {
		printf "%s\n", substr(buf, ss, width)
	}
}

function proc(t)
{
	if (! match(t, /CHUGGA|CHUG|CHOO|CLICK|CLICKETY|CLACK|TICKETSPLEASE|YOURTICKETPLEASE|$/)) {
		derail("WTF")
	}
	pre = substr(t, 1, RSTART - 1)
	tok = substr(t, RSTART, RLENGTH)
	pst = substr(t, RSTART + RLENGTH)
	if (tok == "CHUGGA") {	# needs to be first
		tok = "-"
		return (pre tok proc(pst))
	}
	if (tok == "CHUG") {
		tok = "+"
		return (pre tok proc(pst))
	}
	if (tok == "CHOO") {
		if (substr(pst, 1, 4) == "CHOO") {
			tok = "<"
			sub(/CHOO/, "", pst)
		} else {
			tok = ">"
		}
		return (pre tok proc(pst))
	}
	if (tok == "CLICK" || tok == "CLICKETY") {
		tok = "."
		return (pre tok proc(pst))
	}
	if (tok == "CLACK") {
		tok = ","
		return (pre tok proc(pst))
	}
	if (tok == "TICKETSPLEASE") {
		tok = "["
		return (pre tok proc(pst))
	}
	if (tok == "YOURTICKETPLEASE") {
		tok = "]"
		return (pre tok proc(pst))
	}
}