Debian Codegraph @

net/sf/saxon/regex/charclass/Categories.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.regex.charclass;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.Builder;
12 import net.sf.saxon.lib.ParseOptions;
13 import net.sf.saxon.lib.Validation;
14 import net.sf.saxon.om.AxisInfo;
15 import net.sf.saxon.om.NodeInfo;
16 import net.sf.saxon.pattern.NameTest;
17 import net.sf.saxon.pattern.NodeKindTest;
18 import net.sf.saxon.serialize.charcode.XMLCharacterData;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.iter.AxisIterator;
21 import net.sf.saxon.tree.tiny.TinyElementImpl;
22 import net.sf.saxon.type.Type;
23 import net.sf.saxon.z.*;
24
25 import javax.xml.transform.stream.StreamSource;
26 import java.io.InputStream;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.function.IntPredicate;
31
32 /**
33 * Data for Regular expression character categories. The data is in an XML file derived from the Unicode
34 * database (In Saxon 9.6, this is based on Unicode 6.2.0). Since Saxon 9.4,
35 * we no longer make use of Java's support for character categories since there are too many differences
36 * from Unicode.
37 */
38 public class Categories {
39
40 /**
41 * A Category is a CharacterClass represented in a regular expression as \p{Xx}.
42 * The label Xx is retained, and can be used to determine whether or not two
43 * categories are disjoint.
44 */
45
46 public static class Category implements CharacterClass {
47
48 private String label;
49 private IntPredicate predicate;
50
51 public Category(String label, java.util.function.IntPredicate predicate) {
52 this.label = label;
53 this.predicate = predicate;
54 }
55
56 public boolean test(int value) {
57 return predicate.test(value);
58 }
59
60 public boolean isDisjoint(CharacterClass other) {
61 if (other instanceof Category) {
62 char majorCat0 = label.charAt(0);
63 String otherLabel = ((Category)other).label;
64 char majorCat1 = otherLabel.charAt(0);
65 return majorCat0 != majorCat1 ||
66 (label.length() > 1 && otherLabel.length() > 1 && !label.equals(otherLabel));
67
68 } else if (other instanceof InverseCharacterClass) {
69 return other.isDisjoint(this);
70 } else if (other instanceof SingletonCharacterClass) {
71 return !test(((SingletonCharacterClass)other).getCodepoint());
72 } else if (other instanceof IntSetCharacterClass) {
73 IntSet intSet = other.getIntSet();
74 if (intSet.size() > 100) {
75 // too expensive to test, and increasingly likely to be non-disjoint anyway
76 return false;
77 }
78 IntIterator ii = intSet.iterator();
79 while (ii.hasNext()) {
80 if (test(ii.next())) {
81 return false;
82 }
83 }
84 return true;
85 } else {
86 return false;
87 }
88 }
89
90 public IntSet getIntSet() {
91 return extent(predicate);
92 }
93
94 private static IntSet extent(IntPredicate predicate) {
95 if (predicate instanceof IntSetPredicate) {
96 return ((IntSetPredicate) predicate).getIntSet();
97 }
98 return null;
99 }
100 }
101
102
103 private static HashMap<String, Category> CATEGORIES = null;
104
105 static void build() {
106
107 CATEGORIES = new HashMap<>(30);
108
109 InputStream in = Configuration.locateResource("categories.xml", new ArrayList<>(), new ArrayList<>());
110 if (in == null) {
111 throw new RuntimeException("Unable to read categories.xml file");
112 }
113
114 Configuration config = new Configuration();
115 ParseOptions options = new ParseOptions();
116 options.setSchemaValidationMode(Validation.SKIP);
117 options.setTreeModel(Builder.TINY_TREE);
118 NodeInfo doc;
119 try {
120 doc = config.buildDocumentTree(new StreamSource(in, "categories.xml"), options).getRootNode();
121 } catch (XPathException e) {
122 throw new RuntimeException("Failed to build categories.xml", e);
123 }
124
125 int fp_name = config.getNamePool().allocateFingerprint("", "name");
126 int fp_f = config.getNamePool().allocateFingerprint("", "f");
127 int fp_t = config.getNamePool().allocateFingerprint("", "t");
128
129 AxisIterator iter = doc.iterateAxis(AxisInfo.DESCENDANT, new NameTest(Type.ELEMENT, "", "cat", config.getNamePool()));
130 iter.forEach(item -> {
131 String cat = ((TinyElementImpl)item).getAttributeValue(fp_name);
132 IntRangeSet irs = new IntRangeSet();
133 AxisIterator iter2 = item.iterateAxis(AxisInfo.CHILD, NodeKindTest.ELEMENT);
134 iter2.forEach(r -> {
135 String from = ((TinyElementImpl)r).getAttributeValue(fp_f);
136 String to = ((TinyElementImpl) r).getAttributeValue(fp_t);
137 irs.addRange(Integer.parseInt(from, 16), Integer.parseInt(to, 16));
138 });
139 CATEGORIES.put(cat, new Category(cat, new IntSetPredicate(irs)));
140 });
141
142 String c = "CLMNPSZ";
143 for (int i = 0; i < c.length(); i++) {
144 char ch = c.charAt(i);
145 IntPredicate ip = null;
146 for (Map.Entry<String, Category> entry : CATEGORIES.entrySet()) {
147 if (entry.getKey().charAt(0) == ch) {
148 ip = ip == null ? entry.getValue() : ip.or(entry.getValue());
149 }
150 }
151 String label = ch + "";
152 CATEGORIES.put(label, new Category(label, ip));
153 }
154 }
155
156 public final static CharacterClass ESCAPE_s =
157 new IntSetCharacterClass(IntArraySet.make(new int[]{9, 10, 13, 32}, 4));
158
159 public final static CharacterClass ESCAPE_S = new InverseCharacterClass(ESCAPE_s);
160
161 public final static PredicateCharacterClass ESCAPE_i =
162 new PredicateCharacterClass(value -> XMLCharacterData.isNCNameStart11(value) || value == ':');
163
164 public final static CharacterClass ESCAPE_I = new InverseCharacterClass(ESCAPE_i);
165
166 public final static PredicateCharacterClass ESCAPE_c =
167 new PredicateCharacterClass(value -> XMLCharacterData.isNCName11(value) || value == ':');
168
169 public final static CharacterClass ESCAPE_C = new InverseCharacterClass(ESCAPE_c);
170
171 public final static Category ESCAPE_d = getCategory("Nd");
172
173 public final static CharacterClass ESCAPE_D = new InverseCharacterClass(ESCAPE_d);
174
175 static Category CATEGORY_P = getCategory("P");
176 static Category CATEGORY_Z = getCategory("Z");
177 static Category CATEGORY_C = getCategory("C");
178
179 public final static PredicateCharacterClass ESCAPE_w =
180 new PredicateCharacterClass(value -> !(CATEGORY_P.test(value) || CATEGORY_Z.test(value) || CATEGORY_C.test(value)));
181
182 public final static CharacterClass ESCAPE_W = new InverseCharacterClass(ESCAPE_w);
183
184 /**
185 * Get a predicate to test characters for membership of one of the Unicode
186 * character categories
187 *
188 * @param cat a one-character or two-character category name, for example L or Lu
189 * @return a predicate that tests whether a given character belongs to the category
190 */
191
192 public static Category getCategory(String cat) {
193 if (CATEGORIES == null) {
194 build();
195 }
196 return CATEGORIES.get(cat);
197 }
198
199
200 }
201
202 // The following stylesheet was used to generate the categories.xml file from the Unicode 6.2.0 database:
203
204 //<?xml version="1.0" encoding="UTF-8"?>
205 //<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
206 // xmlns:xs="http://www.w3.org/2001/XMLSchema"
207 // xmlns:f="http://local-functions/"
208 // exclude-result-prefixes="xs f"
209 // xpath-default-namespace="http://www.unicode.org/ns/2003/ucd/1.0"
210 // version="3.0">
211 //
212 // <!-- Output XML representation of character categories -->
213 //
214 // <xsl:output method="xml" indent="yes" encoding="us-ascii" saxon:suppress-indentation="cat" xmlns:saxon="http://saxon.sf.net/"/>
215 //
216 // <xsl:param name="v6" select="doc('ucd.all.flat.xml')"/>
217 //
218 // <xsl:key name="cat-key" match="*[@cp]" use="@gc"/>
219 // <xsl:key name="range-key" match="*[@first-cp]" use="@gc"/>
220 //
221 // <xsl:template name="main">
222 // <categories>
223 // <xsl:variable name="categories" select="distinct-values($v6/ucd/repertoire/(char|reserved)/@gc)"/>
224 // <xsl:for-each select="$categories">
225 // <xsl:sort select="."/>
226 //
227 // <cat name="{.}">
228 // <xsl:variable name="chars" select="key('cat-key', ., $v6)/@cp"/>
229 // <xsl:variable name="codes" select="for $c in $chars return f:hexToInt(0,$c)"/>
230 //
231 // <xsl:variable name="ranges" as="element()*">
232 // <xsl:for-each-group select="$codes" group-adjacent=". - position()">
233 // <range f="{f:intToHex(current-group()[1])}" t="{f:intToHex(current-group()[1] + count(current-group()) - 1)}"/>
234 // </xsl:for-each-group>
235 //
236 // <xsl:for-each select="key('range-key', ., $v6)">
237 // <range f="{f:intToHex(f:hexToInt(0,@first-cp))}" t="{f:intToHex(f:hexToInt(0,@last-cp))}"/>
238 // </xsl:for-each>
239 // </xsl:variable>
240 //
241 // <xsl:perform-sort select="$ranges">
242 // <xsl:sort select="f:hexToInt(0,@f)"/>
243 // </xsl:perform-sort>
244 //
245 // </cat>
246 // </xsl:for-each>
247 // </categories>
248 // </xsl:template>
249 //
250 //
251 // <xsl:function name="f:hexToInt" as="xs:integer">
252 // <xsl:param name="acc" as="xs:integer"/>
253 // <xsl:param name="in" as="xs:string"/>
254 // <xsl:choose>
255 // <xsl:when test="$in eq ''">
256 // <xsl:sequence select="$acc"/>
257 // </xsl:when>
258 // <xsl:otherwise>
259 // <xsl:variable name="first" select="string-length(substring-before('0123456789ABCDEF', substring($in, 1, 1)))"/>
260 // <xsl:sequence select="f:hexToInt($acc * 16 + $first, substring($in, 2))"/>
261 // </xsl:otherwise>
262 // </xsl:choose>
263 // </xsl:function>
264 //
265 // <xsl:function name="f:intToHex" as="xs:string">
266 // <xsl:param name="in" as="xs:integer"/>
267 // <xsl:choose>
268 // <xsl:when test="$in eq 0">
269 // <xsl:sequence select="''"/>
270 // </xsl:when>
271 // <xsl:otherwise>
272 // <xsl:variable name="last" select="substring('0123456789ABCDEF', $in mod 16 + 1, 1)"/>
273 // <xsl:sequence select="concat(f:intToHex($in idiv 16), $last)"/>
274 // </xsl:otherwise>
275 // </xsl:choose>
276 // </xsl:function>
277 //
278 //</xsl:stylesheet>