Problem: kmp

Your task is to implement the Knuth-Morris-Pratt (KMP) algorithm to efficiently find all occurrences of a needle (pattern) within a haystack (text) and verify its functional correctness in Dafny. Preconditions: You can assume the input text and pattern are sequences of integers (representing bytes) and their lengths are at most 1,000,000 to ensure index arithmetic does not overflow. Requirements: Implement the method kmp_search which returns a seq<int>. (1) Preprocessing: You must implement a helper to compute the Longest Prefix Suffix (LPS) array (or "next" array), where lps[i] stores the length of the longest proper prefix of the sub-pattern that is also a suffix of that sub-pattern. (2) Search: The main loop must use the LPS array to skip unnecessary comparisons in the text when a mismatch occurs, achieving linear time complexity. (3) Functional Correctness: Prove that despite the optimization, the result is identical to a naive search (Soundness and Completeness). Verification Challenges: (1) LPS Property: Proving that your preprocessing logic actually satisfies the mathematical definition of the LPS table. (2) Safe Skipping: Proving that the "jump" logic (moving the pattern index based on LPS) never skips a valid match. (3) Complex Invariants: The main loop invariant must relate the current state of the pattern index to the prefix of the pattern matched against the text so far.

// Following is the block for necessary definitions
// <preamble>
predicate matches_at(haystack: seq<int>, needle: seq<int>, start_index: int) {
    && 0 <= start_index
    && start_index + |needle| <= |haystack|
    && forall i :: 0 <= i < |needle| ==> 
        haystack[start_index + i] == needle[i]
}
// </preamble>

// Following is the block for potential helper specifications
// <helpers>

// </helpers>

// Following is the block for proofs of lemmas
// <proofs>

// </proofs>

// Following is the block for the main specification
// <spec>
method kmp_search(haystack: seq<int>, needle: seq<int>) returns (indices: seq<int>)
    requires |haystack| < 1000000
    requires |needle| < 1000000
    ensures 
        // Type Constraint: Indices must be non-negative (simulating usize)
        forall k :: 0 <= k < |indices| ==> indices[k] >= 0
    ensures
        // Soundness: Every index returned is a valid match
        forall i :: 0 <= i < |indices| ==> 
            matches_at(haystack, needle, indices[i])
    ensures
        // Completeness: Every valid match in the haystack is found
        forall i :: matches_at(haystack, needle, i) ==> 
            exists k :: 0 <= k < |indices| && indices[k] == i
// </spec>
// <code>
{
    // Implement and verify the KMP search algorithm to find a specific pattern in a string
}
// </code>