Package io.jawk.jrt

Class JRT

java.lang.Object
io.jawk.jrt.JRT
Direct Known Subclasses:
SandboxedJRT

public class JRT extends Object
The Jawk runtime coordinator. The JRT services interpreted and compiled Jawk scripts, mainly for IO and other non-CPU bound tasks. The goal is to house service functions into a Java-compiled class rather than to hand-craft service functions in byte-code, or cut-paste compiled JVM code into the compiled AWK script. Also, since these functions are non-CPU bound, the need for inlining is reduced.

Variable access is achieved through the VariableManager interface. The constructor requires a VariableManager instance (which, in this case, is the compiled Jawk class itself).

Main services include:

  • File and command output redirection via print(f).
  • File and command input redirection via getline.
  • Most built-in AWK functions, such as system(), sprintf(), etc.
  • Automatic AWK type conversion routines.
  • IO management for input rule processing.
  • Random number engine management.
  • Input field ($0, $1, ...) management.

All static and non-static service methods should be package-private to the resultant AWK script class rather than public. However, the resultant script class is not in the io.jawk.jrt package by default, and the user may reassign the resultant script class to another package. Therefore, all accessed methods are public.

Author:
Danny Daglas
See Also:
  • Constructor Details

    • JRT

      public JRT(VariableManager vm, Locale locale, AwkSink awkSink, PrintStream error)
      Create a JRT with explicit default output and error streams.
      Parameters:
      vm - The VariableManager to use with this JRT.
      locale - The Locale to use for number formatting.
      awkSink - default output sink used by plain AWK print operations
      error - default error stream used for process stderr
  • Method Details

    • setAwkSink

      public void setAwkSink(AwkSink sink)
      Sets the sink used by default print and printf operations.
      Parameters:
      sink - output sink to use
    • setErrorStream

      public void setErrorStream(PrintStream errorStream)
      Sets the stream used for the stderr output of spawned processes (e.g. system("...")).
      Parameters:
      errorStream - stream to receive process stderr
    • setWarningStream

      public void setWarningStream(PrintStream warningStream)
      Sets the stream that receives runtime warning messages. Warnings default to System.err, mirroring where gawk sends its diagnostics, and are deliberately kept apart from the process-stderr stream so they can never leak into a captured script output.
      Parameters:
      warningStream - stream to receive runtime warnings
    • bindStandardInput

      public void bindStandardInput(InputSource inputSource)
      Binds the stream that the /dev/stdin special filename reads from to the input source of the execution that is starting. A stream-backed source lends the stream it falls back to when ARGV holds no filename, which is what the run treats as its standard input; a source that produces records some other way has no such stream, so /dev/stdin designates the standard input of the JVM.
      Parameters:
      inputSource - input source bound to this execution
    • printWarning

      public void printWarning(String message)
      Prints a runtime warning message to the warning stream (stderr by default), mirroring where gawk sends its diagnostics.
      Parameters:
      message - warning text to print
    • getAwkSink

      public AwkSink getAwkSink()
      Returns the default output sink used by print and printf.
      Returns:
      the current AWK sink
    • getLocale

      public Locale getLocale()
      Returns the locale used for number formatting in this runtime.
      Returns:
      the runtime locale
    • isJrtManagedSpecialVariable

      public static boolean isJrtManagedSpecialVariable(String name)
      Returns whether the supplied variable name is managed directly by JRT rather than through the AVM runtime stack.
      Parameters:
      name - variable name to inspect
      Returns:
      true when the variable is a JRT-managed special variable
    • isGawkOnlySpecialVariable

      public static boolean isGawkOnlySpecialVariable(String name)
      Returns whether the name is a gawk-only special variable that POSIX mode treats as an ordinary identifier, like gawk --posix does. Shared by the parser and the interpreter so both stay in sync.
      Parameters:
      name - variable name to inspect
      Returns:
      true when POSIX mode must treat the name as ordinary
    • copySpecialVariables

      public static Map<String,Object> copySpecialVariables(Map<String,Object> variableMap)
      Copies only the JRT-managed special variables from the supplied map.
      Parameters:
      variableMap - source variable map
      Returns:
      a new map containing only JRT-managed special variables
    • prepareForExecution

      public void prepareForExecution(String defaultFs, String defaultRs)
      Resets per-execution JRT state and re-applies the default runtime special variables for a new script or expression execution.

      The defaultFs and defaultRs parameters allow the caller to configure the initial field and record separators. Other special variables (OFS, ORS, CONVFMT, OFMT, SUBSEP) use their POSIX-mandated defaults (see Awk constants) which are platform-independent and therefore not parameterized. Platform-specific end-of-line handling is the responsibility of the AwkSink.

      Parameters:
      defaultFs - default field separator, or null for Awk.DEFAULT_FS
      defaultRs - default record separator
    • assignInitialVariables

      public final void assignInitialVariables(Map<String,Object> initialVarMap)
      Assign all -v variables.
      Parameters:
      initialVarMap - A map containing all initial variable names and their values.
    • applySpecialVariable

      public boolean applySpecialVariable(String name, Object value)
      Applies the assignment of a single JRT-managed special variable.
      Parameters:
      name - variable name
      value - value to assign
      Returns:
      true when the name was a JRT-managed special variable, false when the assignment was not handled
    • applySpecialVariables

      public final void applySpecialVariables(Map<String,Object> variableMap)
      Applies only the JRT-managed special variable assignments from the supplied map (FS, RS, OFS, ORS, CONVFMT, OFMT, SUBSEP, FILENAME, NF, NR, FNR, ARGC, IGNORECASE). Non-special variables are silently skipped because they require the runtime stack to be fully initialized (which happens during tuple execution).
      Parameters:
      variableMap - a map of variable names to values
    • assignEnvironmentVariables

      public static void assignEnvironmentVariables(AssocArray aa)
      Called by AVM/compiled modules to assign local environment variables to an associative array (in this case, to ENVIRON).
      Parameters:
      aa - The associative array to populate with environment variables. The module asserts that the associative array is empty prior to population.
    • createAwkMap

      public static Map<Object,Object> createAwkMap(boolean sortedArrayKeys)
      Creates an AWK-managed associative array and exposes it as a plain Map for callers that do not need the concrete runtime type.
      Parameters:
      sortedArrayKeys - true to keep keys sorted
      Returns:
      a new AWK associative array
    • containsAwkKey

      public static boolean containsAwkKey(Map<Object,Object> map, Object key)
      Checks key existence using AWK semantics when the supplied map is backed by an AssocArray, otherwise falling back to regular Map semantics.
      Parameters:
      map - map to inspect
      key - key to look up
      Returns:
      true when the key exists
    • getAssocArrayValue

      public static Object getAssocArrayValue(Map<Object,Object> map, Object key)
      Reads a map element using AWK semantics when the supplied map is backed by an AssocArray. For plain Map instances, missing or null-valued entries are exposed as the AWK blank value so later expression evaluation never receives a raw null.
      Parameters:
      map - map to inspect
      key - key to look up
      Returns:
      the stored value, or the AWK blank value when no concrete value is present
    • getAwkStringEntry

      public String getAwkStringEntry(Map<Object,Object> map, Object key)
      Returns the AWK string value of an associative array entry, or null when the array has no such key. This is the common way to read optional settings out of AWK arrays, such as PROCINFO["sorted_in"] or ENVIRON["TZ"].
      Parameters:
      map - associative array to read
      key - entry key
      Returns:
      the entry value converted with CONVFMT, or null when the key is absent
    • toAwkString

      public String toAwkString(Object o)
      Convert Strings, Integers, and Doubles to Strings based on the CONVFMT variable contents and the stored Locale.
      Parameters:
      o - Object to convert.
      Returns:
      A String representation of o.
    • compare

      public boolean compare(Object o1, Object o2, int mode)
      Compares two objects with this runtime's IGNORECASE, CONVFMT and locale.

      Prefer this over the static compare2 overloads whenever a runtime is available: it is the only form that honours a CONVFMT assigned by the script.

      Parameters:
      o1 - The 1st object.
      o2 - the 2nd object.
      mode - the comparison mode, as in compare2(Object, Object, int)
      Returns:
      a boolean
    • toDouble

      public static double toDouble(Object o)
      Convert a String, Integer, or Double to Double.
      Parameters:
      o - Object to convert.
      Returns:
      the "double" value of o, or 0 if invalid
    • isActuallyLong

      public static boolean isActuallyLong(double d)
      Determines whether a double value actually represents a long integer within the limits of floating point precision.
      Parameters:
      d - the double value to examine
      Returns:
      true if d is effectively an integer
    • toScalarNumber

      public static Object toScalarNumber(double d)
      Converts a computed double to the canonical AWK scalar: a Long when the value is integral and representable as a signed 64-bit integer, and the Double itself otherwise. Values beyond the 64-bit range stay doubles so they are not silently saturated to Long.MAX_VALUE.
      Parameters:
      d - the computed value
      Returns:
      d as a Long when exactly representable, or as a Double
    • truncateToScalar

      public static Object truncateToScalar(double d)
      Truncates a double toward zero, as AWK's int() does, returning a Long when the result is representable and a Double otherwise.
      Parameters:
      d - the value to truncate
      Returns:
      the truncated value as a canonical AWK scalar
    • add

      public static Object add(Object o1, Object o2)
      Adds two AWK scalars. When both operands are exact 64-bit integers and the sum fits in 64 bits, the result stays an exact Long; otherwise both operands are converted with toDouble(Object) and the result is a Double.
      Parameters:
      o1 - the left operand
      o2 - the right operand
      Returns:
      o1 + o2 as a canonical AWK scalar
    • subtract

      public static Object subtract(Object o1, Object o2)
      Subtracts two AWK scalars. When both operands are exact 64-bit integers and the difference fits in 64 bits, the result stays an exact Long; otherwise both operands are converted with toDouble(Object) and the result is a Double.
      Parameters:
      o1 - the left operand
      o2 - the right operand
      Returns:
      o1 - o2 as a canonical AWK scalar
    • multiply

      public static Object multiply(Object o1, Object o2)
      Multiplies two AWK scalars. When both operands are exact 64-bit integers and the product fits in 64 bits, the result stays an exact Long; otherwise both operands are converted with toDouble(Object) and the result is a Double.
      Parameters:
      o1 - the left operand
      o2 - the right operand
      Returns:
      o1 * o2 as a canonical AWK scalar
    • divide

      public static Object divide(Object o1, Object o2)
      Divides two AWK scalars. When both operands are exact 64-bit integers and the quotient is a 64-bit integer with no remainder, the result stays an exact Long; every other case (a fractional quotient, a zero divisor, or Long.MIN_VALUE / -1) is computed in floating point, as before.
      Parameters:
      o1 - the dividend
      o2 - the divisor
      Returns:
      o1 / o2 as a canonical AWK scalar
    • mod

      public static Object mod(Object o1, Object o2)
      Computes the remainder of two AWK scalars. When both operands are exact 64-bit integers and the divisor is non-zero, the result stays an exact Long; otherwise the remainder is computed in floating point, so a zero divisor still yields nan.
      Parameters:
      o1 - the dividend
      o2 - the divisor
      Returns:
      o1 % o2 as a canonical AWK scalar
    • pow

      public static Object pow(Object o1, Object o2)
      Raises an AWK scalar to a power. Exponentiation is always computed in floating point, like gawk's ^ operator.
      Parameters:
      o1 - the base
      o2 - the exponent
      Returns:
      o1 ^ o2 as a Double
    • negate

      public static Object negate(Object o)
      Negates an AWK scalar. An exact 64-bit integer stays an exact Long (except Long.MIN_VALUE, whose negation does not fit); everything else is converted with toDouble(Object) and negated as a Double.
      Parameters:
      o - the scalar to negate
      Returns:
      -o as a canonical AWK scalar
    • toLong

      public static long toLong(Object o)
      Convert a String, Long, or Double to Long.
      Parameters:
      o - Object to convert.
      Returns:
      the "long" value of o, or 0 if invalid
    • parseFieldNumber

      public static long parseFieldNumber(Object obj)
      Convert a field designator to a non-negative long, raising an AWK runtime exception when the value is invalid.
      Parameters:
      obj - the object identifying the field (for example, the result of a numeric expression)
      Returns:
      the parsed field number as a long
    • compare2

      public static boolean compare2(Object o1, Object o2, int mode)
      Compares two objects. Whether to employ less-than, equals, or greater-than checks depends on the mode chosen by the callee. It handles Awk variable rules and type conversion semantics.
      Parameters:
      o1 - The 1st object.
      o2 - the 2nd object.
      mode -
      • < 0 - Return true if o1 < o2.
      • 0 - Return true if o1 == o2.
      • > 0 - Return true if o1 > o2.
      Returns:
      a boolean
    • compare2

      public static boolean compare2(Object o1, Object o2, int mode, boolean ignoreCase)
      Compares two objects like compare2(Object, Object, int), folding case in string comparisons when ignoreCase is set: gawk's IGNORECASE applies to string relational operators, not only to regexp operations.
      Parameters:
      o1 - The 1st object.
      o2 - the 2nd object.
      mode - the comparison mode, as in compare2(Object, Object, int)
      ignoreCase - whether string comparisons ignore case
      Returns:
      a boolean
    • index

      public int index(String haystack, String needle)
      Implements the index() builtin: the 1-based position of needle within haystack, or 0 when absent, folding case when IGNORECASE is set.
      Parameters:
      haystack - text to search
      needle - text to find
      Returns:
      1-based match position, 0 when not found
    • toJavaScalar

      public static Object toJavaScalar(Object value)
      Converts an internal runtime scalar to the value exposed through Java APIs.
      Parameters:
      value - internal scalar value
      Returns:
      plain Java scalar value
    • isParseableNumber

      public boolean isParseableNumber(String value)
      Returns whether the supplied text parses as an AWK number under this runtime's locale, as used for strnum recognition. As POSIX specifies for numeric strings, leading and trailing blanks around the number are ignored, but text that is nothing but blanks does not qualify.
      Parameters:
      value - text to test
      Returns:
      true when value is an input numeric string
    • untypedToBlank

      public static Object untypedToBlank(Object value)
      Replaces the untyped marker by AWK's assigned blank scalar. Reading a missing array element creates and returns the untyped marker (so typeof() can see it), but an assignment must not propagate it: after x = a[missing], x is an assigned blank scalar (typeof(x) == "unassigned"), exactly as in gawk. This is a single instanceof on the assignment paths.
      Parameters:
      value - value about to be stored by an assignment
      Returns:
      the assigned blank scalar when the value was the untyped marker, otherwise the original value
    • inc

      public static Object inc(Object o)
      Return an object which is numerically equivalent to one plus a given object. An exact 64-bit integer stays an exact Long (unless the increment overflows). For other numbers and for Strings, the value is converted to a double first; a String without a numeric prefix counts as 0, so the result is 1.
      Parameters:
      o - The object to increase.
      Returns:
      o + 1 if o is numeric or contains a numeric prefix; otherwise, 1.0
    • dec

      public static Object dec(Object o)
      Return an object which is numerically equivalent to one minus a given object. An exact 64-bit integer stays an exact Long (unless the decrement overflows). For other numbers and for Strings, the value is converted to a double first; a String without a numeric prefix counts as 0, so the result is -1.
      Parameters:
      o - The object to increase.
      Returns:
      o - 1 if o is numeric or contains a numeric prefix; otherwise, -1.0
    • toBoolean

      public final boolean toBoolean(Object o)
      Converts an Integer, Double, String, Pattern, or ConditionPair to a boolean.
      Parameters:
      o - The object to convert to a boolean.
      Returns:
      For the following class types for o:
      • Integer - o.intValue() != 0
      • Long - o.longValue() != 0
      • Double - o.doubleValue() != 0
      • String - o.length() > 0
      • UninitializedObject - false
      • Pattern - $0 ~ o
      If o is none of these types, an error is thrown.
    • split

      public int split(Object array, Object string)
      Splits the string into parts separated by one or more spaces; blank first and last fields are eliminated. This conforms to the 2-argument version of AWK's split function.
      Parameters:
      array - The array to populate.
      string - The string to split.
      Returns:
      The number of parts resulting from this split operation.
    • split

      public int split(Object fieldSeparator, Object array, Object string)
      Splits the string into parts separated the regular expression fs. This conforms to the 3-argument version of AWK's split function.

      If fs is blank, it behaves similar to the 2-arg version of AWK's split function.

      Parameters:
      fieldSeparator - Field separator regular expression.
      array - The array to populate.
      string - The string to split.
      Returns:
      The number of parts resulting from this split operation.
    • getPartitioningReader

      public PartitioningReader getPartitioningReader()
      Returns the underlying PartitioningReader currently in use by the active InputSource, or null if the source is not stream-based.
      Returns:
      the active reader, or null
    • getInputLine

      public Object getInputLine()

      Getter for the field inputLine.

      Returns:
      the current input line scalar value, or null
    • getNF

      public Integer getNF()
      Retrieve the current value of NF. When fields are initialized this returns the number of fields in $0; otherwise 0.
      Returns:
      current NF value
    • setNF

      public void setNF(Object nfObject)
      Set NF to the specified value and update $0 and fields accordingly.
      Parameters:
      nfObject - value to assign to NF
    • getNR

      public Long getNR()
      Get the current NR value as tracked by JRT.
      Returns:
      current NR
    • setNR

      public void setNR(Object value)
      Assign NR to a specific value; also updates the VariableManager copy.
      Parameters:
      value - value to assign
    • getFNR

      public Long getFNR()
      Get the current FNR value as tracked by JRT.
      Returns:
      current FNR
    • setFNR

      public void setFNR(Object value)
      Assign FNR to a specific value; also updates the VariableManager copy.
      Parameters:
      value - value to assign
    • getFSVar

      public Object getFSVar()
      Get FS from the VariableManager.
      Returns:
      FS value
    • getFSString

      public String getFSString()
      Returns the current FS value as a string.
      Returns:
      current field separator
    • setFS

      public void setFS(Object value)
      Set FS via the VariableManager.
      Parameters:
      value - new FS value
    • setIGNORECASE

      public void setIGNORECASE(Object value)
      Sets IGNORECASE, precomputing its truth value so regexp operations can test a boolean instead of coercing the raw value on every match.
      Parameters:
      value - new IGNORECASE value
    • getIGNORECASEVar

      public Object getIGNORECASEVar()
      Get IGNORECASE from the VariableManager.
      Returns:
      IGNORECASE value
    • isIgnoreCase

      public boolean isIgnoreCase()
      Returns whether IGNORECASE is currently nonzero, making regexp operations case-insensitive. The truth value is precomputed when IGNORECASE is assigned.
      Returns:
      true when IGNORECASE is nonzero
    • regexpFlags

      public int regexpFlags()
      Returns the Pattern flags implied by the current IGNORECASE setting; dynamic regexps should be compiled with these flags.
      Returns:
      Pattern.CASE_INSENSITIVE when IGNORECASE is truthy, 0 otherwise
    • replaceFirst

      public int replaceFirst(String orig, String repl, String ere)
      sub() functionality: replaces the first match of ere in orig with repl, honoring IGNORECASE. The substituted text is available through getReplaceResult().
      Parameters:
      orig - original text
      repl - AWK replacement text
      ere - regular expression
      Returns:
      number of replacements performed (0 or 1)
    • replaceAll

      public int replaceAll(String orig, String repl, String ere)
      gsub() functionality: replaces every match of ere in orig with repl, honoring IGNORECASE. The substituted text is available through getReplaceResult().
      Parameters:
      orig - original text
      repl - AWK replacement text
      ere - regular expression
      Returns:
      number of replacements performed
    • getReplaceResult

      public String getReplaceResult()
      Returns:
      substituted text
    • matches

      public boolean matches(String text, Object regexp)
      Evaluates the AWK match operator (text ~ regexp), honoring IGNORECASE for both precompiled regexp constants and dynamic expressions.
      Parameters:
      text - text to match
      regexp - precompiled Pattern or dynamic regexp text
      Returns:
      true when the regexp matches anywhere in the text
    • matchPosition

      public int matchPosition(String s, String ere)
      match() functionality: locates ere in s honoring IGNORECASE, updating RSTART and RLENGTH.
      Parameters:
      s - text to search
      ere - regular expression
      Returns:
      the match position (RSTART), or 0 when there is no match
    • splitTokenizer

      public Enumeration<Object> splitTokenizer(String input, Object separator)
      Builds the tokenizer splitting input by the given separator, following AWK field-splitting rules (" " splits on whitespace runs, "" splits into characters, a single character is literal) and honoring IGNORECASE for regexp separators. A precompiled Pattern separator (a regexp literal) is used directly.
      Parameters:
      input - text to split
      separator - field separator: precompiled pattern or text
      Returns:
      tokenizer producing the split parts
    • prepareReplacement

      public static String prepareReplacement(String awkRepl, boolean backreferences)
      Converts an AWK replacement text into a Java Matcher replacement: & becomes the whole match, \& a literal ampersand, and $ is escaped.
      Parameters:
      awkRepl - AWK replacement text
      backreferences - whether \N denotes capture group N, as in gawk's gensub(); when false, \N stays literal as in sub() and gsub()
      Returns:
      the equivalent Java replacement string
    • prepareReplacement

      public static String prepareReplacement(String awkRepl, int maxGroup)
      Converts an AWK replacement text into a Java Matcher replacement, resolving gensub-style backreferences against a known number of capture groups: \N beyond maxGroup is replaced by the empty string, as gawk does, instead of producing a group reference that would make the matcher throw.
      Parameters:
      awkRepl - AWK replacement text
      maxGroup - highest valid capture group number, or a negative value to disable backreferences entirely (sub()/gsub() semantics)
      Returns:
      the equivalent Java replacement string
    • caseAwarePattern

      public Pattern caseAwarePattern(Pattern pattern)
      Returns the pattern itself, or its case-insensitive twin when IGNORECASE is set. Twins are compiled once and cached here: the JDK's Pattern.compile(String) performs no caching of its own (every call reparses the expression), so dropping this cache would recompile the regexp on every record matched against a regexp constant.
      Parameters:
      pattern - base pattern
      Returns:
      pattern honoring the current IGNORECASE setting
    • dynamicPattern

      public Pattern dynamicPattern(String ere)
      Compiles a dynamic (string) regexp with the flags implied by the current IGNORECASE setting, caching compiled patterns by expression text: dynamic regexps are typically reused across records (for example a gsub(dynstr, ...) loop), and the JDK's Pattern.compile(String, int) reparses the expression on every call. Each IGNORECASE setting has its own cache; the settings cannot share one because Pattern.flags() reflects inline flag constructs such as (?i), so it cannot tell apart a pattern compiled under the other setting.
      Parameters:
      ere - dynamic regular expression text
      Returns:
      the compiled pattern honoring the current IGNORECASE setting
    • getRSVar

      public Object getRSVar()
      Get RS from the VariableManager.
      Returns:
      RS value
    • getRSString

      public String getRSString()
      Returns the current RS value as a string.
      Returns:
      current record separator
    • setRS

      public void setRS(Object value)
      Set RS via the VariableManager and apply it to the current reader if any.
      Parameters:
      value - new RS value
    • getOFSVar

      public Object getOFSVar()
      Get OFS from the VariableManager.
      Returns:
      OFS value
    • getOFSString

      public String getOFSString()
      Returns the current OFS value as a string.
      Returns:
      current output field separator
    • setOFS

      public void setOFS(Object value)
      Set OFS via the VariableManager.
      Parameters:
      value - new OFS value
    • getORSVar

      public Object getORSVar()
      Get ORS from the VariableManager.
      Returns:
      ORS value
    • getORSString

      public String getORSString()
      Returns the current ORS value as a string.
      Returns:
      current output record separator
    • setORS

      public void setORS(Object value)
      Set ORS via the VariableManager.
      Parameters:
      value - new ORS value
    • getRSTART

      public Integer getRSTART()
      Get RSTART tracked by JRT (1-based).
      Returns:
      current RSTART
    • setRSTART

      public void setRSTART(Object value)
      Set RSTART tracked by JRT (1-based) and mirror to VariableManager.
      Parameters:
      value - new RSTART
    • getRLENGTH

      public Integer getRLENGTH()
      Get RLENGTH tracked by JRT.
      Returns:
      current RLENGTH
    • setRLENGTH

      public void setRLENGTH(Object value)
      Set RLENGTH tracked by JRT and mirror to VariableManager.
      Parameters:
      value - new RLENGTH
    • getFILENAME

      public Object getFILENAME()
      Get FILENAME as tracked by JRT.
      Returns:
      current FILENAME (empty string for stdin/pipe)
    • setFILENAMEViaJrt

      public void setFILENAMEViaJrt(Object name)
      Set FILENAME through VariableManager and update JRT mirror.
      Parameters:
      name - file name to set
    • getERRNO

      public Object getERRNO()
      Get ERRNO as tracked by JRT.
      Returns:
      current ERRNO (empty string when no input error is pending)
    • setERRNO

      public void setERRNO(Object value)
      Set ERRNO tracked by JRT.
      Parameters:
      value - new ERRNO value
    • getARGIND

      public Object getARGIND()
      Get ARGIND as tracked by JRT.
      Returns:
      ARGV index of the current input file (0 before any file is open)
    • setARGIND

      public void setARGIND(Object value)
      Set ARGIND tracked by JRT.
      Parameters:
      value - new ARGIND value
    • getSUBSEPVar

      public Object getSUBSEPVar()
      Get SUBSEP from the VariableManager.
      Returns:
      SUBSEP value
    • getSUBSEPString

      public String getSUBSEPString()
      Returns the current SUBSEP value as a string.
      Returns:
      current multidimensional-array subscript separator
    • setSUBSEP

      public void setSUBSEP(Object value)
      Set SUBSEP via the VariableManager.
      Parameters:
      value - new SUBSEP value
    • getCONVFMTVar

      public Object getCONVFMTVar()
      Get CONVFMT from the VariableManager.
      Returns:
      CONVFMT value
    • getCONVFMTString

      public String getCONVFMTString()
      Returns the current CONVFMT value as a string.
      Returns:
      current numeric conversion format
    • setCONVFMT

      public void setCONVFMT(Object value)
      Set CONVFMT via the VariableManager.
      Parameters:
      value - new CONVFMT value
    • getOFMTString

      public String getOFMTString()
      Get OFMT from the VariableManager.
      Returns:
      OFMT value
    • setOFMT

      public void setOFMT(Object value)
      Set OFMT via the VariableManager.
      Parameters:
      value - new OFMT value
    • getARGCVar

      public Object getARGCVar()
      Get ARGC from the VariableManager.
      Returns:
      ARGC value
    • setARGC

      public void setARGC(Object value)
      Set ARGC via the VariableManager.
      Parameters:
      value - new ARGC value
    • setInputLine

      public void setInputLine(Object inputLineParam)

      Setter for the field inputLine.

      Parameters:
      inputLineParam - input value
    • toInputScalar

      public Object toInputScalar(Object value)
      Creates an input-derived AWK scalar value.
      Parameters:
      value - input text
      Returns:
      input-derived scalar value
    • consumeInput

      public boolean consumeInput(InputSource source) throws IOException
      Attempt to consume one record from a structured input source and expose it as the current input record.
      Parameters:
      source - source strategy that provides records and optional pre-split fields
      Returns:
      true if a record was consumed; false when the source is exhausted
      Throws:
      IOException - if the source raises an I/O error
    • consumeCurrentFileInput

      public boolean consumeCurrentFileInput(InputSource source) throws IOException
      Attempt to consume one record from the current input file only, without ever advancing to the next input file. Used by the per-file main input loop when BEGINFILE/ENDFILE rules or nextfile are present, so that the ENDFILE rules can run at each file boundary.

      When the current input file could not be opened (a pending ERRNO set by advanceToNextFile(InputSource) that no nextfile consumed), the usual fatal error is raised, mirroring gawk.

      Parameters:
      source - source strategy that provides records and optional pre-split fields
      Returns:
      true if a record was consumed; false at the end of the current input file
      Throws:
      IOException - if the source raises an I/O error
    • consumeCurrentFileInputToTarget

      public Object consumeCurrentFileInputToTarget(InputSource source) throws IOException
      Attempt to consume one record of the current input file only for getline target, returning the input value and leaving the current input record state untouched. Used instead of consumeInputToTarget(InputSource) while the per-file main input loop is active, so a getline in an action never crosses a file boundary behind the BEGINFILE/ENDFILE rules' back.
      Parameters:
      source - source strategy that provides records and optional pre-split fields
      Returns:
      the consumed input value, or null at the end of the current input file
      Throws:
      IOException - if the source raises an I/O error
    • advanceToNextFile

      public boolean advanceToNextFile(InputSource source) throws IOException
      Advance the main input to the next input file, applying pending name=value command-line assignments along the way. On success, FILENAME, FNR, ARGIND, and ERRNO are updated and $0 is cleared, so the BEGINFILE rules observe the new file. A file that cannot be opened is still reported as available, with ERRNO carrying the error description (gawk BEGINFILE error handling).
      Parameters:
      source - source strategy that provides records and optional pre-split fields
      Returns:
      true when a new input file (or the initial stdin stream) is available; false when input is exhausted
      Throws:
      IOException - if an I/O error occurs while traversing ARGV
    • hasPendingInputFileError

      public boolean hasPendingInputFileError(InputSource source)
      Returns whether the current input file of the given source failed to open, leaving a pending error that only a nextfile statement in a BEGINFILE rule may bypass.
      Parameters:
      source - source strategy that provides records
      Returns:
      true when the current input file could not be opened
    • consumeInputToTarget

      public Object consumeInputToTarget(InputSource source) throws IOException
      Attempt to consume one record from a structured input source for getline target, returning the input value and leaving the current input record state untouched.
      Parameters:
      source - source strategy that provides records and optional pre-split fields
      Returns:
      the consumed input value, or null when the source is exhausted
      Throws:
      IOException - if the source raises an I/O error
    • consumeInputForEval

      public boolean consumeInputForEval(InputSource source) throws IOException
      Consume at most one record from a structured source for expression evaluation.
      Parameters:
      source - source strategy that provides records and optional pre-split fields
      Returns:
      true if a record was consumed, false otherwise
      Throws:
      IOException - if the source raises an I/O error
    • initializeInputFields

      protected void initializeInputFields(String record, List<String> preFields)
      Initialize $0..$NF from a pre-split field list.
      Parameters:
      record - current $0 text
      preFields - current fields where index 0 is $1
    • jrtParseFields

      public void jrtParseFields()
      Splits $0 into $1, $2, etc. Called when an update to $0 has occurred.
    • hasInputFields

      public boolean hasInputFields()
      Reports whether a record is currently loaded, and therefore whether the input fields hold anything.
      Returns:
      true if at least one input field has been initialized.
    • jrtSetNF

      public void jrtSetNF(Object nfObj)
      Adjust the current input field list and $0 when NF is updated by the AWK script. Fields are either truncated or extended with empty values so that NF truly reflects the number of fields.
      Parameters:
      nfObj - New value for NF
    • jrtGetInputField

      public Object jrtGetInputField(Object fieldnumObj)
      Retrieve the contents of a particular input field.
      Parameters:
      fieldnumObj - Object referring to the field number.
      Returns:
      Contents of the field.
    • jrtGetInputField

      public Object jrtGetInputField(long fieldnum)

      jrtGetInputField.

      Parameters:
      fieldnum - a long
      Returns:
      a Object object
    • jrtSetInputField

      public String jrtSetInputField(Object valueObj, long fieldNum)
      Stores value_obj into an input field.
      Parameters:
      valueObj - The RHS of the assignment.
      fieldNum - field number to update.
      Returns:
      A string representation of valueObj.
    • rebuildDollarZeroFromFields

      protected void rebuildDollarZeroFromFields()
      Rebuilds $0 from the current field values, joining them with OFS, and caches the result as the current input line.

      Does nothing when no record is loaded. Provided for subclasses that mutate the fields directly rather than through jrtSetInputField(Object, long), so that $0 stays consistent with them.

    • jrtConsumeFileInputForGetline

      public Integer jrtConsumeFileInputForGetline(String fileNameParam)
      Reads one record from a file for a redirected getline, translating the outcome into the AWK-visible return code.
      Parameters:
      fileNameParam - name of the file to read from
      Returns:
      1 when a record was read (available through jrtGetInputString()), 0 at end of input, and -1 when the file cannot be opened or read, in which case ERRNO carries the gawk-style error description
      Throws:
      AwkRuntimeException - when the filename is the empty string, the fatal error gawk raises for a null-string redirection
    • jrtConsumeCommandInputForGetline

      public Integer jrtConsumeCommandInputForGetline(String cmdString)
      Reads one record from the output of a command for a redirected getline, translating the outcome into the AWK-visible return code.
      Parameters:
      cmdString - the command to execute
      Returns:
      1 when a record was read (available through jrtGetInputString()), 0 at end of input, and -1 when the process cannot be spawned, in which case ERRNO carries the error description
      Throws:
      AwkRuntimeException - when the command is the empty string, the fatal error gawk raises for a null-string redirection
    • jrtGetInputString

      public String jrtGetInputString()
      Retrieve the record last consumed by a redirected getline.
      Returns:
      the last record read by jrtConsumeFileInputForGetline(String) or jrtConsumeCommandInputForGetline(String)
    • getOutputFiles

      public Map<String,PrintStream> getOutputFiles()

      Getter for the field outputFiles.

      Returns:
      a Map object
    • getFileAwkSink

      protected AwkSink getFileAwkSink(String fileNameParam, boolean append)
      Resolves the sink used by file redirection. The gawk special filenames /dev/stdout and /dev/stderr (and their /dev/fd/1 and /dev/fd/2 spellings) are routed to the streams the process already holds open instead of being opened, and therefore truncated, as regular files, and /dev/null designates the platform's null device on Windows too.
      Parameters:
      fileNameParam - target file name
      append - whether output should be appended
      Returns:
      the sink that writes to the requested file
    • getPipeAwkSink

      protected AwkSink getPipeAwkSink(String cmd)
      Resolves the sink used by pipe redirection.
      Parameters:
      cmd - command to execute
      Returns:
      the sink connected to the process stdin
    • printDefault

      public void printDefault(Object[] values) throws IOException
      Writes a standard AWK print operation to the default output.
      Parameters:
      values - values to print
      Throws:
      IOException - if the sink cannot be written to
    • printToFile

      public void printToFile(String fileNameParam, boolean append, Object[] values) throws IOException
      Writes a standard AWK print operation to a redirected file.
      Parameters:
      fileNameParam - target file name
      append - whether output should be appended
      values - values to print; an empty array prints $0
      Throws:
      IOException - if the sink cannot be written to
    • printToProcess

      public void printToProcess(String cmd, Object[] values) throws IOException
      Writes a standard AWK print operation to a redirected process.
      Parameters:
      cmd - command to execute
      values - values to print; an empty array prints $0
      Throws:
      IOException - if the sink cannot be written to
    • printfDefault

      public void printfDefault(String format, Object[] values) throws IOException
      Writes a formatted AWK output string to the specified sink.
      Parameters:
      format - format string passed to printf
      values - values supplied after the format string
      Throws:
      IOException - if the sink cannot be written to
    • sprintf

      public String sprintf(String format, Object... values)
      Formats a string in the same way as AWK's sprintf() built-in, through the default output sink and with the current CONVFMT value.
      Parameters:
      format - format string passed to sprintf
      values - arguments supplied after the format string
      Returns:
      formatted text
    • printfToFile

      public void printfToFile(String fileNameParam, boolean append, String format, Object[] values) throws IOException
      Writes formatted AWK output to a redirected file.
      Parameters:
      fileNameParam - target file name
      append - whether output should be appended
      format - format string passed to printf
      values - values supplied after the format string
      Throws:
      IOException - if the sink cannot be written to
    • printfToProcess

      public void printfToProcess(String cmd, String format, Object[] values) throws IOException
      Writes formatted AWK output to a redirected process.
      Parameters:
      cmd - command to execute
      format - format string passed to printf
      values - values supplied after the format string
      Throws:
      IOException - if the sink cannot be written to
    • jrtGetPrintStream

      public PrintStream jrtGetPrintStream(String fileNameParam, boolean append)
      Retrieve the PrintStream which writes to a particular file, creating the PrintStream if necessary.
      Parameters:
      fileNameParam - The file which to write the contents of the PrintStream.
      append - true to append to the file, false to overwrite the file.
      Returns:
      a PrintStream object
    • jrtConsumeFileInput

      public boolean jrtConsumeFileInput(String fileNameParam) throws IOException
      Reads one record from a file opened by a redirected getline.

      The reader is opened on first use and kept until it is explicitly closed or the VM exits. Unlike the main input loop, this transport leaves the current record ($0 and its fields), NR, FNR, and FILENAME untouched: gawk documents getline [var] < file as setting only the target of the read. The consumed record is exposed through jrtGetInputString().

      The gawk special filename /dev/stdin (and its /dev/fd/0 spelling) reads the standard input of the process rather than a file of that name, and /dev/null reads the platform's null device, which reports end of input immediately on Windows too.

      Parameters:
      fileNameParam - name of the file to read from
      Returns:
      true when a record was read; false at end of input
      Throws:
      IOException - if the file cannot be opened or read; a failed open is not cached, so a later getline from the same name retries it
    • setSpawnedProcessesInheritStandardInput

      public void setSpawnedProcessesInheritStandardInput(boolean inherit)
      Declares whether processes spawned on behalf of the script share the standard input of this JVM. POSIX gives the children of system() and of a command pipe the same standard input as awk itself, which is how terminal-aware commands like "stty size" | getline find the controlling terminal. That is only faithful when Jawk reads the real standard input of the process, which no capture of System.in can establish — an embedder may have replaced the stream with System.setIn at any point, including before this class initializes — so eligibility is asserted explicitly by the one caller that can vouch for it: the command-line entry point of the process. Everywhere else the flag stays false and the child's standard input is closed, since a Java stream cannot be lent to another OS process, and exposing the host JVM's real descriptor 0 instead would leak input the embedder never gave to Jawk.
      Parameters:
      inherit - true when the standard input this run reads is the standard input of the JVM process itself
    • jrtConsumeCommandInput

      public boolean jrtConsumeCommandInput(String cmd) throws IOException
      Reads one record from the output of a command spawned by a redirected getline.

      The process is spawned on first use and kept until the pipe is explicitly closed or the VM exits. As with file redirection, the current record ($0 and its fields), NR, FNR, and FILENAME are left untouched: gawk documents cmd | getline [var] as setting only the target of the read. The consumed record is exposed through jrtGetInputString().

      Parameters:
      cmd - the command to execute
      Returns:
      true when a record was read; false at end of input
      Throws:
      IOException - if the process cannot be spawned; a failed spawn is not cached, so a later getline from the same command retries it
    • jrtSpawnForOutput

      public PrintStream jrtSpawnForOutput(String cmd)
      Retrieve the PrintStream which shuttles data to stdin for a process, executing the process if necessary. Threads are created to shuttle the data to/from the process.
      Parameters:
      cmd - The command to execute.
      Returns:
      The PrintStream which to write to provide input data to the process.
    • jrtClose

      public Integer jrtClose(String fileNameParam)
      Attempt to close an open stream, whether it is an input file, output file, input process, or output process.

      The specification did not describe AWK behavior when attempting to close streams/processes with the same file/command name. In this case, all open streams with this name are closed.

      Parameters:
      fileNameParam - The filename/command process to close.
      Returns:
      Integer(0) upon a successful close, Integer(-1) otherwise.
    • jrtCloseAll

      public void jrtCloseAll()

      jrtCloseAll.

    • jrtSystem

      public Integer jrtSystem(String cmd)
      Executes the command specified by cmd and waits for termination, returning an Integer object containing the return code. The command inherits the standard input of the JVM when Jawk reads the real standard input (CLI runs), as POSIX requires of system(); otherwise its standard input is closed. Threads are created to shuttle stdout and stderr of the command to stdout/stderr of the calling process.
      Parameters:
      cmd - The command to execute.
      Returns:
      Integer(return_code) of the created process. Integer(-1) is returned on an IO error.
    • sprintfNoCatch

      public static String sprintfNoCatch(Locale locale, String fmtArg, Object... arr) throws IllegalFormatException

      sprintfFunctionNoCatch.

      Parameters:
      locale - a Locale object
      fmtArg - a String object
      arr - an array of Object objects
      Returns:
      a String object
      Throws:
      IllegalFormatException - if any.
    • printfNoCatch

      public static void printfNoCatch(Locale locale, String fmtArg, Object... arr)

      printfFunctionNoCatch.

      Parameters:
      locale - a Locale object
      fmtArg - a String object
      arr - an array of Object objects
    • printfNoCatch

      public static void printfNoCatch(PrintStream ps, Locale locale, String fmtArg, Object... arr)

      printfFunctionNoCatch.

      Parameters:
      ps - a PrintStream object
      locale - a Locale object
      fmtArg - a String object
      arr - an array of Object objects
    • substr

      public static String substr(Object startposObj, String str)

      substr.

      Parameters:
      startposObj - a Object object
      str - a String object
      Returns:
      a String object
    • substr

      public static String substr(Object sizeObj, Object startposObj, String str)

      substr.

      Parameters:
      sizeObj - a Object object
      startposObj - a Object object
      str - a String object
      Returns:
      a String object
    • timeSeed

      public static int timeSeed()

      timeSeed.

      Returns:
      a int
    • newRandom

      public static BSDRandom newRandom(int seed)

      newRandom.

      Parameters:
      seed - a int
      Returns:
      a Random object
    • applyRS

      public void applyRS(Object rsObj)

      applyRS.

      Parameters:
      rsObj - a Object object