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.io.IOException;
26 import java.io.OutputStream;
27 import java.io.PrintStream;
28 import java.util.List;
29 import java.util.Locale;
30 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
31
32 /**
33 * Output target used by AWK {@code print} and {@code printf} statements.
34 * <p>
35 * Implementations decide how to represent AWK output, whether as text written
36 * to a stream, appended characters, or structured values collected by the
37 * embedding application. Numeric rendering uses the sink's immutable
38 * construction-time locale.
39 * </p>
40 */
41 public abstract class AwkSink {
42
43 private final Locale locale;
44
45 /**
46 * Creates a sink using the default {@link Locale#US} formatting rules.
47 */
48 protected AwkSink() {
49 this(Locale.US);
50 }
51
52 /**
53 * Creates a sink using the supplied locale for numeric formatting.
54 *
55 * @param localeParam locale to use for numeric formatting
56 */
57 protected AwkSink(Locale localeParam) {
58 this.locale = localeParam == null ? Locale.US : localeParam;
59 }
60
61 /**
62 * Returns the locale used by this sink when it renders numeric values.
63 *
64 * @return sink locale
65 */
66 public final Locale getLocale() {
67 return locale;
68 }
69
70 /**
71 * Writes one AWK {@code print} operation.
72 *
73 * @param ofs output field separator
74 * @param ors output record separator
75 * @param ofmt numeric output format used by plain {@code print}
76 * @param values values supplied to {@code print}
77 * @throws IOException if the sink cannot write the output
78 */
79 public abstract void print(String ofs, String ors, String ofmt, Object... values) throws IOException;
80
81 /**
82 * Writes one AWK {@code print} statement without arguments to the default
83 * output, which prints the current record.
84 * <p>
85 * The default implementation calls
86 * {@link #print(String, String, String, Object...)} with {@code record}, so
87 * a sink that does not override this method writes exactly what
88 * {@code print $0} writes. Override it to receive the record's fields
89 * instead, for instance to collect one value per field.
90 * </p>
91 * <p>
92 * {@code fields} holds {@code $1} to {@code $NF} as the script left them,
93 * including assigned fields and an {@code NF} the script changed. Each element
94 * is the value {@code $i} returns (an unassigned field renders as the empty
95 * string); {@link #formatPrintArgument(Object, String)} renders it as
96 * {@code print $i} would. The list is a read-only view of the current record,
97 * valid only during this call, that splits the record only when it is read:
98 * copy it to keep it.
99 * </p>
100 * <p>
101 * A rule without an action (a pattern alone) prints through this method too.
102 * {@code print $0}, {@code print} with arguments, and a redirected
103 * {@code print} (including {@code > "/dev/stdout"}) call
104 * {@link #print(String, String, String, Object...)}.
105 * </p>
106 *
107 * @param ofs output field separator
108 * @param ors output record separator
109 * @param ofmt numeric output format used by plain {@code print}
110 * @param fields read-only view of the current fields {@code $1} to
111 * {@code $NF}
112 * @param record the current record {@code $0}
113 * @throws IOException if the sink cannot write the output
114 */
115 public void printRecord(String ofs, String ors, String ofmt, List<Object> fields, Object record) throws IOException {
116 print(ofs, ors, ofmt, record);
117 }
118
119 /**
120 * Writes one AWK {@code printf} operation.
121 *
122 * @param ofs output field separator
123 * @param ors output record separator
124 * @param ofmt numeric output format available to the sink
125 * @param convfmt number-to-string conversion format ({@code CONVFMT}),
126 * used by {@code %s} to convert numeric values the way AWK does
127 * @param format format string passed to {@code printf}
128 * @param values arguments supplied after the format string
129 * @throws IOException if the sink cannot write the output
130 */
131 public abstract void printf(String ofs, String ors, String ofmt, String convfmt, String format, Object... values)
132 throws IOException;
133
134 /**
135 * Flushes any buffered output held by this sink.
136 *
137 * @throws IOException if the sink cannot be flushed
138 */
139 public void flush() throws IOException {
140 // Most sinks do not buffer explicitly.
141 }
142
143 /**
144 * Returns a {@link PrintStream} view that receives raw process output written
145 * by spawned commands such as {@code system("...")}.
146 * <p>
147 * The default implementation returns a stream that silently discards all
148 * output. Override this method in sinks that need to capture process output.
149 * </p>
150 *
151 * @return print stream that should receive raw process output
152 */
153 @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "The shared discard stream is stateless and safe to expose.")
154 public PrintStream getPrintStream() {
155 return NULL_PRINT_STREAM;
156 }
157
158 /** Shared discard stream returned by the default {@link #getPrintStream()}. */
159 private static final PrintStream NULL_PRINT_STREAM = newNullPrintStream();
160
161 /**
162 * A shared no-op sink that silently discards all output.
163 * <p>
164 * This singleton is safe to share across all JRT/AVM instances because
165 * its {@link #print(String, String, String, Object...)},
166 * {@link #printf(String, String, String, String, String, Object...)}, and
167 * {@link #flush()} operations are all no-ops.
168 */
169 public static final AwkSink NOP_SINK = new NoOpAwkSink();
170
171 private static final class NoOpAwkSink extends AwkSink {
172
173 NoOpAwkSink() {
174 super();
175 }
176
177 @Override
178 public void print(String ofs, String ors, String ofmt, Object... values) {
179 // discard
180 }
181
182 @Override
183 public void printf(String ofs, String ors, String ofmt, String convfmt, String format, Object... values) {
184 // discard
185 }
186 }
187
188 private static PrintStream newNullPrintStream() {
189 try {
190 return new PrintStream(new OutputStream() {
191 @Override
192 public void write(int b) {
193 // discard
194 }
195
196 @Override
197 public void write(byte[] b, int off, int len) {
198 // discard
199 }
200 }, false, "UTF-8") {
201
202 @Override
203 public void close() {
204 // Prevent closing; this stream is a shared singleton.
205 }
206 };
207 } catch (java.io.UnsupportedEncodingException e) {
208 throw new IllegalStateException(e);
209 }
210 }
211
212 /**
213 * Creates a sink backed by an {@link OutputStream}.
214 *
215 * @param outputStream stream that should receive AWK output
216 * @return sink writing to {@code outputStream}
217 */
218 public static AwkSink from(OutputStream outputStream) {
219 return from(outputStream, Locale.US);
220 }
221
222 /**
223 * Creates a sink backed by an {@link OutputStream}.
224 *
225 * @param outputStream stream that should receive AWK output
226 * @param locale locale to use for numeric formatting
227 * @return sink writing to {@code outputStream}
228 */
229 public static AwkSink from(OutputStream outputStream, Locale locale) {
230 return new OutputStreamAwkSink(outputStream, locale);
231 }
232
233 /**
234 * Creates a sink backed by a {@link PrintStream}.
235 *
236 * @param printStream stream that should receive AWK output
237 * @return sink writing to {@code printStream}
238 */
239 public static AwkSink from(PrintStream printStream) {
240 return from(printStream, Locale.US);
241 }
242
243 /**
244 * Creates a sink backed by a {@link PrintStream}.
245 *
246 * @param printStream stream that should receive AWK output
247 * @param locale locale to use for numeric formatting
248 * @return sink writing to {@code printStream}
249 */
250 public static AwkSink from(PrintStream printStream, Locale locale) {
251 return new OutputStreamAwkSink(printStream, locale);
252 }
253
254 /**
255 * Creates a sink backed by an {@link Appendable}.
256 *
257 * @param appendable appendable that should receive AWK output
258 * @return sink writing to {@code appendable}
259 */
260 public static AwkSink from(Appendable appendable) {
261 return from(appendable, Locale.US);
262 }
263
264 /**
265 * Creates a sink backed by an {@link Appendable}.
266 *
267 * @param appendable appendable that should receive AWK output
268 * @param locale locale to use for numeric formatting
269 * @return sink writing to {@code appendable}
270 */
271 public static AwkSink from(Appendable appendable, Locale locale) {
272 return new AppendableAwkSink(appendable, locale);
273 }
274
275 /**
276 * Formats one operand of a plain AWK {@code print} statement.
277 * <p>
278 * Numeric values are rendered with {@code OFMT} (or as integers when they
279 * hold an integral value). String values — including numeric strings that
280 * originate from input — are printed verbatim, as required by POSIX.
281 * </p>
282 *
283 * @param value operand to format
284 * @param ofmt numeric output format
285 * @return the textual representation AWK would print for this operand
286 */
287 protected final String formatPrintArgument(Object value, String ofmt) {
288 return AwkPrintf.toAwkString(value, ofmt, locale);
289 }
290
291 /**
292 * Formats a string in the same way as AWK's {@code sprintf()} built-in,
293 * converting numeric {@code %s} operands with the supplied {@code CONVFMT}
294 * value.
295 * <p>
296 * Subclasses may override this method to customize formatting. The default
297 * implementation delegates to
298 * {@link AwkPrintf#sprintf(Locale, String, String, Object...)}. The
299 * built-in sinks render {@code printf} output through this method, so
300 * overriding it keeps {@code printf} and {@code sprintf} consistent.
301 * </p>
302 *
303 * @param convfmt number-to-string conversion format ({@code CONVFMT})
304 * @param format format string
305 * @param values arguments supplied after the format string
306 * @return formatted text
307 */
308 public String sprintf(String convfmt, String format, Object... values) {
309 Object[] safeValues = values == null ? new Object[0] : values;
310 return AwkPrintf.sprintf(locale, convfmt, format, safeValues);
311 }
312 }