/* Generated by re2swift */
#sourceLocation(file: "swift/fill/02_fill.re", line: 1)
// re2swift $INPUT -o $OUTPUT
import Foundation

#sourceLocation(file: "swift/fill/02_fill.swift", line: 7)
let yymaxfill = 1
#sourceLocation(file: "swift/fill/02_fill.re", line: 4)


struct Input {
  static let bufferSize = 4096 - yymaxfill

  var file: FileHandle

  var yyinput  = ContiguousArray<UInt8>(repeating: 0, count: Self.bufferSize + yymaxfill)
  var yylimit  = Self.bufferSize
  var yycursor = Self.bufferSize
  var token    = -1
  var eof      = false
}

extension Input {
  mutating func lex() -> Int? {
    var count = 0
    loop: while true {
      self.token = self.yycursor
      
#sourceLocation(file: "swift/fill/02_fill.swift", line: 30)
  var yych: UInt8 = 0
  var yystate: UInt = 0
  yyl: while true {
    switch yystate {
      case 0:
        if self.yylimit <= self.yycursor {
          if self.fill(1) != .ok { return nil }
        }
        yych = self.yyinput[self.yycursor]
        self.yycursor += 1
        switch yych {
          case 0x00:
            yystate = 1
            continue yyl
          case 0x20:
            yystate = 3
            continue yyl
          case 0x27:
            yystate = 5
            continue yyl
          default:
            yystate = 2
            continue yyl
        }
      case 1:
#sourceLocation(file: "swift/fill/02_fill.re", line: 30)
        
            // Check that it is the sentinel, not some unexpected null.
            return self.token == self.yylimit - yymaxfill ? count : nil;

#sourceLocation(file: "swift/fill/02_fill.swift", line: 61)
      case 2:
#sourceLocation(file: "swift/fill/02_fill.re", line: 39)
        return nil
#sourceLocation(file: "swift/fill/02_fill.swift", line: 65)
      case 3:
        if self.yylimit <= self.yycursor {
          if self.fill(1) != .ok { return nil }
        }
        yych = self.yyinput[self.yycursor]
        switch yych {
          case 0x20:
            self.yycursor += 1
            yystate = 3
            continue yyl
          default:
            yystate = 4
            continue yyl
        }
      case 4:
#sourceLocation(file: "swift/fill/02_fill.re", line: 38)
        continue loop
#sourceLocation(file: "swift/fill/02_fill.swift", line: 83)
      case 5:
        if self.yylimit <= self.yycursor {
          if self.fill(1) != .ok { return nil }
        }
        yych = self.yyinput[self.yycursor]
        self.yycursor += 1
        switch yych {
          case 0x27:
            yystate = 6
            continue yyl
          case 0x5C:
            yystate = 7
            continue yyl
          default:
            yystate = 5
            continue yyl
        }
      case 6:
#sourceLocation(file: "swift/fill/02_fill.re", line: 34)
        
          count += 1
          continue loop

#sourceLocation(file: "swift/fill/02_fill.swift", line: 107)
      case 7:
        if self.yylimit <= self.yycursor {
          if self.fill(1) != .ok { return nil }
        }
        self.yycursor += 1
        yystate = 5
        continue yyl
      default: fatalError("internal lexer error")
    }
  }
#sourceLocation(file: "swift/fill/02_fill.re", line: 40)

    }
  }

  mutating func fill(_ need: Int) -> FillStatus {
    guard !self.eof else {
      return .eof
    }

    let shift = self.token
    let used = self.yylimit - self.token
    let free = Self.bufferSize - used

    // Error: Lexeme too long. In the real world we can reallocate a larger buffer.
    if self.token < need {
      return .longLexeme
    }

    // Shift buffer contents, discarding everything up to the current lexeme.
    self.yyinput.replaceSubrange(..<used, with: self.yyinput[shift..<self.yylimit])
    self.yylimit  -= shift
    self.yycursor -= shift
    self.token = 0

    // Fill free space at the end of buffer with new data from file.
    let read: Int
    do {
      if let data = try self.file.read(upToCount: free) {
        read = data.count
        self.yyinput.replaceSubrange(self.yylimit..<(self.yylimit + read), with: data)
      } else {
        read = 0
      }
    } catch {
      fatalError("cannot read from file: \(error.localizedDescription)")
    }

    // If read less than expected, this is end of input => add zero padding
    // so that the lexer can access characters at the end of buffer.
    self.yylimit += read
    if read < free {
      self.eof = true
      self.yyinput.withUnsafeMutableBytes {
        _ = memset($0.baseAddress! + self.yylimit, 0, yymaxfill)
      }
      self.yylimit += yymaxfill
    }

    return .ok
  }

  enum FillStatus {
    case ok, eof, longLexeme
  }
}

let fileName = "input"
let content = "'qu\0tes' 'are' 'fine: \\'' ";

// Prepare input file: a few times the size of the buffer,
// containing strings with zeroes and escaped quotes.
guard FileManager.default.createFile(
    atPath: fileName,
    contents: Data(String(repeating: content, count: Input.bufferSize).utf8)
) else {
  fatalError("failed to write file \"\(fileName)\"")
}

// Number of quoted strings written to file
let count = 3 * Input.bufferSize

// Initialize lexer state
// This immediately triggers YYFILL, as the check `in.yycursor < in.yylimit` fails.
guard let file = FileHandle(forReadingAtPath: fileName) else {
  throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue)
}
var `in` = Input(file: file)

// Run the lexer
assert(`in`.lex() == count)

// Cleanup: remove input file
try file.close()
try FileManager.default.removeItem(atPath: fileName)
