-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.ts
More file actions
64 lines (62 loc) · 1.78 KB
/
shell.ts
File metadata and controls
64 lines (62 loc) · 1.78 KB
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
import { run } from './index'
const prompt = require('prompt-sync')()
while (true) {
let textInput = prompt('REPL > ')
let [result, error] = run('<stdin>', textInput)
if (error) {
console.log(error.asString())
} else if (result !== null && result !== undefined) {
if (
result.constructor &&
result.constructor.name === 'ListValue' &&
Array.isArray(result.elements)
) {
const filtered = result.elements.filter(
(e: any) =>
e !== null &&
e !== undefined &&
!(
typeof e.asString === 'function' &&
(e.asString() === '' || e.asString() === '[]')
)
)
// Heuristic: if input is a single line and starts with '[', treat as list literal
if (textInput.trim().startsWith('[')) {
console.log(
'[' +
filtered
.map((e: any) =>
typeof e.asString === 'function'
? e.asString()
: String(e)
)
.join(', ') +
']'
)
} else if (filtered.length > 0) {
const last = filtered[filtered.length - 1]
// If the last statement is a print statement, don't print its value again
const lines = textInput.trim().split(/\r?\n/).filter((l: string) => l.trim() !== '')
const lastLine = lines[lines.length - 1].trim()
if (!/^print\s*\(/.test(lastLine)) {
if (last && typeof last.asString === 'function') {
console.log(last.asString())
} else {
console.log(last)
}
}
}
// If filtered.length === 0, print nothing
} else if (
typeof result.asString === 'function' &&
result.asString() !== '' &&
result.asString() !== '[]'
) {
const lines = textInput.trim().split(/\r?\n/).filter((l: string) => l.trim() !== '')
const lastLine = lines[lines.length - 1].trim()
if (!/^print\s*\(/.test(lastLine)) {
console.log(result.asString())
}
}
}
}