- private Outputable parseCommand(String s2) {
- if (s2.startsWith("=_")) {
- final String raw = s2.substring(2);
- return new TranslateCommand(raw);
- } else if (s2.startsWith("=$")) {
- final String raw = s2.substring(2);
- return new OutputVariableCommand(raw);
- } else if (s2.startsWith("=s,")) {
- String command = s2.substring(3);
- final LinkedList<String> store = new LinkedList<String>();
- while (command.startsWith("$")) {
- int idx = command.indexOf(",");
- store.add(command.substring(0, idx));
- command = command.substring(idx + 1);
- }
- final String text = command;
- return new SprintfCommand(text, store);
- } else {
- System.out.println("Unknown processing instruction: " + s2);
- }
- return null;
- }
+ private TemplateBlock parse(Reader r) throws IOException {
+ LinkedList<String> splitted = new LinkedList<String>();
+ LinkedList<Outputable> commands = new LinkedList<Outputable>();
+ StringBuffer buf = new StringBuffer();
+ outer:
+ while (true) {
+ while ( !endsWith(buf, "<?")) {
+ int ch = r.read();
+ if (ch == -1) {
+ break outer;
+ }
+ buf.append((char) ch);
+ }
+ buf.delete(buf.length() - 2, buf.length());
+ splitted.add(buf.toString());
+ buf.delete(0, buf.length());
+ while ( !endsWith(buf, "?>")) {
+ int ch = r.read();
+ if (ch == -1) {
+ throw new EOFException();
+ }
+ buf.append((char) ch);
+ }
+ buf.delete(buf.length() - 2, buf.length());
+ String com = buf.toString().replace("\n", "");
+ buf.delete(0, buf.length());
+ Matcher m = CONTROL_PATTERN.matcher(com);
+ if (m.matches()) {
+ String type = m.group(1);
+ String variable = m.group(2);
+ TemplateBlock body = parse(r);
+ if (type.equals("if")) {
+ commands.add(new IfStatement(variable, body));
+ } else if (type.equals("foreach")) {
+ commands.add(new ForeachStatement(variable, body));
+ } else {
+ throw new IOException("Syntax error: unknown control structure: " + type);
+ }
+ continue;
+ }
+ if (com.matches(" ?\\} ?")) {
+ break;
+ }
+ commands.add(parseCommand(com));
+ }
+ splitted.add(buf.toString());
+ String[] contents = splitted.toArray(new String[splitted.size()]);
+ Outputable[] vars = commands.toArray(new Outputable[commands.size()]);
+ return new TemplateBlock(contents, vars);
+ }