summaryrefslogtreecommitdiff
path: root/RGens/src/main/java/bjc/rgens/server/GrammarServerEngine.java
blob: 2f608ec300e02c65f79371f4b24f76f6423fabef (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
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
package bjc.rgens.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;
import bjc.utils.funcdata.IMap;
import bjc.utils.funcutils.ListUtils;
import bjc.utils.gen.WeightedGrammar;

public class GrammarServerEngine {
	private IMap<String, WeightedGrammar<String>> loadedGrammars;
	private IMap<String, WeightedGrammar<String>> exportedRules;
	
	public static boolean debugMode = false;
	
	public GrammarServerEngine(IMap<String, WeightedGrammar<String>> loadedGrammars,
			IMap<String, WeightedGrammar<String>> exportedRules) {
		this.loadedGrammars = loadedGrammars;
		this.exportedRules = exportedRules;
	}

	public String getInitialRule(String grammarName) {
		return loadedGrammars.get(grammarName).getInitialRule();
	}
	
	public boolean hasInitialRule(String grammarName) {
		return loadedGrammars.get(grammarName).hasInitialRule();
	}
	
	public boolean hasExportedRule(String ruleName) {
		return exportedRules.containsKey(ruleName);
	}
	
	public boolean hasLoadedGrammar(String grammarName) {
		return loadedGrammars.containsKey(grammarName);
	}
	
	public void doLoadConfig(String fileName) {
		File inputFile = new File(fileName);
	
		try(FileInputStream inputStream = new FileInputStream(inputFile)) {
			try(Scanner fle = new Scanner(inputStream)) {
				while(fle.hasNextLine()) {
					String line = fle.nextLine().trim();
	
					// Handle comments
					if(line.equals("") ||
							line.startsWith("#") ||
							line.startsWith("//")) {
						continue;
					}
	
					// Handle mixed whitespace in input
					line = line.replaceAll("\\s+", " ");
	
					String path;
					String name;
	
					if(line.lastIndexOf(' ') != -1) {
						path = line.substring(0, line.lastIndexOf(' '));
						name = line.substring(line.lastIndexOf(' ') + 1, line.length());
					} else {
						path = line;
	
						File pathFile = new File(path);
						String pathName = pathFile.getName();
	
						if(pathFile.isDirectory()) {
							// Load all the files in the directory recursively
							Queue<File> entries = new LinkedList<>();
							
							for (File entry : pathFile.listFiles()) {
								entries.add(entry);
							}
							
							while(!entries.isEmpty()) {
								File entry = entries.poll();
								
								String entryPath = entry.getName();
								
								if(entry.isHidden()) continue;
								if(entry.isDirectory()) {
									for (File newEntry : entry.listFiles()) {
										entries.add(newEntry);
									}
									
									continue;
								}
								
								name = entryPath.substring(0, entryPath.lastIndexOf('.'));
								
								doLoadGrammarEntry(entry.toString(), name);
							}
							
							continue;
						}
						
						name = pathName.substring(0, pathName.lastIndexOf('.'));
					}
	
					doLoadGrammarEntry(path, name);
				}
			}
		} catch(IOException ioex) {
			System.out.printf("? Error reading configuration from file"
					+ " (reason: %s)\n", ioex.getMessage());
		}
	}

	private void doLoadGrammarEntry(String path, String name) {
		if(path.endsWith(".gram")) {
			doLoadGrammar(name, path);
		} else if(path.endsWith(".template")) {
			System.out.println("Error: Templates are not supported yet");
		} else if(path.endsWith(".long")) {
			doLoadLongRule(name, path);
		} else {
			System.out.println("Error: Unknown filetype " + 
					path.substring(path.lastIndexOf("."), path.length()));
		}
	}

	public void doLoadLongRule(String ruleName, String ruleFile) {
		ruleName = "[" + ruleName + "]";
	
		if(debugMode) {
			System.out.printf("Loading long rule (named %s) from path %s\n",
					ruleName, ruleFile);
		}

		try (FileInputStream inputStream = new FileInputStream(ruleFile)) {
			try (Scanner fle = new Scanner(inputStream)) {
				IList<IList<String>> ruleParts = new FunctionalList<>();
	
				while(fle.hasNextLine()) {
					ruleParts.add(new FunctionalList<>(fle.nextLine().trim().split(" ")));
				}
	
				WeightedGrammar<String> longGram = new WeightedGrammar<>();
	
				longGram.addSpecialRule(ruleName, () -> ruleParts.randItem());
				longGram.setInitialRule(ruleName);
	
				exportedRules.put(ruleName, longGram);
	
				if(debugMode) {
					System.out.printf("Loaded long rule (named %s) from path %s\n",
							ruleName, ruleFile);
				}
			}
		} catch (IOException ioex) {
			System.out.printf("Error reading long rule (%s)\n", ioex.getMessage());
		}
	}

	public void doLoadGrammar(String grammarName, String grammarPath) {
		if(debugMode) {
			System.out.printf("Loading grammar (named %s) from path %s\n",
					grammarName, grammarPath);
		}

		try (FileInputStream inputStream = new FileInputStream(grammarPath)) {
			WeightedGrammar<String> newGram = 
				ServerGrammarReader.fromStream(inputStream).merge((gram, exports) -> {
					for(String export : exports.toIterable()) {
						if(debugMode) {
							System.out.printf("\tLoaded exported rule %s from grammar %s\n",
								export, grammarName);

							if(exportedRules.containsKey(export)) {
								System.out.printf("\tWarning: Exported rule %s from grammar %s" +
										" shadows a pre-existing rule\n", export, grammarName);
							}
						}

						exportedRules.put(export, gram);
					}

					return gram;
				});

			loadedGrammars.put(grammarName, newGram);
		} catch (IOException ioex) {
			System.out.printf("? Error reading grammar from file"
					+ " (reason: %s)\n", ioex.getMessage());
		}

		if(debugMode) {
			System.out.printf("Loaded grammar (named %s) from path %s\n",
					grammarName, grammarPath);
		}
	}
	
	public void doGenerateExportedRule(String ruleName) {
		String ruleResult = ListUtils.collapseTokens(
				exportedRules.get(ruleName)
				.generateListValues(ruleName, " "));
	
		System.out.println("Generated Result: ");
		System.out.println("\t" + ruleResult.replaceAll("\\s+", " "));
	}

	public void doGenerateGrammar(String currentGram, String ruleName) {
		doGenerateGrammar(loadedGrammars.get(currentGram), ruleName);	
	}

	public void doGenerateGrammar(WeightedGrammar<String> currentGram, String ruleName) {
		String ruleResult = ListUtils.collapseTokens(
				currentGram.generateListValues(ruleName, " "));
	
		System.out.println("Generated Result: ");
		System.out.println("\t" + ruleResult.replaceAll("\\s+", " "));
	}

	public void doShowExportedRules() {
		System.out.printf("Currently exported rules (%d total):\n",
				exportedRules.getSize());
	
		exportedRules.forEachKey(key -> {
			System.out.println("\t" + key);
		});
	}

	public void doShowGrammarRules(String gramName) {
		WeightedGrammar<String> gram = loadedGrammars.get(gramName);
	
		IList<String> ruleNames = gram.getRuleNames();
	
		System.out.printf("Rules for grammar %s (%d total)\n",
				gramName, ruleNames.getSize());
	
		ruleNames.forEach(rule -> {
			System.out.println("\t" + rule);
		});
	}

	public void doShowLoadedGrammars() {
		System.out.printf("Currently loaded grammars (%d total):\n",
				loadedGrammars.getSize());
	
		loadedGrammars.forEachKey(key -> {
			System.out.println("\t" + key);
		});
	}

	public void doStressTest(int count) {
		exportedRules.forEachKey(key -> {
			doStressTest(key, count);
		});
	}
	
	public void doStressTest(String ruleName, int count) {
		doStressTest(exportedRules.get(ruleName), ruleName, count);
	}

	public void doStressTest(WeightedGrammar<String> gram, String ruleName, int count) {
		if(debugMode) System.out.println("Stress-testing rule " + ruleName);
		
		IList<String> res = new FunctionalList<>();
		IList<String> foundTags = new FunctionalList<>();

		boolean foundBroken = false;

		for(int i = 0; i < count; i++) {
			res = gram.generateListValues(ruleName, " ");

			for(String tok : res.toIterable()) {
				if(tok.matches("\\[\\S+\\]") && !foundTags.contains(tok)) {
					System.out.println("\tWarning: Possible un-expanded rule " + tok + " found" 
							+ " in expansion of " + ruleName);

					doFindRule(tok);

					foundBroken = true;

					foundTags.add(tok);
				}
			}
		}

		if(debugMode) {
			if(!foundBroken) System.out.printf("Rule %s succesfully passed stress-testing\n", ruleName);
			else System.out.printf("Rule %s failed stress-testing\n", ruleName);
		}
	}
	
	private void doFindRule(String ruleName) {
		loadedGrammars.forEach((gramName, gram) -> {
			if(gram.hasRule(ruleName)) {
				System.out.printf("\t\tFound rule %s in grammar %s\n", ruleName, gramName);
			}
		});
	}
}