Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dojo-compiler): add sierra to cairo debug information #2392

Merged
merged 2 commits into from
Sep 6, 2024

Conversation

kariy
Copy link
Member

@kariy kariy commented Sep 6, 2024

related #2333

Summary by CodeRabbit

  • New Features

    • Enhanced compilation process with optional debug information for improved debugging capabilities.
    • Introduced structured debug information mapping for Starknet contracts.
    • New module for debug functionality to streamline debugging processes.
  • Bug Fixes

    • Adjusted handling of debug data during compilation to ensure accurate retrieval and storage.
  • Documentation

    • Updated documentation to reflect new debug information structures and functions for better user guidance.

@kariy kariy requested a review from glihm September 6, 2024 17:21
Copy link

coderabbitai bot commented Sep 6, 2024

Walkthrough

Ohayo, sensei! The recent changes enhance the DojoCompiler by integrating debug information into the compilation process. A new structure, SierraToCairoDebugInfo, is added to various functions and data structures, enabling the collection and storage of debug data alongside compiled contracts. Additionally, a new module for handling debug information is created, improving the organization and functionality of the codebase.

Changes

Files Change Summary
crates/dojo-lang/src/compiler.rs Enhanced DojoCompiler to include optional debug information in compilation, modifying function signatures and adding new functions for debug data handling.
crates/dojo-lang/src/scarb_internal/debug.rs Introduced new file for compiling Starknet contracts into debug information with key functions and data structures for mapping debug data.
crates/dojo-lang/src/scarb_internal/mod.rs Added a new public module declaration for debug, improving modularity without altering existing logic.

Sequence Diagram(s)

sequenceDiagram
    participant Compiler
    participant DebugInfo
    participant Workspace

    Compiler->>DebugInfo: Request debug information
    DebugInfo-->>Compiler: Return debug data
    Compiler->>Workspace: Save compiled classes with debug info
Loading

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 12f6a9e and f8ea470.

Files selected for processing (1)
  • crates/dojo-lang/src/compiler.rs (18 hunks)
Additional comments not posted (5)
crates/dojo-lang/src/compiler.rs (5)

44-44: New module import for debug information handling.

The import of SierraToCairoDebugInfo from crate::scarb_internal::debug is crucial for the new debugging capabilities. This ensures that the necessary structures are available for handling the debug information.


46-53: Addition of debug_info to CompiledArtifact.

The inclusion of an optional debug_info field in the CompiledArtifact struct is a significant enhancement. This allows each compiled artifact to potentially carry its own debug information, enhancing traceability and debugging capabilities.


Line range hint 298-506: Refactoring of update_files to handle new debug information.

The update_files function now handles the new debug information structure, ensuring that if debug data is present, it is saved alongside the contract artifacts. This is a critical update that supports the new debugging features introduced in this PR.

The function has been expanded to handle various scenarios and save the corresponding debug information files. This comprehensive approach ensures that all necessary data is available for debugging and verification purposes.


Line range hint 519-589: Enhancements to model and contract artifact handling.

The functions get_dojo_model_artifacts and get_dojo_contract_artifacts have been updated to handle the new tuple structure that includes SierraToCairoDebugInfo. This change is essential for maintaining consistency across the compiler's functionality and ensuring that debug information is correctly associated with each compiled class.

These updates are well-implemented and align with the overall goal of enhancing the compiler's debugging capabilities.


703-720: New function to save debug information as JSON.

The addition of save_json_artifact_debug_file is a key enhancement that supports the new debugging features. This function serializes the SierraToCairoDebugInfo into a JSON format, which is crucial for external tools and systems to utilize this debug information effectively.

This function is well-implemented and crucial for the success of the debugging enhancements.


Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Outside diff range, codebase verification and nitpick comments (1)
crates/dojo-lang/src/scarb_internal/mod.rs (1)

35-35: Ohayo, sensei! New module declaration looks good.

The pub mod debug; declaration is syntactically correct and properly placed within the file. However, it would be beneficial to add documentation to clarify the responsibilities and usage of the debug module to help other developers understand its role in the system.

