1 8 13 package jfun.parsec; 14 15 import java.util.ArrayList ; 16 import java.util.Arrays ; 17 import java.util.Comparator ; 18 import java.util.HashMap ; 19 20 import jfun.parsec.tokens.Tokens; 21 22 27 final class Operators implements java.io.Serializable { 28 static WordsData instance(final String [] names){ 29 final HashMap <String ,Object > operators = new HashMap <String ,Object >(); 30 final String [] ops = sort(names); 31 final Parser[] lxs = new Parser[ops.length]; 32 for(int i=0; i<ops.length; i++){ 33 final String s = ops[i]; 34 final Parser<?> scanner = s.length()==1? 35 Scanners.isChar(s.charAt(0)): Scanners.isString(s); 36 final Object tok = Tokens.reserved(s); 37 operators.put(s, tok); 38 final Parser<Tok> lx = Lexers.lexer(scanner, ConstTokenizer.instance(tok)); 39 lxs[i] = lx; 40 } 41 return new WordsData(Maps.jmap(operators), lxs); 42 } 43 private static final Comparator <Object > com = new Comparator <Object >(){ 44 public int compare(final Object a, final Object b){ 45 if(a==b) return 0; 46 if(a==null) return -1; 47 if(b==null) return 1; 48 return a.toString().length() - b.toString().length(); 49 } 50 }; 51 private static final class Suite{ 52 private final ArrayList <String > list = new ArrayList <String >(); 53 Suite(String s){ 55 if(s.length()>0) 56 list.add(s); 57 } 58 boolean add(final String v){ 59 if(v.length()==0) return true; 60 for(int i=list.size()-1; i>=0; i--){ 61 final String s = (String )list.get(i); 62 if(s.startsWith(v)){ 63 if(s.length()==v.length()) return true; list.add(i+1, v); 65 return true; 66 } 67 } 68 return false; 69 } 70 int size(){return list.size();} 71 String get(int i){return (String )list.get(i);} 72 } 73 private static final class Suites{ 74 private final ArrayList <Suite> list = new ArrayList <Suite>(); 75 void add(final String v){ 77 for(int i=0; i<list.size(); i++){ 78 final Suite suite = (Suite)list.get(i); 79 if(suite.add(v)) return; 80 } 81 list.add(new Suite(v)); 82 } 83 String [] toArray(){ 84 final ArrayList <String > result = new ArrayList <String >(); 85 for(int i=list.size()-1;i>=0;i--){ 86 final Suite suite = (Suite)list.get(i); 87 for(int j=0; j<suite.size(); j++){ 88 result.add(suite.get(j)); 89 } 90 } 91 final String [] ret = new String [result.size()]; 92 result.toArray(ret); 93 return ret; 94 } 95 } 96 public static String [] sort(final String [] names){ 97 final String [] _names = (String [])names.clone(); 99 Arrays.sort(_names, com); 100 final Suites suites = new Suites(); 101 for(int i=_names.length-1; i>=0; i--){ 102 suites.add(_names[i]); 103 } 104 return suites.toArray(); 105 } 106 } 107 | Popular Tags |