summaryrefslogtreecommitdiff
path: root/RGens/src/main/java/bjc/rgens/newparser/RGrammars.java
blob: b8987266511b1a5ecb3569243a34a0b093096dc6 (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
package bjc.rgens.newparser;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Get access to the included grammars.
 *
 * @author Ben Culkin
 */
public class RGrammars {
	private static RGrammarSet gramSet;

	private static void loadSet() {
		URL rsc = RGrammarTest.class.getResource("/server-config-sample.cfg");

		try {
			Path cfgPath = Paths.get(rsc.toURI());

			gramSet = RGrammarSet.fromConfigFile(cfgPath);
		} catch (IOException | URISyntaxException ex) {
			RuntimeException rtex = new RuntimeException("Could not load grammars");

			rtex.initCause(ex);

			throw rtex;
		}
	}

	public static String generateExport(String exportName) throws GrammarException {
		if(gramSet == null) loadSet();

		if(!gramSet.getExportedRules().contains(exportName)) {
			throw new GrammarException(String.format("No built-in rule named %s", exportName));
		}

		RGrammar gram = gramSet.getExportSource(exportName);

		String res = gram.generate(exportName);
		if(exportName.contains("+")) res = res.replaceAll("\\s+", "");

		return res;
	}
}