Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/parity-matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,12 @@ loads, cached success and retry after failure. `Language.Data` uses generative
State keys. EditorState facets and Lezer mounted-language queries supply
ordered contributions by position.

Native-only Scheme and Common Lisp stream providers opt into an extension to
bracket matching. The matcher uses explicit delimiter nodes for these languages
and skips the upstream raw-text fallback. Native and Melange editor tests cover
the option; the delimiter producers are covered in the standalone
[native catalog](../integrations/logseq-native-modes/README.md).

### Language data

`packages/language-data` exposes `codemirror-ml.language_data` and the
Expand Down
43 changes: 20 additions & 23 deletions integrations/logseq-native-modes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,29 +39,26 @@ templates.

## Scheme and Common Lisp bracket matching

Logseq enables structural bracket highlighting for Clojure and EDN. The legacy
Scheme and Common Lisp modes provide syntax highlighting, but their token
types cannot reliably identify structural delimiters. With the generic bracket
matcher enabled and the caret just after the opening parenthesis, these inputs
produce the following matches (zero-based UTF-16 offsets).
Scheme and Common Lisp provide structural delimiter nodes for
`Editor_highlight.bracket_matching ()`. The stream driver retains each
delimiter's syntax highlighting style and emits its one-code-unit range as a
separate node, even when adjoining styles merge. In these languages the matcher
uses the parser's delimiter nodes. Strings, escaped symbols, character
literals, and comments supply no bracket marks.

| Mode | Input | Expected closing offset | Actual closing offset |
| --- | --- | --- | --- |
| Scheme | `'(")")` | 5 | 3 (inside the string) |
| Scheme | `(#\))` | 4 | 3 (character literal) |
| Common Lisp | `(\))` | 3 | 2 (escaped symbol) |
The following examples give matching ranges when the caret is just after the
opening parenthesis. Offsets are zero-based UTF-16.

The [Scheme tokenizer](legacy-modes/mode/scheme.ml) uses the same `atom` style
for quoted list delimiters and their contents. It also does not consume the
delimiter glyph in a `#\)` character literal as part of the literal. The
[Common Lisp tokenizer](legacy-modes/mode/commonlisp.ml) consumes the backslash
before classifying the next character, so an escaped `)` gets the same
`bracket` style as a list closer.
| Mode | Input | Opening offset | Closing offset |
| --- | --- | --- | --- |
| Scheme | `'(")")` | 1 | 5 |
| Scheme | `(#\))` | 0 | 4 |
| Common Lisp | `(\))` | 0 | 3 |

The [generic matcher](../../packages/language/bracket_matching.ml) compares
syntax node types when scanning raw characters without delimiter metadata.
The native catalog and upstream CodeMirror Legacy Modes 6.5.5 with Language
6.13.1 reproduce these results. Disabling token merging in upstream
`StreamLanguage` leaves the results unchanged. Reliable matching requires
reader-aware recognition of literals and escapes, plus a way for the matcher
to use only explicitly identified structural delimiters.
Upstream CodeMirror Legacy Modes 6.5.5 with Language 6.13.1 treats the literal
parentheses in these examples as closes, even with `mergeTokens: false`.
The native Scheme mode recognizes parentheses and square brackets. The native
Common Lisp mode recognizes parentheses using the default reader delimiters.
Custom Common Lisp readtables, dialect-specific reader extensions and Scheme
dialect-specific delimiters outside this set would require further lexer
support. Hosts enable the matcher extension on the code editor where needed.
108 changes: 107 additions & 1 deletion integrations/logseq-native-modes/catalog/test/test_mode_catalog.ml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,111 @@ let parse mode source =
Parser.parse (Language.parser language) (Input.of_text (Input.Text.of_utf8 source))
| None -> failwith ("Missing provider for " ^ mode)

