pages/oh.js
2026-11-19 14:59:44 +01:00

849 lines
14 KiB
JavaScript

// I thank God for allowing me to program
console.warn('God is King of kings and Lord of lords')
let stack = []
let source = ''
let pointer = 0
let escape = { t: '\t',
0: '\0',
r: '\r',
n: '\n' }
let env = Object.create(null)
const root = env
const w = root
let tracing = 1
let compiling = []
let executing = []
const special = new Set('[{("`)}]')
const space_regex = /\s/
const number_regex = /^-?\d+\.?\d*$/
const method_args_regex = /-+$/
let nodep, browserp
let out = console.log.bind(console)
//wws
function read_word ()
{
let chr
let word = ''
while ((chr = source[pointer++]) !== undefined && space_regex.test(chr))
;
while (chr !== undefined && !space_regex.test(chr))
{
if (special.has(chr))
{
if (word === '')
return chr
pointer--
return word
}
word += chr
chr = source[pointer++]
}
if (word !== '')
return word
}
function error (...message)
{
//werr
let str = ''
if (compiling.length)
{
str += 'while compiling: ' + compiling.join(' -> ') + ' \n'
compiling.length = 0
}
if (executing.length)
{
str += 'while executing: ' + executing.join(' -> ') + ' \n'
executing.length = 0
}
str += refrep(...message) + ' \n'
const oh = new Error(str)
oh.name = '0'
throw oh
}
function undef (value, ...message)
{
if (value === undefined)
error(...message)
else
return value
}
function nulldef (value, ...message)
{
if (value === undefined || value === null)
error(...message)
else
return value
}
function represent (element)
{
represented = new Map()
return represent_element(element)
}
function represent_element (element)
{
if (element === undefined)
return 'nil'
if (element === null)
return 'null'
const type = typeof element
if (type === 'string')
return JSON.stringify(element)
if (type === 'function')
return 'λ'
if (type === 'object')
{
if (represented.has(element))
return represented.get(element)
if (Array.isArray(element))
{
represented.set(element, 'circular list')
const str = '(' + element.map(represent_element).join(' ') + ')'
represented.set(element, str)
return str
}
if (browserp && element instanceof HTMLElement)
return element.outerHTML
let str = ''
const name = element?.constructor?.name
if (name && name !== 'Object')
{
str += name + ' '
represented.set(element, 'circular ' + name)
}
else
{
represented.set(element, 'circular object')
}
str += '{' + Object.entries(element).map(x => x[0] + represent_element(x[1])).join(', ') + '}'
represented.set(element, str)
return str
}
return element
}
function refrep (...elements)
{
represented = new Map()
return elements.map(x =>
{
const type = typeof x
if (type === 'string' || type === 'number' || type === 'boolean')
return x
return represent_element(x)
}).join(' ')
}
function represent_stack ()
{
represented = new Map()
return '[' + stack.map(represent_element).join(' ') + ']'
}
function put (...items)
{
stack.push.apply(stack, items)
}
function get ()
{
if (stack.length)
return stack.pop()
error('stack empty when trying to get one element')
}
function get2 ()
{
if (stack.length < 2)
error('wanted to get two elements, the stack:', stack)
else
return stack.splice(-2)
}
function get3 ()
{
if (stack.length < 3)
error('wanted to get three elements, the stack:', stack)
else
return stack.splice(-3)
}
function get4 ()
{
if (stack.length < 4)
error('wanted to get four elements, the stack:', stack)
else
return stack.splice(-4)
}
function getn (n)
{
if (stack.length < n)
error('wanted to get', n, 'elements, the stack:', stack)
else
return stack.splice(-n)
}
function compile (element)
{
//cps
const type = typeof element
if (type === 'string')
{
const word = env[element]
if (word)
{
if (word.hasOwnProperty('immediate'))
{
if (tracing)
{
executing.push('immediate word: ' + element)
word()
executing.pop()
}
else
{
word()
}
if (word.immediate)
{
const value = get()
if (typeof value === 'function')
return value
error('immediate 1 word', element, 'did not return a function on the stack', value)
}
return
}
if (tracing)
{
const name = element
return () =>
{
executing.push(name)
word()
executing.pop()
}
}
return word
}
return compile_atom(element)
}
if (type === 'function')
return element
if (Array.isArray(element))
return compile_list(element)
const el = element
const value = () => put(element)
return value
}
function compile_atom (atom)
{
//ats
if (number_regex.test(atom))
{
const n = parseFloat(atom)
const number = () => put(n)
return number
}
if (atom[0] === "'")
{
const str = atom.slice(1)
const string = () => put(str)
return string
}
if (atom[0] === '-')
{
if (atom[1] === '-')
{
const matches = atom.match(method_args_regex)
if (matches)
{
const args = matches[0].length
const name = translate_case(atom.slice(2, -args))
return () =>
{
const object = nulldef(get(), atom, 'the object is null or nil')
const method = object[name]
if (typeof method !== 'function')
error(name, 'is not a method of', object, atom)
put(method.apply(object, getn(args)))
}
}
const name = translate_case(atom.slice(2))
return () =>
{
const object = nulldef(get(), atom, 'the object is null or nil')
if (typeof object[name] !== 'function')
error(name, 'is not a method of', object, atom)
put(object[name]())
}
}
else
{
const matches = atom.match(method_args_regex)
if (matches)
{
const args = matches[0].length
const name = translate_case(atom.slice(1, -args))
return () =>
{
const object = nulldef(get(), atom, 'the object is null or nil')
const method = object[name]
if (typeof method !== 'function')
error(name, 'is not a method of', object, atom)
method.apply(object, getn(args))
}
}
const name = translate_case(atom.slice(1))
return () =>
{
const object = nulldef(get(), atom, 'the object is null or nil')
if (typeof object[name] !== 'function')
error(name, 'is not a method of', object, atom)
object[name]()
}
}
}
//ets
error(atom, 'not recognized')
}
function compile_list (list)
{
const res = []
const len = list.length
for (let i = 0; i < len; i++)
{
const element = list[i]
if (Array.isArray(element))
{
const el = element
const list = () => put(element)
res.push(list)
}
else
{
res.push(compile(element))
}
}
return res
}
function compile_into_list (word, list)
{
const value = compile(word)
if (value)
list.push(value)
}
function make_block (name, delimiter = 'end')
{
if (tracing)
{
compiling.push(name)
const block = []
let word
while ((word = read_word()) !== delimiter)
{
undef(word, 'block did not find the', delimiter, 'delimiter')
compile_into_list(word, block)
}
compiling.pop()
return block
}
const block = []
let word
while ((word = read_word()) !== delimiter)
{
undef(word, 'block did not find the', delimiter, 'delimiter')
compile_into_list(word, block)
}
return block
}
function block (name, delimiter)
{
if (tracing)
{
const code = make_block(name, delimiter)
const len = code.length
const block = () =>
{
for (let i = 0; i < len; ++i)
code[i]()
}
block.name = name
return block
}
const code = make_block(name, delimiter)
const len = code.length
const block = () =>
{
for (let i = 0; i < len; ++i)
code[i]()
}
block.name = name
return block
}
function make_env_block (name, delimiter = 'end', e = Object.create(env))
{
if (tracing)
{
compiling.push(name)
const block = []
let word
const old = env
try
{
env = e
while ((word = read_word()) !== delimiter)
{
undef(word, 'env block did not find the', delimiter, 'delimiter')
compile_into_list(word, block)
}
compiling.pop()
return block
}
finally
{
env = old
}
}
const block = []
let word
const old = env
try
{
env = e
while ((word = read_word()) !== delimiter)
{
undef(word, 'block did not find the', delimiter, 'delimiter')
compile_into_list(word, block)
}
return block
}
finally
{
env = old
}
}
function env_block (name, delimiter, e)
{
if (tracing)
{
const code = make_env_block(name, delimiter, e)
const len = code.length
const block = () =>
{
for (let i = 0; i < len; ++i)
code[i]()
}
block.name = name
return block
}
const code = make_env_block(name, delimiter, e)
const len = code.length
const block = () =>
{
for (let i = 0; i < len; ++i)
code[i]()
}
block.name = name
return block
}
function interpret_string (str)
{
const old = source
const oldp = pointer
try
{
source = str
pointer = 0
let word
while ((word = read_word()) !== undefined)
{
const value = compile(word)
if (value)
value()
}
}
finally
{
source = old
pointer = oldp
}
}
function node ()
{
nodep = 1
function repl ()
{
process.stdin.on('data', x =>
{
const str = x.toString()
if (str === '\n')
process.exit()
try
{
interpret_string(str)
console.log(represent_stack())
}
catch (e)
{
console.error(e)
}
})
}
repl()
}
function init ()
{
if (typeof window === 'undefined')
node()
else
browser()
}
function translate_case (str)
{
let res = ''
const len = str.length
for (let i = 0; i < len; i++)
{
let chr = str[i]
if (chr === '\\')
{
chr = str[++i]
if (escape[chr])
res += escape[chr]
else
res += chr
}
else
{
res += chr
}
}
return res
}
function browser ()
{
//brs
const hide_oh = document.createElement('style')
document.head.appendChild(hide_oh)
hide_oh.sheet.insertRule('oh { display: none; }')
async function load_scripts ()
{
for (let oh of [...document.getElementsByTagName('oh')])
{
oh.remove()
const src = oh.getAttribute('src')
if (src)
{
const res = await fetch(src)
if (res.ok)
interpret_string(await res.text())
else
error('failed to load file', src, res)
}
if (oh.textContent.trim())
interpret_string(oh.textContent)
}
}
window.addEventListener('load', load_scripts)
}
function immediate (flag, names)
{
for (let name of names.split(' '))
{
const word = env[name]
if (!word)
error('word', name, 'does not exist when trying to make it immediate', flag)
else
word.immediate = flag
}
}
function read_name (caller)
{
return undef(read_word(), caller, 'did not read a word')
}
class iterator
{
constructor (list)
{
if (!Array.isArray(list))
error('iterator did not receive a list', list)
this.list = list
this.pointer = -1
}
next ()
{
if (++this.pointer >= this.list.length)
this.pointer = 0
return this.list[this.pointer]
}
previous ()
{
if (--this.pointer < 0)
this.pointer = this.list.length - 1
return this.list[this.pointer]
}
random ()
{
this.pointer = Math.floor(Math.random() * this.list.length)
return this.list[this.pointer]
}
}
function build_list ()
{
const list = []
let word
while ((word = read_word()) !== ')')
{
undef(word, '( did not find a terminating )')
if (number_regex.test(word))
{
list.push(parseFloat(word))
}
else if (word === '(')
{
list.push(build_list())
}
else
{
list.push(word)
}
}
return list
}
function word_or_list (caller, word, list)
{
const token = read_word(caller)
if (token === '(')
list(build_list())
else if (token === '[')
list(with_stack(block('[', ']')))
else
word(token)
}
function make_binding ()
{
const binding = () => put(binding.value)
binding.value = 0
return binding
}
function with_stack (code, s = [])
{
const old = stack
try
{
stack = s
code()
return s
}
finally
{
stack = old
}
}
//wds
w[':'] = () =>
{
const name = read_name(':')
env[name] = env_block(name, ';')
}
w['God'] = () => out('God is King of kings and Lord of lords')
w['('] = () =>
{
const list = build_list()
put(() => put(list.slice()))
}
w.constant = () =>
{
const name = read_name('constant')
let value
env[name] = () => put(value)
put(() => value = get())
}
w.constants = () =>
{
const word = read_name('constants')
if (word === '(')
{
const names = build_list()
const len = names.length
let values
for (let i = 0; i < len; i++)
{
const index = i
env[names[i]] = () => put(values[i])
}
put(() => values = getn(len))
}
else
{
error('constants did not read a list', word)
}
}
w.r = () => stack.length = 0
w.drop = get
w.iterator = () => put(new iterator(get()))
w.console = () => put(console)
w.math = () => put(Math)
w.flatten = () =>
{
const element = get()
if (!Array.isArray(element))
error('flatten did not receive a list', element)
stack.push.apply(stack, element)
}
w['---'] = () =>
{
while (source[pointer] !== undefined && source[pointer++] !== '\n')
;
}
w.declare = () =>
{
word_or_list('declare',
name => env[name] = make_binding(),
names =>
{
for (let name of names)
env[name] = make_binding()
})
}
w.wait = () =>
{
const code = make_block('wait')
const len = code.length
put(async () =>
{
const s = []
for (let i = 0; i < len; i++)
{
with_stack(code[i], s)
if (s[s.length - 1] instanceof Promise)
s.push(await s.pop())
}
})
}
w['['] = () =>
{
const code = block('[', ']')
put(() => put(with_stack(code)))
}
w['fetch-json'] = () =>
{
const url = get()
put((async () =>
{
const res = await fetch(url)
if (res.ok)
return await res.json()
error('fetch-json failed to fetch url', url, res)
})())
}
w.compile = () => put(compile(get()))
w.eval = () => get()()
immediate(0, ': --- declare')
immediate(1, 'constants constant ( [ wait')
init()