1:- module(lsp_colours, [file_colours/2,
    2                        file_range_colours/4,
    3                        token_types/1,
    4                        token_modifiers/1]).

LSP Colours

Module with predicates for colourizing Prolog code, via library(prolog_colour).

author
- James Cash
   12:- use_module(library(apply), [maplist/4]).   13:- use_module(library(apply_macros)).   14:- use_module(library(debug), [debug/3]).   15:- use_module(library(lists), [numlist/3, nth0/3]).   16:- use_module(library(prolog_colour), [prolog_colourise_stream/3,
   17                                       prolog_colourise_term/4]).   18:- use_module(library(prolog_source), [read_source_term_at_location/3]).   19:- use_module(library(yall)).   20
   21:- include('_lsp_path_add.pl').   22:- use_module(lsp(lsp_changes), [doc_text/2]).   23:- use_module(lsp(lsp_utils), [seek_to_line/2,
   24                               linechar_offset/3]).   25
   26token_types([namespace,
   27             type,
   28             class,
   29             enum,
   30             interface,
   31             struct,
   32             typeParameter,
   33             parameter,
   34             variable,
   35             property,
   36             enumMember,
   37             event,
   38             function,
   39             member,
   40             macro,
   41             keyword,
   42             modifier,
   43             comment,
   44             string,
   45             number,
   46             regexp,
   47             operator
   48            ]).
   49token_modifiers([declaration,
   50                 definition,
   51                 readonly,
   52                 static,
   53                 deprecated,
   54                 abstract,
   55                 async,
   56                 modification,
   57                 documentation,
   58                 defaultLibrary
   59                ]).
   60
   61token_types_dict(Dict) :-
   62    token_types(Types),
   63    length(Types, Len),
   64    Len0 is Len - 1,
   65    numlist(0, Len0, Ns),
   66    maplist([Type, Idx, Type-Idx]>>true, Types, Ns,
   67            Pairs),
   68    dict_create(Dict, _, Pairs).
 file_colours(+File, -Colours) is det
True when Colours is a list of colour information corresponding to the file File.
   74file_colours(File, Tuples) :-
   75    file_colours_helper(File, Colours0),
   76    sort(2, @=<, Colours0, Colours),
   77    flatten_colour_terms(File, Colours, Tuples).
 file_range_colours(+File, +Start, +End, -Colours) is det
True when Colours is a list of colour information corresponding to file File covering the terms between Start and End. Note that it may go beyond either bound.
   84file_range_colours(File, Start, End, Tuples) :-
   85    file_term_colours_helper(File, Start, End, Colours0),
   86    sort(2, @=<, Colours0, Colours),
   87    flatten_colour_terms(File, Colours, Tuples).
   88
   89file_stream(File, S) :-
   90    ( doc_text(File, Changes)
   91    -> open_string(Changes, S)
   92    ;  open(File, read, S) ),
   93    set_stream(S, newline(posix)).
 flatten_colour_terms(+File, +ColourTerms, -Nums) is det
Convert the list of ColourTerms like =colour(Category, Start, Length)= to a flat list of numbers Nums in the format that LSP expects.
See also
- https://microsoft.github.io/language-server-protocol/specifications/specification-3-16/#textDocument_semanticTokens
  101flatten_colour_terms(File, ColourTerms, Nums) :-
  102    token_types_dict(TokenDict),
  103    setup_call_cleanup(
  104        file_stream(File, S),
  105        ( seek(S, 0, bof, _),
  106          phrase(colour_term_to_tuple(S, TokenDict, 0, 1, 0),
  107                 ColourTerms,
  108                 Nums)
  109        ),
  110        close(S)
  111    ).
  112
  113colour_term_to_tuple(Stream, Dict, LastOffset, LastLine, LastChar), R -->
  114    [colour(Type, NewOffset, Len)], !,
  115    { ( colour_type(Type, TypeCategory, Mods),
  116        get_dict(TypeCategory, Dict, TypeCode),
  117        mods_mask(Mods, ModMask) )
  118      -> Seek is NewOffset - LastOffset,
  119         Offset = NewOffset,
  120         stream_seek_line_position(Stream, Seek, LastLine, LastChar, Line, Char),
  121         ( Line == LastLine
  122         -> DeltaLine = 0,
  123            DeltaStart is Char - LastChar
  124         ; DeltaLine is Line - LastLine,
  125           DeltaStart = Char ),
  126         R = [DeltaLine, DeltaStart, Len, TypeCode, ModMask]
  127      ; R = [],
  128        Offset = LastOffset, Line = LastLine, Char = LastChar
  129    },
  130    colour_term_to_tuple(Stream, Dict, Offset, Line, Char).
  131colour_term_to_tuple(_, _, _, _, _) --> [].
 stream_offset_line_position(+Stream, +Seek, -Line, -Char) is det
Advance Stream by Seek characters, then Line will be the current line number that Stream is now at and Char is the position within the line.
  138stream_seek_line_position(Stream, Seek, StartLine, StartChar, Line, LineChar) :-
  139    stream_seek_line_position_(Seek, Stream, StartLine, StartChar, Line, LineChar).
  140
  141stream_seek_line_position_(0, _Stream, Line, Char, Line, Char) :- !.
  142stream_seek_line_position_(Seek0, Stream, StartLine, StartChar, Line, Char) :-
  143    Seek1 is Seek0 - 1,
  144    get_code(Stream, NextCode),
  145    ( NextCode == 0'\n
  146    -> NextLine is StartLine + 1,
  147       NextChar = 0
  148    ; NextLine = StartLine,
  149      NextChar is StartChar + 1 ),
  150    stream_seek_line_position_(Seek1, Stream, NextLine, NextChar, Line, Char).
  151
  152colour_type(directive,                namespace, []).
  153
  154colour_type(head(_,              _),        function,  [declaration]).
  155% colour_type(head_term(_,              _),        function,  [declaration]).
  156colour_type(neck(directive),          operator,  [declaration]).
  157colour_type(neck(':-'),               operator,  [declaration]).
  158colour_type(neck(clause),             operator,  [definition]).
  159colour_type(neck(grammar_rule),       operator,  [definition]).
  160colour_type(goal(built_in,       A),        macro,     []) :- atom(A), !.
  161colour_type(goal(built_in,       _),        function,  [defaultLibrary]).
  162colour_type(goal(undefined,      _),        function,  []).
  163colour_type(goal(imported(_),    _),        function,  []).
  164colour_type(goal(local(_),       _),        function,  []).
  165colour_type(goal(extern(_,_),    _),        function,  []).
  166colour_type(goal(recursion,      _),        member,    []).
  167colour_type(goal(('dynamic'(_)), _),        member, []).
  168% colour_type(goal_term(built_in,       A),        macro,     []) :- atom(A), !.
  169% colour_type(goal_term(built_in,       _),        function,  [defaultLibrary]).
  170% colour_type(goal_term(undefined,      _),        function,  []).
  171% colour_type(goal_term(imported(_),    _),        function,  []).
  172% colour_type(goal_term(local(_),       _),        function,  []).
  173% colour_type(goal_term(extern(_,_),    _),        function,  []).
  174% colour_type(goal_term(recursion,      _),        member,    []).
  175% colour_type(goal_term(('dynamic'(_)), _),        member, []).
  176colour_type(atom,                     string,    []).
  177colour_type(var,                      variable,  []).
  178colour_type(singleton,                variable,  [readonly]).
  179colour_type(fullstop,                 operator,  []).
  180colour_type(control,                  operator,  []).
  181colour_type(dict_key,                 property,  []).
  182colour_type(dict_sep,                 operator,  []).
  183colour_type(string,                   string,    []).
  184colour_type(int,                      number,    []).
  185colour_type(comment(line),            comment,   []).
  186colour_type(comment(structured),      comment,   [documentation]).
  187colour_type(arity,                    parameter, []).
  188colour_type(functor,                  struct,    []).
  189colour_type(option_name,              struct,    []).
  190colour_type(predicate_indicator,      interface, []).
  191colour_type(predicate_indicator(_,    _),        interface, []).
  192colour_type(unused_import,            macro,     [deprecated]).
  193colour_type(undefined_import,         macro,     [deprecated]).
  194colour_type(dcg,                      regexp,    []).
  195colour_type(dcg(terminal),            regexp,    []).
  196colour_type(dcg(plain),               function,  []).
  197colour_type(dcg_right_hand_ctx,       regexp,    []).
  198colour_type(grammar_rule,             regexp,    []).
  199colour_type(identifier,               namespace, []).
  200colour_type(file(_),                  namespace, []).
  201colour_type(file_no_depend(_),        namespace, [abstract]).
  202colour_type(module(_),                namespace, []).
  203
  204mods_mask(Mods, Mask) :-
  205    mods_mask(Mods, 0, Mask).
  206
  207mods_mask([], Mask, Mask).
  208mods_mask([Mod|Mods], Mask0, Mask) :-
  209    token_modifiers(ModsList),
  210    nth0(N, ModsList, Mod),
  211    Mask1 is Mask0 \/ (1 << N),
  212    mods_mask(Mods, Mask1, Mask).
  213
  214%%% Helpers
 file_colours_helper(+Queue, +File) is det
Use prolog_colourise_stream/3 to accumulate a list of colour terms.
  220file_colours_helper(File, Info) :-
  221    Acc = acc([]),
  222    setup_call_cleanup(
  223        file_stream(File, S),
  224        prolog_colourise_stream(
  225            S, File,
  226            {Acc}/[Cat, Start, Len]>>(
  227                arg(1, Acc, Data),
  228                nb_setarg(1, Acc, [colour(Cat, Start, Len)|Data])
  229            )
  230        ),
  231        close(S)
  232    ),
  233    arg(1, Acc, Info).
  234
  235nearest_term_start(Stream, StartL, TermStart) :-
  236    read_source_term_at_location(Stream, _, [line(StartL), error(Error)]),
  237    ( nonvar(Error)
  238    -> ( LineBack is StartL - 1,
  239         nearest_term_start(Stream, LineBack, TermStart) )
  240    ;  TermStart = StartL
  241    ).
  242
  243file_term_colours_helper(File, line_char(StartL, _StartC), End, Info) :-
  244    Acc = acc([]),
  245    setup_call_cleanup(
  246        file_stream(File, S),
  247        ( nearest_term_start(S, StartL, TermLine),
  248          seek(S, 0, bof, _),
  249          set_stream_position(S, '$stream_position'(0,0,0,0)),
  250          seek_to_line(S, TermLine),
  251          colourise_terms_to_position(Acc, File, S, 0-0, End)
  252        ),
  253        close(S)
  254    ),
  255    arg(1, Acc, Info).
  256
  257colourise_terms_to_position(Acc, File, Stream, Prev, End) :-
  258    once(prolog_colourise_term(
  259        Stream, File,
  260        {Acc}/[Cat, Start, Len]>>(
  261            arg(1, Acc, Tail),
  262            nb_setarg(1, Acc, [colour(Cat, Start, Len)|Tail])),
  263        [])),
  264    stream_property(Stream, position(Pos)),
  265    stream_position_data(line_count, Pos, Line),
  266    stream_position_data(line_position, Pos, Char),
  267    End = line_char(EndL, EndC),
  268    ( Line-Char == Prev
  269    -> true
  270    ;  EndL =< Line
  271    -> true
  272    ;  ( EndL == Line, EndC =< Char )
  273    -> true
  274    ; colourise_terms_to_position(Acc, File, Stream, Line-Char, End)
  275    )