let check_lisp_brackets () =
let module State = Codemirror_ml_state in
let module View = Codemirror_ml_view.Editor_view in
let module Decoration = Codemirror_ml_view.Decoration in
let check ?checkpoint (mode, source, caret, expected) =
let language = Option.get (Logseq_native_modes.find mode) in
let doc = State.Utf16.of_utf8 source in
let budget =
match checkpoint with
| None -> []
| Some _ ->
let time = ref 0. in
let clock () =
time := !time +. 1.;
!time
in
[ State.Facet.of_ Language.parse_clock clock
; State.Facet.of_ Language.parse_apply_budget 0. ]
in
let view =
View.create ~doc:(State.Change_set.String doc)
~selection:(State.Editor_selection.single caret)
~extensions:(State.Extension.group
(Language.extension language
:: Codemirror_ml_language.Editor_highlight.bracket_matching ()
:: budget))
()
in
Option.iter
(fun length ->
let tree = Language.syntax_tree (View.state view) in
let first = Tree.resolve_inner tree ~side:Right 0 in
if Tree.length tree <> length || Tree.Syntax_node.to_ first <> 1 then
failwith "Timed-out Scheme parse must publish only complete lines")
checkpoint;
if
not
(Language.force_parsing ~timeout_ms:10_000.
~dispatch:(fun spec ->
if View.dispatch_specs view [ spec ] <> Ok () then
failwith "Could not publish Lisp syntax tree")
(View.state view) (State.Utf16.length doc))
then failwith "Could not parse Lisp fixture";
let marks = ref [] in
State.Editor_state.facet (View.state view) View.decorations
|> List.iter (fun source ->
let set =
match source with View.Static set -> set | View.Dynamic get -> get view
in
State.Range_set.between (Decoration.indexed_ranges set)
~from:0 ~to_:(State.Utf16.length doc)
(fun first last value ->
let attrs =
Decoration.attributes (State.Range_value.payload value)
in
marks := (first, last, List.assoc_opt "class" attrs) :: !marks;
true));
ignore (View.destroy view);
let expected =
List.map (fun pos -> (pos, pos + 1, Some "cm-matchingBracket")) expected
in
if List.sort compare !marks = expected then None
else
let label =
if String.length source < 80 then Printf.sprintf "%S" source
else Printf.sprintf "source with %d UTF-8 bytes" (String.length source)
in
Some (mode ^ " " ^ label)
in
let long_list = "([\n" ^ String.make 600 'x' ^ "\n])" in
let prefix = "(a)\n" in
let start = String.length prefix in
let long_line =
prefix ^ "(" ^ String.concat "" (List.init 5_100 (fun _ -> "x "))
^ "\"\n)\")"
in
let scheme = Option.get (Logseq_native_modes.find "scheme") in
let input = Input.of_text (Input.Text.of_utf8 long_line) in
let partial = Parser.start_parse (Language.parser scheme) input in
(match Partial_parse.advance partial with
| Partial_parse.More when Partial_parse.parsed_pos partial = start -> ()
| _ -> failwith "Expected the Scheme parser to yield during a long line");
let checkpoint_failure =
check ~checkpoint:start
("scheme", long_line, start + 1, [start; String.length long_line - 1])
in
match
Option.to_list checkpoint_failure @ List.filter_map (fun case -> check case)
[ ("scheme", {|'(")")|}, 2, [1; 5])
; ("commonlisp", {|(\))|}, 1, [0; 3])
; ("scheme", {|(😀 #\))|}, 1, [0; 7])
; ("scheme", {|"(x)"|}, 2, [])
; ("commonlisp", {|"(x)"|}, 2, [])
; ("commonlisp", {|#(😀 #\) foo|a\|)|)|}, 19, [1; 18])
; ("commonlisp", {|(foo|a\|)|)|}, 9, [])
; ("scheme", {|(#; #; [a] #(")") x)|}, 1, [0; 19])
; ("scheme", {|(#; #; [a] #(")") x)|}, 13, [])
; ("scheme", {|#| #| |# (x) |#|}, 10, [])
; ("commonlisp", {|#| #| |# (x) |#|}, 10, [])
; ("scheme", long_list, 2, [1; 604])
]
with
| [] -> ()
| failures -> failwith ("Incorrect bracket marks for " ^ String.concat ", " failures)

let () =
let highlighter = Highlight.Highlighter.of_tags [[Highlight.Tags.number], "number"] in
let tokenize mode source =
Expand Down Expand Up @@ -35,4 +140,5 @@ let () =
; "elixir", "# 😀\nanswer = "
];
List.iter (fun mode -> ignore (parse mode "\n"))
(Logseq_native_modes.names ())
(Logseq_native_modes.names ());
check_lisp_brackets ()
80 changes: 44 additions & 36 deletions integrations/logseq-native-modes/legacy-modes/mode/commonlisp.ml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
module Stream = Mode.Stream
module Text = Mode.Text

type lexer = Base | String | Comment
type lexer = Base | String | Bar_symbol | Comment of int
type indentation = Unset | Next | Column of int
type context = { start : int; mutable indent : indentation }
type kind = Space | Open | Close | Symbol | Other

type state = {
mutable lexer : lexer;
mutable last : kind;
mutable structural_bracket : bool;
mutable context : context;
mutable parents : context list;
}
Expand Down Expand Up @@ -64,17 +65,21 @@ let assume_body =

let nil = Mode.text "nil"

let read_symbol stream line =
let rec loop pos =
let read_symbol stream state line =
let rec loop pos quoted =
match at line pos with
| -1 | 0x27 | 0x60 | 0x2c | 0x40 | 0x28 | 0x29 | 0x5b | 0x5d | 0x22 | 0x3b
->
pos
| 0x5c -> loop (min (Text.length line) (pos + 2))
| ch when Stream.is_whitespace_code_unit ch -> pos
| _ -> loop (pos + 1)
| -1 -> (pos, quoted)
| 0x5c -> loop (min (Text.length line) (pos + 2)) quoted
| 0x7c -> loop (pos + 1) (not quoted)
| _ when quoted -> loop (pos + 1) quoted
| 0x27 | 0x60 | 0x2c | 0x40 | 0x28 | 0x29 | 0x5b | 0x5d | 0x22 | 0x3b ->
(pos, false)
| ch when Stream.is_whitespace_code_unit ch -> (pos, false)
| _ -> loop (pos + 1) quoted
in
Stream.set_pos stream (loop (Stream.pos stream))
let stop, quoted = loop (Stream.pos stream) (state.lexer = Bar_symbol) in
state.lexer <- if quoted then Bar_symbol else Base;
Stream.set_pos stream stop

let token_string stream state =
let line = Stream.string stream in
Expand All @@ -89,21 +94,23 @@ let token_string stream state =
Stream.set_pos stream (loop (Stream.pos stream) false);
(Other, Some "string")

let token_comment stream state =
let token_comment stream state depth =
let line = Stream.string stream in
let rec loop pos previous =
match at line pos with
| -1 -> pos
| 0x23 when previous = 0x7c ->
let rec loop pos depth =
match (at line pos, at line (pos + 1)) with
| -1, _ ->
state.lexer <- Comment depth;
pos
| 0x23, 0x7c -> loop (pos + 2) (depth + 1)
| 0x7c, 0x23 when depth = 1 ->
state.lexer <- Base;
pos + 1
| ch -> loop (pos + 1) ch
pos + 2
| 0x7c, 0x23 -> loop (pos + 2) (depth - 1)
| _ -> loop (pos + 1) depth
in
Stream.set_pos stream (loop (Stream.pos stream) (-1));
Stream.set_pos stream (loop (Stream.pos stream) depth);
(Space, Some "comment")

let bar = Mode.text "|"

let base stream state =
if Stream.eat_space stream then (Space, None)
else
Expand All @@ -120,7 +127,6 @@ let base stream state =
(Other, Some "number"))
else
let ch = next () in
let ch = if ch = 0x5c then next () else ch in
match ch with
| 0x22 ->
state.lexer <- String;
Expand All @@ -131,26 +137,22 @@ let base stream state =
Stream.skip_to_end stream;
(Space, Some "comment")
| 0x27 | 0x60 | 0x2c | 0x40 -> (Other, None)
| 0x7c ->
if Stream.skip_to stream bar then (
ignore (next ());
(Other, Some "variableName"))
else (
Stream.skip_to_end stream;
(Other, Some "error"))
| 0x7c | 0x5c ->
Stream.set_pos stream pos;
read_symbol stream state line;
(Symbol, Some "variableName")
| 0x23 -> (
match next () with
| 0x28 -> (Open, Some "bracket")
| 0x2b | 0x2d | 0x3d | 0x2e | 0x27 -> (Other, None)
| 0x7c ->
state.lexer <- Comment;
token_comment stream state
| 0x7c -> token_comment stream state 1
| 0x3a ->
read_symbol stream line;
read_symbol stream state line;
(Other, Some "meta")
| 0x5c ->
ignore (next ());
read_symbol stream line;
let ch = next () in
if digit ch || within 0x41 0x5a ch || within 0x61 0x7a ch then
read_symbol stream state line;
(Other, Some "string.special")
| ch when digit ch ->
let stop = skip line (Stream.pos stream) digit in
Expand All @@ -160,7 +162,7 @@ let base stream state =
else (Other, Some "error")
| _ -> (Other, Some "error"))
| _ ->
read_symbol stream line;
read_symbol stream state line;
let word = Stream.current stream in
let first = at word 0 in
let single ch = first = ch && Text.length word = 1 in
Expand All @@ -185,8 +187,12 @@ let token stream state =
match state.lexer with
| Base -> base stream state
| String -> token_string stream state
| Comment -> token_comment stream state
| Bar_symbol ->
read_symbol stream state (Stream.string stream);
(Symbol, Some "variableName")
| Comment depth -> token_comment stream state depth
in
state.structural_bracket <- kind = Open || kind = Close;
if kind <> Space then (
let context = state.context in
(match context.indent with
Expand Down Expand Up @@ -219,9 +225,11 @@ let common_lisp =
{
lexer = Base;
last = Other;
structural_bracket = false;
context = { start = 0; indent = Column 0 };
parents = [];
}) (* The upstream default copier shares the current and parent frames. *)
~token_ends_in_bracket:(fun state -> state.structural_bracket)
~copy_state:(fun state -> { state with lexer = state.lexer })
~indent:(fun state _ ~unit_width:_ ->
Some
Expand Down
Loading
Loading