### Setup pygccxml for development Source: https://github.com/castxml/pygccxml/blob/develop/docs/install.rst Set up a virtual environment and install pygccxml in editable mode with test dependencies for development. ```shell cd pygccxml # git root python -m virtualenv ./venv source ./venv/bin/activate pip install --editable .[test] ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/castxml/pygccxml/blob/develop/docs/documentation.rst Install Sphinx and the ReadTheDocs theme required for building the documentation. Run this in the root folder. ```shell pip install .[docs] ``` -------------------------------- ### Python API Usage Example Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/print-example/example.py.rst This snippet demonstrates a typical usage of the pygccxml Python API. Ensure pygccxml is installed and configured correctly. ```python from pygccxml import parser from pygccxml import declarations # Parse the C++ header file # Assuming 'example.h' is a valid C++ header file # The 'lines' argument in literalinclude is not directly translatable here, # so we assume the entire content of example.py from line 5 onwards is relevant. # For a real scenario, you would replace 'example.h' with your actual header file. # Placeholder for actual file parsing logic if 'example.py' were available # For demonstration, let's assume a simple header content is parsed. # In a real case, this would involve reading a file or string. # Example of parsing a string (replace with file parsing if needed) header_content = "" """ int add(int a, int b) { return a + b; } class MyClass { public: void greet(); }; """ # Use the parser to get the C++ declarations # In a real scenario, you'd use parser.parse_file('your_header.h') # For this example, we simulate parsing the content string. # The actual 'example.py' content from line 5 is not provided, so this is a conceptual representation. # Assuming 'example.py' contains code to parse a header file and extract declarations. # The following lines are illustrative of pygccxml usage. # Example: Parse a header file (replace 'path/to/your/header.h' with the actual path) # try: # decls = parser.parse_file('path/to/your/header.h', [] # include paths) # except Exception as e: # print(f"Error parsing file: {e}") # exit(1) # For demonstration, let's create a dummy declaration object # This part would be replaced by actual parsed declarations from 'example.py' # root_decls = declarations.declarations_t() # For example, if 'example.py' defined a function 'add': # add_func = declarations.free_function_t('add', ...) # root_decls.append(add_func) # Accessing declarations (example) # for decl in root_decls: # if isinstance(decl, declarations.free_function_t): # print(f"Found function: {decl.name}") # elif isinstance(decl, declarations.class_t): # print(f"Found class: {decl.name}") # Since the actual content of 'example.py' from line 5 is not provided, # this code block is a placeholder illustrating the *type* of operations # one might perform with pygccxml based on the context. # A real 'example.py' would contain specific calls to parser and declarations. print("PyGCCXML example placeholder. Replace with actual code from example.py.") ``` -------------------------------- ### Install pygccxml from source Source: https://github.com/castxml/pygccxml/blob/develop/docs/install.rst Install pygccxml directly from its source code using pip. ```shell pip install . ``` -------------------------------- ### Configure CastXML/GCCXML Start Declarations Source: https://github.com/castxml/pygccxml/blob/develop/docs/faq.rst Reduce the number of parsed declarations by specifying a starting point with '-fxml-start' (gccxml) or '-castxml-start' (castxml). This is useful for optimizing parsing time by focusing on specific classes or namespaces. ```python start_with_declarations attribute of the pygccxml.parser.config_t object ``` -------------------------------- ### Install pygccxml using pip Source: https://github.com/castxml/pygccxml/blob/develop/docs/install.rst Use this command to install the pygccxml library from the Python Package Index. ```shell pip install pygccxml ``` -------------------------------- ### Configure XML Generator Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/notebook/example.ipynb Find the installed XML generator (e.g., castxml) and configure its path and include directories. This setup is crucial for pygccxml to correctly parse C++ code. ```python # Find out the c++ parser. This should resolve to the castxml # version installed in Docker. generator_path, generator_name = utils.find_xml_generator() # Configure the xml generator config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name, include_paths=["/usr/include/eigen3"], compiler_path=generator_path, ) ``` -------------------------------- ### Creating File Configurations in pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Provides examples of helper functions used to create different types of file configurations for the pygccxml parser. ```python parser.create_text_fc parser.create_source_fc parser.create_gccxml_fc parser.create_cached_source_fc ``` -------------------------------- ### Example C++ Header for Compound Types Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/compound/example.rst This C++ header file is used to demonstrate compound types in pygccxml. ```c++ #include #include struct MyStruct { int data; }; using MyInt = int; struct AnotherStruct { volatile_t v; const_t p; restrict_t& r; pointer_t ptr; reference_t ref; array_t arr; member_variable_type_t mv; }; ``` -------------------------------- ### Run pygccxml Test Suite Source: https://github.com/castxml/pygccxml/blob/develop/README.rst Execute the pygccxml test suite using pytest. Ensure pytest is installed. ```bash pytest tests ``` -------------------------------- ### C++ Header File Example Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/elaborated/example.rst This C++ code snippet demonstrates the use of elaborated type specifiers in a header file. ```c++ #include "example.hpp" struct MyStruct { int data; }; class MyClass { public: MyClass(int val) : member(val) {} private: MyStruct member; }; enum class Color { RED, GREEN, BLUE }; union Data { int i; float f; char str[20]; }; void process(class MyClass* obj, struct MyStruct* s, enum Color c, union Data d) { // Function implementation } ``` -------------------------------- ### C++ Example: Clone Method Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst An example C++ struct with a clone method that returns a new object. This is often used in conjunction with call policies. ```c++ struct A{ A* clone() const { return new A(); } ... }; struct B{ B* clone() const { return new B(); } ... }; ``` -------------------------------- ### Run pygccxml Test Suite Source: https://github.com/castxml/pygccxml/blob/develop/docs/index.rst Execute the pygccxml test suite using Python 3. Ensure pygccxml is installed in your environment. ```python python3 -m unittests.test_all ``` -------------------------------- ### Query Member Functions by Name, Access Type, and Arguments Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst This example demonstrates a complex query to find member functions that end with 'impl', are not public, and have a second argument that is a reference to an integer. Use this for intricate filtering needs. ```python #global_ns is the reference to an instance of namespace_t object, #that #represents global namespace query = declarations.custom_matcher_t( lambda mem_fun: mem_fun.name.endswith( 'impl' ) query = query & ~declarations.access_type_matcher_t( 'public' ) global_ns.member_functions( function=query, arg_types=[None, 'int &'] ) ``` -------------------------------- ### Update Travis Setup for Python 3.6 Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md The Travis CI setup has been updated to include Python 3.6 for OS X builds. ```yaml Updated travis setup to python 3.6 for OS X. ``` -------------------------------- ### Work with Multiple Declaration Results Source: https://context7.com/castxml/pygccxml/llms.txt Shows how to get the count of matching declarations and iterate over them using mdecl_wrapper_t. ```python all_clone = global_ns.member_functions('clone') print(len(all_clone)) ``` ```python for clone in global_ns.member_functions('clone'): print(clone.parent.name) ``` -------------------------------- ### Search for Declarations using pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/searching/example.rst This Python script searches for C++ declarations like functions and variables using pygccxml. Ensure you have a C++ file (e.g., example.hpp) and a Python script to run this example. ```python from pygccxml import parser from pygccxml import declarations # Parse the C++ header file # Assuming 'example.hpp' is in the same directory or accessible via include paths # For demonstration, we'll use a placeholder for the actual file content if not provided # In a real scenario, you would parse your actual C++ header. # Example: # xml_generator = parser.XmlGenerator(include_paths=['.']) # xml_generator.parse(open('example.hpp').read()) # root_decls = xml_generator.root_decls # For this example, let's assume we have a parsed declaration object # In a real use case, 'root_decls' would be populated by parser.parse() # We'll simulate a simple declaration for demonstration purposes. # Simulate a function declaration func_decl = declarations.function_t('my_function', declarations.void_t(), [declarations.int_t('arg1')]) # Simulate a variable declaration var_decl = declarations.variable_t('my_variable', declarations.int_t()) # Combine simulated declarations into a list for searching # In a real scenario, this would be the result of parsing your C++ code root_decls = [func_decl, var_decl] # --- Searching Examples --- # 1. Find all functions print('--- All Functions ---') for decl in declarations.get_declarations(root_decls, lambda decl: isinstance(decl, declarations.function_t)): print(decl.name) # 2. Find a specific function by name print('\n--- Specific Function by Name ---') found_func = declarations.find_declaration(root_decls, lambda decl: isinstance(decl, declarations.function_t) and decl.name == 'my_function') if found_func: print(f'Found function: {found_func.name}') else: print('Function my_function not found.') # 3. Find all variables print('\n--- All Variables ---') for decl in declarations.get_declarations(root_decls, lambda decl: isinstance(decl, declarations.variable_t)): print(decl.name) # 4. Find a specific variable by name print('\n--- Specific Variable by Name ---') found_var = declarations.find_declaration(root_decls, lambda decl: isinstance(decl, declarations.variable_t) and decl.name == 'my_variable') if found_var: print(f'Found variable: {found_var.name}') else: print('Variable my_variable not found.') # 5. Find declarations by type (e.g., all integers) print('\n--- All Integers ---') for decl in declarations.get_declarations(root_decls, lambda decl: isinstance(decl, declarations.variable_t) and isinstance(decl.type, declarations.int_t)): print(f'Integer variable: {decl.name}') # Note: In a real project, you would parse your C++ header file like this: # from pygccxml import parser # # # Assuming example.hpp contains your C++ code # with open('example.hpp', 'r') as f: # cpp_code = f.read() # # # Parse the C++ code. Adjust include_paths if necessary. # root_decls = parser.parse(cpp_code, ['-I.']) # # # Then use the above search functions on the parsed root_decls. ``` -------------------------------- ### Find Member Functions by Argument Types Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst This example demonstrates how to filter member functions based on the types of their arguments. You can specify argument types as strings or type objects and use None to skip specific argument positions. This is useful for finding functions with a particular signature. ```python mem_funcs = my_class.member_functions( arg_types=[ None, 'int'] ) ``` -------------------------------- ### C++ Class Declaration Example Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/artificial/example.rst This C++ code defines a class with an explicit constructor. pygccxml will generate an XML representation that includes both this explicit constructor and an implicit copy constructor. ```cpp class MyClass { public: MyClass(int val) : value(val) {} private: int value; }; ``` -------------------------------- ### Accessing Declarations in pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Illustrates a change in pygccxml where 'mdecl_wrapper_t.decls' was renamed to 'declarations' to avoid naming conflicts. This example shows the old way that will now fail. ```python classes = ns.decls("class") classes.decls("method") # This will fail because it finds the attribute decls which is not a callable. ``` -------------------------------- ### Search for Declaration using Loop in Python Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/searching1/example.rst Use this code to iterate through the declarations tree and locate a specific C++ declaration. Ensure pygccxml is installed and the C++ file is parsed. ```python from pygccxml import parser from pygccxml import declarations # Parse the C++ file decls = parser.parse_file('example.hpp', compilation_options=parser.CompilationOptions(include_paths=['.'])) # Get the global namespace global_ns = declarations.global_namespace(decls) # Search for a specific declaration (e.g., a class named 'MyClass') my_class = None for decl in global_ns.declarations(): if isinstance(decl, declarations.class_t) and decl.name == 'MyClass': my_class = decl break # Print the found declaration (if any) if my_class: print(f"Found class: {my_class.name}") else: print("Class 'MyClass' not found.") ``` -------------------------------- ### Pass Flags Argument for Internal Declarations Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Alternatively, you can pass the `flags` argument directly to the config setup to control the inclusion of internal declarations like `__va_list_tag`. ```python flags=["f1"] ``` -------------------------------- ### Compare C++ Function Declarations Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/equality/example.rst This snippet compares two C++ function declarations found using pygccxml. Ensure pygccxml is installed and the C++ file is accessible. ```python from pygccxml import parser from pygccxml import declarations # Parse the C++ file reader = parser.parse_file('example.hpp') global_namespace = reader.global_namespace # Find the two functions func1 = global_namespace.fun('my_function') func2 = global_namespace.fun('another_function') # Compare the declarations if func1 == func2: print('Declarations are identical') else: print('Declarations are different') ``` -------------------------------- ### Define and Parse C++ Code Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/notebook/example.ipynb Define a C++ code string that includes std::vector and Eigen::Matrix, then parse it using pygccxml. This example demonstrates parsing a class with template instantiations. ```python code = r""" #include #include namespace ns { template class ExampleClass { public: std::vector make_std_vector() const; Eigen::Matrix make_matrix3(); }; // Analyze concrete instantiations of the given class. extern template class ExampleClass; extern template class ExampleClass; } // namespace ns """ (global_ns,) = parser.parse_string(code, config) ``` -------------------------------- ### C++ Template Name Mangling Example Source: https://github.com/castxml/pygccxml/blob/develop/docs/upgrade_issues.rst Illustrates C++ template name mangling differences between GCC-XML versions. pygccxml uses the demangled name for class identification. ```cpp template< unsigned long i1> struct item_t{ static const unsigned long v1 = i1; }; struct buggy{ typedef unsigned long ulong; typedef item_t< ulong( 0xDEECE66DUL ) | (ulong(0x5) << 32) > my_item_t; my_item_t my_item_var; }; ``` -------------------------------- ### Parsing Templated Class Instantiations with Parentheses Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md This example demonstrates the corrected parsing of templated class instantiations that include parentheses within their template arguments, specifically for types like std::vector. Ensure your CastXML version supports this. ```cpp myClass(const std::string &, const std::string &)> obj; ``` -------------------------------- ### Find Member Functions by Custom Callable Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst This example shows how to use a custom lambda function to filter member functions based on a specific condition, such as the function name ending with 'impl'. This is useful for complex, non-standard filtering criteria. ```python impls = my_class.member_functions( lambda decl: decl.name.endswith( 'impl' ) ) ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/castxml/pygccxml/blob/develop/docs/documentation.rst Generate the HTML version of the documentation locally. The output will be in the 'docs/_build/html' folder. Run this in the root folder. ```shell make html ``` -------------------------------- ### Build Distribution Wheels Source: https://github.com/castxml/pygccxml/blob/develop/docs/releasing.rst Use the 'build' package to create the source distribution and wheels for the project. ```bash python3 -m build ``` -------------------------------- ### Support for Type Align, Offset, and Size (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Introduces support for retrieving type alignment, offset, and size information, with implementation contributed by Ben Schleimer. ```python from pygccxml import declarations # Assuming 'type_decl' is a declaration object for a type # if hasattr(type_decl, 'align'): # print(f"Alignment: {type_decl.align}") # if hasattr(type_decl, 'offset'): # print(f"Offset: {type_decl.offset}") # if hasattr(type_decl, 'size'): # print(f"Size: {type_decl.size}") ``` -------------------------------- ### Upload to PyPI Source: https://github.com/castxml/pygccxml/blob/develop/docs/releasing.rst Upload the built distribution files (wheels and source distribution) to the Python Package Index (PyPI) using twine. ```bash twine upload dist/* ``` -------------------------------- ### Remove Type Qualifiers and Pointers Source: https://context7.com/castxml/pygccxml/llms.txt Utility functions to strip qualifiers (const, volatile) and pointers/references from C++ types to get the base type. ```python base = declarations.remove_cv(some_type) base = declarations.remove_const(some_type) base = declarations.remove_volatile(some_type) base = declarations.remove_pointer(some_type) base = declarations.remove_reference(some_type) base = declarations.remove_alias(some_type) ``` -------------------------------- ### Working with C++ Templates in pygccxml Source: https://context7.com/castxml/pygccxml/llms.txt Shows how to detect, analyze, and split C++ template names and parameters using pygccxml. Requires parsing C++ header files. ```python from pygccxml import utils, declarations, parser generator_path, generator_name = utils.find_xml_generator() config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name) # Given C++ code: # namespace ns { # struct B { struct D { bool d; }; }; # template struct T {}; # T function(); # } decls = parser.parse(["templates.hpp"], config) global_ns = declarations.get_global_namespace(decls) ns = global_ns.namespace("ns") # Find template declarations for d in ns.declarations: if isinstance(d, declarations.class_declaration_t): class_declaration_t = d if isinstance(d, declarations.class_t): print("Struct:", d) if isinstance(d, declarations.free_function_t): func = d print(class_declaration_t) # Output: ns::T [class declaration] print(func) # Output: ns::T ns::function() [free function] # Check if name is a template instantiation is_template = declarations.templates.is_instantiation(class_declaration_t.name) print(is_template) # Output: True # Split template name into base and parameters name, params = declarations.templates.split(class_declaration_t.name) print(name) # Output: T print(params) # Output: ['ns::B::D', 'bool'] ``` -------------------------------- ### Upgrade Build Tools Source: https://github.com/castxml/pygccxml/blob/develop/docs/releasing.rst Ensure the 'build' package is up to date by upgrading it using pip. ```bash python3 -m pip install --upgrade build ``` -------------------------------- ### Finding Container Traits (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Demonstrates the usage of `find_container_traits` from `pygccxml.declarations` to get traits information for standard container classes. This function was added in version 0.9.5. ```python from pygccxml import declarations # Assuming 'std_vector_int' is a declaration object for std::vector # traits = declarations.find_container_traits(std_vector_int) # if traits: # print(f"Element type: {traits.element_type}") ``` -------------------------------- ### Advanced Matchers and Query API in pygccxml Source: https://context7.com/castxml/pygccxml/llms.txt Demonstrates how to build complex queries using custom matchers and access type matchers to find C++ declarations based on multiple criteria with AND, OR, NOT logic. ```python from pygccxml import utils, declarations, parser generator_path, generator_name = utils.find_xml_generator() config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name) decls = parser.parse(["example.hpp"], config) global_ns = declarations.get_global_namespace(decls) # Custom matcher with lambda custom = declarations.custom_matcher_t( lambda decl: decl.name.endswith('_impl')) # Access type matcher (public, protected, private) not_public = ~declarations.access_type_matcher_t('public') ``` -------------------------------- ### Querying Operators by Symbol in pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Demonstrates how to query for an operator using its symbol as a string. This is an alternative to using the 'symbol' keyword argument. ```python cls = global_namespace.class_('my_class') op = cls.operator('<') #instead of op = cls.operator(symbol='<') ``` -------------------------------- ### Tag the Release Version Source: https://github.com/castxml/pygccxml/blob/develop/docs/releasing.rst Create a Git tag for the new version, prefixed with 'v', and push the tag and master branch to the remote repository. ```bash git tag vmajor.minor.minor ``` ```bash git push origin vmajor.minor.minor && git push origin master ``` -------------------------------- ### Enable '__thiscall__' Attributes with 'f2' Flag Source: https://github.com/castxml/pygccxml/blob/develop/docs/faq.rst Use the 'f2' flag to retain attributes defined with '__thiscall__', which are otherwise ignored by default. This can be set via config.flags or during config setup. ```python config.flags = ["f2"] ``` ```python flags=["f2"] ``` -------------------------------- ### Using declarations.decl_printer_t for Detailed Declaration Info (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Highlights the `declarations.decl_printer_t` class, which provides comprehensive information about declarations. It was improved to sort declarations before printing. ```python from pygccxml import declarations # Assuming 'declaration_object' is an instance of a declaration # printer = declarations.decl_printer_t() # print(printer.print_xml(declaration_object)) # Example usage, actual method might differ ``` -------------------------------- ### Extracting Template Parameters from C++ Declaration Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/templates/example.rst This C++ code snippet defines a template class and demonstrates how template parameters can be extracted. It serves as the source for the Python parsing example. ```c++ template class array { public: T data[N]; }; array a; ``` -------------------------------- ### Merge Develop into Master Source: https://github.com/castxml/pygccxml/blob/develop/docs/releasing.rst Switch to the master branch and merge the develop branch into it to prepare for release. ```bash git checkout master ``` ```bash git merge develop master ``` -------------------------------- ### Parse C++ Code String with pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/parsing-string/example.rst Use this configuration to parse C++ code from a string. Ensure you have an XML generator like castxml or gccxml installed and accessible in your system's PATH. ```python from pygccxml import parser from pygccxml import declarations xml_generator_config = parser.XmlGeneratorConfiguration() xml_generator_config.xml_generator = 'castxml' # or 'gccxml' cxx_code = """ int main() { return 0; } """ declarations.parse(cxx_code, xml_generator_configuration=xml_generator_config) ``` -------------------------------- ### Support for GCC-XML 0.9 (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Ensures compatibility and proper parsing with GCC-XML version 0.9. ```python # No direct code example, implies internal compatibility updates. # Example of checking GCC-XML version (conceptual): # from pygccxml import parser # # # The parser might internally check the GCC-XML version it's interacting with. ``` -------------------------------- ### Extracting C++ Type Information Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/nested-types/example.rst This Python code snippet uses pygccxml to parse C++ code and extract information about variable types. Ensure pygccxml is installed and the C++ file is accessible. ```python from pygccxml import parser from pygccxml import declarations callexpr_example = """ int main() { int a; return 0; } """ declarations.cpptypes.remove_unnamed_types() declarations.cpptypes.use_cache = True reader = parser.ParserOptions() reader.translate_builtins = True # Parse the C++ code module = parser.parse(callexpr_example, reader) # Access the global namespace global_ns = module.global_ns # Find the main function main_func = global_ns.v['main'] # Get the type of the first argument (if any) or return type if main_func.arguments: first_arg_type = main_func.arguments[0].type print(f"Type of first argument: {first_arg_type}") else: return_type = main_func.return_type print(f"Return type: {return_type}") # Example of accessing a variable's type # Assuming 'a' is a variable in the C++ code # You would typically find 'a' through namespace or class scope # For demonstration, let's assume we found it: # var_a = global_ns.variable('a') # This would be how you'd find it if it were global # print(f"Type of variable 'a': {var_a.type}") ``` -------------------------------- ### Handling Ellipsis in Function Signatures (C++) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Demonstrates how pygccxml now correctly identifies functions with ellipsis in their parameter list. Previously, such functions were reported with fewer arguments. ```c++ void do_smth( int, ... ) ``` -------------------------------- ### Enable Hidden Declarations with 'f1' Flag Source: https://github.com/castxml/pygccxml/blob/develop/docs/faq.rst Use the 'f1' flag to include internal declarations like '__va_list_tag' and '__NSConstantString_tag' that are normally ignored by pygccxml. This can be set via config.flags or during config setup. ```python config.flags = ["f1"] ``` ```python flags=["f1"] ``` -------------------------------- ### Configure pygccxml Parser Source: https://context7.com/castxml/pygccxml/llms.txt Customize C++ code parsing by setting include paths, compiler flags, and other options. Configuration can be done programmatically or loaded from a file. ```python from pygccxml import parser # Full configuration example xml_generator_config = parser.xml_generator_configuration_t( xml_generator_path="/usr/bin/castxml", xml_generator="castxml", working_directory=".", include_paths=["/usr/include", "/project/include"], define_symbols=["DEBUG=1", "VERSION=2"], undefine_symbols=["NDEBUG"], cflags="-std=c++17", compiler="gcc", keep_xml=False # Set True to keep generated XML files for debugging ) # Load configuration from file config = parser.load_xml_generator_configuration("pygccxml.cfg") # Example config file content (pygccxml.cfg): # [xml_generator] # xml_generator_path=/usr/bin/castxml # xml_generator=castxml # include_paths=/usr/include;/project/include # compiler=gcc # cflags=-std=c++17 ``` -------------------------------- ### Python 3.5 Unit Tests with Travis CI Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Enable Travis CI unit tests for Python 3.5 compatibility. ```yaml language: python python: - 3.5 install: - pip install -r requirements.txt script: - python setup.py test ``` -------------------------------- ### Combine Matchers with Logical Operators Source: https://context7.com/castxml/pygccxml/llms.txt Demonstrates combining declaration matchers using AND (&), OR (|), and NOT (~) operators for complex queries. ```python combined = custom & not_public ``` -------------------------------- ### Commit Version Changes Source: https://github.com/castxml/pygccxml/blob/develop/docs/releasing.rst Stage all changes and commit them with a message indicating the version bump. ```bash git add . && git commit -m "Bump version major.minor.minor" ``` -------------------------------- ### Declaration Caching in pygccxml Source: https://context7.com/castxml/pygccxml/llms.txt Illustrates different methods for caching parsed C++ declarations to improve performance, including file configuration, directory cache, and file cache. ```python from pygccxml import utils, declarations, parser generator_path, generator_name = utils.find_xml_generator() config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name) # Method 1: Use file_configuration_t with CACHED_SOURCE_FILE file_config = parser.file_configuration_t( data="example.hpp", content_type=parser.CONTENT_TYPE.CACHED_SOURCE_FILE) project_reader = parser.project_reader_t(config) decls = project_reader.read_files( [file_config], compilation_mode=parser.COMPILATION_MODE.FILE_BY_FILE) # Method 2: Use directory cache cache = parser.directory_cache_t(cache_dir="./cache") decls = parser.parse(["example.hpp"], config, cache=cache) # Method 3: Use file cache cache = parser.file_cache_t(cache_file="./declarations.cache") decls = parser.parse(["example.hpp"], config, cache=cache) # Access the parsed declarations global_ns = declarations.get_global_namespace(decls) ``` -------------------------------- ### Parse C++ Code Strings with pygccxml Source: https://context7.com/castxml/pygccxml/llms.txt This snippet demonstrates parsing C++ code directly from a string. It's useful for dynamic analysis or testing without physical files. ```python from pygccxml import utils from pygccxml import declarations from pygccxml import parser # Find the xml generator generator_path, generator_name = utils.find_xml_generator() # Configure the xml generator xml_generator_config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name) # Write a string containing c++ code code = """ class MyClass { int member_var; void doSomething(int arg); }; """ # Parse the code string decls = parser.parse_string(code, xml_generator_config) # Get access to the global namespace global_ns = declarations.get_global_namespace(decls) # Find the class my_class = global_ns.class_("MyClass") print(my_class) # Output: MyClass [class] ``` -------------------------------- ### Handling 'C' Functions (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Introduces support for parsing functions declared with the 'C' linkage convention. ```text # No code example provided for this functionality. ``` -------------------------------- ### Use New Namespace Methods Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Deprecated methods like `nss`, `free_fun`, and `free_funs` on the `namespace_t` class have been replaced. Use the newer `namespaces`, `free_function`, and `free_functions` methods instead. ```python Use the ```namespaces```, ```free_function``` and ```free_functions``` methods instead. ``` -------------------------------- ### Demonstrating Compound Type Chaining in pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/compound/example.rst This Python code illustrates how compound types are represented and chained in pygccxml, showing their order and structure. ```python from pygccxml import parser from pygccxml import declarations # Assume 'example.hpp' is the C++ header file # The following lines parse the C++ code and extract type information # This is a simplified representation of the actual parsing and analysis # Example of how compound types might be accessed and inspected: # (Actual code would involve more detailed pygccxml API usage) # For instance, to get the type of 'v' from 'AnotherStruct': # another_struct_type = declarations.class_declaration('AnotherStruct') # v_member = another_struct_type.get_member('v') # v_type = v_member.type # print(f"Type of 'v': {v_type}") # Expected: volatile_t # Similarly for other members like 'p', 'r', 'ptr', 'ref', 'arr', 'mv' # The key takeaway is understanding the structure and order of these types as defined in pygccxml. # This snippet is a placeholder for the actual pygccxml code that would be used to analyze the C++ header. # The original source indicates lines 6,7,8,17-27,29- of 'example.py' are relevant. # The following is a conceptual representation of what that code might do: # Assuming 'decl_reader' is an instance of pygccxml.parser.SourceReader # and 'module_name' is the name of the parsed C++ module # Example of accessing a specific type: # my_int_type = declarations.find_typedef(module_name, 'MyInt') # print(f"MyInt type: {my_int_type}") # Example of inspecting a class member's type: # another_struct_decl = declarations.class_declaration('AnotherStruct') # for member in another_struct_decl.members(): # print(f"Member '{member.name}' type: {member.type}") # The actual code would involve iterating through declarations and inspecting types. # The provided snippet is a conceptual representation based on the line numbers mentioned. # Placeholder for actual pygccxml analysis code pass ``` -------------------------------- ### Profile Python Application Source: https://github.com/castxml/pygccxml/blob/develop/docs/faq.rst Use cProfile and pyprof2calltree to profile Python applications. This helps identify performance bottlenecks in your script and the pygccxml usage. ```bash python -m cProfile -o profile_data.pyprof script_to_profile.py ``` ```bash pyprof2calltree -i profile_data.pyprof -k ``` -------------------------------- ### Find Member Functions by Header File Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst Use this to find member functions within a specific header file. Provide the full path to the header file. ```python mem_funcs = my_namespace.member_functions( header_dir='/home/roman/xyz/xyz.hpp' ) ``` -------------------------------- ### Update Documentation to Sphinx Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md The documentation has been migrated from epydoc to Sphinx. Use 'make gh-pages' to create and push documentation updates to the GitHub repository. ```bash make gh-pages ``` -------------------------------- ### test_case Class Details Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/print-example/output.txt Details about the 'test_case' class, including its constructors, member functions, and variables. ```APIDOC ## Class: test_case ### Description Represents a test case in the C++ code. ### Constructors #### Constructor 1 - **Signature**: `unittests::test_case::test_case(unittests::test_case const&)` - **Mangled Name**: `_ZN9unittest` - **Return Type**: None - **Arguments**: `::unittests::test_case const & arg0` - **Calling Convention**: `__thiscall__` - **Virtual**: Not Virtual - **Const**: False - **Static**: False - **Copy Constructor**: True - **Location**: [D:\dev\language-binding\sources\pygccxml_dev\docs\example\example.hpp]:21 - **Artificial**: False #### Constructor 2 - **Signature**: `unittests::test_case::test_case(char const*)` - **Mangled Name**: `_ZN9unittest` - **Extern**: True - **Return Type**: None - **Arguments**: `char const * test_case_name` - **Calling Convention**: `__thiscall__` - **Virtual**: Not Virtual - **Const**: False - **Static**: False - **Copy Constructor**: False - **Location**: [D:\dev\language-binding\sources\pygccxml_dev\docs\example\example.hpp]:21 - **Artificial**: False ### Member Functions #### set_up - **Signature**: `unittests::test_case::set_up()` - **Mangled Name**: `_ZN9unittests9test_case6set_upEv` - **Return Type**: void - **Arguments**: None - **Calling Convention**: `__thiscall__` - **Virtual**: Virtual - **Const**: False - **Static**: False - **Location**: [D:\dev\language-binding\sources\pygccxml_dev\docs\example\example.hpp]:23 - **Artificial**: False #### tear_down - **Signature**: `unittests::test_case::tear_down()` - **Mangled Name**: `_ZN9unittests9test_case9tear_downEv` - **Return Type**: void - **Arguments**: None - **Calling Convention**: `__thiscall__` - **Virtual**: Virtual - **Const**: False - **Static**: False - **Location**: [D:\dev\language-binding\sources\pygccxml_dev\docs\example\example.hpp]:25 - **Artificial**: False #### run - **Signature**: `unittests::test_case::run()` - **Mangled Name**: `_ZN9unittests9test_case3runEv` - **Extern**: True - **Return Type**: void - **Arguments**: None - **Calling Convention**: `__thiscall__` - **Virtual**: Pure Virtual - **Const**: False - **Static**: False - **Location**: [D:\dev\language-binding\sources\pygccxml_dev\docs\example\example.hpp]:27 - **Artificial**: False ### Variables #### m_name - **Type**: `char const *` - **Size**: 4 - **Align**: 4 - **Offset**: 4 - **Location**: [D:\dev\language-binding\sources\pygccxml_dev\docs\example\example.hpp]:30 - **Artificial**: False ``` -------------------------------- ### Include C++ Header File Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/print-example/example.hpp.rst This snippet shows how to include a C++ header file using a literal include directive. It specifies the file name and the range of lines to include. ```c++ #include "example.hpp" ``` -------------------------------- ### Normalize Windows Include Paths Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Include paths read from configuration files on Windows are now normalized and enclosed in quotation marks. This enhances robustness when dealing with paths containing spaces. ```python Include paths read from configuration files on windows are now normed and passed between quotation marks. This makes ```pygccxml``` more robust when used on Windows (with paths containing whitespaces). ``` -------------------------------- ### GCC-XML 0.7 XML for member pointers Source: https://github.com/castxml/pygccxml/blob/develop/docs/upgrade_issues.rst XML output from GCC-XML 0.7 representing typedefs for function and variable pointers to members. ```xml ``` -------------------------------- ### Set Compilation Mode Source: https://github.com/castxml/pygccxml/blob/develop/docs/faq.rst Pass the 'compilation_mode=pygccxml.parser.COMPILATION_MODE.ALL_AT_ONCE' flag to the *read_files* method for potentially faster parsing. ```python compilation_mode=pygccxml.parser.COMPILATION_MODE.ALL_AT_ONCE ``` -------------------------------- ### Find Functions by Name, Return Type, or Arguments Source: https://context7.com/castxml/pygccxml/llms.txt Use pygccxml to locate free functions within a C++ namespace. You can search by function name, return type (as a string or type object), or use custom matchers. ```python from pygccxml import utils, declarations, parser generator_path, generator_name = utils.find_xml_generator() config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name) # Given C++ code: # namespace ns { # int func1(int a) { return a + 2; } # double func2(double a) { return a + 2.0; } # double func3(double a) { return a + 3.0; } # } decls = parser.parse(["functions.hpp"], config) global_ns = declarations.get_global_namespace(decls) ns = global_ns.namespace("ns") # Find function by name func = ns.free_function(name="func1") print(func) # Output: int ns::func1(int a) [free function] # Search by return type (string) criteria = declarations.calldef_matcher(return_type="int") func = declarations.matcher.get_single(criteria, ns) print(func) # Output: int ns::func1(int a) [free function] # Search by return type (type object) double_type = declarations.cpptypes.double_t() criteria = declarations.calldef_matcher(return_type=double_type) funcs = declarations.matcher.find(criteria, ns) print(len(funcs)) # Output: 2 print(funcs[0]) # Output: double ns::func2(double a) [free function] print(funcs[1]) # Output: double ns::func3(double a) [free function] # Get function arguments for arg in func.arguments: print(arg.name, str(arg.decl_type)) ``` -------------------------------- ### Find Member Functions by Header Directory Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst Use this to find member functions within a specific header directory. Ensure the header directory path is correctly specified. ```python mem_funcs = my_namespace.member_functions( header_dir='/home/roman/xyz' ) ``` -------------------------------- ### Travis CI Configuration for Unit Tests Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Configure Travis CI to run unit tests for multiple Python versions (2.6, 2.7, 3.2, 3.3, 3.4) after each commit. See the .travis.yml file for details. ```yaml language: python python: - 2.6 - 2.7 - 3.2 - 3.3 - 3.4 install: - pip install -r requirements.txt script: - python setup.py test ``` -------------------------------- ### Enable Caching in pygccxml Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/caching/example.rst Use this Python code to enable caching when parsing C++ headers with pygccxml. Ensure the 'example.hpp' file is accessible. ```python from pygccxml import parser # Enable caching parser.parse("example.hpp", compilation_options=parser.CompilationOptions(use_cache=True)) ``` -------------------------------- ### Parsing Configuration File Bug Fix (Windows) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Addresses a bug specific to Windows related to parsing configuration files. ```text # No code example provided for this fix. ``` -------------------------------- ### Query Namespaces by Name Source: https://github.com/castxml/pygccxml/blob/develop/docs/query_interface.rst This is a simple query to find all namespaces with a specific name. Useful for locating known namespaces. ```python global_ns.namespaces( 'details' ) ``` -------------------------------- ### GCC-XML 0.7 XML for default function call argument Source: https://github.com/castxml/pygccxml/blob/develop/docs/upgrade_issues.rst XML representation from GCC-XML 0.7 for a function argument with a default function call value. ```xml ``` -------------------------------- ### Support for GCC-XML Attributes (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Adds support for parsing GCC-XML attributes, with implementation contributed by Miguel Lobo. ```python # No direct code example, but implies new attributes accessible on declarations. # Example of accessing attributes (conceptual): # # # Assuming 'decl' is a declaration object with GCC-XML attributes # # if hasattr(decl, 'gccxml_attributes'): # # for attr in decl.gccxml_attributes: # # print(f"Attribute: {attr.name}") ``` -------------------------------- ### GCC-XML 0.9 XML for member pointers Source: https://github.com/castxml/pygccxml/blob/develop/docs/upgrade_issues.rst XML output from GCC-XML 0.9 representing typedefs for function and variable pointers to members, showing structural changes. ```xml ``` -------------------------------- ### Class: test_container Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/print-example/output.txt Details of the 'test_container' class. ```APIDOC ## Class: test_container ### Description Represents a C++ class named 'test_container' within the 'unittests' namespace. ### Demangled Name unittests::test_container ### Mangled Name N9unittests14test_containerE ``` -------------------------------- ### Printing and Debugging Declarations in pygccxml Source: https://context7.com/castxml/pygccxml/llms.txt Provides methods for visualizing the C++ declaration tree, obtaining full qualified names, iterating through declarations, and dumping declarations to a string for debugging purposes. ```python from pygccxml import utils, declarations, parser generator_path, generator_name = utils.find_xml_generator() config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name, compiler="gcc") decls = parser.parse(["example.hpp"], config) global_ns = declarations.get_global_namespace(decls) # Print all declarations in a namespace ns = global_ns.namespace("unittests") declarations.print_declarations(ns) # Output: Hierarchical view of all declarations in the namespace # Get the full qualified name of a declaration for func in ns.member_functions("run"): print(declarations.full_name(func)) # Output: ::unittests::test_case::run, ::unittests::test_suite::run, etc. # Iterate over all declarations for decl in ns.declarations: print(decl.name, type(decl).__name__) # Dump declarations to a string output = declarations.dump_declarations(ns) ``` -------------------------------- ### Import pygccxml Modules Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/notebook/example.ipynb Import necessary modules from the pygccxml library. These are required for parsing and analyzing C++ code. ```python from pygccxml import declarations from pygccxml import utils from pygccxml import parser ``` -------------------------------- ### Retrieve and Analyze Class Instantiation Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/notebook/example.ipynb Retrieve a specific template instantiation of a class and analyze its template parameters. This is useful for understanding how pygccxml handles C++ templates. ```python # Retrieve an instantiation and show template parameters. cls, = ns.classes('ExampleClass') declarations.templates.split(cls.name) ``` -------------------------------- ### Replacing md5 with hashlib (Python) Source: https://github.com/castxml/pygccxml/blob/develop/CHANGELOG.md Updates the hashing mechanism from `md5` to the more robust `hashlib` module to remove deprecation warnings. ```python # Example of using hashlib (not specific to pygccxml's internal change) # import hashlib # hasher = hashlib.sha256() # hasher.update(b"data to hash") # print(hasher.hexdigest()) ``` -------------------------------- ### Namespace Information Source: https://github.com/castxml/pygccxml/blob/develop/docs/examples/print-example/output.txt Details about functions within the namespace. ```APIDOC ## Namespace Details ### Overloaded Functions - The namespace contains 2 "run" member functions. - These functions are `::unittests::test_suite::run` and `::unittests::test_case::run`. ### Object Reference - All `test_container_*` refer to the same object: True ``` -------------------------------- ### Check Standard Library Types Source: https://context7.com/castxml/pygccxml/llms.txt Provides functions to identify common C++ standard library types like std::string, std::wstring, std::ostream, and std::wostream. ```python print(declarations.is_std_string(some_type)) print(declarations.is_std_wstring(some_type)) print(declarations.is_std_ostream(some_type)) print(declarations.is_std_wostream(some_type)) ```