Comment on lines +38 to +52
fn compile_contract_with_prepared_and_checked_db_to_debug_info(
db: &RootDatabase,
contract: &ContractDeclaration,
) -> Result<SierraProgramDebugInfo> {
let SemanticEntryPoints { external, l1_handler, constructor } =
extract_semantic_entrypoints(db, contract)?;
let SierraProgramWithDebug { program: _sierra_program, debug_info } = Arc::unwrap_or_clone(
db.get_sierra_program_for_functions(
chain!(&external, &l1_handler, &constructor).map(|f| f.value).collect(),
)
.to_option()
.with_context(|| "Compilation failed without any diagnostics.")?,
);

Ok(debug_info)
Copy link

Choose a reason for hiding this comment

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

Consider enhancing error messages.

The function compile_contract_with_prepared_and_checked_db_to_debug_info is well-implemented. However, consider adding more specific error messages or handling for different cases to improve debugging and maintenance.

Comment on lines +55 to +58
#[derive(Debug, Clone, Serialize)]
pub struct SierraToCairoDebugInfo {
pub sierra_statements_to_cairo_info: HashMap<usize, SierraStatementToCairoDebugInfo>,
}
Copy link

Choose a reason for hiding this comment

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

Add documentation for clarity.

The SierraToCairoDebugInfo structure is crucial for mapping debug information. Consider adding documentation to explain its purpose and usage within the system.

Comment on lines +81 to +115
/// Returns a map from Sierra statement indexes to Cairo function names.
pub fn get_sierra_to_cairo_debug_info(
sierra_program_debug_info: &SierraProgramDebugInfo,
compiler_db: &RootDatabase,
) -> SierraToCairoDebugInfo {
let mut sierra_statements_to_cairo_info: HashMap<usize, SierraStatementToCairoDebugInfo> =
HashMap::new();

for (statement_idx, locations) in
sierra_program_debug_info.statements_locations.locations.iter_sorted()
{
let mut cairo_locations: Vec<Location> = Vec::new();
for location in locations {
let syntax_node = location.syntax_node(compiler_db);
let file_id = syntax_node.stable_ptr().file_id(compiler_db);
let _file_name = file_id.file_name(compiler_db);
let syntax_node_location_span = syntax_node.span_without_trivia(compiler_db);

let (originating_file_id, originating_text_span) =
get_originating_location(compiler_db, file_id, syntax_node_location_span);
let cairo_location = get_location_from_text_span(
originating_text_span,
originating_file_id,
compiler_db,
);
if let Some(cl) = cairo_location {
cairo_locations.push(cl);
}
}
sierra_statements_to_cairo_info
.insert(statement_idx.0, SierraStatementToCairoDebugInfo { cairo_locations });
}

SierraToCairoDebugInfo { sierra_statements_to_cairo_info }
}
Copy link

Choose a reason for hiding this comment

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

Optimize data handling.

The function get_sierra_to_cairo_debug_info performs multiple iterations and data transformations. Consider optimizing these processes to improve performance and maintainability.

Comment on lines +117 to +155
pub fn get_location_from_text_span(
text_span: TextSpan,
file_id: FileId,
compiler_db: &RootDatabase,
) -> Option<Location> {
let current_dir = env::current_dir().expect("Failed to get current directory");
// dbg!(&current_dir);
// let file_path = match compiler_db.lookup_intern_file(file_id) {
// FileLongId::OnDisk(path) => {
// path.strip_prefix(current_dir).expect("Failed to get relative
// path").to_path_buf().to_str().unwrap_or("<unknown>").to_string() },
// FileLongId::Virtual(_) => file_id.full_path(compiler_db),
// };
let file_path = match compiler_db.lookup_intern_file(file_id) {
FileLongId::OnDisk(path) => match path.strip_prefix(&current_dir) {
Ok(relative_path) => relative_path.to_str().unwrap_or("<unknown>").to_string(),
Err(_) => {
return None;
}
},
FileLongId::Virtual(_) => {
return None;
}
};

// let file_path = file_id.full_path(compiler_db);

let start: Option<TextPosition> = text_span
.start
.position_in_file(compiler_db, file_id)
.map(|s| TextPosition { line: s.line, col: s.col });

let end = text_span
.end
.position_in_file(compiler_db, file_id)
.map(|e| TextPosition { line: e.line, col: e.col });

start.zip(end).map(|(start, end)| Location { start, end, file_path })
}
Copy link

Choose a reason for hiding this comment

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

Improve file path handling.

The function get_location_from_text_span handles file paths and positions. Consider making the file path handling more robust to avoid potential issues with path resolutions and errors.

Copy link

codecov bot commented Sep 6, 2024

Codecov Report

Attention: Patch coverage is 88.48168% with 22 lines in your changes missing coverage. Please review.

Project coverage is 68.42%. Comparing base (dd4cd5f) to head (f8ea470).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
crates/dojo-lang/src/scarb_internal/debug.rs 82.05% 14 Missing ⚠️
crates/dojo-lang/src/compiler.rs 92.92% 8 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2392      +/-   ##
==========================================
+ Coverage   68.37%   68.42%   +0.04%     
==========================================
  Files         357      358       +1     
  Lines       47188    47328     +140     
==========================================
+ Hits        32267    32386     +119     
- Misses      14921    14942      +21     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (1)
crates/dojo-lang/src/compiler.rs (1)

Line range hint 104-206: Major changes in the compile method to support debug information.

The compile method has been significantly refactored to support the collection of debug information based on the with_debug_info flag. This is a robust enhancement that aligns with the PR's objectives to improve debugging capabilities for the Dojo compiler.

However, there are a couple of TODO comments (lines 104 and 146) that suggest further simplifications and enhancements are planned. It would be wise to track these in your project management tool to ensure they are not forgotten.

Would you like me to open a GitHub issue to track the completion of these TODO items?

@kariy kariy merged commit ecab100 into main Sep 6, 2024
15 checks passed
@kariy kariy deleted the feat/walnut-debug-info branch September 6, 2024 19:10
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