Class NaftahParserHelper
All methods are static, and instantiation is prevented.
- Author:
- Chakib Daii
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringFormat string for debug or log messages that include an index, text, and payload.A list of literal keywords or token strings defined by the lexer.static final com.ibm.icu.text.Normalizer2Unicode normalizer instance for normalization form NFKC.static final StringString representation for a null value in Naftah.static final PatternRegex pattern for detecting placeholders in the form PLACEHOLDER(key).static final StringRegex pattern for matching qualified calls.static final StringRegex pattern for matching qualified names.private static final Map<org.antlr.v4.runtime.tree.ParseTree,List<org.antlr.v4.runtime.tree.ParseTree>> Cache to store computed subtrees per parse tree node for optimization.static PropertiesLoaded properties representing token symbols, if available. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivatePrivate constructor to prevent instantiation. -
Method Summary
Modifier and TypeMethodDescriptionstatic ObjectaccessObjectUsingQualifiedName(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.static booleancheckInsideLoop(org.antlr.v4.runtime.tree.ParseTree ctx) Checks if the given parse tree node is inside a loop construct.static LoopSignalcheckLoopSignal(Object result) Checks if the given result object is a loop signal and returns the corresponding signal.private static voidRecursively collects all nodes in the subtree rooted at the given node.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.static voiddebugCurrentContextVisit(String methodName, org.antlr.v4.runtime.ParserRuleContext ctx) Logs detailed debug information about the currentParserRuleContextif the logger is configured to log atLevel.FINE.static StringdeclaredValueToString(boolean constant, String name, JavaType type, Object value) Converts a declared variable or constant value to a string representation.static ObjectdoInvokeDeclaredFunction(DeclaredFunction<?> declaredFunction, DefaultNaftahParserVisitor defaultNaftahParserVisitor, List<Pair<String, Object>> args, DefaultContext currentContext) Executes a declared function within the specified context.static ObjectdoRun(NaftahParser parser, List<String> args) Executes the parser by visiting the parse tree and returning the result.static <T> StringFunctionToString(T currentFunction) Converts a function-like object into a detailed string representation for debugging or logging purposes.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.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.static DefaultContextgetBlockContext(NaftahParser.BlockContext ctx, DefaultContext currentContext) Supplies or updates theDefaultContextfor aBlocknode.static org.antlr.v4.runtime.CharStreamgetCharStream(boolean isScriptFile, String script) Creates aCharStreamfrom either script content or a script file.static org.antlr.v4.runtime.CharStreamgetCharStream(String script) Creates aCharStreamdirectly from script content.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 ANTLRLexerand its correspondingCommonTokenStream.static org.antlr.v4.runtime.CommonTokenStreamgetCommonTokenStream(org.antlr.v4.runtime.CharStream charStream) Gets a CommonTokenStream from the given character stream with no error listeners.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 aNaftahLexerand its associatedCommonTokenStreamfrom the givenCharStream.static org.antlr.v4.runtime.CommonTokenStreamgetCommonTokenStream(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.static StringgetDisplayName(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.static <T extends org.antlr.v4.runtime.tree.ParseTree>
TgetFirstChildOfType(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.static StringgetFormattedTokenSymbols(String tokenName, boolean ln) Returns a formatted string representing the symbols associated with a token name.static StringgetFormattedTokenSymbols(org.antlr.v4.runtime.Vocabulary vocabulary, int tokenType, boolean ln) Returns a formatted string of token symbols based on the token type.static <T extends JvmExecutable>
TgetFunction(Collection<T> functions, Number functionIndex) Retrieves a function (or executable) from a collection by its index.static ObjectgetObjectField(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.static ObjectgetObjectField(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.static <T extends org.antlr.v4.runtime.Parser>
TCreates and configures a generic ANTLRParserinstance.static NaftahParsergetParser(org.antlr.v4.runtime.CommonTokenStream commonTokenStream, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners) Creates and configures aNaftahParserusing the providedCommonTokenStream.static NaftahParsergetParser(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.static StringConstructs a qualified name string from the given parse context.static StringConstructs a qualified name string from the given parse context.static DefaultContextSupplies the rootDefaultContextfor visiting aProgramparse tree node.static ObjecthandleDeclaration(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.static <T extends org.antlr.v4.runtime.tree.Tree>
booleanhasAnyExecutedChildOrSubChildOfType(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.static <T extends org.antlr.v4.runtime.tree.Tree>
booleanhasAnyParentOfType(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.static booleanhasAnyParentOfType(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.static <T extends org.antlr.v4.runtime.tree.Tree>
booleanhasChild(T child) Checks if the given child node is non-null.static <T,T1 extends org.antlr.v4.runtime.tree.Tree>
booleanhasChildOfType(List<T> children, Class<T1> type) Checks if any child in the list is of the specified type.static <T,T1 extends org.antlr.v4.runtime.tree.Tree>
booleanhasChildOfType(T child, Class<T1> type) Checks if the given child node is of the specified type.static <T extends org.antlr.v4.runtime.tree.Tree>
booleanhasChildOrSubChildOfType(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.static <T extends org.antlr.v4.runtime.tree.Tree>
booleanhasParentOfType(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.static ObjectinvokeBuiltinFunction(String functionName, BuiltinFunction builtinFunction, Object[] executableArgs, List<Pair<String, Object>> naftahArgs, int line, int column) static ObjectinvokeBuiltinFunction(String functionName, BuiltinFunction builtinFunction, List<Pair<String, Object>> naftahArgs, int line, int column) Invokes a built-in function via reflection with automatic argument conversion.static ObjectinvokeDeclaredFunction(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.static ObjectinvokeFunction(String functionName, boolean forceInvocation, Collection<JvmExecutable> jvmFunctions, List<Pair<String, Object>> naftahArgs, int line, int column) Dynamically finds and invokes a function by name from a collection ofJvmExecutableobjects.static ObjectinvokeFunction(String functionName, boolean forceInvocation, JvmExecutable selectedFunction, Object[] executableArgs, List<Pair<String, Object>> naftahArgs, Object possibleInstance, int line, int column) static ObjectinvokeFunction(String functionName, boolean forceInvocation, JvmExecutable selectedFunction, List<Pair<String, Object>> naftahArgs, Object possibleInstance, int line, int column) static ObjectinvokeJvmClassInitializer(String classInitializerName, List<JvmClassInitializer> jvmClassInitializers, List<Pair<String, Object>> naftahArgs, int line, int column) Selects the best matching JVM class initializer from a collection and invokes it with automatic argument conversion.static ObjectinvokeJvmClassInitializer(String classInitializerName, JvmClassInitializer jvmClassInitializer, Object[] executableArgs, List<Pair<String, Object>> naftahArgs, int line, int column) static ObjectinvokeJvmClassInitializer(String classInitializerName, JvmClassInitializer jvmClassInitializer, List<Pair<String, Object>> naftahArgs, int line, int column) Invokes a specific JVM class initializer (constructor) with automatic argument conversion.static ObjectinvokeJvmFunction(String functionName, boolean forceInvocation, JvmFunction jvmFunction, Object[] executableArgs, List<Pair<String, Object>> naftahArgs, Object possibleInstance, int line, int column) static ObjectinvokeJvmFunction(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.static booleanisDeclaredVariableWithFlag(Object object) Checks whether the given object represents a declared variable paired with a boolean flag.static StringmatchImplementationName(NaftahParser.SelfOrIdContext selfOrIdContext, DefaultContext currentContext) Resolves the name of an implementation from aNaftahParser.SelfOrIdContext.static voidprepareDeclaredFunction(NaftahParserBaseVisitor<?> naftahParserBaseVisitor, DeclaredFunction<?> function) Prepares a declared function by visiting and setting its parameters and return type if not already set.prepareDeclaredFunctionArguments(List<DeclaredParameter> parameters, List<Pair<String, Object>> arguments) Prepares a map of argument names to their values for a declared function.static NaftahParserprepareRun(org.antlr.v4.runtime.CharStream input) Prepares a parser instance from the given input character stream with no error listeners.static NaftahParserprepareRun(org.antlr.v4.runtime.CharStream input, List<org.antlr.v4.runtime.ANTLRErrorListener> errorListeners) Initializes and prepares aNaftahParserinstance from the givenCharStream.static NaftahParserprepareRun(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.static voidprintTokens(org.antlr.v4.runtime.CommonTokenStream tokens, org.antlr.v4.runtime.Vocabulary vocabulary) Prints all tokens produced by the lexer for debugging purposes.static voidresolvePlaceholders(Properties props) Resolves placeholders in the properties values by replacing them with their corresponding property values.private static StringresolveValue(String value, Properties props) Resolves placeholders within a string value using the given properties.static FilesearchForNaftahScriptFile(String input) Searches for a Naftah script file based on a given name, trying multiple extensions.static voidsetForeachVariables(DefaultContext currentContext, Class<? extends NaftahParser.ForeachTargetContext> foreachTargetClass, NTuple variableNames, NTuple targetValues) Sets loop variables in theDefaultContextfor a Naftah `foreach` iteration.static voidsetObjectField(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.static voidsetObjectField(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.static ObjectsetObjectUsingQualifiedName(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.static booleanshouldBreakStatementsLoop(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.spawnTask(DefaultContext currentContext, Supplier<Object> supplier, Runnable cleaner) Spawns a new asynchronous task within the given execution context.static booleanvalidateCode(String script) Validates a snippet of Naftah code without executing it.static voidvalidateVariableExistence(DefaultContext currentContext, String name) Validates whether a variable with the given name already exists in the current context.static Objectvisit(NaftahParserBaseVisitor<?> naftahParserBaseVisitor, org.antlr.v4.runtime.tree.ParseTree tree) Visits the given parse tree using the provided Naftah parser visitor.visitCollectionMultipleElements(DefaultNaftahParserVisitor defaultNaftahParserVisitor, NaftahParser.CollectionMultipleElementsContext collectionMultipleElements) Visits each expression inside a *NaftahParser.CollectionMultipleElementsContextand collects the evaluated results into a list.static <T extends org.antlr.v4.runtime.ParserRuleContext>
ObjectvisitContext(DefaultNaftahParserVisitor defaultNaftahParserVisitor, String methodName, DefaultContext currentContext, T ctx, TriFunction<DefaultNaftahParserVisitor, DefaultContext, T, Object> visitFunction) Simplified overload ofvisitContext(DefaultNaftahParserVisitor, String, DefaultContext, ParserRuleContext, TriFunction, Class)that defaults to returning anObject.static <T extends org.antlr.v4.runtime.ParserRuleContext,R>
RvisitContext(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 customTriFunction, while automatically handling logging, debugging, and execution tracking.static ObjectvisitFunctionCallInChain(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.
-
Field Details
-
FORMATTER
Format string for debug or log messages that include an index, text, and payload.- See Also:
-
PLACEHOLDER_PATTERN
Regex pattern for detecting placeholders in the form PLACEHOLDER(key). -
NULL
String representation for a null value in Naftah.- See Also:
-
QUALIFIED_NAME_REGEX
Regex pattern for matching qualified names.- See Also:
-
QUALIFIED_CALL_REGEX
Regex pattern for matching qualified calls.- See Also:
-
NORMALIZER
public static final com.ibm.icu.text.Normalizer2 NORMALIZERUnicode 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_CACHECache to store computed subtrees per parse tree node for optimization. -
TOKENS_SYMBOLS
Loaded properties representing token symbols, if available. -
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 aNaftahBugErrorwhen 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 checktype- 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 checktypes- 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 checktype- 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 typeT1- the type to check against- Parameters:
child- the child node to checktype- 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 listT1- the type to check against- Parameters:
children- the list of child nodestype- 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 checktype- 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 nodetype- the child class type to look forexecutedParseTreeProperty- 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 nodetype- 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
nodeitself 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 benulltype- the class object representing the desired parse tree type- Returns:
- the first node (including
nodeitself) that is an instance oftype, ornullif no matching node is found
- First, the current
-
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 nodeout- 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 instancetree- 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 contextsfunction- 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
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
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
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 aNaftahParserinstance from the givenCharStream.This method performs the following steps:
- Creates a lexer and token stream from the input
- Registers all provided
ANTLRErrorListenerinstances - Optionally prints the generated tokens when debugging is enabled
- Creates and returns a configured parser instance
- Parameters:
input- the input character stream to be parsederrorListeners- a list ofANTLRErrorListenerinstances to be attached to both the lexer and the parser- Returns:
- a fully configured
NaftahParserready 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 lexervocabulary- the lexer vocabulary used to resolve symbolic token names
-
doRun
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 aNaftahParserusing the providedCommonTokenStream.All default error listeners are removed and replaced with the supplied
ANTLRErrorListenerinstances. The parser is also configured to use aBailErrorStrategyfor fast-fail parsing.- Parameters:
commonTokenStream- the token stream produced by the lexererrorListeners- 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 ANTLRParserinstance.This method:
- Instantiates the parser using the supplied
Supplier - Removes all default error listeners
- Registers the provided
ANTLRErrorListenerinstances - 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 instanceerrorListeners- the error listeners to be added to the parser- Returns:
- a configured parser instance
- Instantiates the parser using the supplied
-
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 aNaftahLexerand its associatedCommonTokenStreamfrom the givenCharStream.All default lexer error listeners are removed and replaced with the provided
ANTLRErrorListenerinstances.- Parameters:
charStream- the input character stream to be tokenizederrorListeners- the error listeners to be attached to the lexer- Returns:
- a
Paircontaining the configured lexer and itsCommonTokenStream
-
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 ANTLRLexerand its correspondingCommonTokenStream.This method:
- Instantiates the lexer using the supplied
Supplier - Removes all default lexer error listeners
- Registers the provided
ANTLRErrorListenerinstances - Creates a
CommonTokenStreambacked by the lexer
- Type Parameters:
T- the concrete type of the lexer- Parameters:
lexerSupplier- supplier used to create the lexer instanceerrorListeners- the error listeners to be added to the lexer- Returns:
- a
Paircontaining the configured lexer and itsCommonTokenStream
- Instantiates the lexer using the supplied
-
getCharStream
public static org.antlr.v4.runtime.CharStream getCharStream(boolean isScriptFile, String script) throws Exception Creates aCharStreamfrom either script content or a script file.When
isScriptFileistrue, thescriptparameter is treated as a file path. The file is located using the internal script resolution logic and then read using UTF-8 encoding.When
isScriptFileisfalse, thescriptparameter is treated as raw script content and converted directly into aCharStream.- Parameters:
isScriptFile-trueifscriptrepresents a script file path,falseif it represents script contentscript- the script content or script file path- Returns:
- a
CharStreamrepresenting the script input - Throws:
Exception- if an error occurs while locating or reading the script file
-
getCharStream
Creates aCharStreamdirectly 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
CharStreamrepresenting the normalized script
-
searchForNaftahScriptFile
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
Resolves placeholders in the properties values by replacing them with their corresponding property values.- Parameters:
props- The Properties object with placeholders to resolve.
-
resolveValue
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, defaultJavaType::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
Returns a formatted string representing the symbols associated with a token name.This method looks up
tokenNamein theTOKENS_SYMBOLSmap (expected to be aPropertiesinstance). If a corresponding entry is found, its value is used as the symbol representation; otherwise,tokenNameitself is used as a fallback.Comma-separated symbols in the resolved value are joined using
" أو"(Arabic for “or”).If
lnistrue, the result is formatted as a bullet point prefixed with a line break.- Parameters:
tokenName- the name of the token to look upln- 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 analyzevocabulary- 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 declaredctx- The declaration context.variableName- The variable name.isConstant- True if the variable is constant.type- the variable type, defaultJavaType::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
DeclaredVariableis 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
DeclaredVariableor a pair containing it and a boolean flag if the context is parsing an assignment.- Parameters:
currentContext- the execution context where the variable is declaredctx- the parser context corresponding to the variable declarationvariableName- the name of the variable to declare or retrievehasConstant- true if the declaration includes a constant modifierhasVariable- true if the declaration includes a variable modifierhasType- true if the declaration specifies a typetype- theJavaTyperepresenting the type of the variable, if any- Returns:
- a
DeclaredVariableobject, or aPairof the variable and a boolean if parsing an * assignment - Throws:
NaftahBugError- if an invalid type is specified for an object creation context
- If the declaration includes a constant, variable, type, or is part of
an object field, a new
-
validateVariableExistence
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
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 currentParserRuleContextif the logger is configured to log atLevel.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 currentParserRuleContextto extract debugging information from.
- The name of the method invoking the debug (as provided in
-
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 customTriFunction, 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
TriFunctionusing the visitor, context, and parser rule. - Marks the context as executed in the
DefaultContextinstance. - 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 theParserRuleContextbeing visitedR- the result type returned by the visitor function- Parameters:
defaultNaftahParserVisitor- the activeDefaultNaftahParserVisitorhandling the traversalmethodName- the name of the visitor method being invoked (for logging and debugging)currentContext- theDefaultContextassociated with the current traversal scopectx- the currentParserRuleContextnode being visitedvisitFunction- aTriFunctionthat takes the visitor, context, and rule, and returns a resultreturnType- the expected type of the returned value- Returns:
- the result of applying the
visitFunction, cast to the specified return type - See Also:
-
DefaultNaftahParserVisitorDefaultContextParserRuleContextTriFunction
- Logs debugging information for the current rule context (via
-
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 ofvisitContext(DefaultNaftahParserVisitor, String, DefaultContext, ParserRuleContext, TriFunction, Class)that defaults to returning anObject.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 theParserRuleContextbeing visited- Parameters:
defaultNaftahParserVisitor- the activeDefaultNaftahParserVisitorhandling the traversalmethodName- the name of the visitor method being invoked (for logging and debugging)currentContext- theDefaultContextassociated with the current traversal scopectx- the currentParserRuleContextnode being visitedvisitFunction- aTriFunctionthat takes the visitor, context, and rule, and returns a result- Returns:
- the result of applying the
visitFunction, as a genericObject - See Also:
-
getRootContext
Supplies the rootDefaultContextfor visiting aProgramparse tree node.Chooses between REPL and standard execution modes based on a system property and the presence of any
FunctionCallStatementwithin the parse tree.- Parameters:
ctx- the rootProgramContextfrom the parse tree- Returns:
- the initialized root context (REPL or standard)
-
getBlockContext
public static DefaultContext getBlockContext(NaftahParser.BlockContext ctx, DefaultContext currentContext) Supplies or updates theDefaultContextfor aBlocknode.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 treecurrentContext- 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 theDefaultContextfor a Naftah `foreach` iteration.This method inspects the type of the
foreachTargetClassto determine how to assign values from thetargetValuestuple to the corresponding loop variables in thecurrentContext.Supported target contexts and their behavior:
NaftahParser.ValueForeachTargetContext: Only a value variable is set.NaftahParser.KeyValueForeachTargetContext: Both key and value variables are set.NaftahParser.IndexAndValueForeachTargetContext: Index and value variables are set.NaftahParser.IndexAndKeyValueForeachTargetContext: Index, key, and value variables are all set.
The mapping from
variableNamestotargetValuesis 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 setforeachTargetClass- the class type of the parsed `foreach` target, determines how variables are mappedvariableNames- aNTupleof loop variable names extracted from the `foreach` declarationtargetValues- aNTupleof 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:
would attempt to retrieve the value ofuser:profile:namenamefromprofile, which is insideuser.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 returnsNone.get()instead of throwing an exception.Examples:
user:profile:name– standard accessuser:profile؟:name– optional chaining onprofileuser؟:profile؟:name– optional chaining on bothuserandprofile
- Parameters:
qualifiedName- the colon-separated variable access path, with optional"؟"suffixescurrentContext- the current execution context used to resolve variablesline- source line number (used for error reporting)column- source column number (used for error reporting)- Returns:
- the resolved
DeclaredVariableif found, orNone.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 aMap<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
NaftahBugErrorusingnewNaftahBugVariableNotFoundError().
- Parameters:
qualifiedName- the colon-separated qualified name (e.g.,user:address؟:city)currentContext- the current evaluation context that holds top-level variablesnewValue- the new value to assign to the final declared variableline- 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
Converts a function-like object into a detailed string representation for debugging or logging purposes.This utility handles multiple kinds of function representations:
BuiltinFunction— returns the detailed string viaBuiltinFunction.toDetailedString().JvmFunction— returns the detailed string viaJvmFunction.toDetailedString().JvmClassInitializer— returns the detailed string viaJvmClassInitializer.toDetailedString().- Other objects — defaults to
Object.toString()if the type is unrecognized.
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
JvmExecutableobjects and efficiently handles bothListand genericCollectionimplementations:- If the collection is a
List, the function is accessed directly by index. - If the collection is a generic
Collection, the method iterates to the specified index usingCollectionUtils.getElementAt(Collection, int).
The function index is provided as a
Numberand converted to an integer internally.- Type Parameters:
T- the type of function, extendingJvmExecutable- Parameters:
functions- the collection of function objectsfunctionIndex- the index of the function to retrieve (as aNumber)- Returns:
- the function object at the specified index
- Throws:
IndexOutOfBoundsException- if the index is out of range
- If the collection is a
-
invokeFunction
public static Object invokeFunction(String functionName, boolean forceInvocation, Collection<JvmExecutable> jvmFunctions, List<Pair<String, Object>> naftahArgs, int line, int column) throws NoSuchMethodExceptionDynamically finds and invokes a function by name from a collection ofJvmExecutableobjects.This method performs the following steps:
- 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. - If the selected function is a non-static
JvmFunction, the first argument is treated as the instance. - 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 theJvmExecutableis not invocable by defaultjvmFunctions- the collection of availableJvmExecutablefunctionsnaftahArgs- the list of arguments asPair, where the first element may be the instance for non-static methodsline- the source line number for error reportingcolumn- the source column number for error reporting- Returns:
- the result of the function invocation
- Throws:
NaftahBugError- if no suitable function is found or invocation failsNoSuchMethodException
- Finds the best matching executable using
-
invokeFunction
public static Object invokeFunction(String functionName, boolean forceInvocation, JvmExecutable selectedFunction, List<Pair<String, Object>> naftahArgs, Object possibleInstance, int line, int column) Invokes a specificJvmExecutable, either aBuiltinFunctionorJvmFunction.This overload delegates to the more general method with
executableArgsset tonull.- Parameters:
functionName- the name of the function for error reportingforceInvocation- true in case of forcing invocation in case theJvmExecutableis not invocable by defaultselectedFunction- the executable to invokenaftahArgs- the arguments prepared for the executablepossibleInstance- the instance to invoke on, ornullfor static methodsline- the source line number for error reportingcolumn- 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) Invokes a specificJvmExecutable, either aBuiltinFunctionorJvmFunction.This is the core method handling actual execution:
BuiltinFunctioninvocation viainvokeBuiltinFunction(java.lang.String, org.daiitech.naftah.builtin.lang.BuiltinFunction, java.util.List<org.daiitech.naftah.builtin.utils.tuple.Pair<java.lang.String, java.lang.Object>>, int, int)JvmFunctioninvocation viainvokeJvmFunction(java.lang.String, boolean, org.daiitech.naftah.builtin.lang.JvmFunction, java.util.List<org.daiitech.naftah.builtin.utils.tuple.Pair<java.lang.String, java.lang.Object>>, java.lang.Object, int, int)- Throws
NaftahBugErrorif the function type is unsupported
- Parameters:
functionName- the name of the function for error reportingforceInvocation- true in case of forcing invocation in case theJvmExecutableis not invocable by defaultselectedFunction- the executable to invokeexecutableArgs- the prepared arguments array for the executable (may benull)naftahArgs- the original list ofPairargumentspossibleInstance- the instance to invoke on, ornullfor static methodsline- the source line number for error reportingcolumn- 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 spawnedTaskand 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 viaDefaultContext.popCall(), ensuring proper debugging and stack-trace fidelity. For asynchronous functions, thread-local cleanup is performed after execution viacurrentContext.cleanThreadLocals().- Parameters:
depth- the current recursion or call depth, used to generate a unique call IDfunctionName- the name of the function to invokedeclaredFunction- the function to invoke; must not be nulldefaultNaftahParserVisitor- the visitor used to evaluate the function bodyargs- the list of (name, value) argument pairs to supply to the functioncurrentContext- the active execution context- Returns:
- for synchronous functions, the evaluated return value; for asynchronous
functions, a
Taskrepresenting 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 isVoid, 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- theDeclaredFunctionbeing executeddefaultNaftahParserVisitor- the visitor used to evaluate the function bodyargs- the raw argument name/value pairs supplied to the functioncurrentContext- theDefaultContextassociated with the call- Returns:
- the evaluated result of the function body, or
None.get()if the function has aVoidreturn 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:
- If
executableArgsis provided, it is passed directly to the underlyingMethod. - If
naftahArgsis provided as aListofPairobjects (name/value pairs), each argument is automatically converted to match the parameter type usingInvocationUtils.invokeJvmExecutable(java.lang.Object, T, java.util.List<org.daiitech.naftah.builtin.utils.tuple.Pair<java.lang.String, java.lang.Object>>, java.lang.Class<?>, boolean).
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 reportingbuiltinFunction- theBuiltinFunctionto invokenaftahArgs- a list of arguments asPairname/value pairsline- the source line number for error reportingcolumn- the source column number for error reporting- Returns:
- the result of the function, or
None.get()if the function returnsvoidornull - Throws:
NaftahBugError- if argument types/count do not match, invocation fails, or instantiation fails
- If
-
invokeBuiltinFunction
public static Object invokeBuiltinFunction(String functionName, BuiltinFunction builtinFunction, Object[] executableArgs, List<Pair<String, Object>> naftahArgs, int line, int column) - Parameters:
functionName- the name of the function for error reportingbuiltinFunction- theBuiltinFunctionto invokeexecutableArgs- the pre-prepared argument array (nullable)naftahArgs- a list of arguments asPairname/value pairsline- the source line numbercolumn- the source column number- Returns:
- the result of the function, or
None.get()ifvoidornull - 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 returnsvoidornull, aNaftahObjectrepresentingnullis returned.- Parameters:
functionName- the name of the function for error reportingforceInvocation- true in case of forcing invocation in case theJvmExecutableis not invocable by defaultjvmFunction- theJvmFunctionto invokenaftahArgs- a list of arguments asPairname/value pairspossibleInstance- the instance for instance methods;nullfor static methodsline- the source line numbercolumn- the source column number- Returns:
- a
NaftahObjectwrapping 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) - Parameters:
functionName- the name of the function for error reportingforceInvocation- true in case of forcing invocation in case theJvmExecutableis not invocable by defaultjvmFunction- theJvmFunctionto invokeexecutableArgs- the pre-prepared argument array (nullable)naftahArgs- a list of arguments asPairname/value pairspossibleInstance- the instance for instance methods;nullfor static methodsline- the source line numbercolumn- the source column number- Returns:
- a
NaftahObjectwrapping 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 aNaftahObject.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- theJvmClassInitializerrepresenting the constructornaftahArgs- a list of arguments asPairname/value pairsline- the source line numbercolumn- the source column number- Returns:
- a
NaftahObjectcontaining 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 aListofPairarguments.- Parameters:
classInitializerName- the name of the class initializer (for error reporting)jvmClassInitializer- theJvmClassInitializerrepresenting the constructorexecutableArgs- the pre-prepared argument array (nullable)naftahArgs- a list of arguments asPairname/value pairsline- the source line numbercolumn- the source column number- Returns:
- a
NaftahObjectcontaining 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 NoSuchMethodExceptionSelects the best matching JVM class initializer from a collection and invokes it with automatic argument conversion.Evaluates all provided
JvmClassInitializerinstances, selects the one whose parameters best match the provided arguments, and then invokes it usinginvokeJvmClassInitializer(String, JvmClassInitializer, Object[], List, int, int).- Parameters:
classInitializerName- the name of the class initializer (for error reporting)jvmClassInitializers- the collection of candidateJvmClassInitializerinstancesnaftahArgs- a list of arguments asPairname/value pairsline- the source line numbercolumn- the source column number- Returns:
- a
NaftahObjectcontaining the newly created instance - Throws:
NaftahBugError- if no suitable constructor is found or invocation failsNoSuchMethodException- 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 contextBuiltinFunction— internal built-in language functionsJvmFunction— Java-reflected methods (static or instance) accessible from NaftahCollection— 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
argsis treated as the target instance. For collections of functions, thefunctionIndexparameter 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 IDdefaultNaftahParserVisitor- the parser visitor driving the executioncurrentContext- the execution context containing functions, variables, and statefunctionName- the name of the function to invokeforceInvocation- true in case of forcing invocation in case theJvmExecutableis not invocable by defaultargs- a list ofPair<String, Object>representing the function argumentsfunctionIndex- an optional numeric index for selecting a function from a collection of overloaded or indexed functions; may benullline- the source line number for error reportingcolumn- 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 missingIllegalArgumentException- if argument counts or types do not match the target functionNullPointerException- if required context or arguments are missingNaftahBugError- if the function object is not invocableNaftahBugError- if a collection of functions cannot be resolved to a single invocableNaftahBugError- if no function exists with the given name in the current contextExample 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
nullvalue. - 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 functionstarget- the object from which the field value should be retrievedfieldName- the name of the field to accessline- source line number (used for error reporting)column- source column number (used for error reporting)- Returns:
- the resolved field value, or
nullif lookup fails or an error occurs
- safe = true — any exceptions encountered during lookup or
reflective access are suppressed and result in a
-
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:
- Generate possible getter names for the field.
- For each getter, check whether the
DefaultContextdefines a corresponding function. - If the function is a
JvmFunction, attempt to access the field using its underlying Java method. - If the function represents multiple overloads, select the best match
via
findBestExecutable. If resolution fails:- in fail-fast mode a
NaftahBugErroris thrown immediately, - otherwise the error is ignored and resolution continues.
- in fail-fast mode a
- If the function is of an unsupported type:
- in fail-fast mode a
NaftahBugErroris thrown, - otherwise the error is ignored.
- in fail-fast mode a
- 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 appropriateNaftahBugError. - safe — if
true, any thrown error results innullbeing returned instead of propagating the exception.
- Parameters:
currentContext- the evaluation context containing available functionstarget- the object from which to retrieve the field value; must not benullfieldName- the name of the field to retrievesafe- whether to swallow any exceptions and returnnullfailFast- whether to throw immediately on resolution errors during getter lookupline- source line number (for error reporting)column- source column number (for error reporting)- Returns:
- the resolved field value, or
nullif not found or ifsafemode 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 andsafe == 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 functionstarget- the object on which to set the field valuefieldName- the name of the field to setvalue- the value to assign to the fieldline- source line number for error reportingcolumn- 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:
- Constructs the qualified setter name for the target field.
- 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
NaftahBugErrorimmediately, - otherwise the error is propagated or suppressed depending on
safe.
- in fail-fast mode, throws a
- If the function type is unsupported:
- in fail-fast mode, throws a
NaftahBugError, - otherwise the error is suppressed depending on
safe.
- in fail-fast mode, throws a
- If it is a
- 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 functionstarget- the object on which to set the field value; must not benullfieldName- the name of the field to setvalue- the value to assign to the fieldsafe- whether to swallow exceptions instead of throwingfailFast- whether to throw immediately on resolution errorsline- source line number for error reportingcolumn- source column number for error reporting- Throws:
NaftahBugError- if an unsupported function type is encounteredNaftahBugError- 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.CollectionMultipleElementsContextand collects the evaluated results into a list.This method iterates over all expression nodes contained in the provided
collectionMultipleElementscontext, invokes the givendefaultNaftahParserVisitoron each one, and stores the returned values in order inside a newly createdArrayList.- Parameters:
defaultNaftahParserVisitor- the visitor used to evaluate each expression in the collectioncollectionMultipleElements- 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
Supplierin aTask, 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.
-
matchImplementationName
public static String matchImplementationName(NaftahParser.SelfOrIdContext selfOrIdContext, DefaultContext currentContext) Resolves the name of an implementation from aNaftahParser.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
NaftahBugErrorwith an Arabic message indicating thatselfcannot be used outside an implementation definition.
- Parameters:
selfOrIdContext- the parse context representing eitherselfor an identifiercurrentContext- the currentDefaultContextproviding execution state- Returns:
- the resolved implementation name, either explicitly from the context or from the current execution * context
- Throws:
NaftahBugError- ifselfis used outside a valid implementation context
- If
-
validateCode
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_PROPERTYis enabled, it is temporarily disabled during validation to avoid debug-related side effects, and restored afterward.- Parameters:
script- the Naftah code to validate- Returns:
trueif the script is syntactically valid;falseif any parsing errors or exceptions are encountered
-
isDeclaredVariableWithFlag
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
Pair<DeclaredVariable, Boolean>
where the boolean value represents an associated flag.- Parameters:
object- the object to check- Returns:
trueif the object is aPair<DeclaredVariable, Boolean>,falseotherwise
- The object is an instance of
-