Ember
Loading...
Searching...
No Matches
LibXMLBehaviorTreeParser.cpp
Go to the documentation of this file.
2#include "Core/BehaviorTree.h"
5#include "Core/Node.h"
6#include "Utils/Logger.h"
7#include <algorithm>
8#include <fstream>
9#include <mutex>
10
11namespace EmberCore {
12
13// Static initialization
17
19 : config_(ParserConfig::CreateDefault()), progress_callback_(nullptr), project_parsing_mode_(false),
20 max_threads_(std::thread::hardware_concurrency()), thread_safe_(true), libxml2_initialized_(false) {
22}
23
25 : config_(config), progress_callback_(nullptr), project_parsing_mode_(false),
26 max_threads_(std::thread::hardware_concurrency()), thread_safe_(true), libxml2_initialized_(false) {
28}
29
31 // Serialize destruction to prevent libxml2 race conditions
32 // This mutex ensures only one parser destructor runs at a time
33 std::lock_guard<std::mutex> lock(destruction_mutex_);
34
35 // Clear internal state that may reference libxml2 memory
36 parsed_trees_.clear();
37 parsed_blackboards_.clear();
39 expansion_stack_.clear();
40
41 // Don't call xmlCleanupParser() here - it's a global resource
42 // libxml2 cleanup should only happen at application shutdown
43}
44
45// Simple error suppression handler (thread-safe)
46static void SuppressLibXMLErrors(void *ctx, const char *msg, ...) {
47 // Suppress all libxml2 error output to avoid thread-safety issues
48 // Errors will be captured via structured error callbacks per-document
49}
50
52 std::call_once(libxml2_init_flag_, [this]() {
53 // Initialize libxml2 with threading support
54 // NOTE: In tests, this is also called in main() before threads for extra safety
55 xmlInitParser();
56 LIBXML_TEST_VERSION
57
58 // Enable threading support
59 xmlInitThreads();
60 thread_safe_ = true;
61 LOG_INFO("LibXMLParser", "libxml2 threading support enabled");
62
63 // Suppress default libxml2 error output (errors will be captured per-document)
64 // This avoids thread-safety issues with global error handlers
65 xmlSetGenericErrorFunc(nullptr, SuppressLibXMLErrors);
66
69 });
70}
71
72std::shared_ptr<BehaviorTree> LibXMLBehaviorTreeParser::ParseFromFile(const EmberCore::String &filepath) {
74 parsed_trees_.clear();
75 parsed_blackboards_.clear();
76 current_file_path_ = filepath;
77
78 // Report progress: Starting
79 if (!ReportProgress("Opening XML file...", 0, 5)) {
80 return nullptr; // User cancelled
81 }
82
83 // Check if file exists
84 std::ifstream file(filepath);
85 if (!file.good()) {
86 AddError(ParseError::FILE_NOT_FOUND, EmberCore::String("File not found: ") + filepath);
87 ReportProgress("ERROR: File not found", 0, 5);
88 return nullptr;
89 }
90
91 // Get file size for logging
92 file.seekg(0, std::ios::end);
93 std::streampos fileSize = file.tellg();
94 file.seekg(0, std::ios::beg);
95
96 EmberCore::String sizeStr;
97 if (fileSize < 1024) {
98 sizeStr = std::to_string(fileSize) + " bytes";
99 } else if (fileSize < 1024 * 1024) {
100 sizeStr = std::to_string(static_cast<double>(fileSize) / 1024.0) + " KB";
101 } else {
102 sizeStr = std::to_string(static_cast<double>(fileSize) / (1024.0 * 1024.0)) + " MB";
103 }
104 ReportProgress("File size: " + sizeStr + "", 0, 5);
105
106 // Report progress: Loading XML
107 if (!ReportProgress("Loading XML document...", 1, 5)) {
108 return nullptr; // User cancelled
109 }
110
111 // Load XML document with libxml2
112 xmlDocPtr doc = xmlParseFile(filepath.c_str());
113 if (!doc) {
114 AddError(ParseError::XML_SYNTAX_ERROR, EmberCore::String("Failed to parse XML file: ") + filepath);
115 ReportProgress("ERROR: XML syntax error", 1, 5);
116 return nullptr;
117 }
118
119 ReportProgress("XML document loaded successfully", 1, 5);
120 LOG_INFO("LibXMLParser", EmberCore::String("Loading: ") + filepath);
121
122 // Report progress: Parsing trees
123 if (!ReportProgress("Parsing behavior trees...", 2, 5)) {
124 xmlFreeDoc(doc);
125 return nullptr; // User cancelled
126 }
127
128 // Parse the document
129 bool success = ParseXMLDocument(doc, filepath);
130 xmlFreeDoc(doc);
131
132 if (!success) {
133 ReportProgress("ERROR: Failed to parse document structure", 2, 5);
134 return nullptr;
135 }
136
137 // Report progress: Finalizing
138 if (!ReportProgress("Finalizing...", 4, 5)) {
139 return nullptr; // User cancelled
140 }
141
142 ReportProgress("Parsed " + std::to_string(parsed_trees_.size()) + " tree(s) successfully", 4, 5);
143
144 // Return the main tree if specified
145 if (!main_tree_name_.empty() && parsed_trees_.count(main_tree_name_)) {
146 auto main_tree = parsed_trees_[main_tree_name_];
147
148 // Validate the tree structure using unified validator
149 if (!ReportProgress("Validating tree structure...", 4, 5)) {
150 return nullptr; // User cancelled
151 }
152
154 auto validation_result = validator.Validate(main_tree.get());
155
156 // Report validation errors (these block loading)
157 if (validation_result.HasErrors()) {
158 LOG_ERROR("LibXMLParser",
159 "Tree validation failed with " + std::to_string(validation_result.ErrorCount()) + " error(s):");
160
161 for (const auto &issue : validation_result.issues) {
162 if (issue.severity == BehaviorTreeValidator::Severity::ERROR) {
164 LOG_ERROR("LibXMLParser", " [" + issue.node_path + "] " + issue.message);
165 }
166 }
167
168 ReportProgress("ERROR: Tree validation failed", 4, 5);
169 return nullptr; // Errors block loading
170 }
171
172 // Report validation warnings (these don't block loading)
173 if (validation_result.HasWarnings()) {
174 LOG_WARNING("LibXMLParser",
175 "Tree has " + std::to_string(validation_result.WarningCount()) + " warning(s):");
176
177 for (const auto &issue : validation_result.issues) {
178 if (issue.severity == BehaviorTreeValidator::Severity::WARNING) {
179 LOG_WARNING("LibXMLParser", " [" + issue.node_path + "] " + issue.message);
180 }
181 }
182 }
183
184 ReportProgress("Tree validation passed", 4, 5);
185 return main_tree;
186 }
187
188 // Return the first tree if no main tree specified
189 if (!parsed_trees_.empty()) {
190 auto first_tree = parsed_trees_.begin()->second;
191
192 // Validate the tree structure
194 auto validation_result = validator.Validate(first_tree.get());
195
196 if (validation_result.HasErrors()) {
197 for (const auto &issue : validation_result.issues) {
198 if (issue.severity == BehaviorTreeValidator::Severity::ERROR) {
200 }
201 }
202 return nullptr; // Errors block loading
203 }
204
205 return first_tree;
206 }
207
208 AddError(ParseError::MISSING_BEHAVIOR_TREE, "No behavior trees found in XML file");
209 return nullptr;
210}
211
212std::shared_ptr<BehaviorTree> LibXMLBehaviorTreeParser::ParseFromString(const EmberCore::String &xml_content) {
213 ClearErrors();
214 parsed_trees_.clear();
215 parsed_blackboards_.clear();
216 current_file_path_ = "<string>";
217
218 // Load XML from string with libxml2
219 xmlDocPtr doc = xmlParseMemory(xml_content.c_str(), xml_content.length());
220 if (!doc) {
221 AddError(ParseError::XML_SYNTAX_ERROR, "Failed to parse XML content");
222 return nullptr;
223 }
224
225 // Parse the document
226 if (!ParseXMLDocument(doc)) {
227 xmlFreeDoc(doc);
228 return nullptr;
229 }
230
231 xmlFreeDoc(doc);
232
233 // Return the main tree if specified
234 if (!main_tree_name_.empty() && parsed_trees_.count(main_tree_name_)) {
235 auto main_tree = parsed_trees_[main_tree_name_];
236
237 // Validate the tree structure
239 auto validation_result = validator.Validate(main_tree.get());
240
241 if (validation_result.HasErrors()) {
242 for (const auto &issue : validation_result.issues) {
243 if (issue.severity == BehaviorTreeValidator::Severity::ERROR) {
245 }
246 }
247 return nullptr; // Errors block loading
248 }
249
250 return main_tree;
251 }
252
253 // Return the first tree if no main tree specified
254 if (!parsed_trees_.empty()) {
255 auto first_tree = parsed_trees_.begin()->second;
256
257 // Validate the tree structure
259 auto validation_result = validator.Validate(first_tree.get());
260
261 if (validation_result.HasErrors()) {
262 for (const auto &issue : validation_result.issues) {
263 if (issue.severity == BehaviorTreeValidator::Severity::ERROR) {
265 }
266 }
267 return nullptr; // Errors block loading
268 }
269
270 return first_tree;
271 }
272
273 AddError(ParseError::MISSING_BEHAVIOR_TREE, "No behavior trees found in XML content");
274 return nullptr;
275}
276
277std::vector<LibXMLBehaviorTreeParser::ParseResult>
278LibXMLBehaviorTreeParser::ParseMultipleFiles(const std::vector<EmberCore::String> &filepaths) {
279
280 std::vector<ParseResult> results;
281 results.reserve(filepaths.size());
282
283 for (const auto &filepath : filepaths) {
284 ParseResult result;
285 result.file_path = filepath;
286
287 try {
288 result.tree = ParseFromFile(filepath);
289 result.success = (result.tree != nullptr);
290 if (!result.success) {
291 std::lock_guard<std::mutex> lock(errors_mutex_);
292 result.errors = errors_;
293 }
294 } catch (const std::exception &e) {
295 result.success = false;
296 result.errors.push_back(
297 ParseError(ParseError::THREAD_ERROR, "Exception parsing " + filepath + ": " + std::string(e.what())));
298 }
299
300 results.push_back(result);
301 }
302
303 return results;
304}
305
306// ============================================================================
307// Project Parsing Methods
308// ============================================================================
309
311 int count = 0;
312 for (const auto &pair : tree_statuses) {
313 if (pair.second.is_implemented) {
314 count++;
315 }
316 }
317 return count;
318}
319
321 return static_cast<int>(tree_statuses.size());
322}
323
325 if (!project) {
326 ProjectParseResult result;
327 result.errors.push_back(ParseError(ParseError::INVALID_VALUE, "Project is null"));
328 return result;
329 }
330
331 // Get absolute paths for all resources
332 std::vector<EmberCore::String> filepaths;
333 for (const auto &resource : project->GetResources()) {
334 filepaths.push_back(project->ResolveResourcePath(resource));
335 }
336
337 // Parse all files with shared registry
339
340 // Update project with tree implementation statuses
341 if (result.success) {
343 }
344
345 return result;
346}
347
349LibXMLBehaviorTreeParser::ParseFilesWithSharedRegistry(const std::vector<EmberCore::String> &filepaths) {
350
351 ProjectParseResult result;
352 result.success = true;
353
354 // Clear existing state
355 ClearErrors();
356 parsed_trees_.clear();
357 parsed_blackboards_.clear();
360 project_parsing_mode_ = true; // Enable project parsing mode
361
362 int total_files = static_cast<int>(filepaths.size());
363 int current_file = 0;
364
365 ReportProgress("Starting project parsing...", 0, total_files + 2);
366
367 // First pass: Parse all files to collect all trees
368 for (const auto &filepath : filepaths) {
369 current_file++;
370 current_file_path_ = filepath;
371
372 ReportProgress("Parsing file " + std::to_string(current_file) + "/" + std::to_string(total_files) + ": " +
373 filepath,
374 current_file, total_files + 2);
375
376 // Check if file exists
377 std::ifstream file(filepath);
378 if (!file.good()) {
379 // Create FileParseInfo even for failed files
380 FileParseInfo failedInfo;
381 failedInfo.filepath = filepath;
382 failedInfo.parsed_successfully = false;
383 failedInfo.errors.push_back("File not found: " + filepath);
384 result.file_infos.push_back(failedInfo);
385
386 result.errors.push_back(
387 ParseError(ParseError::FILE_NOT_FOUND, EmberCore::String("File not found: ") + filepath, filepath));
388 result.success = false;
389 continue;
390 }
391 file.close();
392
393 // Parse the XML file
394 xmlDocPtr doc = xmlParseFile(filepath.c_str());
395 if (!doc) {
396 // Create FileParseInfo even for failed files
397 FileParseInfo failedInfo;
398 failedInfo.filepath = filepath;
399 failedInfo.parsed_successfully = false;
400 failedInfo.errors.push_back("Failed to parse XML file - syntax error");
401 result.file_infos.push_back(failedInfo);
402
404 EmberCore::String("Failed to parse XML file: ") + filepath, filepath));
405 result.success = false;
406 continue;
407 }
408
409 // Parse document but don't expand subtrees yet
410 // (we'll do that after all files are parsed)
411 xmlNodePtr root = xmlDocGetRootElement(doc);
412 if (!root) {
413 // Create FileParseInfo even for failed files
414 FileParseInfo failedInfo;
415 failedInfo.filepath = filepath;
416 failedInfo.parsed_successfully = false;
417 failedInfo.errors.push_back("XML document has no root element");
418 result.file_infos.push_back(failedInfo);
419
420 xmlFreeDoc(doc);
421 result.errors.push_back(
422 ParseError(ParseError::MISSING_ROOT_ELEMENT, "XML document has no root element", filepath));
423 result.success = false;
424 continue;
425 }
426
427 // Get configured element names
428 const auto &doc_config = config_.GetDocumentConfig();
429 const auto &tree_config = config_.GetTreeConfig();
430
431 // Validate root element
432 EmberCore::String root_name = GetNodeName(root);
433 bool root_valid = false;
434 if (doc_config.case_sensitive) {
435 root_valid = (root_name == doc_config.root_element);
436 } else {
437 auto to_lower = [](String str) {
438 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
439 return str;
440 };
441 root_valid = (to_lower(root_name) == to_lower(doc_config.root_element));
442 }
443
444 if (!root_valid) {
445 // Create FileParseInfo even for failed files
446 FileParseInfo failedInfo;
447 failedInfo.filepath = filepath;
448 failedInfo.parsed_successfully = false;
449 failedInfo.errors.push_back("Expected '" + doc_config.root_element + "' element, found '" + root_name +
450 "'");
451 result.file_infos.push_back(failedInfo);
452
453 xmlFreeDoc(doc);
455 EmberCore::String("Expected '") + doc_config.root_element +
456 "' element, found '" + root_name + "'",
457 filepath));
458 result.success = false;
459 continue;
460 }
461
462 // Get main tree if this is the first file with it
463 if (result.main_tree_name.empty()) {
464 EmberCore::String main_tree = GetNodeAttribute(root, doc_config.main_tree_attribute);
465 if (!main_tree.empty()) {
466 result.main_tree_name = main_tree;
467 }
468 }
469
470 // Create file info for detailed validation
471 FileParseInfo fileInfo;
472 fileInfo.filepath = filepath;
473 fileInfo.parsed_successfully = true;
474
475 std::set<String> file_tree_ids;
476 std::set<String> file_bb_ids;
477 std::set<String> subtree_refs_set;
478 std::set<String> bb_includes_set;
479
480 // Parse all BehaviorTree and Blackboard nodes in this file
481 for (xmlNodePtr child = root->children; child; child = child->next) {
482 if (child->type == XML_ELEMENT_NODE) {
483 EmberCore::String name = GetNodeName(child);
484
485 if (name == tree_config.behavior_tree_element) {
486 // Parse BehaviorTree
487 fileInfo.has_behavior_trees = true;
488 fileInfo.tree_count++;
489
490 EmberCore::String tree_id = GetNodeAttribute(child, tree_config.tree_id_attribute);
491 if (tree_id.empty()) {
492 fileInfo.errors.push_back("BehaviorTree element missing required 'ID' attribute");
493 } else {
494 fileInfo.tree_ids.push_back(tree_id);
495
496 // Check for duplicate tree IDs within this file
497 if (file_tree_ids.count(tree_id) > 0) {
498 fileInfo.warnings.push_back("Duplicate tree ID within file: " + tree_id);
499 }
500 file_tree_ids.insert(tree_id);
501
502 auto tree = ParseBehaviorTree(child);
503 if (tree) {
504 parsed_trees_[tree_id] = tree;
505
506 // Track implementation status
507 TreeImplementationStatus status(tree_id);
508 status.is_implemented = tree->HasRootNode() && tree->GetNodeCount() > 0;
509 status.has_root_node = tree->HasRootNode();
510 status.defined_in_file = filepath;
511 tree_implementation_statuses_[tree_id] = status;
512
513 // Collect SubTree references
514 if (tree->HasRootNode()) {
515 CollectSubTreeReferences(tree->GetRootNode(), subtree_refs_set);
516 }
517
518 LOG_INFO("LibXMLParser", "Parsed tree '" + tree_id + "' from " + filepath);
519 }
520 }
521 } else if (name == "Blackboard") {
522 // Parse Blackboard
523 fileInfo.has_blackboards = true;
524 fileInfo.blackboard_count++;
525
526 EmberCore::String bb_id = GetNodeAttribute(child, "ID");
527 if (bb_id.empty()) {
528 fileInfo.errors.push_back("Blackboard element missing required 'ID' attribute");
529 } else {
530 fileInfo.blackboard_ids.push_back(bb_id);
531
532 // Check for duplicate blackboard IDs within this file
533 if (file_bb_ids.count(bb_id) > 0) {
534 fileInfo.warnings.push_back("Duplicate blackboard ID within file: " + bb_id);
535 }
536 file_bb_ids.insert(bb_id);
537
538 // Parse includes attribute
539 EmberCore::String includes = GetNodeAttribute(child, "includes");
540 if (!includes.empty()) {
541 // Validate format {ID1 ID2 ...}
542 if (includes.front() != '{' || includes.back() != '}') {
543 fileInfo.warnings.push_back(
544 "Blackboard '" + bb_id +
545 "' has malformed includes syntax (should be {ID1 ID2 ...})");
546 } else {
547 // Parse includes
548 String includes_content = includes.substr(1, includes.size() - 2);
549 std::istringstream iss(includes_content);
550 String token;
551 while (iss >> token) {
552 if (!token.empty()) {
553 bb_includes_set.insert(token);
554 fileInfo.blackboard_includes.push_back(token);
555 }
556 }
557 }
558 }
559
560 // Validate entries
561 std::set<String> seen_keys;
562 for (xmlNodePtr entryNode = child->children; entryNode; entryNode = entryNode->next) {
563 if (entryNode->type != XML_ELEMENT_NODE)
564 continue;
565 if (GetNodeName(entryNode) != "Entry")
566 continue;
567
568 String key = GetNodeAttribute(entryNode, "key");
569 String type = GetNodeAttribute(entryNode, "type");
570
571 if (key.empty()) {
572 fileInfo.errors.push_back("Blackboard '" + bb_id +
573 "' has Entry missing required 'key' attribute");
574 continue;
575 }
576 if (type.empty()) {
577 fileInfo.errors.push_back("Blackboard '" + bb_id + "' entry '" + key +
578 "' missing required 'type' attribute");
579 continue;
580 }
581
582 // Check for duplicate keys
583 if (seen_keys.count(key) > 0) {
584 fileInfo.warnings.push_back("Blackboard '" + bb_id +
585 "' has duplicate entry key: " + key);
586 }
587 seen_keys.insert(key);
588
589 // Validate type (using existing validation list)
590 static const std::set<String> validTypes = {"bool",
591 "int",
592 "int8",
593 "float",
594 "string",
595 "Currency",
596 "uint8_t",
597 "uint32_t",
598 "size_t",
599 "auto",
600 "vec(int)",
601 "vec(int8)",
602 "vec(uint8_t)",
603 "vec(uint32_t)",
604 "vec(float)",
605 "vec(string)",
606 "vec(Currency)",
607 "vec(vec(uint8_t))",
608 "vec(vec(uint32_t))",
609 "vec(pair(float))",
610 "pair(float)",
611 "pair(int)",
612 "pair(string)",
613 "map(string, string)",
614 "map(string,string)",
615 "map(string, int)",
616 "map(string,int)",
617 "set(string)",
618 "set(int)",
619 "set(uint32_t)",
620 "set",
621 "Results",
622 "ReelFigs",
623 "GameSounds"};
624
625 bool isValidType = validTypes.count(type) > 0;
626 bool isCustomType = !type.empty() && std::isupper(type[0]) &&
627 type.find('(') == String::npos && type.find(')') == String::npos;
628
629 if (!isValidType && !isCustomType) {
630 fileInfo.warnings.push_back("Blackboard '" + bb_id + "' entry '" + key +
631 "' has unsupported type: " + type);
632 }
633 }
634
635 // Actually parse the blackboard
636 auto blackboard = ParseBlackboard(child);
637 if (blackboard) {
638 parsed_blackboards_[bb_id] = std::move(blackboard);
639 LOG_INFO("LibXMLParser", "Parsed blackboard '" + bb_id + "' from " + filepath);
640 }
641 }
642 }
643 }
644 }
645
646 // Store subtree refs in file info
647 fileInfo.subtree_refs.assign(subtree_refs_set.begin(), subtree_refs_set.end());
648
649 // Check if file has neither trees nor blackboards
650 if (!fileInfo.has_behavior_trees && !fileInfo.has_blackboards) {
651 fileInfo.warnings.push_back("No BehaviorTree or Blackboard elements found in file");
652 }
653
654 // Add file info to result
655 result.file_infos.push_back(fileInfo);
656
657 xmlFreeDoc(doc);
658 }
659
660 // Note: Even if some files failed to parse, we continue with validation
661 // for the files that did parse successfully. result.success will remain
662 // false to indicate errors occurred, but we still do cross-file validation.
663
664 // Copy any errors from failed parsing
665 if (!result.success) {
666 std::lock_guard<std::mutex> lock(errors_mutex_);
667 for (const auto &err : errors_) {
668 result.errors.push_back(err);
669 }
670 }
671
672 // Second pass: Collect all SubTree references and identify unimplemented trees
673 ReportProgress("Collecting SubTree references...", total_files + 1, total_files + 2);
674
675 std::set<EmberCore::String> all_references;
676 for (const auto &tree_pair : parsed_trees_) {
677 if (tree_pair.second && tree_pair.second->HasRootNode()) {
678 CollectSubTreeReferences(tree_pair.second->GetRootNode(), all_references);
679 }
680 }
681
682 // Collect all implemented tree IDs
683 std::set<String> implemented_tree_ids;
684 for (const auto &tree_pair : parsed_trees_) {
685 implemented_tree_ids.insert(tree_pair.first);
686 }
687
688 // Track references in implementation status and add per-file warnings
689 for (const auto &ref : all_references) {
691 // This is a referenced but not implemented tree
692 TreeImplementationStatus status(ref);
693 status.is_implemented = false;
694 status.has_root_node = false;
695 tree_implementation_statuses_[ref] = status;
696 unimplemented_references_.insert(ref);
697 result.unimplemented_references.push_back(ref);
698 result.warnings.push_back("Tree '" + ref + "' is referenced but not implemented");
699 LOG_WARNING("LibXMLParser", "Tree '" + ref + "' is referenced but not implemented");
700
701 // Add warning to each file that references this unimplemented tree
702 for (auto &fileInfo : result.file_infos) {
703 for (const auto &subtree_ref : fileInfo.subtree_refs) {
704 if (subtree_ref == ref) {
705 fileInfo.warnings.push_back("References unimplemented tree: " + ref);
706 break;
707 }
708 }
709 }
710 }
711 }
712
713 // Third pass: Expand all SubTree placeholders (with project mode)
714 ReportProgress("Expanding SubTree references...", total_files + 2, total_files + 2);
716
717 // Cross-file validation: detect duplicates and unresolved references
718 ReportProgress("Validating cross-file references...", total_files + 2, total_files + 2);
719
720 // Collect all tree IDs and detect duplicates
721 std::map<String, std::vector<String>> tree_id_to_files;
722 for (const auto &fileInfo : result.file_infos) {
723 for (const auto &tree_id : fileInfo.tree_ids) {
724 tree_id_to_files[tree_id].push_back(fileInfo.filepath);
725 }
726 }
727 for (const auto &pair : tree_id_to_files) {
728 if (pair.second.size() > 1) {
729 result.duplicate_tree_ids.push_back(pair.first);
730 result.warnings.push_back("Duplicate tree ID found across files: " + pair.first);
731 }
732 }
733
734 // Collect all blackboard IDs and detect duplicates
735 std::map<String, std::vector<String>> bb_id_to_files;
736 std::set<String> all_blackboard_ids;
737 for (const auto &fileInfo : result.file_infos) {
738 for (const auto &bb_id : fileInfo.blackboard_ids) {
739 bb_id_to_files[bb_id].push_back(fileInfo.filepath);
740 all_blackboard_ids.insert(bb_id);
741 }
742 }
743 for (const auto &pair : bb_id_to_files) {
744 if (pair.second.size() > 1) {
745 result.duplicate_blackboard_ids.push_back(pair.first);
746 result.warnings.push_back("Duplicate blackboard ID found across files: " + pair.first);
747 }
748 }
749
750 // Detect unresolved blackboard includes
751 std::set<String> unresolved_includes;
752 for (const auto &fileInfo : result.file_infos) {
753 for (const auto &include : fileInfo.blackboard_includes) {
754 if (all_blackboard_ids.count(include) == 0) {
755 unresolved_includes.insert(include);
756 }
757 }
758 }
759 result.unresolved_blackboard_includes.assign(unresolved_includes.begin(), unresolved_includes.end());
760 for (const auto &include : unresolved_includes) {
761 result.warnings.push_back("Unresolved blackboard include: " + include);
762 }
763
764 // Copy circular references detected during expansion
766
767 // Copy results
769
770 // Convert unique_ptr blackboards to shared_ptr
771 for (auto &pair : parsed_blackboards_) {
772 if (pair.second) {
773 // Move ownership from unique_ptr to shared_ptr
774 result.parsed_blackboards[pair.first] = std::shared_ptr<Blackboard>(std::move(pair.second));
775 }
776 }
777
779
780 // Copy any additional errors
781 {
782 std::lock_guard<std::mutex> lock(errors_mutex_);
783 for (const auto &err : errors_) {
784 result.errors.push_back(err);
785 }
786 }
787
788 result.success = result.errors.empty();
789 project_parsing_mode_ = false;
790
791 ReportProgress("Project parsing complete: " + std::to_string(result.GetImplementedTreeCount()) + " implemented, " +
792 std::to_string(result.unimplemented_references.size()) + " unimplemented",
793 total_files + 2, total_files + 2);
794
795 return result;
796}
797
798void LibXMLBehaviorTreeParser::CollectSubTreeReferences(Node *node, std::set<EmberCore::String> &references) {
799 if (!node)
800 return;
801
802 // Check if this is a SubTree placeholder
803 EmberCore::String subtree_ref = node->GetAttribute("__subtree_ref__", "");
804 if (!subtree_ref.empty()) {
805 references.insert(subtree_ref);
806
807 // Track which files reference this tree
808 if (tree_implementation_statuses_.find(subtree_ref) != tree_implementation_statuses_.end()) {
809 auto &status = tree_implementation_statuses_[subtree_ref];
810 if (std::find(status.referenced_in_files.begin(), status.referenced_in_files.end(), current_file_path_) ==
811 status.referenced_in_files.end()) {
812 status.referenced_in_files.push_back(current_file_path_);
813 }
814 }
815 }
816
817 // Recursively check children
818 for (size_t i = 0; i < node->GetChildCount(); ++i) {
819 CollectSubTreeReferences(node->GetChild(i), references);
820 }
821}
822
824 // Clear cache before expansion
826 expansion_stack_.clear();
827 circular_references_.clear();
828
829 for (auto &tree_pair : parsed_trees_) {
830 auto &tree = tree_pair.second;
831 if (tree && tree->HasRootNode()) {
832 // Add the tree ID to the expansion stack before expanding
833 expansion_stack_.insert(tree_pair.first);
834 ExpandSubTreePlaceholderForProject(tree->GetRootNode());
835 expansion_stack_.erase(tree_pair.first);
836 }
837 }
838}
839
841 if (!node)
842 return false;
843
844 bool expanded_any = false;
845
846 // Check if this node is a SubTree placeholder
847 EmberCore::String subtree_ref = node->GetAttribute("__subtree_ref__", "");
848 if (!subtree_ref.empty()) {
849 // This is a SubTree placeholder node
850
851 if (parsed_trees_.find(subtree_ref) != parsed_trees_.end()) {
852 auto referenced_tree = parsed_trees_[subtree_ref];
853 if (referenced_tree && referenced_tree->HasRootNode()) {
854 Node *referenced_root = referenced_tree->GetRootNode();
855
856 // Check for circular reference
857 bool is_expanding = (expansion_stack_.find(subtree_ref) != expansion_stack_.end());
858 bool already_expanded = (expanded_subtree_cache_.find(subtree_ref) != expanded_subtree_cache_.end());
859
860 if (is_expanding) {
861 // Track the circular reference - build a message showing the cycle
862 String cycle_msg = "Circular reference: ";
863 bool first = true;
864 for (const auto &tree_in_stack : expansion_stack_) {
865 if (!first)
866 cycle_msg += " -> ";
867 cycle_msg += tree_in_stack;
868 first = false;
869 }
870 cycle_msg += " -> " + subtree_ref;
871
872 circular_references_.insert(cycle_msg);
873 AddError(ParseError::INVALID_TREE_STRUCTURE, "Circular SubTree reference detected: " + cycle_msg);
874 LOG_ERROR("LibXMLParser", "Circular SubTree reference detected: " + cycle_msg);
875 return false;
876 }
877
878 if (!already_expanded) {
879 expansion_stack_.insert(subtree_ref);
880 ExpandSubTreePlaceholderForProject(referenced_root);
881 expanded_subtree_cache_.insert(subtree_ref);
882 expansion_stack_.erase(subtree_ref);
883 }
884
885 // Copy properties from referenced tree
886 node->SetName(referenced_root->GetName());
887 node->SetType(referenced_root->GetType());
888 node->RemoveAttribute("__is_placeholder__");
889
890 for (const auto &attr_pair : referenced_root->GetAllAttributes()) {
891 node->SetAttribute(attr_pair.first, attr_pair.second);
892 }
893
894 for (size_t i = 0; i < referenced_root->GetChildCount(); ++i) {
895 Node *child = referenced_root->GetChild(i);
896 if (child) {
897 node->AddChild(child->DeepCopy());
898 }
899 }
900
901 expanded_any = true;
902 } else {
903 // Referenced tree exists but is empty - mark as unimplemented
904 node->RemoveAttribute("__is_placeholder__");
905 node->SetAttribute("__unimplemented__", "true");
906 node->SetName("SubTree: " + subtree_ref + " [EMPTY]");
907 LOG_WARNING("LibXMLParser", "SubTree '" + subtree_ref + "' is empty (no root node)");
908 }
909 } else {
910 // Tree not found - in project mode, don't error, just mark as unimplemented
911 // Remove the placeholder marker and mark as unimplemented instead
912 node->RemoveAttribute("__is_placeholder__");
913 node->SetAttribute("__unimplemented__", "true");
914 node->SetName("SubTree: " + subtree_ref + " [NOT IMPLEMENTED]");
915 LOG_WARNING("LibXMLParser", "SubTree '" + subtree_ref + "' not found (unimplemented reference)");
916 }
917 } else {
918 // Not a subtree placeholder, recursively expand children
919 for (size_t i = 0; i < node->GetChildCount(); ++i) {
921 expanded_any = true;
922 }
923 }
924 }
925
926 return expanded_any;
927}
928
930 auto it = tree_implementation_statuses_.find(tree_id);
931 if (it != tree_implementation_statuses_.end()) {
932 return it->second.is_implemented;
933 }
934 return false;
935}
936
937std::vector<EmberCore::String> LibXMLBehaviorTreeParser::GetUnimplementedReferences() const {
938 std::vector<EmberCore::String> result;
939 for (const auto &ref : unimplemented_references_) {
940 result.push_back(ref);
941 }
942 return result;
943}
944
945// ============================================================================
946// Core Parsing Methods
947// ============================================================================
948
949bool LibXMLBehaviorTreeParser::ParseXMLDocument(xmlDocPtr doc, const EmberCore::String &source_path) {
950 xmlNodePtr root = xmlDocGetRootElement(doc);
951 if (!root) {
952 AddError(ParseError::MISSING_ROOT_ELEMENT, "XML document has no root element");
953 return false;
954 }
955
956 // Use configured root element name
957 const auto &doc_config = config_.GetDocumentConfig();
958 EmberCore::String root_name = GetNodeName(root);
959
960 if (doc_config.case_sensitive) {
961 if (root_name != doc_config.root_element) {
962 AddError(ParseError::MISSING_ROOT_ELEMENT, EmberCore::String("Expected '") + doc_config.root_element +
963 "' element, found '" + root_name + "'");
964 return false;
965 }
966 } else {
967 // Case-insensitive comparison
968 auto to_lower = [](String str) {
969 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
970 return str;
971 };
972 if (to_lower(root_name) != to_lower(doc_config.root_element)) {
973 AddError(ParseError::MISSING_ROOT_ELEMENT, EmberCore::String("Expected '") + doc_config.root_element +
974 "' element, found '" + root_name + "'");
975 return false;
976 }
977 }
978
979 // Get main tree to execute using configured attribute name
980 main_tree_name_ = GetNodeAttribute(root, doc_config.main_tree_attribute);
981 if (!main_tree_name_.empty()) {
982 ReportProgress(EmberCore::String("Main tree: ") + main_tree_name_, 2, 5);
983 }
984
985 // Report progress: Parsing structure
986 ReportProgress("Parsing tree structure...", 2, 5);
987
988 // Get configured element names
989 const auto &tree_config = config_.GetTreeConfig();
990 const auto &blackboard_config = config_.GetBlackboardConfig();
991
992 // Count total elements first for better progress reporting
993 int totalElements = 0;
994 for (xmlNodePtr child = root->children; child; child = child->next) {
995 if (child->type == XML_ELEMENT_NODE) {
996 EmberCore::String name = GetNodeName(child);
997 if (name == tree_config.behavior_tree_element || name == blackboard_config.blackboard_element) {
998 totalElements++;
999 }
1000 }
1001 }
1002 ReportProgress("Found " + std::to_string(totalElements) + " element(s) to parse", 2, 5);
1003
1004 // Parse all BehaviorTree nodes
1005 int treeCount = 0;
1006 int blackboardCount = 0;
1007 for (xmlNodePtr child = root->children; child; child = child->next) {
1008 if (child->type == XML_ELEMENT_NODE) {
1009 EmberCore::String name = GetNodeName(child);
1010 if (name == tree_config.behavior_tree_element) {
1011 auto tree = ParseBehaviorTree(child);
1012 if (tree) {
1013 EmberCore::String tree_id = GetNodeAttribute(child, tree_config.tree_id_attribute);
1014 if (!tree_id.empty()) {
1015 parsed_trees_[tree_id] = tree;
1016 treeCount++;
1017 // Report progress for each tree parsed
1018 EmberCore::String progressMsg = "Parsed tree " + std::to_string(treeCount) + "/" +
1019 std::to_string(totalElements) + ": " + tree_id;
1020 ReportProgress(progressMsg, 2, 5);
1021
1022 // Log node count
1023 if (tree->HasRootNode()) {
1024 size_t nodeCount = tree->GetNodeCount();
1025 ReportProgress(" " + std::to_string(nodeCount) + " node(s) in tree", 2, 5);
1026 }
1027 } else {
1029 tree_config.behavior_tree_element + " missing " + tree_config.tree_id_attribute +
1030 " attribute",
1031 child);
1032 ReportProgress(" WARNING: Tree missing ID attribute", 2, 5);
1033 }
1034 }
1035 } else if (name == blackboard_config.blackboard_element) {
1036 auto blackboard = ParseBlackboard(child);
1037 if (blackboard) {
1038 EmberCore::String blackboard_id = blackboard->GetId();
1039 parsed_blackboards_[blackboard_id] = std::move(blackboard);
1040 blackboardCount++;
1041 ReportProgress(EmberCore::String("Parsed blackboard: ") + blackboard_id, 2, 5);
1042 }
1043 } else if (!doc_config.allow_unknown_elements) {
1044 LOG_WARNING("LibXMLParser", "Unknown element '" + name + "' in root (ignored)");
1045 }
1046 }
1047 }
1048
1049 LOG_INFO("LibXMLParser", "Parsed " + std::to_string(parsed_trees_.size()) + " trees and " +
1050 std::to_string(parsed_blackboards_.size()) + " blackboards");
1051
1052 ReportProgress("Parsed " + std::to_string(treeCount) + " tree(s) and " + std::to_string(blackboardCount) +
1053 " blackboard(s)",
1054 2, 5);
1055
1056 // Report progress: Expanding subtrees
1057 ReportProgress("Expanding subtrees...", 3, 5);
1058
1059 // Expand all SubTree placeholders now that all trees have been parsed
1061 ReportProgress("Subtree expansion complete", 3, 5);
1062
1063 // Assign blackboards to all parsed trees after parsing is complete
1064 for (const auto &blackboard_pair : parsed_blackboards_) {
1065 const auto &blackboard = blackboard_pair.second;
1066 for (auto &tree_pair : parsed_trees_) {
1067 tree_pair.second->AddBlackboard(blackboard->Clone());
1068 }
1069 }
1070
1071 // Check for errors
1072 if (HasErrors()) {
1073 LOG_ERROR("LibXMLParser", "Parsing failed with " + std::to_string(errors_.size()) + " error(s):");
1074 for (size_t i = 0; i < errors_.size(); ++i) {
1075 LOG_ERROR("LibXMLParser", " " + std::to_string(i + 1) + ": " + errors_[i].message);
1076 }
1077 return false;
1078 }
1079
1080 LOG_INFO("LibXMLParser", "Parsing completed successfully");
1081 return true;
1082}
1083
1084// Helper methods for libxml2 integration
1086 if (!node || !node->name)
1087 return "";
1088 return std::string(reinterpret_cast<const char *>(node->name));
1089}
1090
1092 if (!node)
1093 return "";
1094
1095 xmlChar *value = xmlGetProp(node, reinterpret_cast<const xmlChar *>(attr_name.c_str()));
1096 if (!value)
1097 return "";
1098
1099 EmberCore::String result = std::string(reinterpret_cast<const char *>(value));
1100 xmlFree(value);
1101 return result;
1102}
1103
1104// Thread-safe error handling
1106 std::lock_guard<std::mutex> lock(errors_mutex_);
1107 return !errors_.empty();
1108}
1109
1110const std::vector<LibXMLBehaviorTreeParser::ParseError> &LibXMLBehaviorTreeParser::GetErrors() const {
1111 std::lock_guard<std::mutex> lock(errors_mutex_);
1112 return errors_;
1113}
1114
1116 std::lock_guard<std::mutex> lock(errors_mutex_);
1117 errors_.clear();
1118}
1119
1121 const EmberCore::String &context) {
1122 std::lock_guard<std::mutex> lock(errors_mutex_);
1123 ParseError error(type, message, current_file_path_);
1124
1125 if (node) {
1126 error.line_number = node->line;
1127 error.column_number = 0; // libxml2 doesn't provide column info in older versions
1128 error.node_path = GetNodePath(node);
1129 }
1130
1131 if (!context.empty()) {
1132 error.context = context;
1133 error.message += " (Context: " + context + ")";
1134 }
1135
1136 errors_.push_back(error);
1137 LOG_ERROR("LibXMLParser", "Parse error: " + message + "");
1138}
1139
1141 if (!node)
1142 return "";
1143
1144 EmberCore::String path;
1145 xmlNodePtr current = node;
1146
1147 while (current && current->parent) {
1148 EmberCore::String node_name = GetNodeName(current);
1149 EmberCore::String id = GetNodeAttribute(current, "ID");
1150 EmberCore::String name = GetNodeAttribute(current, "name");
1151
1152 if (!id.empty()) {
1153 node_name += "[ID=" + id + "]";
1154 } else if (!name.empty()) {
1155 node_name += "[name=" + name + "]";
1156 }
1157
1158 if (path.empty()) {
1159 path = node_name;
1160 } else {
1161 path = node_name + "/" + path;
1162 }
1163
1164 current = current->parent;
1165 }
1166
1167 return path;
1168}
1169
1170bool LibXMLBehaviorTreeParser::ReportProgress(const EmberCore::String &message, int current, int total) {
1171 if (progress_callback_) {
1172 return progress_callback_->OnProgress(message, current, total);
1173 }
1174 // If no callback, always continue
1175 return true;
1176}
1177
1178std::shared_ptr<BehaviorTree> LibXMLBehaviorTreeParser::ParseBehaviorTree(xmlNodePtr tree_node) {
1179 const auto &tree_config = config_.GetTreeConfig();
1180
1181 if (!ValidateRequiredAttribute(tree_node, tree_config.tree_id_attribute)) {
1182 return nullptr;
1183 }
1184
1185 EmberCore::String tree_id = GetNodeAttribute(tree_node, tree_config.tree_id_attribute);
1186 auto behavior_tree = std::make_shared<BehaviorTree>();
1187
1188 // Set the tree name from the ID attribute (important for serialization round-trips)
1189 behavior_tree->SetName(tree_id);
1190
1191 // Capture document-level comments
1192 CaptureComments(tree_node, behavior_tree.get());
1193
1194 // Parse the root node of this behavior tree
1195 xmlNodePtr child = tree_node->children;
1196 std::unique_ptr<Node> root_node = nullptr;
1197
1198 while (child) {
1199 if (child->type == XML_ELEMENT_NODE) {
1200 auto node = ParseNode(child);
1201 if (node) {
1202 if (!root_node) {
1203 root_node = std::move(node);
1204 } else {
1206 tree_config.behavior_tree_element + " can only have one root node", child);
1207 return nullptr;
1208 }
1209 }
1210 }
1211 child = child->next;
1212 }
1213
1214 if (!root_node && tree_config.require_root_node) {
1216 EmberCore::String(tree_config.behavior_tree_element) + " '" + tree_id + "' has no root node");
1217 return nullptr;
1218 }
1219
1220 if (root_node) {
1221 // Create a visual wrapper node for the BehaviorTree itself
1222 auto wrapper_node = std::make_unique<Node>(tree_id, Node::Type::BehaviorTree);
1223
1224 // Copy any BehaviorTree-level attributes to the wrapper node
1225 xmlAttrPtr attr = tree_node->properties;
1226 while (attr) {
1227 EmberCore::String attr_name = reinterpret_cast<const char *>(attr->name);
1228 EmberCore::String attr_value = GetNodeAttribute(tree_node, attr_name);
1229 wrapper_node->SetAttribute(attr_name, attr_value);
1230 attr = attr->next; // CRITICAL: Advance to next attribute
1231 }
1232
1233 // Add the actual root node (Sequence, Selector, etc.) as a child
1234 wrapper_node->AddChild(std::move(root_node));
1235
1236 // Set the wrapper as the BehaviorTree's root
1237 behavior_tree->SetRootNode(std::move(wrapper_node));
1238 }
1239 return behavior_tree;
1240}
1241
1242std::unique_ptr<Node> LibXMLBehaviorTreeParser::ParseNode(xmlNodePtr xml_node) {
1243 if (!xml_node || xml_node->type != XML_ELEMENT_NODE) {
1244 return nullptr;
1245 }
1246
1247 const auto &node_config = config_.GetNodeConfig();
1248 const auto &tree_config = config_.GetTreeConfig();
1249
1250 EmberCore::String element_name = GetNodeName(xml_node);
1251 std::unique_ptr<Node> node = nullptr;
1252
1253 // Element name indicates the category (Control, Action, Decorator, Condition)
1254 // The specific behavior is specified in the ID attribute
1255 if (element_name == node_config.control_element) {
1256 node = ParseControlNode(xml_node);
1257 } else if (element_name == node_config.action_element) {
1258 node = ParseActionNode(xml_node);
1259 } else if (element_name == node_config.condition_element) {
1260 node = ParseConditionNode(xml_node);
1261 } else if (element_name == node_config.decorator_element) {
1262 node = ParseDecoratorNode(xml_node);
1263 } else if (element_name == tree_config.subtree_element) {
1264 node = ParseSubTreeNode(xml_node);
1265 } else if (element_name == node_config.generic_node_element) {
1266 // Generic node - try to infer type
1267 node = ParseActionNode(xml_node); // Default to action
1268 } else {
1269 // Unknown node type - handle according to config
1270 const auto &classification_config = config_.GetClassificationConfig();
1271 switch (classification_config.unknown_behavior) {
1273 AddError(ParseError::UNKNOWN_NODE_TYPE, "Unknown node element: " + element_name, xml_node);
1274 return nullptr;
1276 LOG_WARNING("LibXMLParser", "Unknown node element: " + element_name + " (skipped)");
1277 return nullptr;
1279 LOG_WARNING("LibXMLParser", "Unknown node element: " + element_name + " (creating generic action node)");
1280 node = ParseActionNode(xml_node);
1281 break;
1282 }
1283 }
1284
1285 if (node) {
1286 // For SubTree nodes, attributes and children are handled differently
1287 // (they are copied from the referenced tree)
1288 if (element_name != tree_config.subtree_element) {
1289 SetNodeAttributes(node.get(), xml_node);
1290 ParseChildNodes(node.get(), xml_node);
1291 }
1292 }
1293
1294 return node;
1295}
1296
1297std::unique_ptr<Node> LibXMLBehaviorTreeParser::ParseControlNode(xmlNodePtr xml_node) {
1298 const auto &node_config = config_.GetNodeConfig();
1299
1300 if (!ValidateRequiredAttribute(xml_node, node_config.node_id_attribute)) {
1301 return nullptr;
1302 }
1303
1304 EmberCore::String control_type = GetNodeAttribute(xml_node, node_config.node_id_attribute);
1305
1306 // Validate this is actually a control type
1307 if (!config_.IsControlType(control_type)) {
1308 const auto &classification_config = config_.GetClassificationConfig();
1309 if (classification_config.unknown_behavior == ParserConfig::UnknownTypeBehavior::ERROR) {
1310 AddError(ParseError::UNKNOWN_NODE_TYPE, "Unknown control node type: " + control_type, xml_node);
1311 return nullptr;
1312 }
1313 LOG_WARNING("LibXMLParser", "Unknown control type '" + control_type + "', creating generic control node");
1314 }
1315
1316 auto node = std::make_unique<Node>(control_type, Node::Type::Control);
1317 LOG_TRACE("LibXMLParser", "Created control node: " + control_type);
1318
1319 return node;
1320}
1321
1322std::unique_ptr<Node> LibXMLBehaviorTreeParser::ParseActionNode(xmlNodePtr xml_node) {
1323 const auto &node_config = config_.GetNodeConfig();
1324
1325 if (!ValidateRequiredAttribute(xml_node, node_config.node_id_attribute)) {
1326 return nullptr;
1327 }
1328
1329 EmberCore::String action_type = GetNodeAttribute(xml_node, node_config.node_id_attribute);
1330
1331 // Check if it's a known action type (if list is defined)
1332 if (!config_.IsActionType(action_type)) {
1333 const auto &classification_config = config_.GetClassificationConfig();
1334 if (!classification_config.action_types.empty() &&
1335 classification_config.unknown_behavior == ParserConfig::UnknownTypeBehavior::ERROR) {
1336 AddError(ParseError::UNKNOWN_NODE_TYPE, "Unknown action type: " + action_type, xml_node);
1337 return nullptr;
1338 }
1339 LOG_TRACE("LibXMLParser", "Unknown action type '" + action_type + "', creating generic Action node");
1340 }
1341
1342 auto node = std::make_unique<Node>(action_type, Node::Type::Action);
1343 LOG_TRACE("LibXMLParser", "Created action node: " + action_type);
1344
1345 return node;
1346}
1347
1348std::unique_ptr<Node> LibXMLBehaviorTreeParser::ParseConditionNode(xmlNodePtr xml_node) {
1349 const auto &node_config = config_.GetNodeConfig();
1350
1351 if (!ValidateRequiredAttribute(xml_node, node_config.node_id_attribute)) {
1352 return nullptr;
1353 }
1354
1355 EmberCore::String condition_type = GetNodeAttribute(xml_node, node_config.node_id_attribute);
1356
1357 // Check if it's a known condition type (if list is defined)
1358 if (!config_.IsConditionType(condition_type)) {
1359 const auto &classification_config = config_.GetClassificationConfig();
1360 if (!classification_config.condition_types.empty() &&
1361 classification_config.unknown_behavior == ParserConfig::UnknownTypeBehavior::ERROR) {
1362 AddError(ParseError::UNKNOWN_NODE_TYPE, "Unknown condition type: " + condition_type, xml_node);
1363 return nullptr;
1364 }
1365 LOG_TRACE("LibXMLParser", "Unknown condition type '" + condition_type + "', creating generic Condition node");
1366 }
1367
1368 auto node = std::make_unique<Node>(condition_type, Node::Type::Condition);
1369 LOG_TRACE("LibXMLParser", "Created condition node: " + condition_type);
1370
1371 return node;
1372}
1373
1374std::unique_ptr<Node> LibXMLBehaviorTreeParser::ParseDecoratorNode(xmlNodePtr xml_node) {
1375 const auto &node_config = config_.GetNodeConfig();
1376
1377 if (!ValidateRequiredAttribute(xml_node, node_config.node_id_attribute)) {
1378 return nullptr;
1379 }
1380
1381 EmberCore::String decorator_type = GetNodeAttribute(xml_node, node_config.node_id_attribute);
1382
1383 // Validate this is actually a decorator type
1384 if (!config_.IsDecoratorType(decorator_type)) {
1385 const auto &classification_config = config_.GetClassificationConfig();
1386 if (classification_config.unknown_behavior == ParserConfig::UnknownTypeBehavior::ERROR) {
1387 AddError(ParseError::UNKNOWN_NODE_TYPE, "Unknown decorator type: " + decorator_type, xml_node);
1388 return nullptr;
1389 }
1390 LOG_WARNING("LibXMLParser", "Unknown decorator type '" + decorator_type + "', creating generic decorator node");
1391 }
1392
1393 auto node = std::make_unique<Node>(decorator_type, Node::Type::Decorator);
1394 LOG_TRACE("LibXMLParser", "Created decorator node: " + decorator_type);
1395
1396 return node;
1397}
1398
1399std::unique_ptr<Node> LibXMLBehaviorTreeParser::ParseSubTreeNode(xmlNodePtr xml_node) {
1400 const auto &tree_config = config_.GetTreeConfig();
1401
1402 if (!ValidateRequiredAttribute(xml_node, tree_config.subtree_reference_attribute)) {
1403 return nullptr;
1404 }
1405
1406 EmberCore::String subtree_id = GetNodeAttribute(xml_node, tree_config.subtree_reference_attribute);
1407
1408 // Create a placeholder node that will be expanded later (two-pass system)
1409 // This allows forward references where SubTree A references Tree B that appears later in XML
1410 // Use BehaviorTree type for SubTree placeholders (they reference other behavior trees)
1411 auto placeholder = std::make_unique<Node>("SubTree[" + subtree_id + "]", Node::Type::BehaviorTree);
1412 placeholder->SetAttribute("__subtree_ref__", subtree_id);
1413 placeholder->SetAttribute("__is_placeholder__", "true");
1414
1415 LOG_TRACE("LibXMLParser",
1416 "Created SubTree placeholder for '" + subtree_id + "' (will expand after all trees parsed)");
1417
1418 // TODO: Handle SubTree parameters and variable substitution
1419 // For now, we just store the reference and expand later
1420
1421 return placeholder;
1422}
1423
1424std::unique_ptr<Blackboard> LibXMLBehaviorTreeParser::ParseBlackboard(xmlNodePtr blackboard_node) {
1425 const auto &blackboard_config = config_.GetBlackboardConfig();
1426
1427 if (!ValidateRequiredAttribute(blackboard_node, blackboard_config.blackboard_id_attribute)) {
1428 return nullptr;
1429 }
1430
1431 EmberCore::String blackboard_id = GetNodeAttribute(blackboard_node, blackboard_config.blackboard_id_attribute);
1432 auto blackboard = std::make_unique<Blackboard>(blackboard_id);
1433
1434 // Check for parent attribute (inheritance)
1435 EmberCore::String parent_id = GetNodeAttribute(blackboard_node, blackboard_config.parent_attribute);
1436 if (!parent_id.empty()) {
1437 blackboard->SetParentId(parent_id);
1438 LOG_TRACE("LibXMLParser", "Blackboard '" + blackboard_id + "' inherits from '" + parent_id + "'");
1439 }
1440
1441 // Parse all Entry children
1442 xmlNodePtr child = blackboard_node->children;
1443 while (child) {
1444 if (child->type == XML_ELEMENT_NODE && GetNodeName(child) == blackboard_config.entry_element) {
1445 auto entry = ParseBlackboardEntry(child);
1446 if (entry) {
1447 blackboard->AddEntry(std::move(entry));
1448 }
1449 }
1450 child = child->next;
1451 }
1452
1453 LOG_TRACE("LibXMLParser", "Parsed blackboard '" + blackboard_id + "' with " +
1454 std::to_string(blackboard->GetEntryCount()) + " entries");
1455
1456 return blackboard;
1457}
1458
1459std::unique_ptr<BlackboardEntry> LibXMLBehaviorTreeParser::ParseBlackboardEntry(xmlNodePtr entry_node) {
1460 const auto &blackboard_config = config_.GetBlackboardConfig();
1461
1462 if (!ValidateRequiredAttribute(entry_node, blackboard_config.entry_key_attribute) ||
1463 !ValidateRequiredAttribute(entry_node, blackboard_config.entry_type_attribute)) {
1464 return nullptr;
1465 }
1466
1467 EmberCore::String key = GetNodeAttribute(entry_node, blackboard_config.entry_key_attribute);
1468 EmberCore::String type_str = GetNodeAttribute(entry_node, blackboard_config.entry_type_attribute);
1469 EmberCore::String value = GetNodeAttribute(entry_node, blackboard_config.entry_value_attribute);
1470
1472 if (data_type == BlackboardEntry::DataType::UNKNOWN) {
1473 if (!blackboard_config.allow_undefined_keys) {
1474 AddError(ParseError::INVALID_VALUE, "Unknown blackboard entry type: " + type_str, entry_node);
1475 return nullptr;
1476 }
1477 LOG_WARNING("LibXMLParser", "Unknown blackboard type '" + type_str + "', using AUTO");
1479 }
1480
1481 auto entry = std::make_unique<BlackboardEntry>(key, data_type, value);
1482
1483 if (!entry->IsValidValue()) {
1484 // For empty values on collection/complex types, just warn and continue
1485 // This is common for types like 'set', 'auto', etc. that may be initialized later
1486 LOG_WARNING("LibXMLParser", "Empty or invalid value '" + value + "' for type '" + type_str + "' (key: " + key +
1487 ") - will use default");
1488 // Don't fail parsing for this - it's not critical
1489 }
1490
1491 LOG_TRACE("LibXMLParser",
1492 "Parsed blackboard entry: " + key + " (" + type_str + ") = " + (value.empty() ? "<empty>" : value));
1493
1494 return entry;
1495}
1496
1497void LibXMLBehaviorTreeParser::SetNodeAttributes(Node *node, xmlNodePtr xml_node) {
1498 const auto &node_config = config_.GetNodeConfig();
1499
1500 // Set basic attributes using configured attribute names
1501 EmberCore::String name = GetNodeAttribute(xml_node, node_config.node_name_attribute);
1502 if (!name.empty()) {
1503 node->SetName(name);
1504 }
1505
1506 EmberCore::String id = GetNodeAttribute(xml_node, node_config.node_id_attribute);
1507 if (!id.empty() && name.empty()) {
1508 node->SetName(id); // Use ID as name if no explicit name specified
1509 }
1510
1511 // Explicitly store the ID attribute so it can be serialized back
1512 if (!id.empty()) {
1513 node->SetAttribute(node_config.node_id_attribute, id);
1514 }
1515
1516 // Parse and store all custom attributes (if allowed)
1517 if (node_config.allow_custom_attributes) {
1518 xmlAttrPtr attr = xml_node->properties;
1519 while (attr) {
1520 EmberCore::String attr_name = std::string(reinterpret_cast<const char *>(attr->name));
1521 EmberCore::String attr_value = std::string(reinterpret_cast<const char *>(attr->children->content));
1522
1523 // Store all attributes except the name attribute (already handled above)
1524 // ID attribute is handled explicitly above but we allow it to be stored again to avoid issues
1525 if (attr_name != node_config.node_name_attribute) {
1526 node->SetAttribute(attr_name, attr_value);
1527 LOG_TRACE("LibXMLParser", "Stored node attribute: " + attr_name + " = " + attr_value);
1528 }
1529
1530 attr = attr->next;
1531 }
1532 }
1533}
1534
1535void LibXMLBehaviorTreeParser::ParseChildNodes(Node *parent, xmlNodePtr xml_parent) {
1536 xmlNodePtr child = xml_parent->children;
1537 size_t children_added = 0;
1538
1539 while (child) {
1540 if (child->type == XML_ELEMENT_NODE) {
1541 auto child_node = ParseNode(child);
1542 if (child_node) {
1543 // Now we have unique_ptr, so we can move it directly
1544 parent->AddChild(std::move(child_node));
1545 children_added++;
1546 LOG_TRACE("LibXMLParser", "Added child node to " + parent->GetName());
1547 } else {
1548 LOG_TRACE("LibXMLParser", "Skipped child node for " + parent->GetName());
1549 }
1550 }
1551 child = child->next;
1552 }
1553
1554 // Log if a parent ended up with no children (this might indicate SubTree skipping)
1555 if (children_added == 0 && xml_parent->children) {
1556 LOG_WARNING("LibXMLParser",
1557 "Node '" + parent->GetName() +
1558 "' ended up with no children after parsing (likely due to skipped SubTree nodes)");
1559 }
1560}
1561
1563 // Clear cache before expansion
1565 expansion_stack_.clear(); // Clear the stack tracking for circular reference detection
1566
1567 for (auto &tree_pair : parsed_trees_) {
1568 auto &tree = tree_pair.second;
1569 if (tree && tree->HasRootNode()) {
1570 ExpandSubTreePlaceholder(tree->GetRootNode());
1571 }
1572 }
1573}
1574
1576 if (!node)
1577 return false;
1578
1579 bool expanded_any = false;
1580
1581 // Check if this node is a SubTree placeholder
1582 EmberCore::String subtree_ref = node->GetAttribute("__subtree_ref__", "");
1583 if (!subtree_ref.empty()) {
1584 // This is a SubTree placeholder node - expand it
1585
1586 if (parsed_trees_.find(subtree_ref) != parsed_trees_.end()) {
1587 auto referenced_tree = parsed_trees_[subtree_ref];
1588 if (referenced_tree && referenced_tree->HasRootNode()) {
1589 Node *referenced_root = referenced_tree->GetRootNode();
1590
1591 // Check if this subtree is currently being expanded (circular reference)
1592 // OR if it has already been fully expanded (cache hit)
1593 bool is_expanding = (expansion_stack_.find(subtree_ref) != expansion_stack_.end());
1594 bool already_expanded = (expanded_subtree_cache_.find(subtree_ref) != expanded_subtree_cache_.end());
1595
1596 if (is_expanding) {
1597 // We're in a circular reference - abort
1598 AddError(ParseError::INVALID_TREE_STRUCTURE, "Circular SubTree reference detected: " + subtree_ref);
1599 LOG_ERROR("LibXMLParser", "Circular SubTree reference detected: " + subtree_ref);
1600 return false;
1601 }
1602
1603 if (!already_expanded) {
1604 // First time expanding this subtree - mark as being expanded
1605 expansion_stack_.insert(subtree_ref);
1606
1607 // Recursively expand the referenced tree's root and its children
1608 ExpandSubTreePlaceholder(referenced_root);
1609
1610 // Mark as fully expanded in cache
1611 expanded_subtree_cache_.insert(subtree_ref);
1612
1613 // Remove from expansion stack - this subtree is now safe to reference
1614 expansion_stack_.erase(subtree_ref);
1615 }
1616
1617 // Copy properties and children from the (now fully expanded) referenced_root
1618 node->SetName(referenced_root->GetName());
1619 node->SetType(referenced_root->GetType());
1620 node->RemoveAttribute("__is_placeholder__");
1621
1622 // Copy attributes from referenced tree
1623 for (const auto &attr_pair : referenced_root->GetAllAttributes()) {
1624 node->SetAttribute(attr_pair.first, attr_pair.second);
1625 }
1626
1627 // Deep copy children (which are already fully expanded)
1628 for (size_t i = 0; i < referenced_root->GetChildCount(); ++i) {
1629 Node *child = referenced_root->GetChild(i);
1630 if (child) {
1631 node->AddChild(child->DeepCopy());
1632 }
1633 }
1634
1635 // Since we deep copied from an already-expanded tree,
1636 // we DON'T need to expand the copied children again
1637
1638 expanded_any = true;
1639 } else {
1640 // Referenced tree exists but is empty - mark as unimplemented
1641 node->RemoveAttribute("__is_placeholder__");
1642 node->SetAttribute("__unimplemented__", "true");
1643 node->SetName("SubTree: " + subtree_ref + " [EMPTY]");
1644 LOG_WARNING("LibXMLParser", "SubTree '" + subtree_ref + "' is empty (no root node)");
1645 }
1646 } else {
1647 // SubTree not found - mark as unimplemented instead of leaving as placeholder
1648 // This allows the tree to be used even with missing subtree references
1649 node->RemoveAttribute("__is_placeholder__");
1650 node->SetAttribute("__unimplemented__", "true");
1651 node->SetName("SubTree: " + subtree_ref + " [NOT IMPLEMENTED]");
1652 LOG_WARNING("LibXMLParser", "SubTree '" + subtree_ref + "' not found (unimplemented reference)");
1653 }
1654 } else {
1655 // Not a subtree placeholder, just recursively expand children
1656 for (size_t i = 0; i < node->GetChildCount(); ++i) {
1657 if (ExpandSubTreePlaceholder(node->GetChild(i))) {
1658 expanded_any = true;
1659 }
1660 }
1661 }
1662
1663 return expanded_any;
1664}
1665
1667 if (!node) {
1668 AddError(ParseError::MISSING_ATTRIBUTE, "Node is null when validating attribute '" + attr_name + "'");
1669 return false;
1670 }
1671
1672 EmberCore::String value = GetNodeAttribute(node, attr_name);
1673 if (value.empty()) {
1674 AddError(ParseError::MISSING_ATTRIBUTE, "Required attribute '" + attr_name + "' is missing", node);
1675 return false;
1676 }
1677
1678 return true;
1679}
1680
1681void LibXMLBehaviorTreeParser::CaptureComments(xmlNodePtr parent, BehaviorTree *tree, Node *node) {
1682 if (!parent || !tree) {
1683 return;
1684 }
1685
1686 auto &xml_metadata = tree->GetXMLMetadata();
1687
1688 // Iterate through all children to find comments
1689 for (xmlNodePtr child = parent->children; child; child = child->next) {
1690 if (child->type == XML_COMMENT_NODE) {
1691 // Extract comment text
1692 xmlChar *content = xmlNodeGetContent(child);
1693 if (content) {
1694 EmberCore::String comment_text = reinterpret_cast<const char *>(content);
1695 xmlFree(content);
1696
1697 // Determine if this comment is before or after a node
1698 bool before_node = true;
1699 xmlNodePtr next_element = child->next;
1700 while (next_element && next_element->type != XML_ELEMENT_NODE) {
1701 next_element = next_element->next;
1702 }
1703
1704 if (!next_element) {
1705 before_node = false; // Comment after last element
1706 }
1707
1708 if (node) {
1709 // Associate comment with specific node
1710 XMLMetadata::Comment comment;
1711 comment.text = comment_text;
1712 comment.before_node = before_node;
1713 xml_metadata.node_comments[node->GetId()].push_back(comment);
1714 } else {
1715 // Document-level comment
1716 if (before_node) {
1717 xml_metadata.header_comments.push_back(comment_text);
1718 } else {
1719 xml_metadata.footer_comments.push_back(comment_text);
1720 }
1721 }
1722 }
1723 }
1724 }
1725}
1726
1727} // namespace EmberCore
#define LOG_ERROR(category, message)
Definition Logger.h:116
#define LOG_TRACE(category, message)
Definition Logger.h:113
#define LOG_WARNING(category, message)
Definition Logger.h:115
#define LOG_INFO(category, message)
Definition Logger.h:114
Represents a BehaviorTree project containing multiple XML resources.
void SetTreeImplementationStatus(const std::map< String, TreeImplementationStatus > &statuses)
const std::vector< String > & GetResources() const
String ResolveResourcePath(const String &resource_path) const
Unified validation system for behavior trees.
ValidationResult Validate(const BehaviorTree *tree) const
Validate a behavior tree against the parser profile.
Represents a complete behavior tree data structure.
XMLMetadata & GetXMLMetadata()
static DataType ParseDataType(const EmberCore::String &typeStr)
DataType
Supported data types for blackboard entries.
std::unique_ptr< Node > ParseNode(xmlNodePtr xml_node)
std::shared_ptr< BehaviorTree > ParseFromString(const EmberCore::String &xml_content)
std::vector< EmberCore::String > GetUnimplementedReferences() const
ProjectParseResult ParseFilesWithSharedRegistry(const std::vector< EmberCore::String > &filepaths)
std::set< EmberCore::String > unimplemented_references_
std::set< EmberCore::String > circular_references_
std::unique_ptr< Node > ParseSubTreeNode(xmlNodePtr xml_node)
std::map< EmberCore::String, TreeImplementationStatus > tree_implementation_statuses_
std::unique_ptr< Node > ParseActionNode(xmlNodePtr xml_node)
void ParseChildNodes(Node *parent, xmlNodePtr xml_parent)
bool ParseXMLDocument(xmlDocPtr doc, const EmberCore::String &source_path="")
void AddError(ParseError::Type type, const EmberCore::String &message, xmlNodePtr node=nullptr, const EmberCore::String &context="")
std::unique_ptr< BlackboardEntry > ParseBlackboardEntry(xmlNodePtr entry_node)
std::unique_ptr< Node > ParseConditionNode(xmlNodePtr xml_node)
void CaptureComments(xmlNodePtr parent, BehaviorTree *tree, Node *node=nullptr)
std::set< EmberCore::String > expansion_stack_
void CollectSubTreeReferences(Node *node, std::set< EmberCore::String > &references)
std::unique_ptr< Node > ParseControlNode(xmlNodePtr xml_node)
std::map< EmberCore::String, std::shared_ptr< BehaviorTree > > parsed_trees_
const std::vector< ParseError > & GetErrors() const
EmberCore::String GetNodeAttribute(xmlNodePtr node, const EmberCore::String &attr_name)
EmberCore::String GetNodePath(xmlNodePtr node)
std::unique_ptr< Blackboard > ParseBlackboard(xmlNodePtr blackboard_node)
EmberCore::String GetNodeName(xmlNodePtr node)
ProjectParseResult ParseProject(BehaviorTreeProject *project)
void SetNodeAttributes(Node *node, xmlNodePtr xml_node)
std::shared_ptr< BehaviorTree > ParseFromFile(const EmberCore::String &filepath)
bool IsTreeImplemented(const EmberCore::String &tree_id) const
std::set< EmberCore::String > expanded_subtree_cache_
std::shared_ptr< BehaviorTree > ParseBehaviorTree(xmlNodePtr tree_node)
std::map< EmberCore::String, std::unique_ptr< Blackboard > > parsed_blackboards_
std::unique_ptr< Node > ParseDecoratorNode(xmlNodePtr xml_node)
std::vector< ParseResult > ParseMultipleFiles(const std::vector< EmberCore::String > &filepaths)
bool ReportProgress(const EmberCore::String &message, int current=0, int total=0)
bool ValidateRequiredAttribute(xmlNodePtr node, const EmberCore::String &attr_name)
Represents a node in a behavior tree structure.
Definition Node.h:20
void SetType(Type type)
Definition Node.h:85
void SetName(const String &name)
Definition Node.h:82
const std::map< String, String > & GetAllAttributes() const
Definition Node.cpp:462
String GetAttribute(const String &name, const String &default_value="") const
Definition Node.cpp:451
Node * GetChild(size_t index) const
Definition Node.cpp:175
size_t GetId() const
Definition Node.h:80
Type GetType() const
Definition Node.h:84
const String & GetName() const
Definition Node.h:81
void SetAttribute(const String &name, const String &value)
Definition Node.cpp:444
void RemoveAttribute(const String &name)
Definition Node.cpp:460
void AddChild(std::unique_ptr< Node > child)
Definition Node.cpp:77
size_t GetChildCount() const
Definition Node.h:76
std::unique_ptr< Node > DeepCopy() const
Definition Node.cpp:149
Configuration for XML parser behavior and element/attribute mappings.
Main types header for EmberCore.
static void SuppressLibXMLErrors(void *ctx, const char *msg,...)
std::string String
Framework-agnostic string type.
Definition String.h:14
Per-file parsing information for project validation.
Error information for parsing failures (enhanced with libxml2 details)
std::map< EmberCore::String, TreeImplementationStatus > tree_statuses
std::map< EmberCore::String, std::shared_ptr< BehaviorTree > > parsed_trees
std::map< EmberCore::String, std::shared_ptr< Blackboard > > parsed_blackboards
Status of a tree's implementation in the project.
String defined_in_file
Which file defines this tree (empty if not defined)
bool has_root_node
Whether tree has a root node.
bool is_implemented
Has actual implementation (not just empty/placeholder)