This repository was archived by the owner on Jun 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathKnight.cs
More file actions
65 lines (54 loc) · 1.5 KB
/
Copy pathKnight.cs
File metadata and controls
65 lines (54 loc) · 1.5 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
65
using System;
using System.IO;
using System.Linq;
namespace Knight
{
public class Kn
{
internal static IValue Parse(Stream stream) {
while (!stream.IsEmpty()) {
// strip comments.
if (stream.TakeWhileIfStartsWith('#', c => c != '\n') != null)
continue;
// strip whitespace.
if (stream.TakeWhile(c => char.IsWhiteSpace(c) || "(){}[]:".Contains(c)) != null)
continue;
// if we neither had comments or whitespace, break out.
break;
}
if (stream.IsEmpty())
return null;
return Number.Parse(stream) ??
Boolean.Parse(stream) ??
String.Parse(stream) ??
Null.Parse(stream) ??
(IValue) Identifier.Parse(stream) ??
Function.Parse(stream);
}
public static IValue Run(string stream) => Run(new Stream(stream));
public static IValue Run(Stream stream) {
if (stream.IsEmpty()) {
throw new ParseException("nothing to parse.");
}
IValue value = Parse(stream);
if (value == null) {
throw new ParseException($"Unknown token start '{stream.Take()}'.");
} else {
return value.Run();
}
}
static int Main(string[] args) {
if (args.Length != 2 || args[0] != "-e" && args[0] != "-f") {
Console.Error.WriteLine("usage: {0} (-e 'program' | -f file)", Environment.GetCommandLineArgs()[0]);
return 1;
}
try {
Run(args[0] == "-e" ? args[1] : File.ReadAllText(args[1]));
return 0;
} catch (KnightException err) {
Console.Error.WriteLine("invalid program: {0}", err.Message);
return 1;
}
}
}
}