I would like to play with the idea, so as to see what good can come from it. I would like a simple parser in Tcl. It's goal is to parse a textual tree notation language. Each parent node is not idented, and children nodes are two spaces indented (strictly, because if is is more, then it means the line is indeed a child of a parent node part of the previous line, we can even see code as a grid here, since position is meaningful). I want it in Tcl, because I think we could easily add tcl capabilities to this tree notation language. For Tcl capable parts, let's say they are under a defined tag tnl-tcl (TNL stands for TextualTree Notation Language).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, this is an interesting challenge! Tcl's list processing capabilities make it quite suitable for handling structured data like this. Let's create a parser based on your description.
The core idea is to process the input line by line, keeping track of the current indentation level and using a stack to manage the hierarchy of parent lists where nodes should be appended.
The Parser (tnl_parser.tcl)
tcl
#-----------------------------------------------------------------------
# Tcl Parser for Textual Tree Notation Language (TNL)
#-----------------------------------------------------------------------
# Rules:
# - Parent nodes: No indentation (0 spaces)
# - Children nodes: Exactly 2 spaces indentation relative to parent.
# - Deeper levels: Increments of 2 spaces.
# - Tcl Code Blocks: Marked with 'tnl-tcl' tag, followed by script in {}.
# - Assumes the script block '{...}' is contained on a single line for simplicity.
# - Multiline scripts would require more complex brace-matching logic.
#-----------------------------------------------------------------------
namespace eval tnl {
# Store the parsed tree structure
variable parsedTree {}
# Helper procedure to visually print the parsed tree structure
# (Useful for debugging and understanding the output)
proc printTree {{nodeList $::tnl::parsedTree} {indent ""} {prefix ""}} {
set output ""
if {[llength $nodeList] == 0} {
# This can happen if a node has an empty children list placeholder
# Or if the root is empty.
if {$prefix eq ""} {
append output "$indent$prefix(empty)\n"
}
return $output
}
# Determine the structure: nodeName or nodeName scriptContent
set nodeName [lindex $nodeList 0]
set scriptContent ""
set childrenList {}
set nodeDataLen [llength $nodeList]
if {$nodeDataLen == 3} {
# Node with script: {tnl-tcl script {childList}}
set scriptContent [lindex $nodeList 1]
set childrenList [lindex $nodeList 2]
append output "$indent$prefix($nodeName): \"$scriptContent\"\n"
} elseif {$nodeDataLen == 2} {
# Node with children: {nodeName {childList}}
set childrenList [lindex $nodeList 1]
append output "$indent$prefix$nodeName\n"
} elseif {$nodeDataLen == 1} {
# Leaf node with no explicit children list placeholder (shouldn't happen with current parser)
append output "$indent$prefix$nodeName (leaf?)\n"
} else {
# Should not happen with current parser structure
append output "$indent$prefix(Error: unexpected node format: $nodeList)\n"
}
# Recursively print children if the childrenList is not empty
if {[llength $childrenList] > 0} {
set nextIndent $indent" "
set childPrefix "|-"
for {set i 0} {$i < [llength $childrenList]} {incr i} {
set childNode [lindex $childrenList $i]
set childPrefix "|-"
if {$i == [llength $childrenList] - 1} {
set childPrefix "\`-" ;# Last child
}
# Pass the actual child node list to the recursive call
append output [printTree $childNode $nextIndent $childPrefix]
}
}
return $output
}
# Main parsing procedure
proc parse {text} {
variable parsedTree
set parsedTree {} ; # Reset for potentially multiple calls
# The stack holds references to the *lists* where children should be appended.
# stack[0] always refers to the main 'parsedTree' list.
# stack[1] refers to the children list of the node(s) at level 0.
# stack[2] refers to the children list of the node(s) at level 1. ...and so on.
set stack [list parsedTree]
set lineNum 0
# Split input text into lines
foreach line [split $text \n] {
incr lineNum
set trimmedLine [string trim $line]
# Skip empty lines
if {$trimmedLine eq ""} continue
# 1. Determine Indentation Level
# Find leading spaces using regex. $leadingSpaces will capture the spaces.
if {[regexp {^( *)}( $line leadingSpaces]} == 0} {
# This case should ideally not happen for non-empty lines,
# but handles potential edge cases.
continue
}
set numSpaces [string length $leadingSpaces]
# Validate indentation: Must be an even number (0, 2, 4, ...)
if {$numSpaces % 2 != 0} {
error "TNL Parse Error (Line $lineNum): Invalid indentation - odd number of spaces ($numSpaces).\nLine: '$line|\n'"
}
set level [expr {$numSpaces / 2}]
# 2. Extract Node Content and Check for tnl-tcl
set nodeContent $trimmedLine
set nodeName $nodeContent
set scriptContent ""
set isTclNode 0
# Regex to find 'tnl-tcl { ... }' pattern.
# It captures the tag ('tnl-tcl'), and the content within the braces.
# IMPORTANT: This simple regex assumes the script block '{...}' is on a single line.
# Handling multi-line scripts would require more complex logic (e.g., brace matching).
if {[regexp {^(tnl-tcl)\s*(\{.+\})$} $nodeContent match tag bracedScript]} {
set isTclNode 1
set nodeName $tag
# Extract content from inside the braces and trim whitespace
set scriptContent [string trim [string range $bracedScript 1 end-1]]
# Basic validation for the braced part
if {![string match {\{*\}} $bracedScript]} {
error "TNL Parse Error (Line $lineNum): Malformed tnl-tcl block - braces mismatch?\nLine: '$line|\n'"
}
}
# 3. Create Node Representation
# We'll use a list for each node:
# - Regular node: {nodeName childrenList}
# - tnl-tcl node: {tnl-tcl scriptContent childrenList}
set childrenListForNode {}
if {$isTclNode} {
set currentNodeList [list $nodeName $scriptContent $childrenListForNode]
} else {
set currentNodeList [list $nodeName $childrenListForNode]
}
# 4. Stack Management and Node Placement
set currentStackDepth [llength $stack]
set requiredStackDepth [expr {$level + 1}] ; # +1 because stack[0] is the root container
# Remove parent levels from stack if we are moving up the tree
# (current line's level is less than expected based on stack depth)
while {$currentStackDepth > $requiredStackDepth} {
set stack [lrange $stack 0 end-1] ; # Pop the stack
incr currentStackDepth -1
}
# Check for invalid indentation jumps (e.g., level 0 -> level 2 directly)
if {$currentStackDepth < $requiredStackDepth} {
error "TNL Parse Error (Line $lineNum): Invalid indentation - jumped from level [expr {$currentStackDepth - 2}] to level $level.\nLine: '$line|\n'"
}
# Get the correct parent list from the top of the stack
set parentListContainer [lindex $stack end]
# Append the current node structure to its parent list
lappend $parentListContainer $currentNodeList
# Push the childrenList container for the *current* node onto the stack
# This becomes the parent context for the next level down.
lappend stack $childrenListForNode
}
# Return the final parsed tree (the contents of the root list)
# The structure is directly in parsedTree because we passed 'parsedTree' by reference (implicitly via namespace variable)
# The stack holds references, so modifications affected the original 'parsedTree'.
return $parsedTree
}
# Optional: A procedure to execute tnl-tcl nodes within the parsed tree
proc execute {nodeList} {
if {[llength $nodeList] == 0} return
set nodeName [lindex $nodeList 0]
set nodeDataLen [llength $nodeList]
if {$nodeDataLen == 3} {
# Node with script: {tnl-tcl script {childList}}
set scriptContent [lindex $nodeList 1]
set childrenList [lindex $nodeList 2]
# Execute the Tcl script embedded in the node
if {$nodeName eq "tnl-tcl"} {
puts "Executing TCL script..."
if {[catch {uplevel #0 $scriptContent} result options]} {
puts stderr "Error executing script: $result"
} else {
puts "Script executed successfully. Result: $result"
}
}
# Recursively execute children
foreach child $childrenList {
execute $child
}
} elseif {$nodeDataLen == 2} {
# Node with children: {nodeName {childList}}
set childrenList [lindex $nodeList 1]
# Recursively execute children
foreach child $childrenList {
execute $child
}
}
}
}
# --- Example Usage ---
# Example TNL Input
set tnl_input {
RootNode
Child1
GrandChild1.1
Child2
tnl-tcl { puts "Hello from Child2's Tcl block!" }
tnl-tcl {
# Multiline scripts are tricky with the simple regex.
# This might work if the braces match correctly on one line,
# or if Tcl interprets the content within braces flexibly.
# For robustness, the parser could be enhanced.
puts "This is a Tcl script node."
set x 10
puts "Value of x is $x"
}
AnotherRoot
tnl-tcl { puts "Another root Tcl block." }
}
# Parse the input
try {
set parsed_tree [tnl::parse $tnl_input]
# Set the global variable for printing (or pass it directly)
set ::tnl::parsedTree $parsed_tree
# Print the parsed structure
puts "--- Parsed Tree Structure ---"
puts [tnl::printTree]
# Example of executing the Tcl nodes
puts "\n--- Executing Tcl Blocks ---"
tnl::execute $parsed_tree
} trap {TNL Parse Error *} {errMsg} {
puts stderr "Error parsing TNL:\n$errMsg"
} trap {திய*} {errMsg} {
puts stderr "Execution Error:\n$errMsg"
}
puts "\n--- Testing Edge Cases ---"
# Test empty input
puts "Parsing empty input:"
set empty_tree [tnl::parse ""]
puts "Result: '$empty_tree'"
# Test invalid indentation
puts "\nTesting invalid indentation:"
set bad_indent_input {
NodeA
ChildA
NodeB ;# Incorrect indent
}
catch {tnl::parse $bad_indent_input} errMsg
if {$errMsg ne ""} {
puts "Caught expected error: $errMsg"
} else {
puts "Error: Expected an indentation error but got none."
}
# Test malformed tnl-tcl
puts "\nTesting malformed tnl-tcl:"
set bad_tnl_input {
NodeA
tnl-tcl { puts "hello" ;# Missing closing brace
}
catch {tnl::parse $bad_tnl_input} errMsg
if {$errMsg ne ""} {
puts "Caught expected error: $errMsg"
} else {
puts "Error: Expected a tnl-tcl format error but got none."
}
Explanation:
Namespace tnl: Encapsulates the parser logic and the parsedTree variable.
parseProcedure:
Initializes parsedTree and the stack. The stack is crucial. It holds references to the lists where children nodes should be appended at each level. stack starts with a reference to the top-level parsedTree list.
It iterates through each line of the input text.
Indentation: It calculates the level based on the number of leading spaces (must be even).
Node Content: It extracts the content and checks if it matches the tnl-tcl { ... } pattern using regexp. If it's a tnl-tcl node, it captures the tag name (tnl-tcl) and the script content inside the braces. A simple regex is used, assuming the braces {...} are on the same line.
Node Representation: Each node is stored as a Tcl list. A regular node looks like {NodeName childrenListPlaceholder}. A tnl-tcl node looks like {tnl-tcl scriptContent childrenListPlaceholder}. The childrenListPlaceholder is initially an empty list {} which will be populated by subsequent children.
Stack Management: This is the core logic.
Before adding the current node, it adjusts the stack depth to match the current node's level. If the current line is less indented than the previous one, it pops elements off the stack until the stack depth corresponds to the parent level.
It performs error checking for invalid indentation jumps.
It retrieves the correct parent list from the top of the stack ([lindex $stack end]).
It appends the currentNodeList to this parentListContainer.
Crucially, it pushes the childrenListForNode (the placeholder created as part of currentNodeList) onto the stack. This prepares the stack for processing children of the current node at the next indentation level.
printTree Procedure: A recursive helper function to visualize the nested list structure created by the parser. This is very helpful for debugging.
execute Procedure: A simple recursive procedure demonstrating how you might traverse the parsed tree and execute the Tcl code found in nodes using .
This parser provides a basic but functional way to handle your specified tree notation and integrate Tcl code execution.
tnl-tcl
uplevel #0
Error Handling: Uses try...catch (or catch directly) to handle parsing errors gracefully, reporting the line number and the nature of the error.