View Javadoc
1   package io.jawk.jrt;
2   
3   /*-
4    * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5    * Jawk
6    * ჻჻჻჻჻჻
7    * Copyright (C) 2006 - 2026 MetricsHub
8    * ჻჻჻჻჻჻
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   *
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Lesser Public License for more details.
18   *
19   * You should have received a copy of the GNU General Lesser Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22   * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
23   */
24  
25  import java.util.List;
26  import java.util.Map;
27  import java.util.function.UnaryOperator;
28  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29  import io.jawk.intermediate.UninitializedObject;
30  import io.jawk.intermediate.UntypedObject;
31  
32  /**
33   * An AWK associative array.
34   * <p>
35   * This interface extends {@link Map} and provides AWK-specific behaviour:
36   * automatic key normalization (null and uninitialized values map to {@code ""}),
37   * numeric key coercion ({@code "1"} and {@code 1L} address the same slot), and
38   * auto-creation of blank entries on first access.
39   * </p>
40   * <p>
41   * Concrete implementations directly extend a JDK {@link Map} class to avoid
42   * delegation overhead:
43   * </p>
44   * <ul>
45   * <li>{@link HashAssocArray} &mdash; backed by {@link java.util.HashMap}</li>
46   * <li>{@link ListAssocArray} &mdash; materialized from a {@link java.util.List}
47   * and backed by {@link java.util.HashMap}</li>
48   * <li>{@link SortedAssocArray} &mdash; backed by {@link java.util.TreeMap} with
49   * AWK key ordering</li>
50   * </ul>
51   * <p>
52   * Use the factory methods to create instances:
53   * </p>
54   *
55   * <pre>
56   * AssocArray hash = AssocArray.createHash();
57   * AssocArray sorted = AssocArray.createSorted();
58   * AssocArray list = AssocArray.createFromList(values, sortedArrayKeys);
59   * AssocArray aa = AssocArray.create(sortedArrayKeys);
60   * </pre>
61   *
62   * @author Danny Daglas
63   */
64  public interface AssocArray extends Map<Object, Object> {
65  
66  	/** A blank (uninitialized) value shared across all AWK array accesses. */
67  	UninitializedObject BLANK = new UninitializedObject();
68  
69  	/** An untyped value shared across newly referenced AWK array elements. */
70  	UntypedObject UNTYPED = new UntypedObject();
71  
72  // -------------------------------------------------------------------------
73  // Key-normalization helpers (used by concrete implementations)
74  // -------------------------------------------------------------------------
75  
76  	/**
77  	 * Converts a key to the canonical form expected by AWK: {@code null} and
78  	 * {@link UninitializedObject} map to the empty string, and internal input
79  	 * strings map to their string value.
80  	 *
81  	 * @param key the raw key
82  	 * @return the normalized key, never {@code null}
83  	 */
84  	static Object normalizeKey(Object key) {
85  		if (key == null || key instanceof UninitializedObject) {
86  			return "";
87  		}
88  		if (key instanceof StrNum) {
89  			return key.toString();
90  		}
91  		if (key instanceof Double || key instanceof Float) {
92  			double numericKey = ((Number) key).doubleValue();
93  			if (JRT.isActuallyLong(numericKey)) {
94  				return Long.valueOf((long) Math.rint(numericKey));
95  			}
96  		}
97  		return key;
98  	}
99  
100 	/**
101 	 * Returns whether a subscript value is an integral number that
102 	 * {@link #normalizeKey(Object)} canonicalizes to the same {@code Long}
103 	 * key as its AWK string form. Such a subscript can be used as a key
104 	 * directly, without the CONVFMT string conversion that every other
105 	 * scalar goes through: the resulting key is identical, and skipping the
106 	 * string round-trip keeps integer-indexed loops fast.
107 	 *
108 	 * @param value the subscript value to examine
109 	 * @return {@code true} if the value can be used as a key without string
110 	 *         conversion
111 	 */
112 	static boolean isIntegralNumberKey(Object value) {
113 		if (value instanceof Long || value instanceof Integer) {
114 			return true;
115 		}
116 		return value instanceof Double && JRT.toScalarNumber((Double) value) instanceof Long;
117 	}
118 
119 	/**
120 	 * Attempts to parse the key as a {@code Long}.
121 	 * <p>
122 	 * This accepts and rejects exactly the same inputs as
123 	 * {@link Long#parseLong(String)} (radix 10), but scans the string without
124 	 * ever constructing an exception: most keys are not integer strings (every
125 	 * multidimensional {@code arr[x,y]} key, for instance), and paying the cost
126 	 * of a {@link NumberFormatException} stack-trace fill on every array access
127 	 * is prohibitive.
128 	 * </p>
129 	 *
130 	 * @param key the key to parse (must not be {@code null})
131 	 * @return the {@code Long} value, or {@code null} if the key cannot be parsed
132 	 *         as a long integer
133 	 */
134 	@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Defensive check against contract-violating toString() implementations returning null")
135 	static Long toLongKey(Object key) {
136 		final String str;
137 		if (key instanceof String) {
138 			str = (String) key;
139 		} else {
140 			try {
141 				str = key.toString();
142 			} catch (RuntimeException e) { // NOPMD - EmptyCatchBlock: intentionally ignored
143 				// e.g. an AssocArray used as a key throws on toString():
144 				// treat such keys as non-numeric
145 				return null;
146 			}
147 			if (str == null) {
148 				// a contract-violating toString(): treat the key as non-numeric,
149 				// like the former Long.parseLong(null) NumberFormatException path
150 				return null;
151 			}
152 		}
153 		final int len = str.length();
154 		if (len == 0) {
155 			return null;
156 		}
157 		int i = 0;
158 		boolean negative = false;
159 		long limit = -Long.MAX_VALUE;
160 		final char firstChar = str.charAt(0);
161 		if (firstChar < '0') { // possible leading "+" or "-"
162 			if (firstChar == '-') {
163 				negative = true;
164 				limit = Long.MIN_VALUE;
165 			} else if (firstChar != '+') {
166 				return null;
167 			}
168 			if (len == 1) { // lone "+" or "-"
169 				return null;
170 			}
171 			i = 1;
172 		}
173 		// Accumulate negatively, exactly like Long.parseLong, so that
174 		// Long.MIN_VALUE (whose magnitude exceeds Long.MAX_VALUE) parses too
175 		final long multmin = limit / 10;
176 		long result = 0;
177 		while (i < len) {
178 			// Character.digit keeps parity with Long.parseLong on non-ASCII digits
179 			final int digit = Character.digit(str.charAt(i++), 10);
180 			if (digit < 0 || result < multmin) {
181 				return null;
182 			}
183 			result *= 10;
184 			if (result < limit + digit) {
185 				return null;
186 			}
187 			result -= digit;
188 		}
189 		return negative ? result : -result;
190 	}
191 
192 // -------------------------------------------------------------------------
193 // AWK-specific default methods
194 // -------------------------------------------------------------------------
195 
196 	/**
197 	 * Returns whether a particular key is contained within the associative array.
198 	 * <p>
199 	 * Unlike {@link #get(Object)}, which auto-creates a blank entry when the key
200 	 * is absent, this method does not modify the array. It exists to support the
201 	 * AWK {@code IN} keyword.
202 	 * </p>
203 	 *
204 	 * @param key Key to be checked
205 	 * @return {@code true} if the key (or its numeric equivalent) is present
206 	 */
207 	default boolean isIn(Object key) {
208 		key = normalizeKey(key);
209 		if (containsKey(key)) {
210 			return true;
211 		}
212 		Long lKey = toLongKey(key);
213 		return lKey != null && containsKey(lKey);
214 	}
215 
216 	/**
217 	 * Provides a string representation of this associative array, recursively
218 	 * rendering nested arrays.
219 	 *
220 	 * @return a human-readable map string of the form {@code {key=value, ...}}
221 	 */
222 	default String mapString() {
223 // Since extensions allow assoc arrays to become keys as well,
224 // we render nested arrays recursively rather than using toString().
225 		StringBuilder sb = new StringBuilder().append('{');
226 		int cnt = 0;
227 		for (Map.Entry<Object, Object> entry : entrySet()) {
228 			if (cnt > 0) {
229 				sb.append(", ");
230 			}
231 			Object key = entry.getKey();
232 			if (key instanceof AssocArray) {
233 				sb.append(((AssocArray) key).mapString());
234 			} else {
235 				sb.append(key.toString());
236 			}
237 			sb.append('=');
238 			Object value = entry.getValue();
239 			if (value instanceof AssocArray) {
240 				sb.append(((AssocArray) value).mapString());
241 			} else {
242 				sb.append(value.toString());
243 			}
244 			++cnt;
245 		}
246 		return sb.append('}').toString();
247 	}
248 
249 	/**
250 	 * Stores a value using a primitive {@code long} key, bypassing string parsing.
251 	 * <p>
252 	 * This is a convenience overload for callers that already hold a {@code long}
253 	 * key. The default implementation boxes the key and delegates to
254 	 * {@link #put(Object, Object)}.
255 	 * </p>
256 	 *
257 	 * @param key the long key
258 	 * @param value the value to associate with the key
259 	 * @return the previous value associated with the key, or {@code null}
260 	 */
261 	default Object put(long key, Object value) {
262 		return put(Long.valueOf(key), value);
263 	}
264 
265 	/**
266 	 * Returns the specification version of the underlying JDK {@link Map} class
267 	 * that backs this implementation.
268 	 *
269 	 * @return the specification version string, or {@code null} if unavailable
270 	 */
271 	default String getMapVersion() {
272 		return getClass().getSuperclass().getPackage().getSpecificationVersion();
273 	}
274 
275 // -------------------------------------------------------------------------
276 // Factory methods
277 // -------------------------------------------------------------------------
278 
279 	/**
280 	 * Creates a new hash-based associative array (backed by {@link java.util.HashMap}).
281 	 *
282 	 * @return a new {@link HashAssocArray}
283 	 */
284 	static AssocArray createHash() {
285 		return new HashAssocArray();
286 	}
287 
288 	/**
289 	 * Creates a new sorted associative array (backed by {@link java.util.TreeMap}
290 	 * with AWK key ordering).
291 	 *
292 	 * @return a new {@link SortedAssocArray}
293 	 */
294 	static AssocArray createSorted() {
295 		return new SortedAssocArray();
296 	}
297 
298 	/**
299 	 * Creates a new associative array of the appropriate type.
300 	 *
301 	 * @param sortedArrayKeys {@code true} to create a sorted (tree-backed) array,
302 	 *        {@code false} for a hash-backed array
303 	 * @return a new {@link AssocArray} instance
304 	 */
305 	static AssocArray create(boolean sortedArrayKeys) {
306 		return sortedArrayKeys ? createSorted() : createHash();
307 	}
308 
309 	/**
310 	 * Creates a new associative array materialized from a Java {@link List}.
311 	 * <p>
312 	 * List elements are stored under zero-based {@link Long} keys. Nested
313 	 * {@link List} values are recursively materialized as associative arrays so
314 	 * JSON-like object trees can be traversed with AWK array syntax.
315 	 * </p>
316 	 *
317 	 * @param values list values to expose as an AWK array
318 	 * @param sortedArrayKeys {@code true} to create a sorted array, {@code false}
319 	 *        for a hash-backed array
320 	 * @return a new {@link AssocArray} containing the list values
321 	 */
322 	static AssocArray createFromList(List<?> values, boolean sortedArrayKeys) {
323 		return ListAssocArray.createFromList(values, sortedArrayKeys);
324 	}
325 
326 	/**
327 	 * Normalizes an externally supplied structured value before the AVM stores it.
328 	 * <p>
329 	 * {@link List} and {@link Map} values, at any depth, are copied into new
330 	 * {@link AssocArray} instances; the caller's containers are never modified.
331 	 * </p>
332 	 *
333 	 * @param value value to normalize
334 	 * @param sortedArrayKeys {@code true} when converted lists should use sorted
335 	 *        array keys
336 	 * @return the normalized value
337 	 */
338 	static Object normalizeValue(Object value, boolean sortedArrayKeys) {
339 		return normalizeValue(value, sortedArrayKeys, UnaryOperator.identity());
340 	}
341 
342 	/**
343 	 * Normalizes an externally supplied structured value before the AVM stores it,
344 	 * converting every {@link String} inside a {@link List} or {@link Map}, at any
345 	 * depth, with {@code stringConverter}.
346 	 * <p>
347 	 * The AVM passes {@code JRT::toInputScalar} so that nested strings become
348 	 * numeric strings, like input fields. Lists and maps are copied, never
349 	 * modified.
350 	 * </p>
351 	 *
352 	 * @param value value to normalize
353 	 * @param sortedArrayKeys {@code true} when converted lists should use sorted
354 	 *        array keys
355 	 * @param stringConverter conversion applied to nested {@link String} values
356 	 *        and to nested {@link StrNum} values (which an array from an earlier
357 	 *        run may hold): it receives either type
358 	 * @return the normalized value
359 	 */
360 	static Object normalizeValue(Object value, boolean sortedArrayKeys, UnaryOperator<Object> stringConverter) {
361 		return ListAssocArray.normalizeValue(value, sortedArrayKeys, stringConverter);
362 	}
363 
364 }