Skip to content

Parsing with Ocamllex and Menhir: Minor errors in output_value #3682

@AmateurECE

Description

@AmateurECE

Thanks for the great reference to OCaml! I've been using the book to learn the language. I think there's a bug in the (non-printed) definition of print_list here. The definition is:

and print_list outc arr =
  Out_channel.output_string outc "[";
  List.iteri
    ~f:(fun i v ->
      if i > 0 then Out_channel.output_string outc ", ";
      Out_channel.output_value outc v)
    arr;
  Out_channel.output_string outc "]"

But I think this definition is meant to call the local function output_value, instead of Out_channel.output_value. When I run this with a basic JSON document, it prints some garbage characters to my terminal. I changed it to this:

and print_list outc arr =
  Out_channel.output_string outc "[";
  List.iteri
    ~f:(fun i v ->
      if i > 0 then Out_channel.output_string outc ",";
      output_value outc v)
    arr;
  Out_channel.output_string outc "]"

And this has been working for me. Additionally, I noticed that the definition of output_value does not escape double quotes, which causes some issues when piping to jq or other. So I added this function, and updated output_value to use it:

and print_string outc s =
  let escaped = CCString.replace ~sub:"\"" ~by:"\\\"" s in
  Out_channel.output_string outc ("\"" ^ escaped ^ "\"")

This may not matter since these definitions aren't rendered in the book but I thought I might mention it anyways!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions