Created
October 11, 2010 01:49
-
-
Save rjungemann/619845 to your computer and use it in GitHub Desktop.
Fudi parser in Java (for use with PureData)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.teamsketchy.utils; | |
import java.util.LinkedList; | |
import java.util.ListIterator; | |
public class FudiParser { | |
public static LinkedList<String[]> tokenize(String string) { | |
LinkedList<String[]> tokens = new LinkedList<String[]>(); | |
for(int i = 0; i < string.length(); i++) { | |
String[] token; | |
char c = string.charAt(i); | |
if(c == '\n' || c == '\t' || c == ' ') { | |
token = new String[] { "whitespace", Character.toString(c) }; | |
} else if(c == ';') { | |
token = new String[] { "semicolon", Character.toString(c) }; | |
} else if(c == '\\') { | |
token = new String[] { "backslash", Character.toString(c) }; | |
} else { | |
token = new String[] { "char", Character.toString(c) }; | |
} | |
tokens.addLast(token); | |
} | |
ListIterator<String[]> iterator = tokens.listIterator(); | |
while(iterator.hasNext()) { | |
String[] previousToken = tokens.get(iterator.previousIndex()); | |
String[] token = iterator.next(); | |
if(previousToken[0] == "backslash" && token[0] == "whitespace") { | |
tokens.remove(previousToken); | |
token[0] = "char"; | |
} | |
} | |
iterator = tokens.listIterator(); | |
while(iterator.hasNext()) { | |
String[] previousToken = tokens.get(iterator.previousIndex()); | |
String[] token = iterator.next(); | |
if( | |
previousToken[0] == "char" || previousToken[0] == "atom" && | |
token[0] == "char" | |
) { | |
token[0] = "atom"; | |
token[1] = previousToken[1] + token[1]; | |
tokens.remove(previousToken); | |
} | |
} | |
return tokens; | |
} | |
public static LinkedList<LinkedList<String[]>> parse(String string) { | |
LinkedList<String[]> tokens = tokenize(string); | |
LinkedList<LinkedList<String[]>> messages = | |
new LinkedList<LinkedList<String[]>>(); | |
ListIterator<String[]> iterator = tokens.listIterator(); | |
while(iterator.hasNext()) { | |
String[] token = iterator.next(); | |
if(token[0] == "atom") { | |
LinkedList<String[]> message = new LinkedList<String[]>(); | |
ListIterator<String[]> innerIterator = | |
tokens.listIterator(iterator.previousIndex()); | |
while(innerIterator.hasNext()) { | |
String[] innerToken = innerIterator.next(); | |
if(innerToken[0] == "atom") { | |
message.addLast(innerToken); | |
} else if(innerToken[0] == "semicolon") { | |
break; | |
} | |
} | |
messages.addLast(message); | |
} else { | |
iterator.next(); | |
} | |
} | |
return messages; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment