RedPRL / asai

🩺 A library for compiler diagnostics
https://ocaml.org/p/asai
Apache License 2.0
35 stars 2 forks source link

🔍 Looking up ranges in structured data #162

Open kentookura opened 1 month ago

kentookura commented 1 month ago

When Asai reports an error, the diagnostics are attached to the string source like this:

 → error[(Reporter.Message.Tree_not_found foo-0006)]
 ꭍ ○ when expanding tree at address `foo-0004`
 ■ ./trees/foo-0004.tree
 1 | \import{foo-0006}
   ^ Could not find tree named `foo-0006'

I find myself in the position where it would be really useful if I could use the range to look up nodes in the syntax tree.

Nick Hu once sent a patch implementing an LSP server for Forester that contained the following function:


  let inside = fun (located : 'a Range.located) ->
    match located.loc with
    | Some loc -> begin
        match Range.view loc with
        | `Range (start, end_) ->
          let within (a, b) x = a <= x && x <= b in
          within (start.line_num, end_.line_num ) (pos.line + 1)
          && within ((start.offset - start.start_of_line), (end_.offset - end_.start_of_line - 1)) pos.character
        | _ -> false
      end
    | None -> false

I did not think through the arithmetic, but conceptually, this is the right way to do this, right? Or is there a more elegant way using more library functions?