4.2: Code Generation Prompt Templates

SWE.3 Implementation Prompts

Purpose

Use Cases:

  1. Generate C functions from requirements
  2. Generate MISRA C:2012 compliant code
  3. Create Doxygen documentation headers
  4. Implement standard algorithms (CRC, filters, controllers)

Template 1: Generate C Function

Generate Function from Requirement

Prompt:

You are an AI code generator specialized in automotive embedded C (MISRA C:2012, ISO 26262).

Context: I'm developing an {PROJECT_NAME} ECU for automotive {SAFETY_CLASS}.
Target CPU: {CPU_ARCH (e.g., "TriCore TC397, 300 MHz")}
Coding Standard: MISRA C:2012

Requirement:

{REQUIREMENT_TEXT}


Task: Generate C function implementing the requirement:
1. **Function Signature**: Match requirement (input/output types, return code)
2. **Doxygen Header**: Complete documentation (@brief, @param, @return, @implements, @safety_class)
3. **Implementation**: Algorithm matching requirement (with formulas, constraints)
4. **Error Handling**: Defensive programming (null checks, bounds checks, fail-safe)
5. **MISRA Compliance**: 0 Required rule violations (explicit casts, named constants)

Output Format:
```c
/**
 * @brief {Brief description}
 * @implements [{REQUIREMENT_ID}] {Requirement title}
 * @safety_class {ASIL level}
 * @param[in] {name} {description, type, range, units}
 * @param[out] {name} {description, type, range, units}
 * @return 0 = success, -1 = error
 * @precondition {Conditions before calling}
 * @postcondition {Conditions after successful execution}
 */
{return_type} {function_name}({parameters}) {
    /* Implementation */
}

Constraints:

  • MISRA C:2012 compliant (0 Required violations)
  • Defensive programming (input validation)
  • Named constants (no magic numbers)
  • Units in comments (m, s, kg, °C)

**Example Usage**:

{PROJECT_NAME} = "ACC" {SAFETY_CLASS} = "ASIL-B" {CPU_ARCH} = "Infineon AURIX TriCore TC397, 300 MHz" {REQUIREMENT_TEXT} = " [SWE-045-1] Obstacle Distance Calculation The ACC software shall calculate obstacle distance from radar sensor data.

  • Input: uint16_t radar_raw_mm (distance in millimeters, range: 0-65535)
  • Output: float* distance_m (distance in meters, range: 0.0-65.535m)
  • Return: 0 = success, -1 = invalid sensor data (radar_raw_mm == 0xFFFF)
  • Latency: ≤20ms
  • Safety Class: ASIL-B "

---

## Template 2: Generate MISRA-Compliant Code

### Fix MISRA Violations

**Prompt**:

You are an AI MISRA C:2012 compliance expert.

Code with MISRA Violations:

{NON_COMPLIANT_CODE}

MISRA Violations Detected:

{MISRA_VIOLATIONS_LIST}

Task: Refactor code to fix all MISRA violations:

  1. Required Rules (MUST FIX): Fix all Required rule violations
  2. Advisory Rules (SHOULD FIX): Fix Advisory violations where feasible
  3. Explanation: For each fix, explain what was wrong and why the fix is correct

Output Format:

/* Fixed Code (MISRA C:2012 Compliant) */
{COMPLIANT_CODE}

/*
 * MISRA Fixes Applied:
 * 1. Rule 10.1 (Line 45): Added explicit cast (uint16_t → int16_t)
 *    - Issue: Implicit type conversion
 *    - Fix: (int16_t)radar_data
 *
 * 2. Rule 21.3 (Line 128): Replaced malloc() with static buffer
 *    - Issue: Dynamic memory prohibited in ASIL-B
 *    - Fix: static uint8_t buffer[256];
 */

Constraints:

  • Maintain functionality (no behavior change)
  • MISRA C:2012 compliant (0 Required violations)
  • Provide justification for each change

---

## Template 3: Generate Doxygen Documentation

### Add Documentation Headers

**Prompt**:

You are an AI documentation specialist for embedded C.

Function (without Doxygen):

{FUNCTION_WITHOUT_DOXYGEN}

Task: Generate complete Doxygen header:

  1. @brief: One-line summary (imperative mood: "Calculate...", "Validate...")
  2. @implements: Traceability to requirement ([SWE-XXX])
  3. @param: For each parameter (type, range, units)
  4. @return: Return value description (0 = success, -1 = error)
  5. @safety_class: ASIL level (if safety-critical)
  6. @precondition / @postcondition: Pre/post conditions
  7. @note: Additional notes (complexity, limitations)

Output Format:

/**
 * @brief {One-line description}
 * @implements [{REQUIREMENT_ID}] {Requirement title}
 * @safety_class {ASIL level}
 *
 * @param[in] {name} {Description (type, range, units)}
 * @param[out] {name} {Description (type, range, units)}
 * @return 0 = success, -1 = error code
 * @retval 0 Success
 * @retval -1 {Error description}
 *
 * @precondition {Conditions before calling}
 * @postcondition {Conditions after execution}
 *
 * @note {Additional notes}
 */
{ORIGINAL_FUNCTION}

---

## Template 4: Implement Standard Algorithm

### Generate CRC, PID Controller, Kalman Filter

**Prompt**:

You are an AI algorithm implementation specialist for embedded C.

Algorithm: {ALGORITHM_NAME (e.g., "CRC-32 (IEEE 802.3 polynomial)")}

Context: I'm developing an {PROJECT_NAME} ECU for automotive {SAFETY_CLASS}.

Requirements:

  • Input: {INPUT_TYPE} (range: {RANGE}, units: {UNITS})
  • Output: {OUTPUT_TYPE} (range: {RANGE}, units: {UNITS})
  • Algorithm: {ALGORITHM_DESCRIPTION (e.g., "CRC-32 with polynomial 0xEDB88320")}
  • Performance: {LATENCY_REQUIREMENT (e.g., "≤10 µs on TriCore 300 MHz")}

Task: Generate C implementation:

  1. Algorithm: Standard algorithm (e.g., IEEE 802.3 CRC-32, PID with anti-windup)
  2. Optimization: Optimized for {CPU_ARCH} (loop unrolling, table lookup, fixed-point)
  3. MISRA Compliance: MISRA C:2012 compliant
  4. Documentation: Complete Doxygen header

Output Format:

/**
 * @brief Calculate CRC-32 checksum (IEEE 802.3 polynomial)
 * @param[in] data Pointer to data buffer (must not be NULL)
 * @param[in] length Data length in bytes (range: 0-65535)
 * @return CRC-32 checksum (32-bit unsigned integer)
 * @note Polynomial: 0xEDB88320 (reflected CRC-32)
 * @note Complexity: O(n), where n = length
 */
uint32_t CRC32_Calculate(const uint8_t* data, size_t length) {
    /* Implementation */
}

Constraints:

  • Standard algorithm (no custom variants without justification)
  • Optimized for target CPU
  • MISRA C:2012 compliant

**Example Usage (CRC-32)**:

{ALGORITHM_NAME} = "CRC-32 (IEEE 802.3 polynomial)" {PROJECT_NAME} = "ACC" {SAFETY_CLASS} = "ASIL-B" {INPUT_TYPE} = "const uint8_t* data, size_t length" {OUTPUT_TYPE} = "uint32_t (CRC-32 checksum)" {ALGORITHM_DESCRIPTION} = "CRC-32 with polynomial 0xEDB88320 (reflected)" {LATENCY_REQUIREMENT} = "≤10 µs for 64-byte message on TriCore 300 MHz" {CPU_ARCH} = "TriCore TC397"


---

## Template 5: Generate Safety-Critical Function

### ASIL-B/C Function with Fail-Safe

**Prompt**:

You are an AI safety engineer specialized in ISO 26262 ASIL-B/C code generation.

Context: I'm developing an {PROJECT_NAME} ECU for automotive {SAFETY_CLASS}.

Requirement:

{SAFETY_REQUIREMENT_TEXT}

Fail-Safe Behavior:

{FAIL_SAFE_SPECIFICATION}

Task: Generate safety-critical C function with fail-safe behavior:

  1. Normal Operation: Implement requirement logic
  2. Fail-Safe: Handle all failure modes (sensor fault, CAN timeout, invalid data)
  3. Safe State Transition: Transition to safe state on error (disable function, alert driver)
  4. Diagnostics: Log failures for post-mortem analysis
  5. MISRA Compliance: MISRA C:2012 compliant (safety-critical code)

Output Format:

/**
 * @brief {Function description}
 * @implements [{REQUIREMENT_ID}] {Requirement title}
 * @safety_class {ASIL level}
 *
 * @param[in/out] {parameters}
 * @return 0 = normal operation, -1 = sensor fault (safe state entered)
 *
 * @safety_requirement {ISO 26262 requirement reference}
 * @fail_safe_behavior {Description of safe state transition}
 *
 * @note ASIL-B safety function - requires 100% unit test coverage
 */
{return_type} {function_name}({parameters}) {
    /* Defensive programming: Input validation */
    if ({input_invalid}) {
        /* Fail-safe: Transition to safe state */
        {safe_state_transition}
        return -1;
    }

    /* Normal operation */
    {algorithm_implementation}

    /* Error detection: Check for failures */
    if ({failure_detected}) {
        /* Fail-safe: Transition to safe state */
        {safe_state_transition}
        {diagnostic_logging}
        return -1;
    }

    return 0;  /* Success */
}

Constraints:

  • ISO 26262 compliant (fail-safe behavior, safe state transition)
  • MISRA C:2012 compliant
  • 100% unit test coverage (generate test cases)

---

## Summary

**Code Generation Prompts Covered**:

1. **Generate Function**: Create C function from requirement (MISRA compliant, Doxygen)
2. **Fix MISRA Violations**: Refactor non-compliant code (Required + Advisory rules)
3. **Generate Doxygen**: Add complete documentation headers (@brief, @param, @return, @implements)
4. **Implement Algorithm**: Standard algorithms (CRC, PID, Kalman filter)
5. **Safety-Critical Function**: ASIL-B/C function with fail-safe behavior

**Success Metrics**: 85-90% code correctness, 90-95% MISRA compliance, and 90-95% Doxygen quality

**Next**: Review Prompts (32.03) - Code review, MISRA check, traceability verification

---

**Navigation**: [← 32.01 Requirements Prompts](32.01_Requirements_Prompts.md) | [Contents](../00_Front_Matter/00.06_Table_of_Contents.md) | [32.3 Review Prompts →](32.03_Review_Prompts.md)