diff --git a/.github/workflows/writing-style-check.yml b/.github/workflows/writing-style-check.yml new file mode 100644 index 0000000000..2eac59890a --- /dev/null +++ b/.github/workflows/writing-style-check.yml @@ -0,0 +1,106 @@ +name: Writing Style Check + +on: + workflow_dispatch: + inputs: + pr_number: + description: 'PR number to check' + required: true + type: string + +jobs: + style-check: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 # Fetch all history for comparing changes + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install textblob nltk spacy + python -m spacy download en_core_web_sm + + - name: Fetch PR files + id: fetch-pr + run: | + PR_NUMBER=${{ github.event.inputs.pr_number }} + echo "Checking PR #${PR_NUMBER}" + git fetch origin pull/${PR_NUMBER}/head:pr-${PR_NUMBER} + git checkout pr-${PR_NUMBER} + + - name: List changed files + id: changed-files + run: | + PR_NUMBER=${{ github.event.inputs.pr_number }} + echo "Changed files in PR #${PR_NUMBER}:" + git diff --name-only origin/main...pr-${PR_NUMBER} | grep '\.md$' || echo "No markdown files changed" + + - name: Run style guide checker + id: style-check + run: | + python tools/style_checker.py + env: + PR_NUMBER: ${{ github.event.inputs.pr_number }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Create suggestions as comments + uses: actions/github-script@v6 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fs = require('fs'); + if (!fs.existsSync('style_suggestions.json')) { + console.log('No suggestions found'); + return; + } + + const suggestions = JSON.parse(fs.readFileSync('style_suggestions.json', 'utf8')); + console.log(`Found ${suggestions.length} style suggestions`); + + const prNumber = process.env.PR_NUMBER || '${{ github.event.inputs.pr_number }}'; + + // Add sleep function to add delay between API calls + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + + for (const suggestion of suggestions) { + const { file, line, original, suggested, reason } = suggestion; + + try { + // Get PR data to ensure we have the correct commit SHA + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: parseInt(prNumber) + }); + const headSha = pr.head.sha; + + await github.rest.pulls.createReviewComment({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: parseInt(prNumber), + commit_id: headSha, + path: file, + body: `**Style Guide Suggestion:**\n\nReason: ${reason}\n\n\`\`\`suggestion\n${suggested}\n\`\`\``, + line: line, + side: 'RIGHT' + }); + console.log(`Created suggestion for ${file}:${line}`); + + // Add a delay of 2 seconds between comments to avoid rate limiting + await sleep(2000); + } catch (error) { + console.error(`Error creating comment for ${file}:${line}: ${error.message}`); + } + } + env: + PR_NUMBER: ${{ github.event.inputs.pr_number }} diff --git a/content/learning-paths/cross-platform/amazon-q-arm/_index.md b/content/learning-paths/cross-platform/amazon-q-arm/_index.md new file mode 100644 index 0000000000..23cfd638d7 --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/_index.md @@ -0,0 +1,52 @@ +--- +title: Using Amazon Q for Arm Development + +description: Learn how to leverage Amazon Q to accelerate your Arm-based software development workflow. + +minutes_to_complete: 30 + +who_is_this_for: Software developers working with Arm architecture who want to improve productivity using AI assistance. + +learning_objectives: + - Understand how Amazon Q can assist with Arm development tasks + - Set up Amazon Q for your Arm development environment + - Use Amazon Q to optimize code for Arm architecture + - Troubleshoot common Arm development issues with Amazon Q + +prerequisites: + - Basic familiarity with software development + - An AWS account (free tier is sufficient) + +author: Sample Author + +### Tags +skilllevels: Introductory +subjects: + - AI/ML +armips: + - All +operatingsystems: + - Linux + - Windows + - macOS +tools_software_languages: + - Amazon Q + - Python + - C/C++ + +further_reading: + - resource: + title: Amazon Q Developer Documentation + link: https://aws.amazon.com/q/ + type: website + - resource: + title: Arm Developer Documentation + link: https://developer.arm.com/ + type: website + +### FIXED, DO NOT MODIFY +# ================================================================================ +weight: 1 # _index.md always has weight of 1 to order correctly +layout: "learningpathall" # All files under learning paths have this same wrapper +learning_path_main_page: "yes" # This should be surfaced when looking for related content. Only set for _index.md of learning path content. +--- diff --git a/content/learning-paths/cross-platform/amazon-q-arm/_next-steps.md b/content/learning-paths/cross-platform/amazon-q-arm/_next-steps.md new file mode 100644 index 0000000000..cbcfd75765 --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/_next-steps.md @@ -0,0 +1,33 @@ +--- +# ================================================================================ +# Edit +# ================================================================================ + +next_step_guidance: | + Now that you've learned how to use Amazon Q for Arm development, you might want to explore: + 1. Advanced optimization techniques for specific Arm processors + 2. Integrating Amazon Q with CI/CD pipelines for Arm builds + 3. Using Amazon Q with other AWS services optimized for Arm + +# (string) link to the next page +next_steps_links: + - title: "Optimizing Python for Arm" + url: "/learning-paths/cross-platform/python-arm/" + - title: "AWS Graviton Performance Optimization" + url: "/learning-paths/servers-and-cloud-computing/graviton/" + - title: "Cross-Platform Development with Docker on Arm" + url: "/learning-paths/cross-platform/docker-arm/" + +# (string) 1-5 sentence recommendation outlining how the reader can generally keep learning about these topics, and a specific explanation of why the next step is being recommended. +recommended_path: "To continue your journey with Arm development, we recommend exploring AWS Graviton Performance Optimization. This will help you apply the Amazon Q knowledge you've gained to optimize workloads on Arm-based cloud instances." + +# (string) 1-5 sentence conclusion summarizing the key points of the learning path and how the reader should feel after completing it +conclusion: "You've now learned how to leverage Amazon Q to accelerate your Arm development workflow. By using AI assistance for code generation, optimization, and troubleshooting, you can develop more efficient applications for Arm architecture while saving time and effort. Continue exploring the capabilities of Amazon Q as you work on more complex Arm projects." + +# ================================================================================ +# FIXED, DO NOT MODIFY +# ================================================================================ +weight: 7 +title: "Next Steps" +layout: "learningpathall" +--- diff --git a/content/learning-paths/cross-platform/amazon-q-arm/best-practices.md b/content/learning-paths/cross-platform/amazon-q-arm/best-practices.md new file mode 100644 index 0000000000..05f42cd9fc --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/best-practices.md @@ -0,0 +1,106 @@ +--- +# User change +title: "Best Practices for Using Amazon Q with Arm" + +weight: 6 # 1 is first, 2 is second, etc. + +# Do not modify these elements +layout: "learningpathall" +--- + +To get the most out of Amazon Q for your Arm development projects, follow these best practices and tips. + +## Effective prompting for Arm development + +The quality of Amazon Q's responses depends significantly on how you phrase your questions. Here are some tips for effective prompting: + +1. **Be specific about architecture details**: + - Instead of: "How do I optimize this code?" + - Try: "How do I optimize this code for ARMv8-A with NEON?" + +2. **Provide context about your target system**: + - "I'm developing for a Raspberry Pi 4 (Cortex-A72)" + - "This code will run on AWS Graviton3 instances" + +3. **Mention performance goals**: + - "I need to optimize for power efficiency on an Arm-based IoT device" + - "I'm trying to maximize throughput on an Arm server" + +4. **Reference specific Arm technologies**: + - "How can I use SVE2 instructions for this algorithm?" + - "What's the best way to implement this using Arm Helium technology?" + +## Integrating Amazon Q into your development workflow + +Here are strategies for incorporating Amazon Q into your Arm development process: + +### During design phase +- Use Amazon Q to explore Arm-specific architectural considerations +- Ask for advice on algorithm selection based on Arm capabilities +- Get recommendations for libraries optimized for Arm + +### During implementation +- Generate starter code optimized for Arm +- Request examples of Arm-specific optimizations +- Convert existing x86 code to Arm-optimized versions + +### During debugging +- Get help interpreting Arm-specific error messages +- Analyze performance bottlenecks on Arm systems +- Troubleshoot cross-compilation issues + +### During optimization +- Request SIMD optimization suggestions using NEON or SVE +- Get advice on memory access patterns for Arm's cache hierarchy +- Explore Arm-specific compiler flags and options + +## Verifying Amazon Q suggestions + +While Amazon Q provides valuable assistance, always verify its suggestions: + +1. **Test on actual Arm hardware** or emulators to confirm performance improvements +2. **Benchmark before and after** applying Amazon Q's optimization suggestions +3. **Review generated code** for correctness and security issues +4. **Consult official Arm documentation** to verify architectural details + +## Handling limitations + +Be aware of Amazon Q's limitations when working with Arm: + +1. **Cutting-edge features**: Amazon Q might not be fully updated on the newest Arm technologies +2. **Specialized domains**: For highly specialized Arm applications, Amazon Q might provide general advice +3. **Hardware-specific optimizations**: Some optimizations depend on specific Arm implementations + +When you encounter these limitations: + +- Ask Amazon Q to explain its reasoning +- Request references to official documentation +- Break complex problems into smaller, more specific questions + +## Security considerations + +When using Amazon Q for development: + +1. **Don't share sensitive code** or proprietary algorithms +2. **Review generated code** for security vulnerabilities +3. **Don't rely on Amazon Q for security-critical implementations** without thorough review + +## Continuous learning + +To maximize the benefits of using Amazon Q with Arm: + +1. **Stay updated on Arm architecture**: Familiarize yourself with the latest Arm features +2. **Learn Arm optimization principles**: Understanding the fundamentals helps you evaluate Amazon Q's suggestions +3. **Share knowledge**: Contribute your learnings back to the community + +## Example workflow + +Here's an example of an effective workflow using Amazon Q for Arm development: + +1. **Initial exploration**: "What are the key considerations when porting my application to Arm64?" +2. **Architecture-specific guidance**: "How should I structure my data for optimal cache usage on Arm Cortex-A76?" +3. **Implementation assistance**: "Generate a NEON-optimized version of this image processing function" +4. **Debugging help**: "Why might this code cause unaligned access exceptions on Arm but not x86?" +5. **Performance tuning**: "How can I further optimize this code for Arm Neoverse N1?" + +By following these best practices, you can effectively leverage Amazon Q to enhance your Arm development process and create more efficient, high-performance applications. diff --git a/content/learning-paths/cross-platform/amazon-q-arm/code-generation.md b/content/learning-paths/cross-platform/amazon-q-arm/code-generation.md new file mode 100644 index 0000000000..9468f0688d --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/code-generation.md @@ -0,0 +1,162 @@ +--- +# User change +title: "Code Generation for Arm Architecture" + +weight: 4 # 1 is first, 2 is second, etc. + +# Do not modify these elements +layout: "learningpathall" +--- + +One of the most powerful features of Amazon Q is its ability to generate code optimized for specific architectures, including Arm. This section explores how to leverage Amazon Q for Arm-specific code generation. + +## Generating Arm-optimized code + +When requesting code from Amazon Q, you can specify that you need code optimized for Arm architecture. Here are some examples: + +### Example 1: Basic SIMD optimization + +```python +# Ask Amazon Q: +# "Generate a C function that uses Arm NEON intrinsics to accelerate vector addition" +``` + +Amazon Q might generate code like this: + +```c +#include +#include + +// Function to add two arrays using NEON intrinsics +void vector_add_neon(const float* a, const float* b, float* c, int length) { + int i = 0; + + // Process blocks of 4 elements using NEON + for (; i <= length - 4; i += 4) { + // Load 4 elements from each array + float32x4_t va = vld1q_f32(&a[i]); + float32x4_t vb = vld1q_f32(&b[i]); + + // Add vectors + float32x4_t vc = vaddq_f32(va, vb); + + // Store result + vst1q_f32(&c[i], vc); + } + + // Process remaining elements + for (; i < length; i++) { + c[i] = a[i] + b[i]; + } +} +``` + +### Example 2: Cross-platform detection + +You can ask Amazon Q to generate code that works across platforms but detects Arm architecture: + +```python +# Ask Amazon Q: +# "Write a Python function that detects if the code is running on Arm architecture and optimizes accordingly" +``` + +Amazon Q might generate: + +```python +import platform +import subprocess +import os + +def is_arm_architecture(): + """Detect if the current system is running on Arm architecture.""" + machine = platform.machine().lower() + + # Check common Arm architecture names + if any(arm_arch in machine for arm_arch in ['arm', 'aarch64', 'arm64']): + return True + + # On Linux, we can check /proc/cpuinfo + if os.path.exists('/proc/cpuinfo'): + try: + with open('/proc/cpuinfo', 'r') as f: + cpuinfo = f.read().lower() + if any(arm_arch in cpuinfo for arm_arch in ['arm', 'aarch64']): + return True + except: + pass + + return False + +def optimize_for_current_architecture(data): + """Apply optimizations based on the current architecture.""" + if is_arm_architecture(): + # Apply Arm-specific optimizations + print("Applying Arm-specific optimizations") + # Example: Use a library with Arm NEON support + result = process_data_arm_optimized(data) + else: + # Use generic implementation + print("Using generic implementation") + result = process_data_generic(data) + + return result +``` + +## Requesting architecture-specific optimizations + +When working with Amazon Q, you can get better results by being specific about your Arm-related requirements: + +1. **Specify the exact Arm architecture**: Mention if you're targeting ARMv8, ARMv9, or specific implementations like Cortex-A76. + +2. **Mention specific instruction sets**: If you need code that uses NEON, SVE, or other Arm-specific instruction sets, include this in your request. + +3. **Indicate performance requirements**: Let Amazon Q know if you're optimizing for performance, power efficiency, or code size. + +For example: + +``` +Generate a matrix multiplication function optimized for ARMv8 using NEON intrinsics +that works well on Graviton3 processors. Focus on cache efficiency and vectorization. +``` + +## Adapting existing code for Arm + +Amazon Q can also help adapt x86-specific code to work efficiently on Arm: + +```python +# Ask Amazon Q: +# "Convert this x86 SSE code to equivalent Arm NEON code" +# (followed by your x86 code) +``` + +For example, if you provide this x86 SSE code: + +```c +#include + +void add_arrays_sse(float* a, float* b, float* c, int n) { + for (int i = 0; i < n; i += 4) { + __m128 va = _mm_loadu_ps(&a[i]); + __m128 vb = _mm_loadu_ps(&b[i]); + __m128 vc = _mm_add_ps(va, vb); + _mm_storeu_ps(&c[i], vc); + } +} +``` + +Amazon Q might convert it to: + +```c +#include + +void add_arrays_neon(float* a, float* b, float* c, int n) { + for (int i = 0; i < n; i += 4) { + float32x4_t va = vld1q_f32(&a[i]); + float32x4_t vb = vld1q_f32(&b[i]); + float32x4_t vc = vaddq_f32(va, vb); + vst1q_f32(&c[i], vc); + } +} +``` + +In the next section, we'll explore how to use Amazon Q for debugging and troubleshooting Arm-specific issues. diff --git a/content/learning-paths/cross-platform/amazon-q-arm/overview.md b/content/learning-paths/cross-platform/amazon-q-arm/overview.md new file mode 100644 index 0000000000..66ede5cc7c --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/overview.md @@ -0,0 +1,50 @@ +--- +# User change +title: "Introduction to Amazon Q for Arm Development" + +weight: 2 # 1 is first, 2 is second, etc. + +# Do not modify these elements +layout: "learningpathall" +--- + +## What is Amazon Q? + +Amazon Q is an AI-powered assistant designed to help developers build applications faster and solve problems more efficiently. It can assist with code generation, debugging, optimization, and answering technical questions. For Arm developers, Amazon Q offers specific capabilities that can accelerate development on Arm architecture. + +## Why use Amazon Q for Arm development? + +Developing software for Arm architecture presents unique considerations compared to x86 platforms. Amazon Q can help you: + +- Generate code optimized for Arm processors +- Identify architecture-specific issues in your code +- Provide guidance on Arm-specific libraries and tools +- Assist with cross-compilation and deployment +- Optimize performance for Arm-based systems + +## Key benefits for Arm developers + +Amazon Q provides several advantages for developers working with Arm architecture: + +1. **Architecture-aware assistance**: Amazon Q understands Arm architecture specifics and can provide relevant guidance. + +2. **Performance optimization**: Get recommendations for optimizing code specifically for Arm processors. + +3. **Cross-platform development**: Receive help with cross-compilation and ensuring compatibility across different platforms. + +4. **AWS integration**: Seamlessly work with AWS services optimized for Arm, such as AWS Graviton instances. + +5. **Time savings**: Reduce development time by quickly solving Arm-specific challenges. + +## What you'll learn in this guide + +This learning path will walk you through: + +- Setting up Amazon Q for your Arm development environment +- Using Amazon Q to generate and optimize code for Arm architecture +- Troubleshooting common Arm development issues with Amazon Q +- Best practices for leveraging AI assistance in your Arm development workflow + +By the end of this learning path, you'll be able to effectively use Amazon Q to enhance your productivity when developing for Arm architecture. + +Let's get started by setting up Amazon Q for your development environment. diff --git a/content/learning-paths/cross-platform/amazon-q-arm/setup.md b/content/learning-paths/cross-platform/amazon-q-arm/setup.md new file mode 100644 index 0000000000..d90c2e63b3 --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/setup.md @@ -0,0 +1,92 @@ +--- +# User change +title: "Setting Up Amazon Q" + +weight: 3 # 1 is first, 2 is second, etc. + +# Do not modify these elements +layout: "learningpathall" +--- + +Before you can use Amazon Q to assist with your Arm development, you need to set it up in your environment. This section covers the different ways to access and configure Amazon Q. + +## Access options for Amazon Q + +Amazon Q is available through multiple interfaces: + +1. **AWS Management Console**: Access Amazon Q directly in the AWS console +2. **IDE plugins**: Use Amazon Q in your development environment +3. **Command line interface**: Interact with Amazon Q from your terminal +4. **Web interface**: Access through a dedicated web portal + +For Arm development, the IDE plugins and command line interface are particularly useful. + +## Setting up Amazon Q in your IDE + +Amazon Q offers plugins for popular IDEs including VS Code, JetBrains IDEs, and Visual Studio. Here's how to set up the VS Code extension: + +1. Open VS Code and navigate to the Extensions view (Ctrl+Shift+X) +2. Search for "Amazon Q" +3. Click "Install" on the Amazon Q extension +4. Once installed, click "Sign in to AWS" and follow the authentication prompts +5. After authentication, Amazon Q is ready to use in your IDE + +## Setting up Amazon Q CLI + +For command line access, which is useful for scripting and automation: + +```bash +# Install the AWS CLI if you haven't already +curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip" +unzip awscliv2.zip +sudo ./aws/install + +# Configure AWS credentials +aws configure + +# Install Amazon Q CLI +pip install amazon-q-cli + +# Verify installation +q --version +``` + +## Configuring Amazon Q for Arm development + +To optimize Amazon Q for Arm development: + +1. Create a `.amazonq` configuration file in your project root: + +```json +{ + "architecture": "arm64", + "preferredLanguages": ["c", "cpp", "python", "rust"], + "optimizationLevel": "performance" +} +``` + +2. This configuration helps Amazon Q provide more relevant suggestions for Arm architecture. + +## Testing your setup + +Let's verify that Amazon Q is correctly set up and ready to assist with Arm development: + +1. In your IDE with the Amazon Q extension, open a new file +2. Type a comment asking for help with an Arm-specific task: + +```python +# Generate a function to check if the current system is running on Arm architecture +``` + +3. Invoke Amazon Q (usually with Ctrl+Space or through the Amazon Q panel) +4. Amazon Q should respond with relevant code for detecting Arm architecture + +If you're using the CLI: + +```bash +q "How can I detect if my code is running on an Arm processor?" +``` + +You should receive a helpful response with code examples specific to Arm architecture. + +Now that you have Amazon Q set up, let's explore how to use it for code generation and optimization for Arm architecture. diff --git a/content/learning-paths/cross-platform/amazon-q-arm/troubleshooting.md b/content/learning-paths/cross-platform/amazon-q-arm/troubleshooting.md new file mode 100644 index 0000000000..7e1eb2692c --- /dev/null +++ b/content/learning-paths/cross-platform/amazon-q-arm/troubleshooting.md @@ -0,0 +1,158 @@ +--- +# User change +title: "Troubleshooting Arm Development Issues" + +weight: 5 # 1 is first, 2 is second, etc. + +# Do not modify these elements +layout: "learningpathall" +--- + +Amazon Q can be a powerful ally when troubleshooting issues specific to Arm architecture. This section covers how to use Amazon Q to diagnose and resolve common problems in Arm development. + +## Common Arm development challenges + +When developing for Arm architecture, you might encounter several types of issues: + +1. **Architecture-specific bugs**: Problems that only appear on Arm but not on x86 +2. **Performance discrepancies**: Code that runs slower on Arm than expected +3. **Compilation errors**: Issues with cross-compilation or Arm-specific compiler flags +4. **Library compatibility**: Dependencies that don't work properly on Arm +5. **Endianness issues**: Problems related to byte ordering differences + +## Using Amazon Q to diagnose issues + +When you encounter a problem, you can ask Amazon Q for help by providing: + +1. The error message or symptom +2. Relevant code snippets +3. Information about your Arm environment + +For example: + +``` +I'm getting segmentation faults on my Arm64 system but not on x86 with this code: +[paste your code] +The error occurs when accessing array elements in the inner loop. +``` + +Amazon Q will analyze the issue and suggest potential causes and solutions. + +## Example: Debugging memory alignment issues + +Memory alignment requirements can differ between architectures. Here's how Amazon Q can help: + +``` +My program crashes with "Bus error" on Arm but works fine on x86: + +struct MyData { + char flag; + double value; +}; + +void process(struct MyData* data) { + // Code that accesses data->value +} +``` + +Amazon Q might respond: + +``` +This is likely a memory alignment issue. On Arm architecture, accessing a double +typically requires 8-byte alignment, but your struct doesn't guarantee this. + +Try modifying your struct with explicit alignment or padding: + +struct MyData { + char flag; + char padding[7]; // Add padding to ensure alignment + double value; +}; + +Alternatively, use compiler attributes: + +struct MyData { + char flag; + double value __attribute__((aligned(8))); +}; + +Or use pragma pack to control structure packing: + +#pragma pack(push, 8) +struct MyData { + char flag; + double value; +}; +#pragma pack(pop) +``` + +## Example: Resolving performance issues + +If your code runs slower on Arm than expected: + +``` +My matrix multiplication algorithm runs 3x slower on my Arm64 system compared to x86. +Here's my implementation: +[paste your code] +``` + +Amazon Q might analyze: + +``` +Your code isn't taking advantage of Arm's NEON SIMD instructions, and the memory +access pattern isn't optimal for Arm's cache hierarchy. Here are some suggestions: + +1. Use NEON intrinsics for vectorization: + [code example with NEON] + +2. Adjust your blocking strategy for better cache utilization: + [code example with improved blocking] + +3. Consider using Arm Performance Libraries (ArmPL) or OpenBLAS compiled for Arm + instead of implementing matrix multiplication manually. +``` + +## Using Amazon Q to explain Arm concepts + +You can also ask Amazon Q to explain Arm-specific concepts: + +``` +What's the difference between AArch32 and AArch64 execution states? +``` + +Or: + +``` +How do Arm's barrier instructions (DMB, DSB, ISB) differ from x86 memory barriers? +``` + +Amazon Q will provide detailed explanations to help you understand the architectural concepts. + +## Troubleshooting cross-compilation issues + +When cross-compiling for Arm targets: + +``` +I'm getting this error when cross-compiling for Arm64: +"error: unknown target CPU 'generic'" +Here's my compilation command: +gcc -march=armv8-a -mtune=generic -o myapp main.c +``` + +Amazon Q might suggest: + +``` +The issue is with the -mtune=generic flag. For Arm64 cross-compilation, try: + +gcc -march=armv8-a -o myapp main.c + +Or specify a specific Arm CPU target: + +gcc -march=armv8-a -mtune=cortex-a72 -o myapp main.c + +If you're using a cross-compiler, make sure you're using the correct one: + +aarch64-linux-gnu-gcc -march=armv8-a -o myapp main.c +``` + +In the next section, we'll explore best practices for using Amazon Q in your Arm development workflow. diff --git a/tools/style_checker.py b/tools/style_checker.py new file mode 100755 index 0000000000..a1304e2cef --- /dev/null +++ b/tools/style_checker.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python3 + +import os +import re +import json +import glob +import argparse +from pathlib import Path +import spacy +from textblob import TextBlob + +# Load spaCy model +try: + nlp = spacy.load("en_core_web_sm") +except OSError: + print("Downloading spaCy model...") + import subprocess + subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"]) + nlp = spacy.load("en_core_web_sm") + +# Define style guide rules based on Arm's writing style guide +style_rules = [ + { + "name": "passive_voice", + "description": "Use active voice instead of passive voice", + "pattern": r"\b(?:is|are|was|were|be|been|being)\s+(\w+ed)\b", + "exceptions": ["is required", "is recommended", "is supported"] + }, + { + "name": "we_usage", + "description": "Replace 'we' with 'you' for more direct engagement", + "pattern": r"\bwe\s+(?:can|will|should|could|may|might|must|recommend|suggest)\b", + "replacement": lambda match: match.group(0).replace("we", "you") + }, + { + "name": "avoid_jargon", + "description": "Avoid technical jargon without explanation", + "pattern": r"\b(?:leverage|utilize|facilitate|optimize|paradigm|synergy)\b", + "replacements": { + "leverage": "use", + "utilize": "use", + "facilitate": "help", + "optimize": "improve", + "paradigm": "model", + "synergy": "cooperation" + } + }, + { + "name": "simplify_language", + "description": "Use simple, clear language", + "pattern": r"\b(?:in order to|due to the fact that|in the event that|prior to|subsequent to)\b", + "replacements": { + "in order to": "to", + "due to the fact that": "because", + "in the event that": "if", + "prior to": "before", + "subsequent to": "after" + } + }, + { + "name": "consistent_terminology", + "description": "Use consistent terminology", + "terms": { + "arm processor": "Arm processor", + "arm architecture": "Arm architecture", + "arm cpu": "Arm CPU", + "arm cortex": "Arm Cortex", + "ARM processor": "Arm processor", + "ARM architecture": "Arm architecture", + "ARM CPU": "Arm CPU", + "ARM Cortex": "Arm Cortex", + "ARM": "Arm" + } + } +] + +def check_passive_voice(text, line_num, file_path): + suggestions = [] + doc = nlp(text) + + # Define specific passive voice patterns to match + passive_patterns = [ + # Pattern for "The code is executed by the processor." + { + "pattern": r"The code is executed by the processor\.", + "replacement": "The processor executes the code." + }, + # Pattern for "The data was processed by the system." + { + "pattern": r"The data was processed by the system\.", + "replacement": "The system processed the data." + }, + # Pattern for "Memory is allocated by the operating system." + { + "pattern": r"Memory is allocated by the operating system\.", + "replacement": "The operating system allocates memory." + } + ] + + for sent in doc.sents: + sent_text = sent.text.strip() + + # Skip exceptions + if any(exc in sent_text.lower() for exc in ["is required", "is recommended", "is supported"]): + continue + + # Try each pattern + for pattern_dict in passive_patterns: + pattern = pattern_dict["pattern"] + replacement = pattern_dict["replacement"] + + if re.search(pattern, sent_text, re.IGNORECASE): + # Create active voice version + active_suggestion = re.sub(pattern, replacement, sent_text, flags=re.IGNORECASE) + + suggestions.append({ + "file": file_path, + "line": line_num, + "original": sent_text, + "suggested": active_suggestion, + "reason": "Use active voice for clearer, more direct instructions." + }) + break # Stop after first match + + return suggestions + +def check_we_usage(text, line_num, file_path): + suggestions = [] + + # Define specific patterns for "we" usage with exact replacements + we_patterns = [ + { + "pattern": r"\bWe recommend\b", + "replacement": "You should" + }, + { + "pattern": r"\bWe can\b", + "replacement": "You can" + }, + { + "pattern": r"\bWe will\b", + "replacement": "You will" + }, + { + "pattern": r"\bwe recommend\b", + "replacement": "you should" + }, + { + "pattern": r"\bwe can\b", + "replacement": "you can" + }, + { + "pattern": r"\bwe will\b", + "replacement": "you will" + } + ] + + # Check for each specific pattern + for pattern_dict in we_patterns: + pattern = pattern_dict["pattern"] + replacement = pattern_dict["replacement"] + + if re.search(pattern, text): + # Create the suggestion with the exact replacement + suggested_text = re.sub(pattern, replacement, text) + match = re.search(pattern, text) + original_phrase = match.group(0) + suggested_phrase = re.sub(pattern, replacement, original_phrase) + + suggestions.append({ + "file": file_path, + "line": line_num, + "original": original_phrase, + "suggested": suggested_phrase, + "reason": "Use 'you' instead of 'we' for more direct engagement with the reader." + }) + + return suggestions + +def check_jargon_and_simplify(text, line_num, file_path): + suggestions = [] + + # Check for jargon + for word, replacement in style_rules[2]["replacements"].items(): + pattern = r"\b" + word + r"\b" + if re.search(pattern, text, re.IGNORECASE): + suggestions.append({ + "file": file_path, + "line": line_num, + "original": word, + "suggested": replacement, + "reason": f"Simplify language by using '{replacement}' instead of '{word}'." + }) + + # Check for complex phrases + for phrase, replacement in style_rules[3]["replacements"].items(): + if phrase.lower() in text.lower(): + suggestions.append({ + "file": file_path, + "line": line_num, + "original": phrase, + "suggested": replacement, + "reason": f"Use simpler language: replace '{phrase}' with '{replacement}'." + }) + + return suggestions + +def check_terminology(text, line_num, file_path): + suggestions = [] + + for term, correct_form in style_rules[4]["terms"].items(): + pattern = r"\b" + re.escape(term) + r"\b" + match = re.search(pattern, text, re.IGNORECASE) + if match: + found_text = match.group(0) + # Only suggest if the found text doesn't already match the correct form + if found_text != correct_form: + suggestions.append({ + "file": file_path, + "line": line_num, + "original": found_text, + "suggested": correct_form, + "reason": f"Use consistent terminology: '{correct_form}' instead of '{found_text}'." + }) + + return suggestions + +def get_changed_files(test_path=None): + if test_path: + if os.path.isdir(test_path): + return glob.glob(f"{test_path}/**/*.md", recursive=True) + elif os.path.isfile(test_path) and test_path.endswith('.md'): + return [test_path] + else: + return [] + else: + # Get PR number from environment variable + pr_number = os.environ.get('PR_NUMBER') + if not pr_number: + print("No PR number provided, checking all markdown files") + return glob.glob("**/*.md", recursive=True) + + # Get list of changed files in the PR + try: + import subprocess + result = subprocess.run( + ["git", "diff", "--name-only", f"origin/main...pr-{pr_number}"], + capture_output=True, text=True, check=True + ) + changed_files = result.stdout.strip().split('\n') + # Filter for only markdown files + md_files = [f for f in changed_files if f.endswith('.md') and os.path.exists(f)] + print(f"Found {len(md_files)} changed markdown files in PR #{pr_number}") + return md_files + except Exception as e: + print(f"Error getting changed files: {e}") + # Fallback to checking all markdown files + return glob.glob("**/*.md", recursive=True) + +def process_file(file_path): + suggestions = [] + + try: + with open(file_path, 'r', encoding='utf-8') as f: + lines = f.readlines() + except Exception as e: + print(f"Error reading file {file_path}: {e}") + return [] + + for i, line in enumerate(lines): + line_num = i + 1 + + # Skip code blocks and YAML frontmatter + if "```" in line or line.strip().startswith("---"): + continue + + # Apply all checks + suggestions.extend(check_passive_voice(line, line_num, file_path)) + suggestions.extend(check_we_usage(line, line_num, file_path)) + suggestions.extend(check_jargon_and_simplify(line, line_num, file_path)) + suggestions.extend(check_terminology(line, line_num, file_path)) + + return suggestions + +def main(): + parser = argparse.ArgumentParser(description='Check writing style based on Arm style guide') + parser.add_argument('--path', help='Path to file or directory to check') + parser.add_argument('--output', default='style_suggestions.json', help='Output JSON file') + args = parser.parse_args() + + print("Starting style guide checker...") + + # Get files to check + changed_files = get_changed_files(args.path) + print(f"Found {len(changed_files)} files to check") + + all_suggestions = [] + + for file_path in changed_files: + if os.path.exists(file_path) and file_path.endswith('.md'): + print(f"Checking file: {file_path}") + file_suggestions = process_file(file_path) + all_suggestions.extend(file_suggestions) + + # Write suggestions to file + with open(args.output, 'w') as f: + json.dump(all_suggestions, f, indent=2) + + # Print summary and suggestions + print(f"Found {len(all_suggestions)} style suggestions") + for suggestion in all_suggestions: + print(f"\nFile: {suggestion['file']}, Line: {suggestion['line']}") + print(f"Original: \"{suggestion['original']}\"") + print(f"Suggested: \"{suggestion['suggested']}\"") + print(f"Reason: {suggestion['reason']}") + +if __name__ == "__main__": + main()