diff --git a/docs/parity-matrix.md b/docs/parity-matrix.md index 747cd3c..3e6b6ee 100644 --- a/docs/parity-matrix.md +++ b/docs/parity-matrix.md @@ -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 diff --git a/integrations/logseq-native-modes/README.md b/integrations/logseq-native-modes/README.md index 05048d1..535d8b5 100644 --- a/integrations/logseq-native-modes/README.md +++ b/integrations/logseq-native-modes/README.md @@ -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. diff --git a/integrations/logseq-native-modes/catalog/test/test_mode_catalog.ml b/integrations/logseq-native-modes/catalog/test/test_mode_catalog.ml index b13a431..1270a21 100644 --- a/integrations/logseq-native-modes/catalog/test/test_mode_catalog.ml +++ b/integrations/logseq-native-modes/catalog/test/test_mode_catalog.ml @@ -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 = @@ -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 () diff --git a/integrations/logseq-native-modes/legacy-modes/mode/commonlisp.ml b/integrations/logseq-native-modes/legacy-modes/mode/commonlisp.ml index c10fb83..98c135f 100644 --- a/integrations/logseq-native-modes/legacy-modes/mode/commonlisp.ml +++ b/integrations/logseq-native-modes/legacy-modes/mode/commonlisp.ml @@ -4,7 +4,7 @@ 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 @@ -12,6 +12,7 @@ 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; } @@ -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 @@ -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 @@ -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; @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/integrations/logseq-native-modes/legacy-modes/mode/scheme.ml b/integrations/logseq-native-modes/legacy-modes/mode/scheme.ml index ea94c0f..26a993c 100644 --- a/integrations/logseq-native-modes/legacy-modes/mode/scheme.ml +++ b/integrations/logseq-native-modes/legacy-modes/mode/scheme.ml @@ -5,7 +5,7 @@ module Stream = Mode.Stream module Text = Mode.Text type quote = Double | Bar -type lexer = Base | Quoted of quote | Comment | Expr_comment +type lexer = Base | Quoted of quote | Comment of int type bracket = Paren | Square type context = { bracket : bracket; indent : int } @@ -15,6 +15,9 @@ type state = { mutable indentation : int; mutable commented : int option; mutable quoted : int option; + mutable pending_comments : int list; + mutable literal_comment : bool; + mutable structural_bracket : bool; } module Words = Hashtbl.Make (struct @@ -81,6 +84,14 @@ let word_set words = let keyword = word_set keywords let indent_key = word_set indent_keys let at line pos = if pos < Text.length line then Text.get line pos else -1 + +let character_end line pos = + let first = at line pos and second = at line (pos + 1) in + if first < 0 then pos + else if first >= 0xd800 && first <= 0xdbff && second >= 0xdc00 && second <= 0xdfff + then pos + 2 + else pos + 1 + let digit ch = ch >= 0x30 && ch <= 0x39 let lower ch = if ch >= 0x41 && ch <= 0x5a then ch + 0x20 else ch let whitespace = Stream.is_whitespace_code_unit @@ -209,6 +220,18 @@ let prefix_number line pos = let opener = function 0x28 -> Some Paren | 0x5b -> Some Square | _ -> None +let pending_comment state = + match state.pending_comments with + | depth :: _ -> depth = List.length state.stack + | [] -> false + +let take_pending_comment state = + match state.pending_comments with + | depth :: rest when depth = List.length state.stack -> + state.pending_comments <- rest; + true + | _ -> false + let open_bracket stream state line pos bracket = let after = pos + 1 in let key_end = @@ -224,12 +247,17 @@ let open_bracket stream state line pos bracket = if ch = -1 || ch = 0x3b then column + 1 else column + arg - Stream.start stream in + if take_pending_comment state && state.commented = None then + state.commented <- Some 0; + state.structural_bracket <- state.commented = None; state.stack <- { bracket; indent } :: state.stack; state.commented <- Option.map succ state.commented; state.quoted <- Option.map succ state.quoted; (after, Some "bracket") let close_bracket state pos bracket = + while take_pending_comment state do () done; + state.structural_bracket <- state.commented = None; let style = ref "bracket" in (match state.stack with | context :: rest when context.bracket = bracket -> @@ -249,6 +277,10 @@ let close_bracket state pos bracket = let base stream state line pos = let ch = at line pos and next_pos = pos + 1 in let next = at line next_pos in + let datum style = + if take_pending_comment state then Some "comment" + else Some style + in let default start = let stop = scan line start word in let style = @@ -258,37 +290,56 @@ let base stream state line pos = then "builtin" else "variable" in - (stop, Some style) + (stop, datum style) in match ch with | -1 -> default pos | 0x22 -> state.lexer <- Quoted Double; - (next_pos, Some "string") + state.literal_comment <- pending_comment state; + (next_pos, datum "string") | 0x27 -> let stop = if opener next <> None then ( if state.quoted = None then state.quoted <- Some 0; next_pos) + else if pending_comment state then next_pos else scan line next_pos word in - (stop, Some "atom") + (stop, Some (if pending_comment state then "comment" else "atom")) + | (0x60 | 0x2c) when pending_comment state -> + let stop = if ch = 0x2c && next = 0x40 then next_pos + 1 else next_pos in + (stop, Some "comment") | 0x7c -> state.lexer <- Quoted Bar; - (next_pos, Some "symbol") + state.literal_comment <- pending_comment state; + (next_pos, datum "symbol") + | 0x5c -> default (character_end line next_pos) | 0x23 -> ( match lower next with | 0x7c -> - state.lexer <- Comment; + state.lexer <- Comment 1; (next_pos + 1, Some "comment") - | 0x74 | 0x66 -> (next_pos + 1, Some "atom") + | 0x5c -> + let literal = next_pos + 1 in + let stop = character_end line literal in + let stop = if word (at line literal) then scan line stop word else stop in + (stop, datum "string.special") + | 0x28 when pending_comment state -> (next_pos, Some "comment") + | 0x75 + when at line (next_pos + 1) = 0x38 && at line (next_pos + 2) = 0x28 -> + (next_pos + 2, if pending_comment state then Some "comment" else None) + | 0x74 | 0x66 -> (next_pos + 1, datum "atom") | 0x3b -> - state.lexer <- Expr_comment; + state.pending_comments <- List.length state.stack :: state.pending_comments; (next_pos + 1, Some "comment") - | _ -> prefix_number line pos) + | _ -> + let stop, style = prefix_number line pos in + if pending_comment state && stop > next_pos then (stop, datum "number") + else (stop, style)) | ch when number_start ch -> ( match number line pos Decimal with - | Some stop -> (stop, Some "number") + | Some stop -> (stop, datum "number") | None -> default pos) | 0x3b -> (Text.length line, Some "comment") | 0x28 -> open_bracket stream state line pos Paren @@ -301,28 +352,35 @@ let quoted state line pos quote = let terminator, style = match quote with Double -> (0x22, "string") | Bar -> (0x7c, "symbol") in + let style = if state.literal_comment then "comment" else style in let rec loop pos escaped = match at line pos with | -1 -> pos | ch when ch = terminator && not escaped -> state.lexer <- Base; + state.literal_comment <- false; pos + 1 | ch -> loop (pos + 1) ((not escaped) && ch = 0x5c) in (loop pos false, Some style) -let comment state line pos = - let rec loop pos previous = - match at line pos with - | -1 -> pos - | 0x23 when previous = 0x7c -> +let comment state line pos depth = + 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 - (loop pos (-1), Some "comment") + (loop pos depth, Some "comment") let token stream state = + state.structural_bracket <- false; if state.stack = [] && Stream.sol stream then state.indentation <- Stream.indentation stream; if Stream.eat_space stream then None @@ -332,15 +390,7 @@ let token stream state = match state.lexer with | Base -> base stream state line pos | Quoted quote -> quoted state line pos quote - | Comment -> comment state line pos - | Expr_comment -> - state.lexer <- Base; - if opener (at line pos) <> None then ( - state.commented <- Some 0; - base stream state line pos) - else - ( scan line pos (fun ch -> not (expression_delimiter ch)), - Some "comment" ) + | Comment depth -> comment state line pos depth in Stream.set_pos stream stop; match (state.commented, state.quoted) with @@ -357,7 +407,11 @@ let scheme = indentation = 0; commented = None; quoted = None; + pending_comments = []; + literal_comment = false; + structural_bracket = false; }) + ~token_ends_in_bracket:(fun state -> state.structural_bracket) ~copy_state:(fun state -> { state with lexer = state.lexer }) ~indent:(fun state _ ~unit_width:_ -> Some diff --git a/integrations/logseq-native-modes/stream-language/codemirror_ml_stream_language.ml b/integrations/logseq-native-modes/stream-language/codemirror_ml_stream_language.ml index c5df8fb..95420de 100644 --- a/integrations/logseq-native-modes/stream-language/codemirror_ml_stream_language.ml +++ b/integrations/logseq-native-modes/stream-language/codemirror_ml_stream_language.ml @@ -173,12 +173,15 @@ module Token_table = struct List.fold_left resolve_part [] (String.split_on_char '.' group)) module Styles = Map.Make (struct - type t = string * Highlight.Tag.t list + type t = string * Highlight.Tag.t list * bool - let compare (name_a, tags_a) (name_b, tags_b) = + let compare (name_a, tags_a, bracket_a) (name_b, tags_b, bracket_b) = let by_name = String.compare name_a name_b in - if by_name = 0 then List.compare Highlight.Tag.compare tags_a tags_b - else by_name + if by_name <> 0 then by_name + else + let by_bracket = Bool.compare bracket_a bracket_b in + if by_bracket <> 0 then by_bracket + else List.compare Highlight.Tag.compare tags_a tags_b end) type registry = { @@ -203,7 +206,7 @@ module Token_table = struct set else node_set () - let rec install ((name, tags) as key) props = + let rec install ((name, _, _) as key) props = let before = Atomic.get registry in match Styles.find_opt key before.styles with | Some id -> id @@ -213,7 +216,7 @@ module Token_table = struct let after = { types = node :: before.types; - styles = Styles.add (name, tags) id before.styles; + styles = Styles.add key id before.styles; next_id = id + 1; } in @@ -235,17 +238,19 @@ module Token_table = struct if Atomic.compare_and_set registry before after then id else reserve_top_id () - let create_type extra style = - match tags_for extra style with - | [] -> 0 + let create_type extra style ~name props = + let bracket = props <> [] in + match (if style = "" then [] else tags_for extra style) with + | [] -> if bracket then install (name, [], true) props else 0 | tags -> - let name = String.map (function ' ' -> '_' | c -> c) style in - let props = - match Highlight.style_tags [ (name, tags) ] with - | Ok source -> [ Node_type.Source source ] - | Error _ -> invalid_arg ("Invalid stream token type: " ^ name) - in - install (name, tags) props + (match Highlight.style_tags [ (name, tags) ] with + | Ok source -> + install (name, tags, bracket) (Node_type.Source source :: props) + | Error _ -> invalid_arg ("Invalid stream token type: " ^ name)) + + let create_style extra style = + let name = String.map (function ' ' -> '_' | c -> c) style in + create_type extra style ~name [] let aliases = [ @@ -264,7 +269,7 @@ module Token_table = struct ] |> List.fold_left (fun table (legacy, style) -> - Names.add legacy (create_type Names.empty style) table) + Names.add legacy (create_style Names.empty style) table) Names.empty type t = { @@ -277,17 +282,36 @@ module Token_table = struct let default = of_bindings [] - let rec resolve table style = + let rec resolve_cached table key create = let before = Atomic.get table.resolved in - match Names.find_opt style before with + match Names.find_opt key before with | Some id -> id | None -> - let id = create_type table.extra style in + let id = create table.extra in if Atomic.compare_and_set table.resolved before - (Names.add style id before) + (Names.add key id before) then id - else resolve table style + else resolve_cached table key create + + let resolve table style = + resolve_cached table style (fun extra -> create_style extra style) + + let resolve_bracket table style code = + let prop, name, opposite = + match code with + | 0x28 -> (Node_prop.closed_by, "StreamOpenParen", "StreamCloseParen") + | 0x29 -> (Node_prop.opened_by, "StreamCloseParen", "StreamOpenParen") + | 0x5b -> (Node_prop.closed_by, "StreamOpenSquare", "StreamCloseSquare") + | 0x5d -> (Node_prop.opened_by, "StreamCloseSquare", "StreamOpenSquare") + | 0x7b -> (Node_prop.closed_by, "StreamOpenBrace", "StreamCloseBrace") + | 0x7d -> (Node_prop.opened_by, "StreamCloseBrace", "StreamOpenBrace") + | _ -> invalid_arg "Expected a structural stream delimiter" + in + let key = name ^ "\x00" ^ style in + resolve_cached table key (fun extra -> + create_type extra style ~name + [ Binding (Node_prop.bind prop [ opposite ]) ]) end let chunk_size = 512 @@ -459,6 +483,12 @@ let get_indent driver cx = driver.indent state (without_leading_space line.text) cx module Parse = struct + type line_progress = { + stream : String_stream.t; + end_pos : int; + mutable offset : int; + } + type 'state t = { driver : 'state driver; top : Node_type.t; @@ -473,6 +503,7 @@ module Parse = struct mutable buffer : int array; mutable buffer_pos : int; mutable range_index : int; + mutable pending_line : line_progress option; } let move_range_index parse = @@ -550,7 +581,7 @@ module Parse = struct parse.buffer.(pos + 3) <- 4; parse.buffer_pos <- pos + 4 - let emit_token parse id from to_ offset = + let emit_token ?(merge = true) parse id from to_ offset = let from, to_, offset = if Array.length parse.ranges = 1 then (from, to_, offset) else @@ -560,40 +591,13 @@ module Parse = struct in let last = parse.buffer_pos - 4 in if - parse.driver.spec.merge_tokens && last >= 0 + merge && parse.driver.spec.merge_tokens && last >= 0 && parse.buffer.(last) = id && parse.buffer.(last + 2) = from then parse.buffer.(last + 2) <- to_ else add_token parse id from to_; offset - let parse_line parse ~tab_size ~unit_width = - let line, end_pos = next_line parse in - let spec = parse.driver.spec in - let stream = String_stream.create ~tab_size ~indent_unit:unit_width line in - let rec tokenize offset = - if not (String_stream.eol stream) then - let style = read_token_exn spec stream parse.state in - let start = String_stream.start stream in - let offset = - match style with - | None | Some "" -> offset - | Some style -> - emit_token parse - (Token_table.resolve parse.driver.token_table style) - (parse.parsed_pos + start) - (parse.parsed_pos + String_stream.pos stream) - offset - in - if start <= max_line_length then tokenize offset - in - if String_stream.eol stream then spec.blank_line parse.state unit_width - else tokenize 0; - parse.parsed_pos <- end_pos; - move_range_index parse; - if parse.parsed_pos < parse.to_ then - parse.parsed_pos <- parse.parsed_pos + 1 - let finish_chunk parse = let tree = Tree_build.build ~node_set:(Token_table.node_set ()) ~top_id:0 @@ -612,6 +616,76 @@ module Parse = struct parse.buffer_pos <- 0; parse.chunk_start <- parse.parsed_pos + let parse_line parse ~tab_size ~unit_width = + let spec = parse.driver.spec in + let preserve_state = Option.is_some spec.token_ends_in_bracket in + let progress = + match parse.pending_line with + | Some progress -> progress + | None -> + let line, end_pos = next_line parse in + (* A partial line has no reusable state. Keep earlier whole lines + in their own chunk if we may need to yield. *) + if preserve_state && Text.length line > max_line_length + && parse.chunk_start < parse.parsed_pos + then finish_chunk parse; + let stream = + String_stream.create ~tab_size ~indent_unit:unit_width line + in + if String_stream.eol stream then spec.blank_line parse.state unit_width; + { stream; end_pos; offset = 0 } + in + let stream = progress.stream in + let line = String_stream.string stream in + let limit = String_stream.pos stream + max_line_length in + let rec tokenize offset = + if String_stream.eol stream then true + else + let style = read_token_exn spec stream parse.state in + let start = String_stream.start stream in + let stop = String_stream.pos stream in + let bracket = + match spec.token_ends_in_bracket with + | Some marked -> marked parse.state + | None -> false + in + let emit_style first last offset = + match style with + | Some style when style <> "" && first < last -> + emit_token parse (Token_table.resolve parse.driver.token_table style) + (parse.parsed_pos + first) (parse.parsed_pos + last) offset + | _ -> offset + in + let offset = + if bracket then + let at = stop - 1 in + let offset = emit_style start at offset in + let id = + Token_table.resolve_bracket parse.driver.token_table + (Option.value ~default:"" style) (Text.get line at) + in + emit_token ~merge:false parse id (parse.parsed_pos + at) + (parse.parsed_pos + stop) offset + else emit_style start stop offset + in + if preserve_state && stop > limit && not (String_stream.eol stream) + then ( + progress.offset <- offset; + false) + else if preserve_state || start <= limit then tokenize offset + else true + in + if tokenize progress.offset then ( + parse.pending_line <- None; + parse.parsed_pos <- progress.end_pos; + move_range_index parse; + if parse.parsed_pos < parse.to_ then + parse.parsed_pos <- parse.parsed_pos + 1; + true) + else ( + parse.pending_line <- Some progress; + false) + let finish parse = let children = Array.of_list (List.rev parse.chunks) in Partial_parse.Done @@ -634,19 +708,22 @@ module Parse = struct State.Editor_state.tab_size editor, Indent.get_state_indent_unit editor ) in - while parse.parsed_pos < end_pos do - parse_line parse ~tab_size ~unit_width - done; - if parse.chunk_start < parse.parsed_pos then finish_chunk parse; - if parse.parsed_pos >= parse_end then finish parse + let rec advance_lines () = + parse.parsed_pos >= end_pos + || (parse_line parse ~tab_size ~unit_width && advance_lines ()) + in + if not (advance_lines ()) then Partial_parse.More else - match context with - | Some context - when parse.parsed_pos >= (Parse_context.viewport context).to_ -> - Parse_context.skip_until_in_view context - (Range.make ~from:parse.parsed_pos ~to_:parse_end); - finish parse - | _ -> Partial_parse.More + (if parse.chunk_start < parse.parsed_pos then finish_chunk parse; + if parse.parsed_pos >= parse_end then finish parse + else + match context with + | Some context + when parse.parsed_pos >= (Parse_context.viewport context).to_ -> + Parse_context.skip_until_in_view context + (Range.make ~from:parse.parsed_pos ~to_:parse_end); + finish parse + | _ -> Partial_parse.More) let start driver top input fragments (ranges : Range.t list) = let ranges = Array.of_list ranges in @@ -668,7 +745,8 @@ module Parse = struct | Some context -> let view_from = (Parse_context.viewport context).from in if - frontier < view_from - max_distance_before_viewport + Option.is_none driver.spec.token_ends_in_bracket + && frontier < view_from - max_distance_before_viewport && Array.exists (fun (range : Range.t) -> range.from <= view_from && range.to_ >= view_from) @@ -700,6 +778,7 @@ module Parse = struct buffer = [||]; buffer_pos = 0; range_index = 0; + pending_line = None; } in move_range_index parse; @@ -710,8 +789,16 @@ module Parse = struct end let define ?token_table ?indent spec = + let base = spec.Tokenizer.language_data in + let base = + if Option.is_none spec.token_ends_in_bracket then base + else + Some + (Language.Data.set Language.Data.bracket_matching_structural_only true + (Option.value base ~default:Language.Data.empty)) + in let data = - Language.define_language_facet ?base:spec.Tokenizer.language_data () + Language.define_language_facet ?base () in let indent = match indent with diff --git a/integrations/logseq-native-modes/streamparser/stream_parser.ml b/integrations/logseq-native-modes/streamparser/stream_parser.ml index 0dad116..621efa1 100644 --- a/integrations/logseq-native-modes/streamparser/stream_parser.ml +++ b/integrations/logseq-native-modes/streamparser/stream_parser.ml @@ -12,11 +12,13 @@ type ('state, 'language_data) t = { indent_number : 'state -> String_stream.Text.t -> unit_width:int -> float option; language_data : 'language_data option; merge_tokens : bool; + token_ends_in_bracket : ('state -> bool) option; } let create ?(name = "") ?(blank_line = fun _ _ -> ()) ?(indent = fun _ _ ~unit_width:_ -> None) ?indent_number ?language_data ?(merge_tokens = true) + ?token_ends_in_bracket ~start_state ~copy_state token = let indent_number = match indent_number with | Some callback -> callback @@ -24,4 +26,4 @@ let create ?(name = "") ?(blank_line = fun _ _ -> ()) Option.map float_of_int (indent state after ~unit_width) in { name; start_state; token; blank_line; copy_state; indent; indent_number; - language_data; merge_tokens } + language_data; merge_tokens; token_ends_in_bracket } diff --git a/integrations/logseq-native-modes/streamparser/stream_parser.mli b/integrations/logseq-native-modes/streamparser/stream_parser.mli index 68aaac1..e7d1d18 100644 --- a/integrations/logseq-native-modes/streamparser/stream_parser.mli +++ b/integrations/logseq-native-modes/streamparser/stream_parser.mli @@ -10,6 +10,7 @@ type ('state, 'language_data) t = { indent_number : 'state -> String_stream.Text.t -> unit_width:int -> float option; language_data : 'language_data option; merge_tokens : bool; + token_ends_in_bracket : ('state -> bool) option; } val create : @@ -19,6 +20,7 @@ val create : ?indent_number:('state -> String_stream.Text.t -> unit_width:int -> float option) -> ?language_data:'language_data -> ?merge_tokens:bool -> + ?token_ends_in_bracket:('state -> bool) -> start_state:(int -> 'state) -> copy_state:('state -> 'state) -> (String_stream.t -> 'state -> string option) -> @@ -26,4 +28,8 @@ val create : (** Stateful tokenizers supply a copy operation for their OCaml state. Immutable states can use [Fun.id], and stateless tokenizers can use [unit]. [indent_number] preserves the upstream numeric result, including fractional - columns and NaN. It defaults to converting [indent] to floats. *) + columns and NaN. It defaults to converting [indent] to floats. + [token_ends_in_bracket] describes the last successful token. It is true + when the last UTF-16 code unit is one of the structural delimiters + [()], [[]] or [{}]. Supplying this callback enables structural-only + matching for the language. *) diff --git a/packages/language/bracket_matching.ml b/packages/language/bracket_matching.ml index 42a086a..e21cd14 100644 --- a/packages/language/bracket_matching.ml +++ b/packages/language/bracket_matching.ml @@ -159,8 +159,11 @@ let match_plain doc tree token_type pos direction = in chunks 0 0 -let match_at doc tree pos direction = - if tree == Tree.empty then match_plain doc tree Node_type.none pos direction +let match_at ~structural_only doc tree pos direction = + let fallback node_type = + if structural_only then None else match_plain doc tree node_type pos direction + in + if tree == Tree.empty then fallback Node_type.none else let side = match direction with Forward -> Tree.Right | Backward -> Left @@ -172,7 +175,7 @@ let match_at doc tree pos direction = | Backward -> Node.from node < pos && pos <= Node.to_ node in let rec ancestors = function - | None -> match_plain doc tree (Node.node_type inner) pos direction + | None -> fallback (Node.node_type inner) | Some node -> ( match matching_nodes direction (Node.node_type node) with | Some names when nonempty node -> ( @@ -184,18 +187,19 @@ let match_at doc tree pos direction = in ancestors (Some inner) -let match_cursor doc tree head = +let match_cursor ~structural_only doc tree head = let length = State.Text.length doc in + let match_at = match_at ~structural_only doc tree in let or_else result next = match result with Some _ -> result | None -> next () in let before = - or_else (match_at doc tree head Backward) (fun () -> - if head > 0 then match_at doc tree (head - 1) Forward else None) + or_else (match_at head Backward) (fun () -> + if head > 0 then match_at (head - 1) Forward else None) in or_else before (fun () -> - or_else (match_at doc tree head Forward) (fun () -> - if head < length then match_at doc tree (head + 1) Backward else None)) + or_else (match_at head Forward) (fun () -> + if head < length then match_at (head + 1) Backward else None)) let match_mark = Decoration.mark ~class_name:"cm-matchingBracket" () let mismatch_mark = Decoration.mark ~class_name:"cm-nonmatchingBracket" () @@ -203,13 +207,26 @@ let mismatch_mark = Decoration.mark ~class_name:"cm-nonmatchingBracket" () let decorations state = let doc = State.Editor_state.doc state in let tree = Language.syntax_tree state in + let structural_only = + match State.Editor_state.facet state Language.language with + | None -> false + | Some language -> + (match + State.Editor_state.facet state (Language.data language) + |> Language.Data.get_all Language.Data.bracket_matching_structural_only + with + | value :: _ -> value + | [] -> false) + in let ranges = State.Editor_selection.ranges (State.Editor_state.selection state) in let add acc selection = if not (State.Selection_range.is_empty selection) then acc else - match match_cursor doc tree (State.Selection_range.head selection) with + match + match_cursor ~structural_only doc tree (State.Selection_range.head selection) + with | None -> acc | Some { start; finish; matched } -> ( let mark = if matched then match_mark else mismatch_mark in @@ -227,6 +244,9 @@ let matcher = in let update model update = if Update.doc_changed update || Update.selection_set update || model.paused + || List.exists State.Transaction.reconfigured (Update.transactions update) + || Language.syntax_tree (Update.start_state update) + != Language.syntax_tree (Update.state update) then if Editor.composing (Update.view update) then ( let changes = State.Change_set.desc (Update.changes update) in diff --git a/packages/language/language.ml b/packages/language/language.ml index 9acfcb2..6df5669 100644 --- a/packages/language/language.ml +++ b/packages/language/language.ml @@ -164,6 +164,7 @@ module Data = struct let word_chars = Values.word_chars let comment_tokens = Values.comment_tokens let close_brackets : close_brackets key = key () + let bracket_matching_structural_only : bool key = key () let empty = [] let set key value data = diff --git a/packages/language/language.mli b/packages/language/language.mli index de67fcd..ed6ed3c 100644 --- a/packages/language/language.mli +++ b/packages/language/language.mli @@ -132,6 +132,10 @@ module Data : sig (** Characters used by bracket completion. [None] leaves the default completion policy for following characters in effect. *) + val bracket_matching_structural_only : bool key + (** In the active language, match explicit syntax delimiters and disable + raw-text bracket matching, including while the syntax tree is incomplete. *) + val empty : t val set : 'a key -> 'a -> t -> t diff --git a/test/parity/editor_highlight/editor_highlight_cases.ml b/test/parity/editor_highlight/editor_highlight_cases.ml index 07c0e53..b556d09 100644 --- a/test/parity/editor_highlight/editor_highlight_cases.ml +++ b/test/parity/editor_highlight/editor_highlight_cases.ml @@ -134,9 +134,13 @@ let test_fallback_and_custom_highlights () = check "document changes rebuild visible syntax spans" (spans !rendered = [ (1, 4, "scoped-string"); (5, 10, "dark-boolean") ]) -let handled_language = +let handled_language ?(structural_only = false) ?(gap = 0) () = let open Common in - let data = L.Language.define_language_facet () in + let base = + L.Language.Data.set L.Language.Data.bracket_matching_structural_only + structural_only L.Language.Data.empty + in + let data = L.Language.define_language_facet ~base () in let define ~id ~name props = Node_type.define ~name ~props:(List.map (fun p -> Node_type.Binding p) props) @@ -166,15 +170,21 @@ let handled_language = [| (offset, Node (Tree.make part [||] ~length:1)) |] ~length:(offset + 2)) in - let tree = - Tree.make root [| (0, tag open_tag 1); (3, tag close_tag 2) |] ~length:7 - in + let length = 10 + gap in + let closing = 3 + gap in let parser = Parser.create (fun _ _ _ -> + let limit = ref length in Partial_parse.create - ~advance:(fun () -> Done tree) - ~parsed_pos:(fun () -> 7) - ~stop_at:(fun _ -> ())) + ~advance:(fun () -> + let open_ = (0, tag open_tag 1) in + let children = + if closing + 4 <= !limit then [| open_; (closing, tag close_tag 2) |] + else [| open_ |] + in + Done (Tree.make root children ~length:!limit)) + ~parsed_pos:(fun () -> !limit) + ~stop_at:(fun pos -> limit := pos)) in L.Language.create data parser |> L.Language.extension @@ -208,11 +218,21 @@ let test_bracket_selection_and_composition () = 3, [ (2, 3, nonmatching) ] ); ( "marked handles restrict the extent", - handled_language, - "", + handled_language (), + "(x)", + 2, + pair 1 5 matching ); + ("non-handle part is skipped", handled_language (), "(x)", 0, []); + ( "structural-only mode still matches explicit delimiters", + handled_language ~structural_only:true (), + "(x)", 2, pair 1 5 matching ); - ("non-handle part is skipped", handled_language, "", 0, []); + ( "structural-only mode ignores unmarked delimiters", + handled_language ~structural_only:true (), + "(x)", + 8, + [] ); ( "scan limit checks between chunks", S.Extension.empty, "(" ^ String.make 10_001 'a' ^ ")", @@ -272,6 +292,25 @@ let test_bracket_selection_and_composition () = check "each empty selection receives bracket marks" (spans !rendered = pair 0 1 matching @ pair 4 5 matching) +let test_bracket_parser_refresh () = + let gap = 3_200 in + let editor, rendered, _ = + create ~selection:(S.Editor_selection.single 2) + ("" ^ String.make gap 'x' ^ "(x)") + [ handled_language ~structural_only:true ~gap (); Highlight.bracket_matching () ] + in + let state = Editor.state editor in + let length = S.Text.length (S.Editor_state.doc state) in + check "incomplete tree marks the known opener as unmatched" + (spans !rendered = [ (1, 2, "cm-nonmatchingBracket") ]); + check "parse-only transaction publishes the complete tree" + (L.Language.force_parsing ~dispatch:(dispatch editor) state length); + check "new syntax refreshes bracket marks with the selection unchanged" + (S.Editor_state.selection (Editor.state editor) == S.Editor_state.selection state + && spans !rendered = + [ (1, 2, "cm-matchingBracket"); (gap + 5, gap + 6, "cm-matchingBracket") ]) + let () = test_fallback_and_custom_highlights (); - test_bracket_selection_and_composition () + test_bracket_selection_and_composition (); + test_bracket_parser_refresh ()