Skip to content

Commit

Permalink
Refactor Libfyaml error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kdubb committed Jun 10, 2024
1 parent 2f4c2c4 commit d74a3ef
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 17 deletions.
22 changes: 22 additions & 0 deletions Sources/PotentYAML/Libfyaml.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,28 @@ internal enum Libfyaml {
return diag
}

internal static func hasError(in diag: OpaquePointer?) -> Bool {

guard let diag else {
return true
}

return fy_diag_got_error(diag)
}

internal static func error(from diag: OpaquePointer?) -> (message: String, line: Int, column: Int)? {

guard let diag else {
return nil
}

var prev: UnsafeMutableRawPointer?
guard let error = fy_diag_errors_iterate(diag, &prev) else {
return nil
}

return (String(cString: error.pointee.msg), Int(error.pointee.line), Int(error.pointee.column))
}

}

Expand Down
11 changes: 2 additions & 9 deletions Sources/PotentYAML/YAMLReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -296,18 +296,11 @@ internal struct YAMLReader {

func error(fallback: Error) -> Error {

guard let diag = fy_parser_get_diag(parser) else {
guard let error = Libfyaml.error(from: fy_parser_get_diag(parser)) else {
return fallback
}

var prev: UnsafeMutableRawPointer?
if let error = fy_diag_errors_iterate(diag, &prev) {
return Error.parserError(message: String(cString: error.pointee.msg),
line: Int(error.pointee.line),
column: Int(error.pointee.column))
}

return fallback
return Error.parserError(message: error.message, line: error.line, column: error.column)
}

func destroy() {
Expand Down
12 changes: 4 additions & 8 deletions Sources/PotentYAML/YAMLWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,24 +193,20 @@ internal struct YAMLWriter {

private func failIfError() throws {

guard fy_diag_got_error(fy_emitter_get_diag(emitter)) else {
guard Libfyaml.hasError(in: fy_emitter_get_diag(emitter)) else {
return
}

throw error()
}

private func error() -> Error {
if let diag = fy_emitter_get_diag(emitter) {

var prev: UnsafeMutableRawPointer?
if let error = fy_diag_errors_iterate(diag, &prev) {

return Error.emitError(message: String(cString: error.pointee.msg))
}
guard let error = Libfyaml.error(from: fy_emitter_get_diag(emitter)) else {
return .emitError(message: "Unknown emitter error")
}

return .emitError(message: "Unknown emitter error")
return .emitError(message: error.message)
}

private static let emitOutput: Libfyaml.EmitterOutput = { _, _, str, len, userInfo in
Expand Down

0 comments on commit d74a3ef

Please sign in to comment.