-
Notifications
You must be signed in to change notification settings - Fork 4
/
Loader.java
487 lines (382 loc) · 12 KB
/
Loader.java
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package com.kyper.yarn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Matcher;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.badlogic.gdx.utils.SerializationException;
import com.badlogic.gdx.utils.StringBuilder;
import com.kyper.yarn.Lexer.Regex;
import com.kyper.yarn.Lexer.Token;
import com.kyper.yarn.Lexer.TokenList;
import com.kyper.yarn.Lexer.TokeniserException;
import com.kyper.yarn.Loader.NodeInfo.Position;
import com.kyper.yarn.Parser.Node;
import com.kyper.yarn.Program.ParseException;
public class Loader {
public enum NodeFormat {
Unkown, //type not known
SingleNodeText, //plain text file with single node & no metadata
Json, //json file containing multiple nodes with metadata
Text //text containing multiple nodes with metadata
}
private Dialogue dialogue;
private Program program;
public Loader(Dialogue d) {
if (d == null)
throw new IllegalArgumentException("dialogue d is null");
this.dialogue = d;
}
public Program getProgram() {
return program;
}
/**
* print tokens
*/
public void printTokenList(TokenList token_list) {
StringBuilder b = new StringBuilder();
for (Token token : token_list) {
b.appendLine(String.format("%1$s (%2$s line %3$s)", token.toString(), token.value, token.line_number));
}
dialogue.debug_logger.log("Tokens:");
dialogue.debug_logger.log(b.toString());
}
/**
* print the prase tree of node
*/
public void printParseTree(Parser.ParseNode root) {
dialogue.debug_logger.log("Parse Tree:");
dialogue.debug_logger.log(root.printTree(0));
}
// the preprocessor that cleans up things to make it easier on ANTLR which we do not use yet lol
// replaces \r\n with \n
// adds in INDENTS and DEDENTS where necessary
// replaces \t with four spaces
// takes in a string of yarn and returns a string the compiler can then use
// private static class EmissionTupple {
// public final int depth;
// public final boolean emmited;
// public EmissionTupple(int depth,boolean emitted) {
// this.depth = depth;
// this.emmited = emitted;
// }
// }
//
// private String preProcessor(String node_text) {
// String processed = null;
//
// return processed;
// }
/**
* given a bunch of raw text load all nodes that were inside it. You can call
* this multiple times to append to the collection of nodes, but note that new
* nodes will replace older ones with the same name.
*
* @return the number of nodes that were loaded
*/
public Program load(String text, Library library, String file_name, Program include, boolean show_tokens,
boolean show_parse_tree, String onlyconsider_node, NodeFormat format) {
if (format == NodeFormat.Unkown) {
format = getFormatFromFileName(file_name);
}
//final parsed nodes that were in file
ObjectMap<String, Parser.Node> nodes = new ObjectMap<String, Parser.Node>();
//load the raw data and get an array of node title-text pairs
NodeInfo[] infos = getNodesFromText(text, format);
//for soem weird reason its not used wtf
@SuppressWarnings("unused")
int nodes_loaded = 0;
for (NodeInfo info : infos) {
if (onlyconsider_node != null && !info.title.equals(onlyconsider_node))
continue;
//attempt to parse every nodel log if we encounter any errors
try {
if (nodes.containsKey(info.title)) {
throw new IllegalStateException("Attempted to load node called " + info.title
+ ", but a node with that name already exists!");
}
Lexer lexer = new Lexer();
TokenList tokens = lexer.tokenise(info.body);
if (show_tokens)
printTokenList(tokens);
Node node = new Parser(tokens, library).parse();
//if this node is tagged "rawText", then preserve its source
if (info.tags != null && !info.tags.isEmpty() && info.tags.contains("rawText")) {
node.setSource(info.getBody());
}
node.setName(info.title);
node.setNodeTags(info.tagsList());
if (show_parse_tree)
printParseTree(node);
nodes.put(node.getName(), node);
nodes_loaded++;
} catch (Exception e) {
if (e instanceof TokeniserException) {
String message = String.format("In file %s: Error reading %s:%s", file_name, info.title,
e.getMessage());
throw new TokeniserException(message);
} else if (e instanceof ParseException) {
String message = String.format("In file %s: Error parsing node %s:%s", file_name, info.title,
e.getMessage());
throw new ParseException(message);
} else if (e instanceof IllegalStateException) {
String message = String.format("in file %s: Error reading node %s:%s", file_name, info.title,
e.getMessage());
throw new IllegalStateException(message);
}else {
throw new IllegalStateException("Something went wrong in Yarn:"+e.getMessage());
}
}
}
Compiler compiler = new Compiler(file_name);
for (Entry<String, Parser.Node> n : nodes) {
compiler.compileNode(n.value);
}
if(include!=null)
compiler.program.include(include);
return compiler.program;
}
private static NodeFormat getFormatFromFileName(String file_name) {
NodeFormat format;
String fn = file_name.toLowerCase();
if (fn.endsWith(".json")) {
format = NodeFormat.Json;
} else if (fn.endsWith("yarn.txt")) {
format = NodeFormat.Text;
} else if (fn.endsWith(".node")) {
format = NodeFormat.SingleNodeText;
} else {
throw new IllegalArgumentException(String.format("Unknown file format for file '%s'", file_name));
}
return format;
}
/**
* given either twine,json or xml input, return an array containing info about
* the nodes in text file
*/
@SuppressWarnings("unchecked")
protected NodeInfo[] getNodesFromText(String text, NodeFormat format) {
Array<NodeInfo> nodes = new Array<Loader.NodeInfo>();
switch (format) {
case SingleNodeText:
//if it starts with a comment, treat it as a single line node file
NodeInfo node = new NodeInfo();
node.setTitle("Start");
node.setBody(text);
nodes.add(node);
break;
case Json:
//parse it as json
Json json = new Json();
try {
nodes = json.fromJson(Array.class, Loader.NodeInfo.class, text);
} catch (Exception e) {
if(e instanceof SerializationException) {
dialogue.error_logger.log("Error parsing Yarn input: " + e.getMessage());
}else if(e instanceof ClassCastException) {
dialogue.error_logger.log("Unable to cast yarn");
}
}
break;
case Text:
//check for the existance of atleast one '---'+newline sentinel, which divides
//the headers frmo the body
//we use a regex to match either \r\n or \n line endings
Matcher match = new Regex("---.?\n").match(text);
if (!match.find()) {
dialogue.error_logger.log("Error parsing input: text appears corrupt(no header)");
break;
}
BufferedReader reader = new BufferedReader(new StringReader(text));
Regex header_regex = new Regex("(?<field>.*): *(?<value>.*)");
int line_number = 0;
String line;
try {
while ((line = reader.readLine()) != null) {
//create a new node
NodeInfo info = new NodeInfo();
//read header lines
do {
line_number++;
//skip empty lines
if (line.length() == 0) {
continue;
}
//attempt ot parse header
Matcher header_match = header_regex.match(line);
if (!header_match.find()) {
dialogue.error_logger
.log(String.format("Line %s: cant parse header '%s'", line_number, line));
continue;
}
String field = header_match.group("field");
String value = header_match.group("value");
Object convert_value;
try {
@SuppressWarnings("rawtypes")
Class type = info.typeOfField(field);
if (type == String.class) {
convert_value = value;
} else if (type == Integer.class) {
convert_value = Integer.parseInt(value);
} else if (type == Position.class) {
String[] components = value.split(",");
//expect 2 components x and y
if (components.length != 2) {
throw new IllegalStateException();
}
Position pos = new Position();
pos.setX(Integer.parseInt(components[0]));
pos.setY(Integer.parseInt(components[1]));
convert_value = pos;
} else {
throw new IllegalStateException();
}
if (!info.setField(field, convert_value))
throw new IllegalStateException();
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
} else if (e instanceof IllegalStateException) {
dialogue.error_logger.log(String.format("%s:Error setting %s: invalid value '%s'",
line_number, field, value));
} else if (e instanceof NumberFormatException) {
dialogue.error_logger.log("could not convert " + field + ":" + e.getMessage());
}
}
} while (!(line = reader.readLine()).equals("---"));
line_number++;
//were past the header
Array<String> lines = new Array<String>();
while ((line = reader.readLine()) != null && !line.equals("===")) {
line_number++;
lines.add(line);
}
//were done reading lines, zip em up into a string and store it in the body
info.body = String.join("\n", lines);
//add thsi node to the list
nodes.add(info);
//move on to the next line
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
throw new IllegalStateException("Unkown format " + format.name());
}
return nodes.toArray( NodeInfo.class);
}
public static class NodeInfo {
private String title;
private String body;
//the raw tags
private String tags;
private int colorID;
private Position position;
//getters
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public String getTags() {
return tags;
}
public int getColorID() {
return colorID;
}
public Position getPosition() {
return position;
}
//setters
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
public void setTags(String tags) {
this.tags = tags;
}
public void setColorId(int colorId) {
this.colorID = colorId;
}
public void setPosition(Position position) {
this.position = position;
}
public Array<String> tagsList() {
//no tags return empty
if (tags == null || tags.length() == 0) {
return new Array<String>();
}
return new Array<String>(tags.trim().split(" "));
}
public static class Position {
private int x;
private int y;
public Position() {
x = 0;
y = 0;
}
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
};
public int getX() {
return x;
}
public int getY() {
return y;
}
}
@Override
public String toString() {
return String.format("Node{ title:%1$s ,body:%2$s}", title, body);
}
public boolean setField(String name, Object value) {
if (name.equals("title")) {
title = (String) value;
return true;
} else if (name.equals("tags")) {
tags = (String) value;
return true;
} else if (name.equals("colorID")) {
colorID = (Integer) value;
return true;
} else if (name.equals("position")) {
position = (Position) value;
return true;
} else if (name.equals("body")) {
body = (String) value;
return true;
}
return false;
}
@SuppressWarnings("rawtypes")
public Class typeOfField(String name) {
if (name.equals("title")) {
return String.class;
} else if (name.equals("tags")) {
return String.class;
} else if (name.equals("colorID")) {
return Integer.class;
} else if (name.equals("position")) {
return Position.class;
} else if (name.equals("body")) {
return String.class;
}
throw new IllegalArgumentException("field not found " + name);
}
}
}