Class NaftahParserHelper

java.lang.Object
org.daiitech.naftah.parser.NaftahParserHelper

public final class NaftahParserHelper extends Object
Helper class for various parsing-related utilities used in the Naftah language parser. Includes methods for working with parse trees, preparing function calls, resolving placeholders, and other parsing helper utilities.

All methods are static, and instantiation is prevented.

Author:
Chakib Daii
  • Field Details

    • FORMATTER

      public static final String FORMATTER
      Format string for debug or log messages that include an index, text, and payload.
      See Also:
    • PLACEHOLDER_PATTERN

      public static final Pattern PLACEHOLDER_PATTERN
      Regex pattern for detecting placeholders in the form PLACEHOLDER(key).
    • NULL

      public static final String NULL
      String representation for a null value in Naftah.
      See Also:
    • QUALIFIED_NAME_REGEX

      public static final String QUALIFIED_NAME_REGEX
      Regex pattern for matching qualified names.
      See Also:
    • QUALIFIED_CALL_REGEX

      public static final String QUALIFIED_CALL_REGEX
      Regex pattern for matching qualified calls.
      See Also:
    • NORMALIZER

      public static final com.ibm.icu.text.Normalizer2 NORMALIZER
      Unicode normalizer instance for normalization form NFKC.
    • SUB_TREE_CACHE

      private static final Map<org.antlr.v4.runtime.tree.ParseTree,List<org.antlr.v4.runtime.tree.ParseTree>> SUB_TREE_CACHE
      Cache to store computed subtrees per parse tree node for optimization.
    • TOKENS_SYMBOLS

      public static Properties TOKENS_SYMBOLS
      Loaded properties representing token symbols, if available.
    • LEXER_LITERALS

      public static List<String> LEXER_LITERALS
      A list of literal keywords or token strings defined by the lexer.

      These are fixed words or symbols in the language (e.g., operators, control keywords) that are recognized directly by the lexer and mapped to specific tokens.

  • Constructor Details

    • NaftahParserHelper

      private NaftahParserHelper()
      Private constructor to prevent instantiation. Always throws a NaftahBugError when called.
  • Method Details

    • hasParentOfType

      public static <T extends org.antlr.v4.runtime.tree.Tree> boolean hasParentOfType(org.antlr.v4.runtime.tree.ParseTree ctx, Class<T> type)
      Checks if the given parse tree node has a direct parent of the specified type.
      Type Parameters:
      T - the type of the parent tree node
      Parameters:
      ctx - the parse tree node to check
      type - the parent class type to look for
      Returns:
      true if the parent is of the specified type; false otherwise
    • hasAnyParentOfType

      public static boolean hasAnyParentOfType(org.antlr.v4.runtime.tree.ParseTree ctx, List<Class<? extends org.antlr.v4.runtime.tree.Tree>> types)
      Checks if the given parse tree node has any parent of any of the specified types.
      Parameters:
      ctx - the parse tree node to check
      types - list of class types to check for as parent types
      Returns:
      true if any parent matches one of the types; false otherwise
    • hasAnyParentOfType

      public static <T extends org.antlr.v4.runtime.tree.Tree> boolean hasAnyParentOfType(org.antlr.v4.runtime.tree.ParseTree ctx, Class<T> type)
      Checks recursively if the given parse tree node has any ancestor (parent or further up) of the specified type.
      Type Parameters:
      T - the type of the ancestor tree node
      Parameters:
      ctx - the parse tree node to check
      type - the ancestor class type to look for
      Returns:
      true if any ancestor is of the specified type; false otherwise
    • hasChild

      public static <T extends org.antlr.v4.runtime.tree.Tree> boolean hasChild(T child)
      Checks if the given child node is non-null.
      Type Parameters:
      T - the type of the child node
      Parameters:
      child - the child node to check
      Returns:
      true if child is not null; false otherwise
    • hasChildOfType

      public static <T, T1 extends org.antlr.v4.runtime.tree.Tree> boolean hasChildOfType(T child, Class<T1> type)
      Checks if the given child node is of the specified type.
      Type Parameters:
      T - the child node type
      T1 - the type to check against
      Parameters:
      child - the child node to check
      type - the class type to check
      Returns:
      true if child is non-null and of the specified type; false otherwise
    • hasChildOfType

      public static <T, T1 extends org.antlr.v4.runtime.tree.Tree> boolean hasChildOfType(List<T> children, Class<T1> type)
      Checks if any child in the list is of the specified type.
      Type Parameters:
      T - the type of elements in the children list
      T1 - the type to check against
      Parameters:
      children - the list of child nodes
      type - the class type to check
      Returns:
      true if any child is of the specified type; false otherwise
    • hasChildOrSubChildOfType

      public static <T extends org.antlr.v4.runtime.tree.Tree> boolean hasChildOrSubChildOfType(org.antlr.v4.runtime.tree.ParseTree ctx, Class<T> type)
      Checks if the given parse tree node has a child or sub-child of the specified type.
      Type Parameters:
      T - the type to check for in descendants
      Parameters:
      ctx - the parse tree node to check
      type - the class type to check
      Returns:
      true if any child or descendant is of the specified type; false otherwise
    • hasAnyExecutedChildOrSubChildOfType

      public static <T extends org.antlr.v4.runtime.tree.Tree> boolean hasAnyExecutedChildOrSubChildOfType(org.antlr.v4.runtime.tree.ParseTree ctx, Class<T> type, org.antlr.v4.runtime.tree.ParseTreeProperty<Boolean> executedParseTreeProperty)
      Checks if any executed child or sub-child of the specified type exists under the given node, based on the provided execution property.
      Type Parameters:
      T - the type of child to check
      Parameters:
      ctx - the root parse tree node
      type - the child class type to look for
      executedParseTreeProperty - a property map indicating executed nodes
      Returns:
      true if any executed child or descendant is of the specified type; false otherwise
    • getAllChildrenOfType

      public static <T extends org.antlr.v4.runtime.tree.Tree> List<org.antlr.v4.runtime.tree.ParseTree> getAllChildrenOfType(org.antlr.v4.runtime.tree.ParseTree ctx, Class<T> type)
      Retrieves all children of the given parse tree node that are of the specified type.
      Type Parameters:
      T - the type of children to retrieve
      Parameters:
      ctx - the parse tree node
      type - the class type to filter children by
      Returns:
      a list of children of the specified type, or empty list if none found
    • getFirstChildOfType

      public static <T extends org.antlr.v4.runtime.tree.ParseTree> T getFirstChildOfType(org.antlr.v4.runtime.tree.ParseTree node, Class<T> type)
      Recursively searches the given parse tree node and its descendants for the first occurrence of a child whose type matches the specified class.

      The search is performed in a pre-order, depth-first manner:

      • First, the current node itself is checked.
      • If it matches the requested type, it is returned immediately.
      • Otherwise, each child is visited in the order they appear in the tree.

      This method does not restrict the search to direct children; it will return the first matching descendant at any depth.

      Type Parameters:
      T - the expected parse tree subtype
      Parameters:
      node - the root of the subtree to search; may be null
      type - the class object representing the desired parse tree type
      Returns:
      the first node (including node itself) that is an instance of type, or null if no matching node is found
    • getAllChildren

      public static List<org.antlr.v4.runtime.tree.ParseTree> getAllChildren(org.antlr.v4.runtime.tree.ParseTree ctx)
      Collects all nodes in the subtree rooted at the given parse tree node, including itself. Uses an internal cache to optimize repeated calls on the same node.
      Parameters:
      ctx - the root parse tree node
      Returns:
      list of all descendant nodes including the root node
    • collect

      private static void collect(org.antlr.v4.runtime.tree.ParseTree node, List<org.antlr.v4.runtime.tree.ParseTree> out)
      Recursively collects all nodes in the subtree rooted at the given node.
      Parameters:
      node - the current parse tree node
      out - the list to accumulate nodes
    • visit

      public static Object visit(NaftahParserBaseVisitor<?> naftahParserBaseVisitor, org.antlr.v4.runtime.tree.ParseTree tree)
      Visits the given parse tree using the provided Naftah parser visitor.
      Parameters:
      naftahParserBaseVisitor - the visitor instance
      tree - the parse tree to visit
      Returns:
      the result of the visit operation
    • prepareDeclaredFunction

      public static void prepareDeclaredFunction(NaftahParserBaseVisitor<?> naftahParserBaseVisitor, DeclaredFunction<?> function)
      Prepares a declared function by visiting and setting its parameters and return type if not already set.
      Parameters:
      naftahParserBaseVisitor - the visitor to use for visiting parameter and return type contexts
      function - the declared function to prepare
    • prepareDeclaredFunctionArguments

      public static Map<String,Object> prepareDeclaredFunctionArguments(List<DeclaredParameter> parameters, List<Pair<String,Object>> arguments)
      Prepares a map of argument names to their values for a declared function.
      Parameters:
      parameters - List of declared parameters for the function.
      arguments - List of pairs representing argument name (nullable) and value.
      Returns:
      A map of parameter names to argument values.
      Throws:
      NaftahBugError - if more arguments are passed than parameters, or if required parameters are missing or duplicated.
    • getQualifiedName

      public static String getQualifiedName(NaftahParser.QualifiedNameContext ctx)
      Constructs a qualified name string from the given parse context.
      Parameters:
      ctx - The qualified name parse context.
      Returns:
      The fully qualified name as a string.
    • getQualifiedName

      public static String getQualifiedName(NaftahParser.QualifiedObjectAccessContext ctx)
      Constructs a qualified name string from the given parse context.
      Parameters:
      ctx - The object access parse context.
      Returns:
      The fully qualified name as a string.
    • prepareRun

      public static NaftahParser prepareRun(org.antlr.v4.runtime.CharStream input)
      Prepares a parser instance from the given input character stream with no error listeners.
      Parameters:
      input - The input character stream.
      Returns:
      The prepared parser instance.
    • prepareRun

      public static NaftahParser prepareRun(org.antlr.v4.runtime.CharStream input, org.antlr.v4.runtime.ANTLRErrorListener errorListener)
      Prepares a parser instance from the given input character stream with a single error listener.
      Parameters:
      input - The input character stream.
      errorListener - The error listener to add.
      Returns:
      The prepared parser instance.
    • prepareRun

      public static NaftahParser prepareRun(org.antlr.v4.runtime.CharStream input, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners)
      Initializes and prepares a NaftahParser instance from the given CharStream.

      This method performs the following steps:

      • Creates a lexer and token stream from the input
      • Registers all provided ANTLRErrorListener instances
      • Optionally prints the generated tokens when debugging is enabled
      • Creates and returns a configured parser instance
      Parameters:
      input - the input character stream to be parsed
      errorListeners - a list of ANTLRErrorListener instances to be attached to both the lexer and the parser
      Returns:
      a fully configured NaftahParser ready for execution
    • printTokens

      public static void printTokens(org.antlr.v4.runtime.CommonTokenStream tokens, org.antlr.v4.runtime.Vocabulary vocabulary)
      Prints all tokens produced by the lexer for debugging purposes.

      Each token is printed with its symbolic name and its original text representation as extracted from the input.

      This method forces the token stream to be fully populated by invoking BufferedTokenStream.fill().

      Parameters:
      tokens - the token stream generated by the lexer
      vocabulary - the lexer vocabulary used to resolve symbolic token names
    • doRun

      public static Object doRun(NaftahParser parser, List<String> args)
      Executes the parser by visiting the parse tree and returning the result.
      Parameters:
      parser - The parser instance.
      Returns:
      The result of visiting the parse tree.
    • getParser

      public static NaftahParser getParser(org.antlr.v4.runtime.CommonTokenStream commonTokenStream, org.antlr.v4.runtime.ANTLRErrorListener errorListener)
      Creates a parser instance from the given token stream and a single error listener.
      Parameters:
      commonTokenStream - The token stream.
      errorListener - The error listener.
      Returns:
      The parser instance.
    • getParser

      public static NaftahParser getParser(org.antlr.v4.runtime.CommonTokenStream commonTokenStream, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners)
      Creates and configures a NaftahParser using the provided CommonTokenStream.

      All default error listeners are removed and replaced with the supplied ANTLRErrorListener instances. The parser is also configured to use a BailErrorStrategy for fast-fail parsing.

      Parameters:
      commonTokenStream - the token stream produced by the lexer
      errorListeners - the error listeners to be attached to the parser
      Returns:
      a fully configured NaftahParser
    • getParser

      public static <T extends org.antlr.v4.runtime.Parser> T getParser(Supplier<T> parserSupplier, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners)
      Creates and configures a generic ANTLR Parser instance.

      This method:

      • Instantiates the parser using the supplied Supplier
      • Removes all default error listeners
      • Registers the provided ANTLRErrorListener instances
      • Configures the parser to use a shared BailErrorStrategy
      Type Parameters:
      T - the concrete type of the parser
      Parameters:
      parserSupplier - supplier used to create the parser instance
      errorListeners - the error listeners to be added to the parser
      Returns:
      a configured parser instance
    • getCommonTokenStream

      public static org.antlr.v4.runtime.CommonTokenStream getCommonTokenStream(org.antlr.v4.runtime.CharStream charStream)
      Gets a CommonTokenStream from the given character stream with no error listeners.
      Parameters:
      charStream - The character stream.
      Returns:
      The CommonTokenStream.
    • getCommonTokenStream

      public static org.antlr.v4.runtime.CommonTokenStream getCommonTokenStream(org.antlr.v4.runtime.CharStream charStream, org.antlr.v4.runtime.ANTLRErrorListener errorListener)
      Gets a CommonTokenStream from the given character stream and a single error listener.
      Parameters:
      charStream - The character stream.
      errorListener - The error listener.
      Returns:
      The CommonTokenStream.
    • getCommonTokenStream

      public static Pair<NaftahLexer,org.antlr.v4.runtime.CommonTokenStream> getCommonTokenStream(org.antlr.v4.runtime.CharStream charStream, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners)
      Creates and configures a NaftahLexer and its associated CommonTokenStream from the given CharStream.

      All default lexer error listeners are removed and replaced with the provided ANTLRErrorListener instances.

      Parameters:
      charStream - the input character stream to be tokenized
      errorListeners - the error listeners to be attached to the lexer
      Returns:
      a Pair containing the configured lexer and its CommonTokenStream
    • getCommonTokenStream

      public static <T extends org.antlr.v4.runtime.Lexer> Pair<T,org.antlr.v4.runtime.CommonTokenStream> getCommonTokenStream(Supplier<T> lexerSupplier, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners)
      Creates and configures a generic ANTLR Lexer and its corresponding CommonTokenStream.

      This method:

      • Instantiates the lexer using the supplied Supplier
      • Removes all default lexer error listeners
      • Registers the provided ANTLRErrorListener instances
      • Creates a CommonTokenStream backed by the lexer
      Type Parameters:
      T - the concrete type of the lexer
      Parameters:
      lexerSupplier - supplier used to create the lexer instance
      errorListeners - the error listeners to be added to the lexer
      Returns:
      a Pair containing the configured lexer and its CommonTokenStream
    • getCharStream

      public static org.antlr.v4.runtime.CharStream getCharStream(boolean isScriptFile, String script) throws Exception
      Creates a CharStream from either script content or a script file.

      When isScriptFile is true, the script parameter is treated as a file path. The file is located using the internal script resolution logic and then read using UTF-8 encoding.

      When isScriptFile is false, the script parameter is treated as raw script content and converted directly into a CharStream.

      Parameters:
      isScriptFile - true if script represents a script file path, false if it represents script content
      script - the script content or script file path
      Returns:
      a CharStream representing the script input
      Throws:
      Exception - if an error occurs while locating or reading the script file
    • getCharStream

      public static org.antlr.v4.runtime.CharStream getCharStream(String script)
      Creates a CharStream directly from script content.

      The script text is normalized before being converted into a character stream. Optional debugging output may be produced when the debug property is enabled.

      Platform-specific handling (e.g., Windows vs POSIX) is encapsulated internally.

      Parameters:
      script - the script content
      Returns:
      a CharStream representing the normalized script
    • searchForNaftahScriptFile

      public static File searchForNaftahScriptFile(String input)
      Searches for a Naftah script file based on a given name, trying multiple extensions.

      Tries in this order: - actual supplied name - name.naftah - name.nfth - name.na - name.nsh

      Parameters:
      input - The input file name or path.
      Returns:
      The File object pointing to the found script file, or the original if none found.
      Since:
      0.0.1
    • resolvePlaceholders

      public static void resolvePlaceholders(Properties props)
      Resolves placeholders in the properties values by replacing them with their corresponding property values.
      Parameters:
      props - The Properties object with placeholders to resolve.
    • resolveValue

      private static String resolveValue(String value, Properties props)
      Resolves placeholders within a string value using the given properties.
      Parameters:
      value - The string potentially containing placeholders.
      props - The properties to use for resolving placeholders.
      Returns:
      The resolved string, possibly wrapped in single quotes if placeholders were replaced.
    • declaredValueToString

      public static String declaredValueToString(boolean constant, String name, JavaType type, Object value)
      Converts a declared variable or constant value to a string representation.
      Parameters:
      constant - True if the variable is constant, false if mutable.
      name - The name of the variable.
      type - the variable type, default JavaType::ofObject.
      value - The value of the variable.
      Returns:
      A formatted string representing the declared variable or constant.
    • getFormattedTokenSymbols

      public static String getFormattedTokenSymbols(org.antlr.v4.runtime.Vocabulary vocabulary, int tokenType, boolean ln)
      Returns a formatted string of token symbols based on the token type.
      Parameters:
      vocabulary - The vocabulary containing token definitions.
      tokenType - The token type.
      ln - If true, formats output with a line break.
      Returns:
      A string representing token symbols, or null if none found.
    • getFormattedTokenSymbols

      public static String getFormattedTokenSymbols(String tokenName, boolean ln)
      Returns a formatted string representing the symbols associated with a token name.

      This method looks up tokenName in the TOKENS_SYMBOLS map (expected to be a Properties instance). If a corresponding entry is found, its value is used as the symbol representation; otherwise, tokenName itself is used as a fallback.

      Comma-separated symbols in the resolved value are joined using " أو" (Arabic for “or”).

      If ln is true, the result is formatted as a bullet point prefixed with a line break.

      Parameters:
      tokenName - the name of the token to look up
      ln - whether to format the result as a bullet point on its own line
      Returns:
      a formatted symbol string; never null
    • getDisplayName

      public static String getDisplayName(org.antlr.v4.runtime.tree.ParseTree node, org.antlr.v4.runtime.Vocabulary vocabulary)
      Returns the display name of a token using the given ANTLR vocabulary.
      Parameters:
      node - the terminal node (token) to analyze
      vocabulary - the ANTLR vocabulary (usually from the lexer)
      Returns:
      the display name of the token (e.g., '+', 'IDENTIFIER', etc.)
      Throws:
      NaftahBugError - if the node or token is null
    • createDeclaredVariable

      public static Pair<DeclaredVariable,Boolean> createDeclaredVariable(int depth, org.antlr.v4.runtime.ParserRuleContext ctx, String variableName, boolean isConstant, JavaType type)
      Creates a declared variable instance from the parser context.
      Parameters:
      depth - the depth of context where declared
      ctx - The declaration context.
      variableName - The variable name.
      isConstant - True if the variable is constant.
      type - the variable type, default JavaType::ofObject.
      Returns:
      A pair containing the declared variable and a boolean flag.
    • handleDeclaration

      public static Object handleDeclaration(DefaultContext currentContext, org.antlr.v4.runtime.ParserRuleContext ctx, String variableName, boolean hasConstant, boolean hasVariable, boolean hasType, JavaType type)
      Handles the declaration of a variable or constant in the current execution context.

      This method manages both standard variable/constant declarations and special cases like object field declarations. It also performs type validation when creating objects with a specific type.

      Behavior:

      • If the declaration includes a constant, variable, type, or is part of an object field, a new DeclaredVariable is created.
      • If the context is inside an object creation and a type is specified, it ensures that the object type is compatible with all types (i.e., Object.class).
      • If the variable is not part of an object field, it is registered in the DefaultContext.
      • If none of the declaration flags are set, it checks for a previously declared variable with the same name and reuses it if found. Otherwise, it creates a generic variable of type Object.

      The method returns either the DeclaredVariable or a pair containing it and a boolean flag if the context is parsing an assignment.

      Parameters:
      currentContext - the execution context where the variable is declared
      ctx - the parser context corresponding to the variable declaration
      variableName - the name of the variable to declare or retrieve
      hasConstant - true if the declaration includes a constant modifier
      hasVariable - true if the declaration includes a variable modifier
      hasType - true if the declaration specifies a type
      type - the JavaType representing the type of the variable, if any
      Returns:
      a DeclaredVariable object, or a Pair of the variable and a boolean if parsing an * assignment
      Throws:
      NaftahBugError - if an invalid type is specified for an object creation context
    • validateVariableExistence

      public static void validateVariableExistence(DefaultContext currentContext, String name)
      Validates whether a variable with the given name already exists in the current context.

      Checks both local variables in the current context and any broader variables in scope. If a variable with the same name exists, a NaftahBugError is thrown.

      Parameters:
      currentContext - The current scope or context to check for variable existence.
      name - The name of the variable to validate.
      Throws:
      NaftahBugError - if a variable with the same name already exists in the context.
    • checkLoopSignal

      public static LoopSignal checkLoopSignal(Object result)
      Checks if the given result object is a loop signal and returns the corresponding signal.
      Parameters:
      result - The result object to check.
      Returns:
      The detected loop signal, or LoopSignal.NONE if none.
    • checkInsideLoop

      public static boolean checkInsideLoop(org.antlr.v4.runtime.tree.ParseTree ctx)
      Checks if the given parse tree node is inside a loop construct.
      Parameters:
      ctx - The parse tree node to check.
      Returns:
      True if inside a loop, false otherwise.
    • shouldBreakStatementsLoop

      public static boolean shouldBreakStatementsLoop(DefaultContext currentContext, org.antlr.v4.runtime.tree.ParseTree currentStatement, Object result)
      Determines whether to break out of a loop based on the current context, statement, and result.
      Parameters:
      currentContext - The current execution context.
      currentStatement - The current parse tree statement.
      result - The result of the statement execution.
      Returns:
      True if the loop should break, false otherwise.
    • debugCurrentContextVisit

      public static void debugCurrentContextVisit(String methodName, org.antlr.v4.runtime.ParserRuleContext ctx)
      Logs detailed debug information about the current ParserRuleContext if the logger is configured to log at Level.FINE.

      This method formats and logs a message containing:

      • The name of the method invoking the debug (as provided in methodName).
      • The rule index, text, and payload of the current parse context (ctx).

      Example log message format: methodName(ruleIndex: contextText : contextPayload)

      Parameters:
      methodName - the name of the method calling this logger (used for traceability).
      ctx - the current ParserRuleContext to extract debugging information from.
    • visitContext

      public static <T extends org.antlr.v4.runtime.ParserRuleContext, R> R visitContext(DefaultNaftahParserVisitor defaultNaftahParserVisitor, String methodName, DefaultContext currentContext, T ctx, TriFunction<DefaultNaftahParserVisitor,DefaultContext,T,Object> visitFunction, Class<R> returnType)
      Visits a specific parser rule context by applying a custom TriFunction, while automatically handling logging, debugging, and execution tracking.

      This method provides a uniform mechanism for visiting ANTLR parser rule contexts in the Naftah parsing system. It ensures that every context visit is logged and marked as executed, and that a provided visitor function is safely applied to the current context.

      Behavior summary

      • Logs debugging information for the current rule context (via debugCurrentContextVisit).
      • Logs execution entry for the context (via logExecution).
      • Applies the provided TriFunction using the visitor, context, and parser rule.
      • Marks the context as executed in the DefaultContext instance.
      • Casts the visit result to the specified returnType.

      This version provides type safety by allowing the caller to specify the expected return type.

      Type Parameters:
      T - the type of the ParserRuleContext being visited
      R - the result type returned by the visitor function
      Parameters:
      defaultNaftahParserVisitor - the active DefaultNaftahParserVisitor handling the traversal
      methodName - the name of the visitor method being invoked (for logging and debugging)
      currentContext - the DefaultContext associated with the current traversal scope
      ctx - the current ParserRuleContext node being visited
      visitFunction - a TriFunction that takes the visitor, context, and rule, and returns a result
      returnType - the expected type of the returned value
      Returns:
      the result of applying the visitFunction, cast to the specified return type
      See Also:
    • visitContext

      public static <T extends org.antlr.v4.runtime.ParserRuleContext> Object visitContext(DefaultNaftahParserVisitor defaultNaftahParserVisitor, String methodName, DefaultContext currentContext, T ctx, TriFunction<DefaultNaftahParserVisitor,DefaultContext,T,Object> visitFunction)
      Simplified overload of visitContext(DefaultNaftahParserVisitor, String, DefaultContext, ParserRuleContext, TriFunction, Class) that defaults to returning an Object.

      This variant is useful when the expected result type is not known in advance or when generic type casting is unnecessary.

      Type Parameters:
      T - the type of the ParserRuleContext being visited
      Parameters:
      defaultNaftahParserVisitor - the active DefaultNaftahParserVisitor handling the traversal
      methodName - the name of the visitor method being invoked (for logging and debugging)
      currentContext - the DefaultContext associated with the current traversal scope
      ctx - the current ParserRuleContext node being visited
      visitFunction - a TriFunction that takes the visitor, context, and rule, and returns a result
      Returns:
      the result of applying the visitFunction, as a generic Object
      See Also:
    • getRootContext

      public static DefaultContext getRootContext(NaftahParser.ProgramContext ctx)
      Supplies the root DefaultContext for visiting a Program parse tree node.

      Chooses between REPL and standard execution modes based on a system property and the presence of any FunctionCallStatement within the parse tree.

      Parameters:
      ctx - the root ProgramContext from the parse tree
      Returns:
      the initialized root context (REPL or standard)
    • getBlockContext

      public static DefaultContext getBlockContext(NaftahParser.BlockContext ctx, DefaultContext currentContext)
      Supplies or updates the DefaultContext for a Block node.

      Decides REPL or standard context registration based on the REPL mode and whether the block contains function call statements or expressions.

      Parameters:
      ctx - the block context in the parse tree
      currentContext - the currently active execution context
      Returns:
      a new or updated execution context
    • setForeachVariables

      public static void setForeachVariables(DefaultContext currentContext, Class<? extends NaftahParser.ForeachTargetContext> foreachTargetClass, NTuple variableNames, NTuple targetValues)
      Sets loop variables in the DefaultContext for a Naftah `foreach` iteration.

      This method inspects the type of the foreachTargetClass to determine how to assign values from the targetValues tuple to the corresponding loop variables in the currentContext.

      Supported target contexts and their behavior:

      The mapping from variableNames to targetValues is as follows:

      • For value-only iteration: variableNames[0]targetValues[1]
      • For key-value iteration: variableNames[0] → key, variableNames[1] → value
      • For index-value iteration: variableNames[0] → index, variableNames[1] → value
      • For index-key-value iteration: variableNames[0] → index, variableNames[1] → key, * variableNames[2] → value
      Parameters:
      currentContext - the execution context in which loop variables will be set
      foreachTargetClass - the class type of the parsed `foreach` target, determines how variables are mapped
      variableNames - a NTuple of loop variable names extracted from the `foreach` declaration
      targetValues - a NTuple of values to assign to the loop variables
    • accessObjectUsingQualifiedName

      public static Object accessObjectUsingQualifiedName(String qualifiedName, DefaultContext currentContext, int line, int column)
      Resolves a qualified variable name (with optional safe chaining) to its corresponding value from the current execution context.

      The qualified name uses colon-separated (`:`) segments to represent nested access into maps. For example:

      
       user:profile:name
       
      would attempt to retrieve the value of name from profile, which is inside user.

      Supports optional chaining via the Arabic question mark suffix "؟" on any segment. If optional chaining is specified and any part of the chain is missing, the method returns None.get() instead of throwing an exception.

      Examples:

      • user:profile:name – standard access
      • user:profile؟:name – optional chaining on profile
      • user؟:profile؟:name – optional chaining on both user and profile
      Parameters:
      qualifiedName - the colon-separated variable access path, with optional "؟" suffixes
      currentContext - the current execution context used to resolve variables
      line - source line number (used for error reporting)
      column - source column number (used for error reporting)
      Returns:
      the resolved DeclaredVariable if found, or None.get() if not found with safe chaining
      Throws:
      NaftahBugError - if a variable in the access chain is not found and safe chaining is not enabled
    • setObjectUsingQualifiedName

      public static Object setObjectUsingQualifiedName(String qualifiedName, DefaultContext currentContext, Object newValue, int line, int column)
      Sets the value of a variable or nested property based on a qualified name string.

      The qualified name is a colon-separated path (e.g., user:profile:name) that may represent a deeply nested structure, where each intermediate level is a Map<String, DeclaredVariable>.
      The method supports optional safe-chaining by appending the Arabic question mark character (؟) to any segment (e.g., user؟:profile؟:name) to avoid exceptions if intermediate keys are missing.

      Behavior:

      • If the qualified name has only one part, the method sets the top-level variable.
      • If the qualified name represents a nested structure, the method traverses the map hierarchy, updating the final declared variable's value if found.
      • If any non-optional segment is missing, it throws a NaftahBugError using newNaftahBugVariableNotFoundError().
      Parameters:
      qualifiedName - the colon-separated qualified name (e.g., user:address؟:city)
      currentContext - the current evaluation context that holds top-level variables
      newValue - the new value to assign to the final declared variable
      line - source line number (used for error reporting)
      column - source column number (used for error reporting)
      Returns:
      the top-level DeclaredVariable (even if nested values were updated)
      Throws:
      NaftahBugError - if a non-optional intermediate or final variable is not found
    • FunctionToString

      public static <T> String FunctionToString(T currentFunction)
      Converts a function-like object into a detailed string representation for debugging or logging purposes.

      This utility handles multiple kinds of function representations:

      This method is useful for introspection, debugging, or logging information about function objects in a consistent and human-readable format.

      Type Parameters:
      T - the type of the function object
      Parameters:
      currentFunction - the function object to convert; may be a built-in, JVM function, JVM class initializer, or any other object
      Returns:
      a detailed string representation of the function, or the default Object.toString() for unknown types
    • getFunction

      public static <T extends JvmExecutable> T getFunction(Collection<T> functions, Number functionIndex)
      Retrieves a function (or executable) from a collection by its index.

      This method works with any collection of JvmExecutable objects and efficiently handles both List and generic Collection implementations:

      The function index is provided as a Number and converted to an integer internally.

      Type Parameters:
      T - the type of function, extending JvmExecutable
      Parameters:
      functions - the collection of function objects
      functionIndex - the index of the function to retrieve (as a Number)
      Returns:
      the function object at the specified index
      Throws:
      IndexOutOfBoundsException - if the index is out of range
    • invokeFunction

      public static Object invokeFunction(String functionName, boolean forceInvocation, Collection<JvmExecutable> jvmFunctions, List<Pair<String,Object>> naftahArgs, int line, int column) throws NoSuchMethodException
      Dynamically finds and invokes a function by name from a collection of JvmExecutable objects.

      This method performs the following steps:

      1. Finds the best matching executable using InvocationUtils.findBestExecutable(java.util.Collection<T>, java.util.List<org.daiitech.naftah.builtin.utils.tuple.Pair<java.lang.String, java.lang.Object>>) based on the provided arguments.
      2. If the selected function is a non-static JvmFunction, the first argument is treated as the instance.
      3. Delegates the actual invocation to invokeFunction(String, boolean, JvmExecutable, Object[], List, Object, int, int).
      Parameters:
      functionName - the name of the function to invoke (used for error reporting)
      forceInvocation - true in case of forcing invocation in case the JvmExecutable is not invocable by default
      jvmFunctions - the collection of available JvmExecutable functions
      naftahArgs - the list of arguments as Pair, where the first element may be the instance for non-static methods
      line - the source line number for error reporting
      column - the source column number for error reporting
      Returns:
      the result of the function invocation
      Throws:
      NaftahBugError - if no suitable function is found or invocation fails
      NoSuchMethodException
    • invokeFunction

      public static Object invokeFunction(String functionName, boolean forceInvocation, JvmExecutable selectedFunction, List<Pair<String,Object>> naftahArgs, Object possibleInstance, int line, int column)
      Invokes a specific JvmExecutable, either a BuiltinFunction or JvmFunction.

      This overload delegates to the more general method with executableArgs set to null.

      Parameters:
      functionName - the name of the function for error reporting
      forceInvocation - true in case of forcing invocation in case the JvmExecutable is not invocable by default
      selectedFunction - the executable to invoke
      naftahArgs - the arguments prepared for the executable
      possibleInstance - the instance to invoke on, or null for static methods
      line - the source line number for error reporting
      column - the source column number for error reporting
      Returns:
      the result of the invocation
      Throws:
      NaftahBugError - if the function type is unsupported or invocation fails
    • invokeFunction

      public static Object invokeFunction(String functionName, boolean forceInvocation, JvmExecutable selectedFunction, Object[] executableArgs, List<Pair<String,Object>> naftahArgs, Object possibleInstance, int line, int column)
      Parameters:
      functionName - the name of the function for error reporting
      forceInvocation - true in case of forcing invocation in case the JvmExecutable is not invocable by default
      selectedFunction - the executable to invoke
      executableArgs - the prepared arguments array for the executable (may be null)
      naftahArgs - the original list of Pair arguments
      possibleInstance - the instance to invoke on, or null for static methods
      line - the source line number for error reporting
      column - the source column number for error reporting
      Returns:
      the result of the invocation
      Throws:
      NaftahBugError - if the function type is unsupported or invocation fails
    • invokeDeclaredFunction

      public static Object invokeDeclaredFunction(int depth, String functionName, DeclaredFunction<?> declaredFunction, DefaultNaftahParserVisitor defaultNaftahParserVisitor, List<Pair<String,Object>> args, DefaultContext currentContext)
      Invokes a declared function within the current execution context, supporting both synchronous and asynchronous execution models.

      This method prepares the function’s parameters, binds argument values, updates the execution context, and then invokes the function body using the provided DefaultNaftahParserVisitor. If the function is declared as asynchronous, its body is executed inside a spawned Task and the task object is returned immediately. For synchronous functions, the body is executed directly and the returned value becomes the result.

      All function calls are recorded in the context’s call stack using DefaultContext.pushCall(org.daiitech.naftah.builtin.lang.DeclaredFunction<?>, java.util.Map<java.lang.String, java.lang.Object>), and removed afterward via DefaultContext.popCall(), ensuring proper debugging and stack-trace fidelity. For asynchronous functions, thread-local cleanup is performed after execution via currentContext.cleanThreadLocals().

      Parameters:
      depth - the current recursion or call depth, used to generate a unique call ID
      functionName - the name of the function to invoke
      declaredFunction - the function to invoke; must not be null
      defaultNaftahParserVisitor - the visitor used to evaluate the function body
      args - the list of (name, value) argument pairs to supply to the function
      currentContext - the active execution context
      Returns:
      for synchronous functions, the evaluated return value; for asynchronous functions, a Task representing the pending computation
      Throws:
      RuntimeException - if evaluation of the function body fails
    • doInvokeDeclaredFunction

      public static Object doInvokeDeclaredFunction(DeclaredFunction<?> declaredFunction, DefaultNaftahParserVisitor defaultNaftahParserVisitor, List<Pair<String,Object>> args, DefaultContext currentContext)
      Executes a declared function within the specified context.

      This method manages the full lifecycle of a function call, including:

      • Setting the implementation name in the current context.
      • Preparing the function’s parameter metadata and evaluating argument values.
      • Binding parameters and arguments into the current context for correct resolution during body evaluation.
      • Maintaining the call stack by pushing the function call before evaluation and popping it afterward.
      • Invoking the function body via the provided DefaultNaftahParserVisitor.
      • Returning None.get() if the function’s return type is Void, otherwise returning the evaluated result.

      Callers should ensure prepareDeclaredFunction(org.daiitech.naftah.parser.NaftahParserBaseVisitor<?>, org.daiitech.naftah.builtin.lang.DeclaredFunction<?>) has been invoked if any prerequisite preparation is required for the function.

      The call stack is updated even if an exception occurs during function execution, guaranteeing that context state remains consistent. After the function is popped, the implementation name in the context is restored to the parent call or cleared if no parent exists.

      Parameters:
      declaredFunction - the DeclaredFunction being executed
      defaultNaftahParserVisitor - the visitor used to evaluate the function body
      args - the raw argument name/value pairs supplied to the function
      currentContext - the DefaultContext associated with the call
      Returns:
      the evaluated result of the function body, or None.get() if the function has a Void return type
    • invokeBuiltinFunction

      public static Object invokeBuiltinFunction(String functionName, BuiltinFunction builtinFunction, List<Pair<String,Object>> naftahArgs, int line, int column)
      Invokes a built-in function via reflection with automatic argument conversion.

      This method supports two types of argument inputs:

      Supports conversions for primitives, arrays, collections, and generic types. If conversion fails or the argument count does not match, detailed runtime errors including line and column are thrown.

      Parameters:
      functionName - the name of the function for error reporting
      builtinFunction - the BuiltinFunction to invoke
      naftahArgs - a list of arguments as Pair name/value pairs
      line - the source line number for error reporting
      column - the source column number for error reporting
      Returns:
      the result of the function, or None.get() if the function returns void or null
      Throws:
      NaftahBugError - if argument types/count do not match, invocation fails, or instantiation fails
    • invokeBuiltinFunction

      public static Object invokeBuiltinFunction(String functionName, BuiltinFunction builtinFunction, Object[] executableArgs, List<Pair<String,Object>> naftahArgs, int line, int column)
      Invokes a built-in function with either pre-prepared argument array or List of Pair arguments.
      Parameters:
      functionName - the name of the function for error reporting
      builtinFunction - the BuiltinFunction to invoke
      executableArgs - the pre-prepared argument array (nullable)
      naftahArgs - a list of arguments as Pair name/value pairs
      line - the source line number
      column - the source column number
      Returns:
      the result of the function, or None.get() if void or null
      Throws:
      NaftahBugError - if argument types/count do not match, invocation fails, or instantiation fails
    • invokeJvmFunction

      public static Object invokeJvmFunction(String functionName, boolean forceInvocation, JvmFunction jvmFunction, List<Pair<String,Object>> naftahArgs, Object possibleInstance, int line, int column)
      Invokes a JVM function (static or instance) with automatic argument conversion.

      For instance methods, the first argument must be the object instance. Arguments are converted to match the method parameter types, including primitives, arrays, collections, and generic types.

      The result is wrapped in a NaftahObject. If the method returns void or null, a NaftahObject representing null is returned.

      Parameters:
      functionName - the name of the function for error reporting
      forceInvocation - true in case of forcing invocation in case the JvmExecutable is not invocable by default
      jvmFunction - the JvmFunction to invoke
      naftahArgs - a list of arguments as Pair name/value pairs
      possibleInstance - the instance for instance methods; null for static methods
      line - the source line number
      column - the source column number
      Returns:
      a NaftahObject wrapping the result
      Throws:
      NaftahBugError - if instance is missing, arguments mismatch, invocation fails, instantiation fails, or the function is non-invocable
    • invokeJvmFunction

      public static Object invokeJvmFunction(String functionName, boolean forceInvocation, JvmFunction jvmFunction, Object[] executableArgs, List<Pair<String,Object>> naftahArgs, Object possibleInstance, int line, int column)
      Invokes a JVM function with either pre-prepared argument array or List of Pair arguments.
      Parameters:
      functionName - the name of the function for error reporting
      forceInvocation - true in case of forcing invocation in case the JvmExecutable is not invocable by default
      jvmFunction - the JvmFunction to invoke
      executableArgs - the pre-prepared argument array (nullable)
      naftahArgs - a list of arguments as Pair name/value pairs
      possibleInstance - the instance for instance methods; null for static methods
      line - the source line number
      column - the source column number
      Returns:
      a NaftahObject wrapping the result
      Throws:
      NaftahBugError - if instance is missing, arguments mismatch, invocation fails, instantiation fails, or the function is non-invocable
    • invokeJvmClassInitializer

      public static Object invokeJvmClassInitializer(String classInitializerName, JvmClassInitializer jvmClassInitializer, List<Pair<String,Object>> naftahArgs, int line, int column)
      Invokes a specific JVM class initializer (constructor) with automatic argument conversion.

      Creates a new instance of the class represented by the provided JvmClassInitializer. Arguments are automatically converted to match the constructor's parameter types. The resulting instance is wrapped in a NaftahObject.

      Reflection exceptions are caught and rethrown as detailed Naftah-specific errors, including the class name, constructor signature, and source location (line/column).

      Parameters:
      classInitializerName - the name of the class initializer (for error reporting)
      jvmClassInitializer - the JvmClassInitializer representing the constructor
      naftahArgs - a list of arguments as Pair name/value pairs
      line - the source line number
      column - the source column number
      Returns:
      a NaftahObject containing the newly created instance
      Throws:
      NaftahBugError - if arguments do not match, constructor cannot be accessed, or instantiation fails
      See Also:
    • invokeJvmClassInitializer

      public static Object invokeJvmClassInitializer(String classInitializerName, JvmClassInitializer jvmClassInitializer, Object[] executableArgs, List<Pair<String,Object>> naftahArgs, int line, int column)
      Invokes a JVM class initializer with either pre-prepared argument array or a List of Pair arguments.
      Parameters:
      classInitializerName - the name of the class initializer (for error reporting)
      jvmClassInitializer - the JvmClassInitializer representing the constructor
      executableArgs - the pre-prepared argument array (nullable)
      naftahArgs - a list of arguments as Pair name/value pairs
      line - the source line number
      column - the source column number
      Returns:
      a NaftahObject containing the newly created instance
      Throws:
      NaftahBugError - if arguments do not match, constructor cannot be accessed, or instantiation fails
    • invokeJvmClassInitializer

      public static Object invokeJvmClassInitializer(String classInitializerName, List<JvmClassInitializer> jvmClassInitializers, List<Pair<String,Object>> naftahArgs, int line, int column) throws NoSuchMethodException
      Selects the best matching JVM class initializer from a collection and invokes it with automatic argument conversion.

      Evaluates all provided JvmClassInitializer instances, selects the one whose parameters best match the provided arguments, and then invokes it using invokeJvmClassInitializer(String, JvmClassInitializer, Object[], List, int, int).

      Parameters:
      classInitializerName - the name of the class initializer (for error reporting)
      jvmClassInitializers - the collection of candidate JvmClassInitializer instances
      naftahArgs - a list of arguments as Pair name/value pairs
      line - the source line number
      column - the source column number
      Returns:
      a NaftahObject containing the newly created instance
      Throws:
      NaftahBugError - if no suitable constructor is found or invocation fails
      NoSuchMethodException
      See Also:
    • visitFunctionCallInChain

      public static Object visitFunctionCallInChain(int depth, DefaultNaftahParserVisitor defaultNaftahParserVisitor, DefaultContext currentContext, String functionName, boolean forceInvocation, List<Pair<String,Object>> args, Number functionIndex, int line, int column)
      Resolves and executes a function call within a potential chain of calls.

      This method identifies the correct function type from the current context and invokes it, handling the following cases:

      • DeclaredFunction — user-defined functions stored in the current context
      • BuiltinFunction — internal built-in language functions
      • JvmFunction — Java-reflected methods (static or instance) accessible from Naftah
      • Collection — a group of callable functions (overloaded or indexed) where a numeric index may be required to select the target

      The method supports both instance and static JVM functions. For instance methods, the first argument in args is treated as the target instance. For collections of functions, the functionIndex parameter selects which function to invoke. If omitted, the method attempts to resolve the best match automatically.

      During execution, a unique function call ID is generated for the current context to support tracing and debugging.

      Parameters:
      depth - the current recursion or call depth, used to generate a unique call ID
      defaultNaftahParserVisitor - the parser visitor driving the execution
      currentContext - the execution context containing functions, variables, and state
      functionName - the name of the function to invoke
      forceInvocation - true in case of forcing invocation in case the JvmExecutable is not invocable by default
      args - a list of Pair<String, Object> representing the function arguments
      functionIndex - an optional numeric index for selecting a function from a collection of overloaded or indexed functions; may be null
      line - the source line number for error reporting
      column - the source column number for error reporting
      Returns:
      the result of executing the resolved function
      Throws:
      NaftahBugError - if the function cannot be invoked or the instance for an instance method is missing
      IllegalArgumentException - if argument counts or types do not match the target function
      NullPointerException - if required context or arguments are missing
      NaftahBugError - if the function object is not invocable
      NaftahBugError - if a collection of functions cannot be resolved to a single invocable
      NaftahBugError - if no function exists with the given name in the current context

      Example usage:

      visitFunctionCallInChain(0, visitor, context, "print", List.of(Pair.of("arg", "Hello, world!")), null, 12, 8); 
      See Also:
    • getObjectField

      public static Object getObjectField(DefaultContext currentContext, Object target, String fieldName, int line, int column)
      Retrieves the value of a field from the given target object using context-aware resolution with default safety behavior.

      This overload is equivalent to calling:
      getObjectField(currentContext, target, fieldName, true, false, line, column)

      Behavior defaults:

      • safe = true — any exceptions encountered during lookup or reflective access are suppressed and result in a null value.
      • failFast = false — getter resolution errors are ignored and the method continues searching or falls back to direct reflection.
      Parameters:
      currentContext - the evaluation context containing available functions
      target - the object from which the field value should be retrieved
      fieldName - the name of the field to access
      line - source line number (used for error reporting)
      column - source column number (used for error reporting)
      Returns:
      the resolved field value, or null if lookup fails or an error occurs
    • getObjectField

      public static Object getObjectField(DefaultContext currentContext, Object target, String fieldName, boolean safe, boolean failFast, int line, int column)
      Retrieves the value of a field from a target object using context-aware resolution.

      The lookup proceeds in the following order:

      1. Generate possible getter names for the field.
      2. For each getter, check whether the DefaultContext defines a corresponding function.
      3. If the function is a JvmFunction, attempt to access the field using its underlying Java method.
      4. If the function represents multiple overloads, select the best match via findBestExecutable. If resolution fails:
        • in fail-fast mode a NaftahBugError is thrown immediately,
        • otherwise the error is ignored and resolution continues.
      5. If the function is of an unsupported type:
        • in fail-fast mode a NaftahBugError is thrown,
        • otherwise the error is ignored.
      6. If no suitable getter in the context is found or resolution fails, fall back to direct reflective field access.

      Error handling behavior is controlled by two flags:

      • failFast — if true, any getter-resolution error or unsupported function type immediately throws an appropriate NaftahBugError.
      • safe — if true, any thrown error results in null being returned instead of propagating the exception.
      Parameters:
      currentContext - the evaluation context containing available functions
      target - the object from which to retrieve the field value; must not be null
      fieldName - the name of the field to retrieve
      safe - whether to swallow any exceptions and return null
      failFast - whether to throw immediately on resolution errors during getter lookup
      line - source line number (for error reporting)
      column - source column number (for error reporting)
      Returns:
      the resolved field value, or null if not found or if safe mode suppresses an error
      Throws:
      NaftahBugError - if fail-fast mode is enabled and:
      • an unsupported function type is found
      • an ambiguous or invalid overloaded function set is encountered
      Throwable - if an unexpected exception occurs and safe == false
    • setObjectField

      public static void setObjectField(DefaultContext currentContext, Object target, String fieldName, Object value, int line, int column)
      Sets the value of a field on a target object using context-aware resolution with default safety behavior.

      This is equivalent to calling:
      setObjectField(currentContext, target, fieldName, value, true, false, line, column)

      Parameters:
      currentContext - the current evaluation context containing available functions
      target - the object on which to set the field value
      fieldName - the name of the field to set
      value - the value to assign to the field
      line - source line number for error reporting
      column - source column number for error reporting
    • setObjectField

      public static void setObjectField(DefaultContext currentContext, Object target, String fieldName, Object value, boolean safe, boolean failFast, int line, int column)
      Sets the value of a field on a target object using context-aware resolution.

      The method proceeds as follows:

      1. Constructs the qualified setter name for the target field.
      2. If a matching setter exists in the DefaultContext:
        • If it is a JvmFunction, calls it using reflection.
        • If multiple overloads exist, selects the best match based on the value type. If resolution fails:
          • in fail-fast mode, throws a NaftahBugError immediately,
          • otherwise the error is propagated or suppressed depending on safe.
        • If the function type is unsupported:
          • in fail-fast mode, throws a NaftahBugError,
          • otherwise the error is suppressed depending on safe.
      3. If no setter is found in the context, falls back to direct reflective field access.

      Error handling behavior:

      • safe — if true, exceptions during resolution or reflective access are swallowed; otherwise they are thrown.
      • failFast — if true, resolution errors throw immediately without fallback.
      Parameters:
      currentContext - the current evaluation context containing available functions
      target - the object on which to set the field value; must not be null
      fieldName - the name of the field to set
      value - the value to assign to the field
      safe - whether to swallow exceptions instead of throwing
      failFast - whether to throw immediately on resolution errors
      line - source line number for error reporting
      column - source column number for error reporting
      Throws:
      NaftahBugError - if an unsupported function type is encountered
      NaftahBugError - if an ambiguous set of overloaded invocables is found
    • visitCollectionMultipleElements

      public static List<Object> visitCollectionMultipleElements(DefaultNaftahParserVisitor defaultNaftahParserVisitor, NaftahParser.CollectionMultipleElementsContext collectionMultipleElements)
      Visits each expression inside a * NaftahParser.CollectionMultipleElementsContext and collects the evaluated results into a list.

      This method iterates over all expression nodes contained in the provided collectionMultipleElements context, invokes the given defaultNaftahParserVisitor on each one, and stores the returned values in order inside a newly created ArrayList.

      Parameters:
      defaultNaftahParserVisitor - the visitor used to evaluate each expression in the collection
      collectionMultipleElements - the parse-tree context containing multiple expression elements to visit
      Returns:
      a list of objects representing the evaluated results of each expression
    • spawnTask

      public static Task<Object> spawnTask(DefaultContext currentContext, Supplier<Object> supplier, Runnable cleaner)
      Spawns a new asynchronous task within the given execution context.

      This method wraps the provided Supplier in a Task, registers it with the current context, executes it asynchronously, and optionally tracks it in the current scope stack.

      The context's pending task counter is incremented, so that the context will not be deregistered until all spawned tasks complete.

      Parameters:
      currentContext - the context in which the task should execute
      supplier - a Supplier providing the task's computation
      cleaner - a Runnable to clean up thread-local state or other resources after the task completes
      Returns:
      the spawned Task object representing the asynchronous computation
    • matchImplementationName

      public static String matchImplementationName(NaftahParser.SelfOrIdContext selfOrIdContext, DefaultContext currentContext)
      Resolves the name of an implementation from a NaftahParser.SelfOrIdContext.

      This method determines whether the context explicitly specifies an identifier or implicitly refers to the current implementation in the execution context.

      • If selfOrIdContext.ID() is present, the method returns its text as the implementation name.
      • If no explicit ID is provided, the method retrieves the implementation name from the provided DefaultContext.
      • If the implementation name cannot be determined (i.e., it is null in the current context), the method throws a NaftahBugError with an Arabic message indicating that self cannot be used outside an implementation definition.
      Parameters:
      selfOrIdContext - the parse context representing either self or an identifier
      currentContext - the current DefaultContext providing execution state
      Returns:
      the resolved implementation name, either explicitly from the context or from the current execution * context
      Throws:
      NaftahBugError - if self is used outside a valid implementation context
    • validateCode

      public static boolean validateCode(String script)
      Validates a snippet of Naftah code without executing it.

      This method parses the provided script to check for syntax errors or other issues that would prevent the code from running successfully. The validation is done in a “dry-run” mode—no code is executed, only parsed.

      If the system property defined by DEBUG_PROPERTY is enabled, it is temporarily disabled during validation to avoid debug-related side effects, and restored afterward.

      Parameters:
      script - the Naftah code to validate
      Returns:
      true if the script is syntactically valid; false if any parsing errors or exceptions are encountered
    • isDeclaredVariableWithFlag

      public static boolean isDeclaredVariableWithFlag(Object object)
      Checks whether the given object represents a declared variable paired with a boolean flag.

      The method verifies that:

      • The object is an instance of Pair
      • The first type parameter of the pair is DeclaredVariable
      • The second type parameter of the pair is Boolean
      This is typically used to detect structures of the form:
       Pair<DeclaredVariable, Boolean>
       
      where the boolean value represents an associated flag.
      Parameters:
      object - the object to check
      Returns:
      true if the object is a Pair<DeclaredVariable, Boolean>, false otherwise