- Add UI controls for audience level and explanation type selection - Fetch available options dynamically from GET endpoint with fallback - Implement proper state management with URL persistence - Fix critical bug where class property initializers overwrote saved state - Add cache status indicators (client/server/fresh) in bottom bar - Update API integration for new camelCase field names - Include audience, explanation, and bypassCache parameters in requests - Add comprehensive TypeScript interfaces for type safety Key Features: - Audience levels: Beginner, Intermediate, Expert - Explanation types: Assembly, Source, Optimization - State preserved across page reloads and URL sharing - Multi-level caching with clear status indicators - Graceful fallback when API unavailable 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
7.9 KiB
Claude Explain
Claude Explain is a feature in Compiler Explorer that uses Claude AI to provide natural language explanations of assembly code generation. This feature helps users understand how their source code is translated into assembly, what optimizations are applied, and why certain compiler decisions were made.
How It Works
- After compilation, users can click the "Explain with Claude" button (robot icon) in the compiler pane toolbar.
- A dedicated Explain pane opens, prompting users to consent to sending their code and compilation output to the Claude Explain API.
- Users can customize their explanation by selecting:
- Audience Level: Beginner, Intermediate, or Expert
- Explanation Type: Assembly-focused, Source-to-assembly mapping, or Optimization-focused
- Once consent is given (persisted for the browser session), the code, compiler information, and assembly output are sent to the API.
- Claude analyzes the relationship between the source code and generated assembly, then provides a tailored explanation.
- The explanation is displayed in markdown format with syntax highlighting in the explain pane.
- Subsequent compilations automatically update the explanation if the explain pane is open.
- Responses are cached both client-side and server-side to avoid redundant API calls.
Configuration
The Claude Explain feature requires minimal configuration:
# In compiler-explorer.defaults.properties
explainApiEndpoint=https://api.compiler-explorer.com/explain
That's it! No tool configuration is needed. The explain button automatically appears in the compiler toolbar when an API endpoint is configured and hides when it's not.
Privacy Notice
When using Claude Explain:
- Your source code and compilation output are sent to an external API.
- Data is only sent after explicit user consent.
- Consent is remembered for your browser session.
- The API is provided by Anthropic, the makers of Claude.
- The API may store information to improve its service.
- You can add
// no-aicomment to your source code to prevent it from being sent to the API (planned feature).
Technical Implementation
The feature consists of:
-
Server-side configuration: A single property setting to configure the API endpoint.
-
Client-side component:
- The
ExplainViewclass (static/panes/explain-view.ts) which extendsPaneto:- Display a consent prompt with clear information about what data is sent
- Make API requests to the Claude Explain endpoint
- Cache responses using an LRU cache (200KB limit) to reduce API costs
- Present the explanation with markdown rendering and syntax highlighting
- Handle error states and loading indicators
- Show usage statistics (tokens, cost, model) in a bottom bar
- Uses the
markedlibrary for markdown rendering - Features theme-aware styling (light/dark modes)
- Includes a reload button to bypass cache and get fresh explanations
- The
-
Compiler integration:
- A button is added to the compiler pane toolbar
- The button disables when an explain view is already open for that compiler
- Proper event handling for view lifecycle
UI Features
The explain pane provides:
- Clean rendering of markdown content using the
markedlibrary - Syntax highlighting for code blocks using Prism.js
- Theme-aware styling that adapts to light/dark modes
- Responsive layout with font scaling support
- Loading states with animated spinner
- Error states with helpful messages
- Customization controls:
- Audience Level selector: Choose between Beginner, Intermediate, or Expert explanations
- Explanation Type selector: Focus on Assembly, Source-to-assembly mapping, or Optimizations
- Bottom status bar showing:
- AI model used (e.g., claude-3-opus-20240229)
- Token usage (input/output/total)
- Estimated cost (input/output/total)
- Cache status indicator (client cache, server cache, or fresh generation)
- Reload button to bypass all caches
- Session-persistent consent (you only need to consent once per browser session)
API Integration
GET Request - Available Options
On first load, the client fetches available options:
GET /
Returns:
{
"audience": [
{
"value": "beginner",
"description": "For beginners learning assembly language. Uses simple language and explains technical terms."
},
{
"value": "intermediate",
"description": "For users familiar with basic assembly concepts. Focuses on compiler behavior and choices."
},
{
"value": "expert",
"description": "For advanced users. Uses technical terminology and covers advanced optimizations."
}
],
"explanation": [
{
"value": "assembly",
"description": "Explains the assembly instructions and their purpose."
},
{
"value": "source",
"description": "Explains how source code constructs map to assembly instructions."
},
{
"value": "optimization",
"description": "Explains compiler optimizations and transformations applied to the code."
}
]
}
POST Request - Generate Explanation
The client sends a POST request to generate an explanation:
{
"language": "c++",
"compiler": "GCC 13.2",
"code": "Source code",
"compilationOptions": ["-O2", "-std=c++20"],
"instructionSet": "amd64",
"asm": ["Assembly output lines"],
"audience": "intermediate", // Optional, default: "beginner"
"explanation": "optimization", // Optional, default: "assembly"
"bypassCache": false // Optional, default: false
}
The API returns:
{
"status": "ok",
"explanation": "Markdown-formatted explanation",
"model": "claude-3-opus-20240229",
"usage": {
"inputTokens": 500,
"outputTokens": 300,
"totalTokens": 800
},
"cost": {
"inputCost": 0.0015,
"outputCost": 0.0045,
"totalCost": 0.006
},
"cached": false // Indicates if served from server-side cache
}
Caching
The explain feature uses multi-level caching to reduce API costs and improve response times:
Client-Side Cache
- Responses are cached using an LRU (Least Recently Used) cache
- Cache key is based on the hash of the API request payload (including audience and explanation type)
- Cache has a 200KB size limit
- Stored in browser memory for the session
Server-Side Cache
- The API server also caches responses
- Cached responses are indicated by
cached: truein the API response - Server cache is shared across all users
Cache Bypass
- Users can bypass all caches using the reload button in the bottom bar
- This sends
bypassCache: trueto the API, forcing fresh generation - Fresh responses are still written to both caches for future use
Cache Status Display
- The bottom bar shows cache status:
- 🔄 "Cached (client)" - Served from browser cache
- 🔄 "Cached (server)" - Served from API server cache
- ✨ "Fresh" - Newly generated explanation
Limitations
- Claude may not be able to explain every compiler optimization or assembly pattern.
- Large assemblies may be truncated before being sent to the API.
- The feature requires an internet connection to access the external API.
- Currently available for all languages supported by Compiler Explorer.
- Some UI themes (particularly pink) may have styling issues.
Future Improvements
- Support for
// no-aimagic comment to prevent code from being sent to API - Better language detection based on compiler properties
- Instruction set detection from compiler properties
- Persistent user preferences (audience level, explanation type) across sessions
- Persistent consent across browser sessions (currently session-only)
- Extract common UI patterns to base classes
- Add frontend tests for the explain view
- Fix theme-specific styling issues
- Improve error handling with more granular UI states
- Support for additional explanation types and audience levels as they become available