Path: blob/master/test/jdk/java/lang/Character/CharCheck.java
41152 views
/*1* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/**26*27* @author Alan Liu28* @author John O'Conner29*/3031import java.io.*;323334/**35* This class either loads or dumps the character properties of all Unicode36* characters out to a file. When loading, it compares the loaded data with37* that obtained through the java.lang.Character API. This allows detection of38* changes to the character properties between versions of the Java VM. A39* typical usage would be to dump the properties under an early VM, and load40* them under a later VM.41*42* Also: Check the current VM's character properties against those in a43* Unicode database. The database should be of the format44* available on ftp.unicode.org/Public/UNIDATA.45*46*/47public class CharCheck {48static int differences = 0;4950public static void main(String args[]) throws Exception {5152if (args.length != 2 && args.length != 3) usage();53if (args[0].equals("dump"))54dump(Integer.parseInt(args[1], 16), new ObjectOutputStream(new FileOutputStream(args[2])));55else if (args[0].equals("load"))56load(Integer.parseInt(args[1], 16), new ObjectInputStream(new FileInputStream(args[2])));57else if (args[0].equals("check"))58check(Integer.parseInt(args[1], 16), new File(args[2]));59else if (args[0].equals("char"))60showChar(Integer.parseInt(args[1],16));61else if (args[0].equals("fchar"))62showFileChar(args[1], Integer.parseInt(args[2],16));63else usage();64if (differences != 0) {65throw new RuntimeException("There are differences between Character properties and the specification.");66}67}6869static void usage() {70System.err.println("Usage: java CharCheck <command>");71System.err.println("where <command> is one of the following:");72System.err.println("dump <plane> <file> - dumps the character properties of the given plane,");73System.err.println(" read from the current VM, to the given file.");74System.err.println("load <plane> <file> - loads the character properties from the given");75System.err.println(" file and compares them to those of the given character plane");76System.err.println(" in the current VM.");77System.err.println("check <plane> <file> - compare the current VM's character properties");78System.err.println(" in the given plane to those listed in the given file, ");79System.err.println(" which should be in the format available on ");80System.err.println(" ftp.unicode.org/Public/2.0-Update.");81System.err.println("char <code> - show current VM properties of the given Unicode char.");82System.err.println("fchar <file> <code> - show file properties of the given Unicode char.");83System.exit(0);84}8586static String getTypeName(int type) {87return (type >= 0 && type < UnicodeSpec.generalCategoryList.length) ?88(UnicodeSpec.generalCategoryList[type][UnicodeSpec.LONG] + '(' + type + ')') :89("<Illegal type value " + type + ">");90}9192static int check(int plane, File specFile) throws Exception {9394String version = System.getProperty("java.version");95System.out.println("Current VM version " + version);96int rangeLimit = (plane << 16) | 0xFFFF;97String record;98UnicodeSpec[] spec = UnicodeSpec.readSpecFile(specFile, plane);99int rangeStart = 0x0000;100boolean isRange = false;101102lastCheck = (plane << 16) - 1;103104for (int currentSpec = 0; currentSpec < spec.length; currentSpec++) {105int c = spec[currentSpec].getCodePoint();106if (isRange) {107// Must see end of range now108if (spec[currentSpec].getName().endsWith("Last>")) {109for (int d=rangeStart; d<=c; d++) {110checkOneChar(d, spec[currentSpec]);111}112}113else {114// No good -- First without Last115System.out.println("BAD FILE: First without last at '" + escape(rangeStart) + "'");116}117isRange = false;118}119else {120// Look for a First, Last pair: This is a pair of entries like the following:121// 4E00;<CJK Ideograph, First>;Lo;0;L;;;;;N;;;;;122// 9FA5;<CJK Ideograph, Last>;Lo;0;L;;;;;N;;;;;123if (spec[currentSpec].getName().endsWith("First>")) {124rangeStart = c;125isRange = true;126}127else {128checkOneChar(c, spec[currentSpec]);129}130}131}132133// Check undefined chars at the end of the range134135while (lastCheck < rangeLimit) checkOneCharDefined(++lastCheck, "?", false);136137System.out.println("Total differences: "+differences);138return differences;139}140141static int lastCheck = -1;142143static final void checkOneCharDefined(int c, String name, boolean fileDefined) {144if (Character.isDefined(c) != fileDefined)145showDifference(c, name, "isDefined", ""+(!fileDefined), ""+fileDefined);146}147148// In GenerateCharacter, the following ranges are handled specially.149// Each is the start of a 26-character range with values 10..35.150static final char NUMERIC_EXCEPTION[] = { '\u0041', '\u0061', '\uFF21', '\uFF41' };151152static void checkOneChar(int c, UnicodeSpec charSpec) {153// Handle intervening ranges -- we assume that we will be called in monotonically154// increasing order. If the last char we checked is more than one before this155// char, then check the intervening range -- it should all be undefined.156int lowerLimit = (c & 0xFF0000);157if (lastCheck >= lowerLimit && (lastCheck+1) != c) {158for (int i=lastCheck+1; i<c; ++i)159checkOneCharDefined(i, "?", false);160}161162lastCheck = c;163164// isDefined should be true165checkOneCharDefined(c, charSpec.getName(), true);166167// Check lower, upper, and titlecase conversion168int upper = Character.toUpperCase(c);169int lower = Character.toLowerCase(c);170int title = Character.toTitleCase(c);171int upperDB = charSpec.hasUpperMap() ? charSpec.getUpperMap() : c;172int lowerDB = charSpec.hasLowerMap() ? charSpec.getLowerMap() : c;173int titleDB = charSpec.hasTitleMap() ? charSpec.getTitleMap() : c;174if (upper != upperDB) showDifference(c, charSpec.getName(), "upper", hex6(upper), hex6(upperDB));175if (lower != lowerDB) showDifference(c, charSpec.getName(), "lower", hex6(lower), hex6(lowerDB));176if (title != titleDB) showDifference(c, charSpec.getName(), "title", hex6(title), hex6(titleDB));177178// Check the character general category (type)179int type = Character.getType(c);180int typeDB = charSpec.getGeneralCategory();181if (type != typeDB) {182showDifference(c, charSpec.getName(), "type",183UnicodeSpec.generalCategoryList[type][UnicodeSpec.SHORT],184UnicodeSpec.generalCategoryList[typeDB][UnicodeSpec.SHORT]);185}186187// Check the mirrored property188boolean isMirrored = Character.isMirrored(c);189boolean isMirroredDB = charSpec.isMirrored();190if (isMirrored != isMirroredDB) {191showDifference(c, charSpec.getName(), "isMirrored", ""+isMirrored, ""+isMirroredDB);192}193194// Check the directionality property195byte directionality = Character.getDirectionality(c);196byte directionalityDB = charSpec.getBidiCategory();197if (directionality != directionalityDB) {198showDifference(c, charSpec.getName(), "directionality", ""+directionality, ""+directionalityDB);199}200201// Check the decimal digit property202int decimalDigit = Character.digit(c, 10);203int decimalDigitDB = -1;204if (charSpec.getGeneralCategory() == UnicodeSpec.DECIMAL_DIGIT_NUMBER) {205decimalDigitDB = charSpec.getDecimalValue();206}207if (decimalDigit != decimalDigitDB)208showDifference(c, charSpec.getName(), "decimal digit", ""+decimalDigit, ""+decimalDigitDB);209210// Check the numeric property211int numericValue = Character.getNumericValue(c);212int numericValueDB;213if (charSpec.getNumericValue().length() == 0) {214numericValueDB = -1;215// Handle exceptions where Character deviates from the UCS spec216for (int k=0; k<NUMERIC_EXCEPTION.length; ++k) {217if (c >= NUMERIC_EXCEPTION[k] && c < (char)(NUMERIC_EXCEPTION[k]+26)) {218numericValueDB = c - NUMERIC_EXCEPTION[k] + 10;219break;220}221}222}223else {224String strValue = charSpec.getNumericValue();225int parsedNumericValue;226if (strValue.equals("10000000000")227|| strValue.equals("1000000000000")) {228System.out.println("Skipping strValue: " + strValue229+ " for " + charSpec.getName()230+ "(0x" + Integer.toHexString(c) + ")");231parsedNumericValue = -2;232} else {233parsedNumericValue = strValue.indexOf('/') < 0 ?234Integer.parseInt(strValue) : -2;235}236numericValueDB = parsedNumericValue < 0 ? -2 : parsedNumericValue;237}238if (numericValue != numericValueDB)239showDifference(c, charSpec.getName(), "numeric value", ""+numericValue, ""+numericValueDB);240}241242static void showDifference(int c, String name, String property, String vmValue, String dbValue) {243System.out.println(escape("Mismatch at '" + hex6(c) + "' (" + name+ "): " +244property + "=" + vmValue + ", db=" + dbValue));245++differences;246}247248/**249* Given a record containing ';'-separated fields, return the fieldno-th250* field. The first field is field 0.251*/252static String getField(String record, int fieldno) {253int i=0;254int j=record.indexOf(';');255while (fieldno > 0) {256i=j+1;257j=record.indexOf(';', i);258}259return record.substring(i, j);260}261262static final int FIELD_COUNT = 15;263264/**265* Given a record containing ';'-separated fields, return an array of266* the fields. It is assumed that there are FIELD_COUNT fields per record.267*/268static void getFields(String record, String[] fields) {269int i=0;270int j=record.indexOf(';');271fields[0] = record.substring(i, j);272for (int n=1; n<FIELD_COUNT; ++n) {273i=j+1;274j=record.indexOf(';', i);275fields[n] = (j<0) ? record.substring(i) : record.substring(i, j);276}277}278279/**280* Given a record containing ';'-separated fields, return an array of281* the fields. It is assumed that there are FIELD_COUNT fields per record.282*/283static String[] getFields(String record) {284String[] fields = new String[FIELD_COUNT];285getFields(record, fields);286return fields;287}288289static void dump(int plane, ObjectOutputStream out) throws Exception {290String version = System.getProperty("java.version");291System.out.println("Writing file version " + version);292out.writeObject(version);293294long[] data = new long[0x20000];295long[] onechar = new long[2];296int j=0;297int begin = plane<<16;298int end = begin + 0xFFFF;299for (int i = begin; i <= end; ++i) {300getPackedCharacterData(i, onechar);301data[j++] = onechar[0];302data[j++] = onechar[1];303}304out.writeObject(data);305}306307static long[] loadData(ObjectInputStream in) throws Exception {308String version = System.getProperty("java.version");309String inVersion = (String)in.readObject();310System.out.println("Reading file version " + inVersion);311System.out.println("Current version " + version);312313long[] data = (long[])in.readObject();314if (data.length != 0x20000) {315System.out.println("BAD ARRAY LENGTH: " + data.length);316}317return data;318}319320static int load(int plane, ObjectInputStream in) throws Exception {321long[] data = CharCheck.loadData(in);322CharCheck.checkData(data, plane);323return differences;324}325326327static int checkData(long[] data, int plane) {328long[] onechar = new long[2];329330for (int i=0; i<0x10000; ++i) {331int c = (plane << 16) | i;332getPackedCharacterData(c, onechar);333if (data[2*i] != onechar[0] || data[2*i+1] != onechar[1]) {334long[] filechar = { data[2*i], data[2*i+1] };335showDifference(c, onechar, filechar);336}337}338System.out.println("Total differences: " + differences);339return differences;340}341342static String hex6(long n) {343String q = Long.toHexString(n).toUpperCase();344return "000000".substring(Math.min(6, q.length())) + q;345}346347static void showChar(int c) {348long[] chardata = new long[2];349getPackedCharacterData(c, chardata);350System.out.println("Current VM properties for '" + hex6(c) + "': " +351hex6(chardata[1]) + ' ' + hex6(chardata[0]));352String[] data = unpackCharacterData(chardata);353for (int i=0; i<data.length; ++i)354System.out.println(" " + escape(data[i]));355}356357static void showFileChar(String fileName, int c) throws Exception {358ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));359String inVersion = (String)in.readObject();360System.out.println("Reading file version " + inVersion);361362long[] data = (long[])in.readObject();363if (data.length != 0x20000) {364System.out.println("BAD ARRAY LENGTH: " + data.length);365}366int offset = c & 0xFFFF;367long[] chardata = { data[2*offset], data[2*offset+1] };368String[] datap = unpackCharacterData(chardata);369System.out.println(escape("File properties for '" + hex6(c)+ "':"));370for (int i=0; i<datap.length; ++i)371System.out.println(" " + escape(datap[i]));372}373374/**375* The packed character data encapsulates all the information obtainable376* about a character in a single numeric value.377*378* data[0]:379*380* 5 bits for getType()381* 6 bits for digit() -- add one382* 6 bits for getNumericValue() -- add two383* 15 bits for isXxx()384*385* 21 bits for toUpperCase()386*387*388* data[1]:389* 21 bits for toLowerCase()390* 21 bits for toTitleCase()391*/392static void getPackedCharacterData(int c, long[] data) {393data[0] =394(long)Character.getType(c) |395((long)(Character.digit(c, Character.MAX_RADIX) + 1) << 5) |396((long)(Character.getNumericValue(c) + 2) << 11) |397(Character.isDefined(c) ? (1L<<17) : 0L) |398(Character.isDigit(c) ? (1L<<18) : 0L) |399(Character.isIdentifierIgnorable(c) ? (1L<<19) : 0L) |400(Character.isISOControl(c) ? (1L<<20) : 0L) |401(Character.isJavaIdentifierPart(c) ? (1L<<21) : 0L) |402(Character.isJavaIdentifierStart(c) ? (1L<<22) : 0L) |403(Character.isLetter(c) ? (1L<<23) : 0L) |404(Character.isLetterOrDigit(c) ? (1L<<24) : 0L) |405(Character.isLowerCase(c) ? (1L<<25) : 0L) |406(Character.isSpaceChar(c) ? (1L<<26) : 0L) |407(Character.isTitleCase(c) ? (1L<<27) : 0L) |408(Character.isUnicodeIdentifierPart(c) ? (1L<<28) : 0L) |409(Character.isUnicodeIdentifierStart(c) ? (1L<<29) : 0L) |410(Character.isUpperCase(c) ? (1L<<30) : 0L) |411(Character.isWhitespace(c) ? (1L<<31) : 0L) |412((long)Character.toUpperCase(c) << 32);413data[1] = (long)Character.toLowerCase(c) |414((long)Character.toTitleCase(c) << 21);415}416417/**418* Given a long, set the bits at the given offset and length to the given value.419*/420static long setBits(long data, int offset, int length, long value) {421long himask = -1L << (offset+length);422long lomask = ~(-1L << offset);423long lengthmask = ~(-1L << length);424return (data & (himask | lomask)) | ((value & lengthmask) << offset);425}426427/**428* Given packed character data, change the attribute429* toLower430*/431static void setToLower(long[] data, int value) {432data[0] = setBits(data[0], 48, 16, value);433}434435/**436* Given packed character data, change the attribute437* toUpper438*/439static void setToUpper(long[] data, int value) {440data[0] = setBits(data[0], 32, 16, value);441}442443/**444* Given packed character data, change the attribute445* toTitle446*/447static void setToTitle(long[] data, int value) {448data[1] = value;449}450451/**452* Given packed character data, change the attribute453* getType454*/455static void setGetType(long[] data, int value) {456data[0] = setBits(data[0], 0, 5, value);457}458459/**460* Given packed character data, change the attribute461* isDefined462*/463static void setIsDefined(long[] data, boolean value) {464data[0] = setBits(data[0], 17, 1, value?1:0);465}466467/**468* Given packed character data, change the attribute469* isJavaIdentifierPart470*/471static void setIsJavaIdentifierPart(long[] data, boolean value) {472data[0] = setBits(data[0], 21, 1, value?1:0);473}474475/**476* Given packed character data, change the attribute477* isJavaIdentifierStart478*/479static void setIsJavaIdentifierStart(long[] data, boolean value) {480data[0] = setBits(data[0], 22, 1, value?1:0);481}482483static String[] unpackCharacterData(long[] dataL) {484long data = dataL[0];485String[] result = {486"type=" + getTypeName((int)(data&0x1F)),487"digit=" + (((data>>5)&0x3F)-1),488"numeric=" + (((data>>11)&0x3F)-2),489"isDefined=" + (((data>>17)&1)==1),490"isDigit=" + (((data>>18)&1)==1),491"isIdentifierIgnorable=" + (((data>>19)&1)==1),492"isISOControl=" + (((data>>20)&1)==1),493"isJavaIdentifierPart=" + (((data>>21)&1)==1),494"isJavaIdentifierStart=" + (((data>>22)&1)==1),495"isLetter=" + (((data>>23)&1)==1),496"isLetterOrDigit=" + (((data>>24)&1)==1),497"isLowerCase=" + (((data>>25)&1)==1),498"isSpaceChar=" + (((data>>26)&1)==1),499"isTitleCase=" + (((data>>27)&1)==1),500"isUnicodeIdentifierPart=" + (((data>>28)&1)==1),501"isUnicodeIdentifierStart=" + (((data>>29)&1)==1),502"isUpperCase=" + (((data>>30)&1)==1),503"isWhitespace=" + (((data>>31)&1)==1),504"toUpper=" + hex6(((int)(data>>32) & 0X1FFFFF)),505"toLower=" + hex6((int)(dataL[1] & 0x1FFFFF)),506"toTitle=" + hex6(((int)(dataL[1] >> 21) & 0x1FFFFF))507};508return result;509}510511static String[] getCharacterData(int c) {512long[] data = new long[2];513getPackedCharacterData(c, data);514return unpackCharacterData(data);515}516517static void showDifference(int c, long[] currentData, long[] fileData) {518System.out.println("Difference at " + hex6(c));519String[] current = unpackCharacterData(currentData);520String[] file = unpackCharacterData(fileData);521for (int i=0; i<current.length; ++i) {522if (!current[i].equals(file[i])) {523System.out.println(escape(" current " + current[i] +524", file " + file[i]));525}526}527++differences;528}529530static String escape(String s) {531StringBuffer buf = new StringBuffer();532for (int i=0; i<s.length(); ++i) {533char c = s.charAt(i);534if (c >= 0x20 && c <= 0x7F) buf.append(c);535else {536buf.append("\\u");537String h = "000" + Integer.toHexString(c);538if (h.length() > 4) h = h.substring(h.length() - 4);539buf.append(h);540}541}542return buf.toString();543}544545static String escape(int c) {546StringBuffer buf = new StringBuffer();547if (c >= 0x20 && c <= 0x7F) buf.append(c);548else {549buf.append("\\u");550String h = "000" + Integer.toHexString(c);551if (h.length() > 4) h = h.substring(h.length() - 4);552buf.append(h);553}554return buf.toString();555}556}557558559//eof560561562