-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_readme.py
More file actions
executable file
·2054 lines (1707 loc) · 69.9 KB
/
Copy pathgenerate_readme.py
File metadata and controls
executable file
·2054 lines (1707 loc) · 69.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright Institute for Automotive Engineering (ika), RWTH Aachen University
# SPDX-License-Identifier: Apache-2.0
"""
Auto-generates ROS2 interface documentation (topics, actions, parameters)
by parsing C++ source files in a ROS2 repository and writing full package
README.md files next to package.xml.
Usage:
python3 scripts/generate_readme.py [REPO_ROOT]
REPO_ROOT defaults to the script's parent directory.
The READMEs generated are <package_dir>/README.md for discovered ROS packages.
"""
import difflib
import ast
import re
import subprocess
import sys
from codecs import decode as codecs_decode
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Optional
from xml.etree import ElementTree
try:
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
except ModuleNotFoundError as exc:
if exc.name == 'jinja2':
Environment = None
FileSystemLoader = None
TemplateNotFound = Exception
else:
raise
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class TopicInterface:
name: str
msg_type: str
TRANSPORT_MESSAGE_TYPES = {
'image_transport': 'sensor_msgs/msg/Image',
'point_cloud_transport': 'sensor_msgs/msg/PointCloud2',
}
TRANSPORT_SUBSCRIBE_TOPIC_ARGUMENTS = {
'point_cloud_transport::SubscriberFilter': 1,
}
@dataclass
class ActionInterface:
name: str
action_type: str
@dataclass
class ServiceInterface:
name: str
srv_type: str
@dataclass
class Parameter:
name: str
ros_type: str
default: str
description: str
@dataclass
class NodeInterfaces:
node_name: str
subscribers: list = field(default_factory=list)
publishers: list = field(default_factory=list)
service_servers: list = field(default_factory=list)
action_servers: list = field(default_factory=list)
action_clients: list = field(default_factory=list)
parameters: list = field(default_factory=list)
@dataclass
class RepoMetadata:
host: str
provider: str
owner: str
repo: str
owner_lower: str
pages_url: str
repo_https_url: str
container_image: str
@dataclass
class PackageSection:
title: str
kind: str
interface_entries: list = field(default_factory=list)
nodes: list = field(default_factory=list)
launch_files: list = field(default_factory=list)
@dataclass
class PackageTemplateContext:
package_name: str
package_description: str
sections: list[PackageSection]
@dataclass
class PackageDocEntry:
name: str
path: str
description: str
@dataclass
class InterfaceTableRow:
name: str
interface_type: str
description: str
@dataclass
class InterfaceDefinitionEntry:
full_type: str
rel_path: str
description: str
@dataclass
class LaunchArgumentRow:
name: str
default: str
description: str
@dataclass
class LaunchFileTemplateContext:
name: str
rel_path: str
arguments: list[LaunchArgumentRow]
@dataclass
class NodeTemplateContext:
node_name: str
manual_text: str
subscribers: list[InterfaceTableRow]
publishers: list[InterfaceTableRow]
service_servers: list[InterfaceTableRow]
action_servers: list[InterfaceTableRow]
action_clients: list[InterfaceTableRow]
parameters: list[Parameter]
@dataclass
class TopLevelTemplateContext:
title: str
repo_name: str
owner: str
owner_lower: str
provider: str
pages_url: str
repo_https_url: str
container_image: str
intro_block: Optional[str]
pre_quickstart_block: str
quickstart_body: Optional[str]
quickstart_package: str
quickstart_launch_file: str
repository_packages: list[PackageDocEntry]
licensing_extra_body: str
acknowledgements_body: Optional[str]
# ---------------------------------------------------------------------------
# Type helpers
# ---------------------------------------------------------------------------
MANUAL_TABLE_HEADERS = {
'| Topic | Type | Description |': 'topic',
'| Action | Type | Description |': 'action',
'| Service | Type | Description |': 'service',
'| Type | Description |': 'interface',
'| Argument | Default | Description |': 'launch_arg',
}
def cpp_ros_type(cpp_type: str, type_aliases: dict) -> str:
"""Resolve type aliases and convert C++ ROS type to ROS notation (:: -> /)."""
t = cpp_type.strip()
t = type_aliases.get(t, t)
for alias, target in type_aliases.items():
if t.startswith(f'{alias}::'):
t = f'{target}::{t[len(alias) + 2:]}'
break
return t.replace('::', '/').strip()
PYTHON_PARAM_TYPE_MAP = {
'BOOL': 'bool',
'INTEGER': 'int',
'DOUBLE': 'float',
'STRING': 'string',
'BYTE_ARRAY': 'byte[]',
'BOOL_ARRAY': 'bool[]',
'INTEGER_ARRAY': 'int[]',
'DOUBLE_ARRAY': 'float[]',
'STRING_ARRAY': 'string[]',
}
def cpp_param_type(cpp_type: str) -> str:
"""Map C++ type to ROS parameter type name."""
t = cpp_type.strip()
if t in ('double', 'float'):
return 'float'
if t in ('int', 'long', 'long int', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t'):
return 'int'
if t == 'bool':
return 'bool'
if t == 'std::string':
return 'string'
vector_match = re.match(r'std::vector\s*<\s*([^>]+)\s*>', t)
if vector_match:
element_type = vector_match.group(1).strip()
if element_type in ('double', 'float'):
return 'float[]'
if element_type in ('int', 'long', 'long int', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t'):
return 'int[]'
if element_type == 'bool':
return 'bool[]'
if element_type == 'std::string':
return 'string[]'
return f'{element_type}[]'
return t
def format_default(default_str: Optional[str], cpp_type: str, enum_value_map: dict[str, str]) -> str:
"""Format a C++ default value for Markdown display."""
if default_str is None:
return '[]' if 'vector' in cpp_type else ''
formatted = default_str.strip()
if formatted in enum_value_map:
return enum_value_map[formatted]
if 'vector' in cpp_type and formatted.startswith('{') and formatted.endswith('}'):
return f'[{formatted[1:-1].strip()}]'
return formatted
# ---------------------------------------------------------------------------
# Discovery
# ---------------------------------------------------------------------------
def git_tracked_files(repo_root: Path) -> list[Path]:
"""Return files tracked by the target repository without descending into submodules."""
result = subprocess.run(
['git', 'ls-files', '-z'],
cwd=repo_root,
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or 'git ls-files failed')
return [repo_root / path for path in result.stdout.split('\0') if path]
def find_packages(repo_root: Path) -> list:
"""Return [(package_name, package_dir, package_description)] for ROS packages."""
packages = []
package_xmls = sorted(path for path in git_tracked_files(repo_root) if path.name == 'package.xml')
for pkg_xml in package_xmls:
if not pkg_xml.is_file():
continue
try:
root = ElementTree.parse(pkg_xml).getroot()
name_el = root.find('name')
description_el = root.find('description')
if name_el is not None and name_el.text:
description = ''
if description_el is not None and description_el.text:
description = ' '.join(description_el.text.split())
packages.append((name_el.text.strip(), pkg_xml.parent, description))
except ElementTree.ParseError:
pass
return packages
def find_node_sources(package_dir: Path) -> list:
"""Return .cpp files that define a ROS node (contain ': Node("..." )')."""
node_pattern = re.compile(r':\s*(?:(?:\w+)::)*Node\s*\(')
return [
cpp for cpp in sorted(package_dir.rglob('*.cpp'))
if node_pattern.search(cpp.read_text(errors='replace'))
]
def python_defines_node(source: str) -> bool:
"""Return whether the Python source defines a class deriving from rclpy's Node."""
try:
tree = ast.parse(source)
except SyntaxError:
return False
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
for base in node.bases:
base_name = base.attr if isinstance(base, ast.Attribute) else getattr(base, 'id', '')
if base_name == 'Node':
return True
return False
def find_python_node_sources(package_dir: Path) -> list:
"""Return .py files that define a ROS node (a class deriving from Node)."""
return [
py for py in sorted(package_dir.rglob('*.py'))
if python_defines_node(py.read_text(errors='replace'))
]
def find_headers(package_dir: Path) -> list:
"""Return all header files (.hpp, .h) in the package."""
return [
p for ext in ('*.hpp', '*.h')
for p in sorted(package_dir.rglob(ext))
]
def find_interface_files(package_dir: Path, subdir: str, ext: str) -> list:
"""Return sorted list of interface definition files in package_dir/subdir/."""
iface_dir = package_dir / subdir
if not iface_dir.is_dir():
return []
return sorted(iface_dir.glob(f'*.{ext}'))
def find_launch_files(package_dir: Path) -> list:
"""Return launch files (.py, .xml, .yaml) found in any launch/ subdirectory."""
launch_dir = package_dir / 'launch'
if not launch_dir.is_dir():
return []
return [
p for ext in ('*.py', '*.xml', '*.yaml', '*.yml')
for p in sorted(launch_dir.rglob(ext))
]
# ---------------------------------------------------------------------------
# Extraction from source/header text
# ---------------------------------------------------------------------------
def extract_node_name(source: str) -> Optional[str]:
m = re.search(r':\s*(?:(?:\w+)::)*Node\s*\(\s*"([^"]+)"', source)
return m.group(1) if m else None
def extract_cpp_string_symbols(source: str) -> dict[str, str]:
"""Return simple C++ string constants and local aliases found in source."""
symbols: dict[str, str] = {}
string_literal = r'(?:u8|u|U|L)?"((?:\\.|[^"\\])*)"'
const_patterns = (
rf'\b(?:static\s+)?(?:inline\s+)?(?:constexpr\s+)?(?:const\s+)?(?:std::string|char\s*(?:const)?\s*\*|const\s+char\s*\*)\s+'
rf'((?:(?:\w+)::)?\w+)\s*=\s*({string_literal})\s*;',
rf'\b(?:static\s+)?(?:inline\s+)?(?:constexpr\s+)?(?:const\s+)?(?:std::string|char\s*(?:const)?\s*\*|const\s+char\s*\*)\s+'
rf'((?:(?:\w+)::)?\w+)\s*\{{\s*({string_literal})\s*\}}\s*;',
rf'\b(?:static\s+)?(?:inline\s+)?(?:constexpr\s+)?(?:const\s+)?char\s+'
rf'((?:(?:\w+)::)?\w+)\s*\[[^\]]*\]\s*=\s*({string_literal})\s*;',
)
for pattern in const_patterns:
for match in re.finditer(pattern, source):
name = match.group(1)
value = decode_cpp_string_literal(match.group(3))
symbols[name] = value
symbols[name.split('::')[-1]] = value
local_pattern = re.compile(r'\bstd::string\s+(\w+)\s*=\s*([^;]+);', re.DOTALL)
for match in local_pattern.finditer(source):
value = resolve_cpp_string_expression(match.group(2), symbols)
if value:
symbols[match.group(1)] = value
return symbols
def resolve_cpp_string_expression(expr: str, symbols: dict[str, str]) -> Optional[str]:
"""Resolve string literals, known string symbols, and simple topic resolution wrappers."""
expr = expr.strip()
if not expr:
return None
resolve_match = re.search(r'resolve_topic_name\s*\((.*)\)', expr, re.DOTALL)
if resolve_match:
return resolve_cpp_string_expression(resolve_match.group(1), symbols)
literal_expr_pattern = re.compile(r'(?:\s*(?:u8|u|U|L)?"((?:\\.|[^"\\])*"))+\s*\Z', re.DOTALL)
literal_expr_match = literal_expr_pattern.fullmatch(expr)
if literal_expr_match:
literal_pattern = re.compile(r'(?:u8|u|U|L)?"((?:\\.|[^"\\])*)"', re.DOTALL)
return ''.join(
decode_cpp_string_literal(match.group(1))
for match in literal_pattern.finditer(expr)
)
cleaned = re.sub(r'\bthis->', '', expr)
cleaned = cleaned.strip('() ')
if cleaned in symbols:
return symbols[cleaned]
if cleaned.split('::')[-1] in symbols:
return symbols[cleaned.split('::')[-1]]
return ' '.join(expr.split())
def find_cpp_templated_call_bodies(source: str, function_name: str) -> list[tuple[str, str]]:
"""Return [(template_argument, call_body)] for C++ calls with one template argument."""
calls = []
pattern = re.compile(rf'(?<!::)\b{re.escape(function_name)}\s*<([^>]+)>\s*\(')
for match in pattern.finditer(source):
start = match.end()
depth = 1
i = start
while i < len(source) and depth > 0:
if source[i] == '(':
depth += 1
elif source[i] == ')':
depth -= 1
i += 1
if depth == 0:
calls.append((match.group(1).strip(), source[start:i - 1]))
return calls
def find_cpp_member_call_bodies(source: str, function_name: str) -> list[tuple[str, str]]:
"""Return [(receiver_expression, call_body)] for C++ member calls."""
calls = []
pattern = re.compile(
rf'(?P<receiver>(?:this->)?\w+(?:\s*(?:->|\.)\s*\w+)*)\s*(?:->|\.)\s*{re.escape(function_name)}\s*\('
)
for match in pattern.finditer(source):
start = match.end()
depth = 1
i = start
while i < len(source) and depth > 0:
if source[i] == '(':
depth += 1
elif source[i] == ')':
depth -= 1
i += 1
if depth == 0:
calls.append((match.group('receiver').strip(), source[start:i - 1]))
return calls
def find_cpp_qualified_call_bodies(source: str, function_name: str) -> list[tuple[str, str]]:
"""Return [(namespace_or_class, call_body)] for C++ qualified calls."""
calls = []
pattern = re.compile(rf'\b((?:\w+::)+){re.escape(function_name)}\s*\(')
for match in pattern.finditer(source):
start = match.end()
depth = 1
i = start
while i < len(source) and depth > 0:
if source[i] == '(':
depth += 1
elif source[i] == ')':
depth -= 1
i += 1
if depth == 0:
calls.append((match.group(1).rstrip(':'), source[start:i - 1]))
return calls
def unwrap_cpp_type(cpp_type: str) -> str:
"""Remove common ownership wrappers around a C++ type."""
stripped = re.sub(r'\s+', '', cpp_type)
wrapper_match = re.fullmatch(r'(?:std::)?(?:unique_ptr|shared_ptr|weak_ptr)<(.+)>', stripped)
if wrapper_match:
return wrapper_match.group(1)
return stripped
def extract_cpp_variable_types(source: str) -> dict[str, str]:
"""Return variable/member names mapped to declared C++ types."""
variable_types: dict[str, str] = {}
type_token = r'(?:std::(?:unique_ptr|shared_ptr|weak_ptr)<\s*)?(?:(?:\w+)::)*\w+(?:\s*>)?'
pattern = re.compile(rf'\b({type_token})\s+(\w+)\s*(?:[;=({{])')
for match in pattern.finditer(source):
cpp_type = unwrap_cpp_type(match.group(1))
variable_types[match.group(2)] = cpp_type
make_shared_pattern = re.compile(
r'\bauto\s+(\w+)\s*=\s*std::make_shared\s*<\s*([^>]+)\s*>\s*\('
)
for match in make_shared_pattern.finditer(source):
variable_types[match.group(1)] = match.group(2).strip()
return variable_types
def transport_message_type_from_cpp_type(cpp_type: str, aliases: dict) -> Optional[str]:
"""Infer message type for known ROS transport helper classes."""
resolved = aliases.get(cpp_type, cpp_type)
for namespace, msg_type in TRANSPORT_MESSAGE_TYPES.items():
if resolved == namespace or resolved.startswith(f'{namespace}::'):
return msg_type
return None
def transport_message_type_from_receiver(receiver: str, variable_types: dict[str, str], aliases: dict) -> Optional[str]:
"""Infer message type for member transport calls from the receiver object."""
cleaned = re.sub(r'\bthis->', '', receiver).strip()
root = re.split(r'\s*(?:->|\.)\s*', cleaned, maxsplit=1)[0]
cpp_type = variable_types.get(root)
if cpp_type:
return transport_message_type_from_cpp_type(cpp_type, aliases)
return transport_message_type_from_cpp_type(root, aliases)
def transport_subscribe_topic_argument(
args: list[str],
receiver: str,
variable_types: dict[str, str],
aliases: dict,
) -> Optional[str]:
"""Return the topic argument from a transport subscribe call."""
cleaned = re.sub(r'\bthis->', '', receiver).strip()
root = re.split(r'\s*(?:->|\.)\s*', cleaned, maxsplit=1)[0]
cpp_type = variable_types.get(root, root)
resolved_type = aliases.get(cpp_type, cpp_type)
topic_index = TRANSPORT_SUBSCRIBE_TOPIC_ARGUMENTS.get(resolved_type, 0)
return args[topic_index] if len(args) > topic_index else None
def is_transport_like(cpp_name: str) -> bool:
"""Return whether a C++ receiver/type/qualifier looks like a ROS transport helper."""
return 'transport' in cpp_name.lower()
def unknown_transport_message(function_name: str, transport_name: str) -> str:
"""Return a clear error for unsupported transport helper APIs."""
known = ', '.join(sorted(TRANSPORT_MESSAGE_TYPES))
return (
f'Unable to infer ROS message type for transport call {transport_name}.{function_name}(...). '
f'Add the transport to TRANSPORT_MESSAGE_TYPES. Known transports: {known}.'
)
def should_fail_unknown_transport(receiver: str, variable_types: dict[str, str]) -> bool:
"""Return whether an unknown member call likely belongs to a transport helper."""
cleaned = re.sub(r'\bthis->', '', receiver).strip()
root = re.split(r'\s*(?:->|\.)\s*', cleaned, maxsplit=1)[0]
return is_transport_like(receiver) or is_transport_like(variable_types.get(root, ''))
def unique_topic_interfaces(interfaces: list[TopicInterface]) -> list[TopicInterface]:
"""Return interfaces with duplicate topic/type pairs removed while preserving order."""
seen: set[tuple[str, str]] = set()
result = []
for interface in interfaces:
key = (interface.name, interface.msg_type)
if key in seen:
continue
seen.add(key)
result.append(interface)
return result
def extract_subscribers(source: str, aliases: dict, string_symbols: dict[str, str], variable_types: dict[str, str]) -> list:
subscribers = []
for cpp_type, call_body in find_cpp_templated_call_bodies(source, 'create_subscription'):
args = split_cpp_arguments(call_body)
if not args:
continue
topic = resolve_cpp_string_expression(args[0], string_symbols)
if topic:
subscribers.append(TopicInterface(name=topic, msg_type=cpp_ros_type(cpp_type, aliases)))
for receiver, call_body in find_cpp_member_call_bodies(source, 'subscribe'):
args = split_cpp_arguments(call_body)
if not args:
continue
topic_arg = transport_subscribe_topic_argument(args, receiver, variable_types, aliases)
topic = resolve_cpp_string_expression(topic_arg, string_symbols) if topic_arg else None
msg_type = transport_message_type_from_receiver(receiver, variable_types, aliases)
if topic and msg_type:
subscribers.append(TopicInterface(name=topic, msg_type=msg_type))
elif topic and should_fail_unknown_transport(receiver, variable_types):
raise RuntimeError(unknown_transport_message('subscribe', receiver))
for qualifier, call_body in find_cpp_qualified_call_bodies(source, 'create_subscription'):
args = split_cpp_arguments(call_body)
if len(args) < 2:
continue
topic = resolve_cpp_string_expression(args[1], string_symbols)
msg_type = transport_message_type_from_cpp_type(qualifier, aliases)
if topic and msg_type:
subscribers.append(TopicInterface(name=topic, msg_type=msg_type))
elif topic and is_transport_like(qualifier):
raise RuntimeError(unknown_transport_message('create_subscription', qualifier))
return unique_topic_interfaces(subscribers)
def extract_publishers(source: str, aliases: dict, string_symbols: dict[str, str], variable_types: dict[str, str]) -> list:
publishers = []
for cpp_type, call_body in find_cpp_templated_call_bodies(source, 'create_publisher'):
args = split_cpp_arguments(call_body)
if not args:
continue
topic = resolve_cpp_string_expression(args[0], string_symbols)
if topic:
publishers.append(TopicInterface(name=topic, msg_type=cpp_ros_type(cpp_type, aliases)))
for receiver, call_body in find_cpp_member_call_bodies(source, 'advertise'):
args = split_cpp_arguments(call_body)
if not args:
continue
topic = resolve_cpp_string_expression(args[0], string_symbols)
msg_type = transport_message_type_from_receiver(receiver, variable_types, aliases)
if topic and msg_type:
publishers.append(TopicInterface(name=topic, msg_type=msg_type))
elif topic and should_fail_unknown_transport(receiver, variable_types):
raise RuntimeError(unknown_transport_message('advertise', receiver))
for qualifier, call_body in find_cpp_qualified_call_bodies(source, 'create_publisher'):
args = split_cpp_arguments(call_body)
if len(args) < 2:
continue
topic = resolve_cpp_string_expression(args[1], string_symbols)
msg_type = transport_message_type_from_cpp_type(qualifier, aliases)
if topic and msg_type:
publishers.append(TopicInterface(name=topic, msg_type=msg_type))
elif topic and is_transport_like(qualifier):
raise RuntimeError(unknown_transport_message('create_publisher', qualifier))
return unique_topic_interfaces(publishers)
def extract_action_servers(source: str, aliases: dict) -> list:
return [
ActionInterface(name=m.group(2), action_type=cpp_ros_type(m.group(1), aliases))
for m in re.finditer(
r'rclcpp_action::create_server\s*<([^>]+)>\s*\(\s*this\s*,\s*"([^"]+)"', source)
]
def extract_action_clients(source: str, aliases: dict) -> list:
return [
ActionInterface(name=m.group(2), action_type=cpp_ros_type(m.group(1), aliases))
for m in re.finditer(
r'rclcpp_action::create_client\s*<([^>]+)>\s*\(\s*this\s*,\s*"([^"]+)"', source)
]
def extract_service_servers(source: str, aliases: dict) -> list:
return [
ServiceInterface(name=m.group(2), srv_type=cpp_ros_type(m.group(1), aliases))
for m in re.finditer(r'create_service\s*<([^>]+)>\s*\(\s*"([^"]+)"', source)
]
def find_cpp_call_bodies(source: str, function_name: str) -> list[str]:
"""Return the argument body of each function call, excluding declarations/definitions."""
bodies = []
pattern = re.compile(rf'(?<!::)\b{re.escape(function_name)}\s*\(')
for match in pattern.finditer(source):
start = match.end()
depth = 1
i = start
in_string = False
in_char = False
in_line_comment = False
in_block_comment = False
escaped = False
while i < len(source) and depth > 0:
char = source[i]
next_char = source[i + 1] if i + 1 < len(source) else ''
if in_line_comment:
if char == '\n':
in_line_comment = False
i += 1
continue
if in_block_comment:
if char == '*' and next_char == '/':
in_block_comment = False
i += 2
else:
i += 1
continue
if in_string:
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char == '"':
in_string = False
i += 1
continue
if in_char:
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char == "'":
in_char = False
i += 1
continue
if char == '/' and next_char == '/':
in_line_comment = True
i += 2
continue
if char == '/' and next_char == '*':
in_block_comment = True
i += 2
continue
if char == '"':
in_string = True
i += 1
continue
if char == "'":
in_char = True
i += 1
continue
if char == '(':
depth += 1
elif char == ')':
depth -= 1
i += 1
if depth == 0:
bodies.append(source[start:i - 1])
return bodies
def split_cpp_arguments(call_body: str) -> list[str]:
"""Split a C++ call body into top-level arguments."""
args = []
current = []
paren_depth = 0
brace_depth = 0
bracket_depth = 0
in_string = False
in_char = False
in_line_comment = False
in_block_comment = False
escaped = False
i = 0
while i < len(call_body):
char = call_body[i]
next_char = call_body[i + 1] if i + 1 < len(call_body) else ''
if in_line_comment:
current.append(char)
if char == '\n':
in_line_comment = False
i += 1
continue
if in_block_comment:
current.append(char)
if char == '*' and next_char == '/':
current.append(next_char)
in_block_comment = False
i += 2
else:
i += 1
continue
if in_string:
current.append(char)
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char == '"':
in_string = False
i += 1
continue
if in_char:
current.append(char)
if escaped:
escaped = False
elif char == '\\':
escaped = True
elif char == "'":
in_char = False
i += 1
continue
if char == '/' and next_char == '/':
current.extend([char, next_char])
in_line_comment = True
i += 2
continue
if char == '/' and next_char == '*':
current.extend([char, next_char])
in_block_comment = True
i += 2
continue
if char == '"':
current.append(char)
in_string = True
i += 1
continue
if char == "'":
current.append(char)
in_char = True
i += 1
continue
if char == '(':
paren_depth += 1
elif char == ')':
paren_depth -= 1
elif char == '{':
brace_depth += 1
elif char == '}':
brace_depth -= 1
elif char == '[':
bracket_depth += 1
elif char == ']':
bracket_depth -= 1
elif char == ',' and paren_depth == 0 and brace_depth == 0 and bracket_depth == 0:
args.append(''.join(current).strip())
current = []
i += 1
continue
current.append(char)
i += 1
trailing = ''.join(current).strip()
if trailing:
args.append(trailing)
return args
def decode_cpp_string_literal(text: str) -> str:
"""Decode the content of a regular C++ string literal."""
return codecs_decode(text, 'unicode_escape')
def extract_cpp_string_expression(expr: str) -> str:
"""Collapse adjacent C++ string literals into a single Python string."""
literal_pattern = re.compile(r'(?:u8|u|U|L)?"((?:\\.|[^"\\])*)"', re.DOTALL)
literals = [decode_cpp_string_literal(match.group(1)) for match in literal_pattern.finditer(expr)]
if not literals:
return ' '.join(expr.split())
return ''.join(literals)
def extract_cpp_string_literal_expression(expr: str) -> Optional[str]:
"""Collapse adjacent C++ string literals, or return None if the expression has no string literal."""
literal_pattern = re.compile(r'(?:u8|u|U|L)?"((?:\\.|[^"\\])*)"', re.DOTALL)
literals = [decode_cpp_string_literal(match.group(1)) for match in literal_pattern.finditer(expr)]
if not literals:
return None
return ''.join(literals)
def extract_parameter_member_name(expr: str) -> Optional[str]:
"""Return the referenced member name from a parameter storage expression."""
expr = expr.strip()
member_match = re.fullmatch(r'(?:\w+\.)?(\w+)', expr)
if member_match:
return member_match.group(1)
return None
def extract_raw_parameters(source: str) -> list:
"""Return [(param_name, member_var_name, description)] from parameter declarations."""
params = []
for call_body in find_cpp_call_bodies(source, 'declareAndLoadParameter'):
args = split_cpp_arguments(call_body)
if len(args) < 3:
continue
name = extract_cpp_string_literal_expression(args[0])
member_name = extract_parameter_member_name(args[1])
description = extract_cpp_string_expression(args[2])
if not name or not member_name:
continue
params.append((name, member_name, description))
return params
def ast_constant_string(node: "ast.AST | None") -> Optional[str]:
"""Return the value of a string-constant AST node, else None."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
return None
def python_call_argument(call: ast.Call, index: Optional[int], name: str) -> "ast.AST | None":
"""Return a call argument by keyword name, falling back to positional index."""
for keyword in call.keywords:
if keyword.arg == name:
return keyword.value
if index is not None and index < len(call.args) and not isinstance(call.args[index], ast.Starred):
return call.args[index]
return None
def python_call_name(call: ast.Call) -> str:
"""Return the called function/method name for a Python call node."""
func = call.func
if isinstance(func, ast.Attribute):
return func.attr
if isinstance(func, ast.Name):
return func.id
return ''
def build_python_import_type_map(tree: ast.AST) -> dict[str, str]:
"""Map imported interface class names to ROS 'pkg/kind/Type' strings."""
result: dict[str, str] = {}
for node in ast.walk(tree):
if not isinstance(node, ast.ImportFrom) or not node.module:
continue
parts = node.module.split('.')
if len(parts) < 2 or parts[-1] not in ('msg', 'srv', 'action'):
continue
prefix = '/'.join(parts)
for alias in node.names:
if alias.name == '*':
continue
local = alias.asname or alias.name
result[local] = f'{prefix}/{alias.name}'
return result
def resolve_python_interface_type(node: "ast.AST | None", type_map: dict[str, str]) -> Optional[str]:
"""Resolve a message/service/action type argument to ROS notation."""
if isinstance(node, ast.Name):
name = node.id
elif isinstance(node, ast.Attribute):
name = node.attr
else:
return None
return type_map.get(name, name)
def render_python_default(node: "ast.AST | None", source: str) -> str:
"""Render a Python default-value expression for Markdown display."""
if node is None:
return ''
if isinstance(node, ast.Constant):
value = node.value
if isinstance(value, bool):
return 'true' if value else 'false'
if value is None:
return ''
if isinstance(value, str):
return value
return repr(value)
if isinstance(node, (ast.List, ast.Tuple)):
return '[' + ', '.join(render_python_default(element, source) for element in node.elts) + ']'
return (ast.get_source_segment(source, node) or ast.unparse(node)).strip()