Skip to content

wip: native script analysis support#2946

Closed
pranavthakur0-0 wants to merge 2 commits intomandiant:masterfrom
pranavthakur0-0:native-script-analysis
Closed

wip: native script analysis support#2946
pranavthakur0-0 wants to merge 2 commits intomandiant:masterfrom
pranavthakur0-0:native-script-analysis

Conversation

@pranavthakur0-0
Copy link
Copy Markdown

Checklist

  • No CHANGELOG update needed
  • No new tests needed
  • No documentation update needed
  • This submission includes AI-generated code and I have provided details in the description.

@google-cla
Copy link
Copy Markdown

google-cla bot commented Mar 19, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

Copy link
Copy Markdown

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add bug fixes, new features, breaking changes and anything else you think is worthwhile mentioning to the master (unreleased) section of CHANGELOG.md. If no CHANGELOG update is needed add the following to the PR description: [x] No CHANGELOG update needed

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request adds support for analyzing script files, initially focusing on Python. It integrates tree-sitter to parse scripts and extract features, enabling capa to detect capabilities within these files. The changes include new modules for script feature extraction, a language handler interface, and a Python-specific language handler. This enhancement expands capa's ability to analyze a broader range of file types.

Highlights

  • Script Analysis Support: This PR introduces native script analysis support to capa, enabling the tool to analyze scripting languages like Python.
  • Tree-sitter Integration: The implementation leverages tree-sitter for parsing scripts into ASTs, facilitating feature extraction for capability detection.
  • Language Handler Abstraction: A modular architecture is introduced, where core infrastructure is language-agnostic, and each supported language implements a LanguageHandler plugin.
  • Python Support: Initial support for Python scripts is included, with the potential to extend to other scripting languages in the future.
  • Feature Extraction: The PR implements feature extraction at various scopes, including file, function, basic block, and instruction levels, mirroring existing backends.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces native script analysis support to capa, primarily focusing on Python scripts using tree-sitter. It adds a new ScriptAddress type, integrates script format and backend into the existing capa infrastructure, and provides a modular LanguageHandler interface for extensibility. The Python language handler includes detailed logic for extracting API calls, strings, and numbers from AST nodes, handling various import syntaxes and string literal formats. The changes are well-structured and demonstrate a clear path for supporting additional scripting languages.

Comment thread capa/features/address.py
Comment on lines +198 to +200
def __lt__(self, other):
assert isinstance(other, ScriptAddress)
return (self.line, self.column) < (other.line, other.column)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The __lt__ method should return NotImplemented when comparing with an incompatible type, rather than raising an AssertionError. This allows for more graceful handling of mixed-type comparisons in Python.

Suggested change
def __lt__(self, other):
assert isinstance(other, ScriptAddress)
return (self.line, self.column) < (other.line, other.column)
def __lt__(self, other):
if not isinstance(other, ScriptAddress):
return NotImplemented
return (self.line, self.column) < (other.line, other.column)

Comment on lines +200 to +202
def get_function_name(self, addr: Address) -> str:
# not used in the current pipeline for script analysis
return ""
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The get_function_name method, which is part of the StaticFeatureExtractor interface, currently returns an empty string. While the comment indicates it's not used in the current pipeline, returning a more descriptive placeholder like "" would be more informative if it were to be used in the future, or if debugging output were to rely on it. This aligns with the fallback behavior in PythonLanguageHandler.get_function_name.

Suggested change
def get_function_name(self, addr: Address) -> str:
# not used in the current pipeline for script analysis
return ""
def get_function_name(self, addr: Address) -> str:
# not used in the current pipeline for script analysis
return "<unknown>"

Comment on lines +317 to +331
text = node.text.decode("utf-8")
# handle triple-quoted strings
for quote in ('"""', "'''", '"', "'"):
if text.startswith(quote) and text.endswith(quote):
return text[len(quote) : -len(quote)]
# handle prefixed strings like b"...", r"...", f"..."
# strip the prefix first
for prefix in ("b", "B", "r", "R", "f", "F", "rb", "Rb", "rB", "RB", "br", "Br", "bR", "BR"):
if text.startswith(prefix):
text = text[len(prefix) :]
break
for quote in ('"""', "'''", '"', "'"):
if text.startswith(quote) and text.endswith(quote):
return text[len(quote) : -len(quote)]
return ""
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for stripping prefixes and quotes in _extract_string_value is a bit repetitive and could be refactored for better clarity and robustness. A helper function to strip quotes, combined with a single pass to strip prefixes, would make the code cleaner and easier to maintain.

    def _strip_quotes(self, s: str) -> str:
        for quote in ('"""', "'''", '"', "'"):
            if s.startswith(quote) and s.endswith(quote):
                return s[len(quote) : -len(quote)]
        return s

    def _extract_string_value(self, node: Node) -> str:
        text = node.text.decode("utf-8")
        
        # First, try to strip any prefix (e.g., b, r, f, rb, etc.).
        # Iterate through common prefixes, prioritizing longer ones.
        for prefix in ("rb", "br", "rB", "Rb", "RB", "bR", "Br", "b", "B", "r", "R", "f", "F"):
            if text.startswith(prefix):
                text = text[len(prefix):]
                break
        
        # Then, strip the quotes from the remaining string.
        return self._strip_quotes(text)

@mike-hunhoff
Copy link
Copy Markdown
Collaborator

dup of #2931

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants