Compute a document difference metric 0-1.0 between two documents that are identical other than (likely) the whitespace and comments. 1.0 means the docs are maximally different and 0 means docs are identical. The Levenshtein distance between the docs counts only whitespace diffs as the non-WS c
(String original, String formatted, Class<? extends Lexer> lexerClass)
| 214 | * mismatched whitespace? real text are like anchors. |
| 215 | */ |
| 216 | public static double docDiff(String original, |
| 217 | String formatted, |
| 218 | Class<? extends Lexer> lexerClass) |
| 219 | throws Exception |
| 220 | { |
| 221 | // Grammar must strip all but real tokens and whitespace (and put that on hidden channel) |
| 222 | CodeBuffTokenStream original_tokens = Tool.tokenize(original, lexerClass); |
| 223 | // String s = original_tokens.getText(); |
| 224 | CodeBuffTokenStream formatted_tokens = Tool.tokenize(formatted, lexerClass); |
| 225 | // String t = formatted_tokens.getText(); |
| 226 | |
| 227 | // walk token streams and examine whitespace in between tokens |
| 228 | int i = -1; |
| 229 | int ws_distance = 0; |
| 230 | int original_ws = 0; |
| 231 | int formatted_ws = 0; |
| 232 | while ( true ) { |
| 233 | Token ot = original_tokens.LT(i); // TODO: FIX THIS! can't use LT() |
| 234 | if ( ot==null || ot.getType()==Token.EOF ) break; |
| 235 | List<Token> ows = original_tokens.getHiddenTokensToLeft(ot.getTokenIndex()); |
| 236 | original_ws += tokenText(ows).length(); |
| 237 | |
| 238 | Token ft = formatted_tokens.LT(i); // TODO: FIX THIS! can't use LT() |
| 239 | if ( ft==null || ft.getType()==Token.EOF ) break; |
| 240 | List<Token> fws = formatted_tokens.getHiddenTokensToLeft(ft.getTokenIndex()); |
| 241 | formatted_ws += tokenText(fws).length(); |
| 242 | |
| 243 | ws_distance += whitespaceEditDistance(tokenText(ows), tokenText(fws)); |
| 244 | i++; |
| 245 | } |
| 246 | // it's probably ok to ignore ws diffs after last real token |
| 247 | |
| 248 | int max_ws = Math.max(original_ws, formatted_ws); |
| 249 | double normalized_ws_distance = ((float) ws_distance)/max_ws; |
| 250 | return normalized_ws_distance; |
| 251 | } |
| 252 | |
| 253 | /** Compare an input document's original text with its formatted output |
| 254 | * and return the ratio of the incorrectWhiteSpaceCount to total whitespace |
nothing calls this directly
no test coverage detected