1 package io.jawk.util;
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.HashMap;
26 import java.util.Locale;
27 import java.util.Map;
28 import java.util.Objects;
29 import java.util.concurrent.atomic.AtomicLong;
30 import io.jawk.Awk;
31
32 /**
33 * Reusable behavioral configuration for the Jawk engine.
34 * <p>
35 * Instances hold settings that control how the AWK interpreter behaves
36 * (field separator, locale, sorted keys, initial variables, and default
37 * record separator) but do <em>not</em> carry per-execution state such as
38 * input sources, filename arguments, or output destinations. This
39 * separation allows a single {@code AwkSettings} object to be shared
40 * across many invocations of {@link io.jawk.Awk#eval},
41 * {@link io.jawk.Awk#script}, or {@link io.jawk.Awk#createAvm()}.
42 * </p>
43 * <p>
44 * Output is configured on the execution builder returned by
45 * {@link io.jawk.Awk#script(String)} or {@link io.jawk.Awk#script(io.jawk.AwkProgram)}
46 * and is therefore always per-execution.
47 * </p>
48 *
49 * @author Danny Daglas
50 */
51 public class AwkSettings {
52
53 /**
54 * Shared immutable settings instance representing the default configuration.
55 */
56 public static final AwkSettings DEFAULT_SETTINGS = new ImmutableAwkSettings();
57
58 /**
59 * Contains variable assignments which are applied prior to
60 * executing the script (-v assignments).
61 * The values may be of type <code>Integer</code>,
62 * <code>Double</code>, <code>String</code>,
63 * {@link io.jawk.jrt.AssocArray} (for array variables),
64 * or any {@link java.util.Map} or {@link java.util.List}. Maps and lists,
65 * at any depth, are copied into new AWK arrays (list indexes become
66 * zero-based {@link java.lang.Long} keys, and nested strings become numeric
67 * strings): the caller's map or list is never modified, and the script's
68 * writes stay in the copy.
69 */
70 private final Map<String, Object> variables = new HashMap<String, Object>();
71
72 /**
73 * Initial Field Separator (FS) value.
74 * <code>null</code> means the default FS value.
75 */
76 private volatile String fieldSeparator = null;
77
78 /**
79 * Whether to maintain array keys in sorted order;
80 * <code>false</code> by default.
81 */
82 private volatile boolean useSortedArrayKeys = false;
83
84 /**
85 * Whether to accept gawk-style arrays of arrays syntax such as {@code a[i][j]}
86 * and subarray operands in array-only positions such as {@code split(..., a[i])}.
87 * <code>true</code> by default.
88 */
89 private volatile boolean posix;
90
91 /**
92 * Locale for the output of numbers
93 * <code>US-English</code> by default.
94 */
95 private volatile Locale locale = Locale.US;
96
97 /**
98 * Default value for RS, when not set specifically by the AWK script.
99 * Defaults to {@link Awk#DEFAULT_RS} per POSIX. Platform-specific
100 * end-of-line handling is the responsibility of the input source.
101 */
102 private volatile String defaultRS = Awk.DEFAULT_RS;
103
104 /**
105 * Monotonically increasing counter incremented whenever the settings change.
106 * It allows callers that cache derived runtime state to detect when a new
107 * snapshot must be built.
108 */
109 private final AtomicLong modificationCount = new AtomicLong();
110
111 /**
112 * Creates a settings instance holding Jawk's default configuration, each
113 * field starting at the default documented on its getter.
114 * <p>
115 * Use the setters to depart from it, or the shared {@link #DEFAULT_SETTINGS}
116 * instance when the defaults are enough.
117 * </p>
118 */
119 public AwkSettings() {
120 // Every field is initialized with its documented default.
121 }
122
123 /**
124 * <p>
125 * toDescriptionString.
126 * </p>
127 *
128 * @return a human readable representation of the parameters values.
129 */
130 public String toDescriptionString() {
131 StringBuilder desc = new StringBuilder();
132
133 final char newLine = '\n';
134
135 desc.append("variables = ").append(getVariables()).append(newLine);
136 desc.append("fieldSeparator = ").append(getFieldSeparator()).append(newLine);
137 desc.append("useSortedArrayKeys = ").append(isUseSortedArrayKeys()).append(newLine);
138 desc.append("posix = ").append(isPosix()).append(newLine);
139 return desc.toString();
140 }
141
142 /**
143 * Provides a description of extensions that are enabled/disabled.
144 * The default compiler implementation uses this method
145 * to describe extensions which are compiled into the script.
146 * The description is then provided to the user within the usage.
147 *
148 * @return A description of the extensions which are enabled/disabled.
149 */
150 public String toExtensionDescription() {
151 StringBuilder extensions = new StringBuilder();
152
153 if (isUseSortedArrayKeys()) {
154 extensions.append(", associative array keys are sorted");
155 }
156 if (!isPosix()) {
157 extensions.append(", arrays of arrays");
158 }
159 if (extensions.length() > 0) {
160 return "{extensions: " + extensions.substring(2) + "}";
161 } else {
162 return "{no compiled extensions utilized}";
163 }
164 }
165
166 @SuppressWarnings("unused")
167 private void addInitialVariable(String keyValue) {
168 int equalsIdx = keyValue.indexOf('=');
169 String name = keyValue.substring(0, equalsIdx);
170 String valueString = keyValue.substring(equalsIdx + 1);
171 // note: can overwrite previously defined variables
172 putVariable(name, valueString);
173 }
174
175 /**
176 * Contains variable assignments which are applied prior to
177 * executing the script (-v assignments).
178 * The values may be of type <code>Integer</code>,
179 * <code>Double</code>, <code>String</code>,
180 * {@link io.jawk.jrt.AssocArray} (for array variables),
181 * or any {@link java.util.Map} or {@link java.util.List}. Maps and lists,
182 * at any depth, are copied into new AWK arrays (list indexes become
183 * zero-based {@link java.lang.Long} keys, and nested strings become numeric
184 * strings): the caller's map or list is never modified, and the script's
185 * writes stay in the copy.
186 *
187 * @return the variables
188 */
189 public Map<String, Object> getVariables() {
190 synchronized (variables) {
191 return new HashMap<String, Object>(variables);
192 }
193 }
194
195 /**
196 * Returns the number of explicit mutations applied to this settings
197 * instance.
198 * <p>
199 * The value is intended for cache invalidation only; it has no behavioral
200 * meaning other than changing whenever one of the configuration mutators is
201 * called.
202 * </p>
203 *
204 * @return the current modification counter
205 */
206 public long getModificationCount() {
207 return modificationCount.get();
208 }
209
210 /**
211 * Contains variable assignments which are applied prior to
212 * executing the script (-v assignments).
213 * The values may be of type <code>Integer</code>,
214 * <code>Double</code>, <code>String</code>,
215 * {@link io.jawk.jrt.AssocArray} (for array variables),
216 * or any {@link java.util.Map} or {@link java.util.List}. Maps and lists,
217 * at any depth, are copied into new AWK arrays (list indexes become
218 * zero-based {@link java.lang.Long} keys, and nested strings become numeric
219 * strings): the caller's map or list is never modified, and the script's
220 * writes stay in the copy.
221 *
222 * @param variables the variables to set
223 */
224 public void setVariables(Map<String, Object> variables) {
225 synchronized (this.variables) {
226 this.variables.clear();
227 this.variables.putAll(variables);
228 }
229 markModified();
230 }
231
232 /**
233 * Put or replace a variable entry.
234 *
235 * @param name Variable name
236 * @param value Variable value
237 */
238 public void putVariable(String name, Object value) {
239 synchronized (variables) {
240 variables.put(name, value);
241 }
242 markModified();
243 }
244
245 /**
246 * Initial Field Separator (FS) value.
247 * <code>null</code> means the default FS value.
248 *
249 * @return the fieldSeparator
250 */
251 public String getFieldSeparator() {
252 return fieldSeparator;
253 }
254
255 /**
256 * Initial Field Separator (FS) value.
257 * <code>null</code> means the default FS value.
258 *
259 * @param fieldSeparator the fieldSeparator to set
260 */
261 public void setFieldSeparator(String fieldSeparator) {
262 this.fieldSeparator = fieldSeparator;
263 markModified();
264 }
265
266 /**
267 * Whether to maintain array keys in sorted order;
268 * <code>false</code> by default.
269 *
270 * @return the useSortedArrayKeys
271 */
272 public boolean isUseSortedArrayKeys() {
273 return useSortedArrayKeys;
274 }
275
276 /**
277 * Whether to maintain array keys in sorted order;
278 * <code>false</code> by default.
279 *
280 * @param useSortedArrayKeys the useSortedArrayKeys to set
281 */
282 public void setUseSortedArrayKeys(boolean useSortedArrayKeys) {
283 this.useSortedArrayKeys = useSortedArrayKeys;
284 markModified();
285 }
286
287 /**
288 * Whether POSIX compile-time behavior is enforced, rejecting gawk syntax
289 * such as arrays of arrays ({@code a[i][j]}, subarray operands like
290 * {@code split(..., a[i])}) and typed regexp literals ({@code @/re/}),
291 * and treating the gawk-specific {@code BEGINFILE} / {@code ENDFILE}
292 * patterns as ordinary identifiers. At run time, the backslashes in
293 * {@code sub()} / {@code gsub()} replacement text then follow the POSIX
294 * rules instead of gawk's.
295 *
296 * @return {@code true} when POSIX compile-time behavior is enforced
297 */
298 public boolean isPosix() {
299 return posix;
300 }
301
302 /**
303 * Enables or disables POSIX compile-time behavior. When enabled, gawk
304 * syntax such as arrays of arrays ({@code a[i][j]}, subarray operands like
305 * {@code split(..., a[i])} or {@code for (k in a[i])}) and typed regexp
306 * literals ({@code @/re/}) is rejected, and the gawk-specific
307 * {@code BEGINFILE} / {@code ENDFILE} patterns are not special.
308 *
309 * @param posix {@code true} to enforce POSIX compile-time behavior
310 */
311 public void setPosix(boolean posix) {
312 this.posix = posix;
313 markModified();
314 }
315
316 /**
317 * <p>
318 * Getter for the field <code>locale</code>.
319 * </p>
320 *
321 * @return the Locale that will be used for outputting numbers
322 */
323 public Locale getLocale() {
324 return locale;
325 }
326
327 /**
328 * Sets the Locale for outputting numbers.
329 *
330 * @param pLocale The locale to be used (e.g.: <code>Locale.US</code>)
331 */
332 public void setLocale(Locale pLocale) {
333 locale = pLocale == null ? Locale.US : pLocale;
334 markModified();
335 }
336
337 /**
338 * <p>
339 * Getter for the field <code>defaultRS</code>.
340 * </p>
341 *
342 * @return the default RS, when not set by the AWK script
343 */
344 public String getDefaultRS() {
345 return defaultRS;
346 }
347
348 /**
349 * Sets the default RS, when not set by the AWK script
350 *
351 * @param rs The regular expression that separates records
352 */
353 public void setDefaultRS(String rs) {
354 defaultRS = Objects.requireNonNull(rs, "defaultRS");
355 markModified();
356 }
357
358 /**
359 * Records that this settings instance has been mutated, so that callers
360 * caching derived runtime state can detect it through
361 * {@link #getModificationCount()}.
362 * <p>
363 * Every mutator of this class calls it; subclasses adding their own
364 * configuration must do the same.
365 * </p>
366 */
367 protected final void markModified() {
368 modificationCount.incrementAndGet();
369 }
370
371 private static final class ImmutableAwkSettings extends AwkSettings {
372
373 private ImmutableAwkSettings() {
374 super();
375 }
376
377 @Override
378 public void setVariables(Map<String, Object> variables) {
379 throw unsupported();
380 }
381
382 @Override
383 public void putVariable(String name, Object value) {
384 throw unsupported();
385 }
386
387 @Override
388 public void setFieldSeparator(String fieldSeparator) {
389 throw unsupported();
390 }
391
392 @Override
393 public void setUseSortedArrayKeys(boolean useSortedArrayKeys) {
394 throw unsupported();
395 }
396
397 @Override
398 public void setPosix(boolean posix) {
399 throw unsupported();
400 }
401
402 @Override
403 public void setLocale(Locale pLocale) {
404 throw unsupported();
405 }
406
407 @Override
408 public void setDefaultRS(String rs) {
409 throw unsupported();
410 }
411
412 private UnsupportedOperationException unsupported() {
413 return new UnsupportedOperationException("DEFAULT_SETTINGS is immutable");
414 }
415 }
416 }