commonmarker 2.10.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,16 +2,15 @@
2
2
  name = "commonmarker"
3
3
  version = "1.0.0"
4
4
  edition = "2021"
5
- rust-version = "1.75.0"
5
+ rust-version = "1.89.0"
6
6
  publish = false
7
7
 
8
8
  [dependencies]
9
- magnus = { version = "0.8", features = ["rb-sys"] }
9
+ magnus = { version = "0.9", features = ["rb-sys"] }
10
10
  rb-sys = { version = "*", default-features = false, features = [
11
11
  "stable-api-compiled-fallback",
12
12
  ] }
13
13
  typed-arena = "2.0"
14
- rctree = "0.6"
15
14
  rb-allocator = "0.9"
16
15
 
17
16
  syntect = { version = "5.3", default-features = false, features = [
@@ -21,7 +20,8 @@ syntect = { version = "5.3", default-features = false, features = [
21
20
 
22
21
  # Everywhere except Windows: Oniguruma, the faster engine.
23
22
  [target.'cfg(not(windows))'.dependencies]
24
- comrak = { version = "0.54", default-features = false, features = [
23
+ comrak = { version = "1.2", default-features = false, features = [
24
+ "attributes",
25
25
  "shortcodes",
26
26
  "syntect-onig",
27
27
  ] }
@@ -30,7 +30,8 @@ comrak = { version = "0.54", default-features = false, features = [
30
30
  # linking a second copy (onig_sys) collides at link time and segfaults (xref #467).
31
31
  # syntect-fancy swaps in the pure-Rust fancy-regex backend instead.
32
32
  [target.'cfg(windows)'.dependencies]
33
- comrak = { version = "0.54", default-features = false, features = [
33
+ comrak = { version = "1.2", default-features = false, features = [
34
+ "attributes",
34
35
  "shortcodes",
35
36
  "syntect-fancy",
36
37
  ] }
@@ -1,168 +1,270 @@
1
1
  extern crate core;
2
2
 
3
- use std::fmt::{self, Write};
3
+ use std::fmt;
4
+ use std::sync::{Arc, OnceLock};
4
5
 
6
+ use comrak::html::{self, ChildRendering, Context};
5
7
  use comrak::parse_document;
6
- use magnus::{function, scan_args, RHash, RString, Ruby, Value};
8
+ use comrak::plugins::syntect::SyntectAdapter;
9
+ use comrak::Node;
10
+ use magnus::{method, Class, Module, RString, Ruby, Value};
7
11
  use node::CommonmarkerNode;
8
12
  use plugins::syntax_highlighting::construct_syntax_highlighter_from_plugin;
13
+ use plugins::{comrak_plugins, format_plugins};
9
14
 
15
+ mod nesting;
10
16
  mod options;
11
-
12
17
  mod plugins;
18
+ mod rctree;
19
+ mod utils;
13
20
 
14
21
  use rb_allocator::ruby_global_allocator;
15
22
  use typed_arena::Arena;
16
23
 
17
- use crate::options::{iterate_extension_options, iterate_parse_options, iterate_render_options};
24
+ use crate::options::{default_options_to_hash, format_options, Options};
25
+ use crate::plugins::default_plugins_to_hash;
18
26
 
19
27
  mod node;
20
- mod utils;
21
28
 
22
29
  pub const EMPTY_STR: &str = "";
23
30
 
24
31
  // Inform Ruby's GC about memory allocations.
25
32
  ruby_global_allocator!();
26
33
 
27
- /// A writer that writes directly to a Ruby String, avoiding intermediate Rust allocations.
28
- struct RStringWriter(RString);
29
-
30
- impl Write for RStringWriter {
31
- fn write_str(&mut self, s: &str) -> fmt::Result {
32
- self.0.cat(s);
33
- Ok(())
34
- }
35
- }
36
-
37
- fn commonmark_parse(ruby: &Ruby, args: &[Value]) -> Result<CommonmarkerNode, magnus::Error> {
38
- let args = scan_args::scan_args::<_, (), (), (), _, ()>(args)?;
39
- let (rb_commonmark,): (RString,) = args.required;
40
-
34
+ /// Borrows the CommonMark text as `&str`, rejecting invalid UTF-8.
35
+ fn commonmark_str<'a>(ruby: &Ruby, rb_commonmark: &'a RString) -> Result<&'a str, magnus::Error> {
41
36
  // SAFETY: We hold the GVL and rb_commonmark won't be modified until we return
42
- let commonmark_str = unsafe {
37
+ unsafe {
43
38
  rb_commonmark.as_str().map_err(|e| {
44
39
  magnus::Error::new(
45
40
  ruby.exception_encoding_error(),
46
- format!("invalid UTF-8: {}", e),
41
+ format!("invalid UTF-8: {e}"),
47
42
  )
48
- })?
49
- };
50
-
51
- let kwargs = scan_args::get_kwargs::<_, (), (Option<RHash>, Option<RHash>, Option<RHash>), ()>(
52
- args.keywords,
53
- &[],
54
- &["parse", "render", "extension"],
55
- )?;
56
- let (rb_parse, rb_render, rb_extension) = kwargs.optional;
43
+ })
44
+ }
45
+ }
57
46
 
58
- let mut comrak_parse_options = comrak::options::Parse::default();
59
- let mut comrak_render_options = comrak::options::Render::default();
60
- let mut comrak_extension_options = comrak::options::Extension::default();
47
+ /// Tracks the maximum nesting depth during rendering, replacing a separate
48
+ /// O(N) tree traversal with depth tracking inside the formatter. If `exceeded`
49
+ /// is set, the document is too deeply nested and the partial output is discarded.
50
+ struct DepthState {
51
+ depth: usize,
52
+ max_depth: usize,
53
+ exceeded: bool,
54
+ }
61
55
 
62
- if let Some(rb_parse) = rb_parse {
63
- iterate_parse_options(&mut comrak_parse_options, rb_parse);
64
- }
65
- if let Some(rb_render) = rb_render {
66
- iterate_render_options(&mut comrak_render_options, rb_render);
67
- }
68
- if let Some(rb_extension) = rb_extension {
69
- iterate_extension_options(&mut comrak_extension_options, rb_extension);
56
+ /// Formatter that tracks nesting depth and delegates to comrak's default
57
+ /// formatter. Combines the nesting check with the render, eliminating a
58
+ /// separate tree traversal. Checks before incrementing (matching nesting::check).
59
+ fn format_node_with_depth_check(
60
+ context: &mut Context<DepthState>,
61
+ node: Node<'_>,
62
+ entering: bool,
63
+ ) -> Result<ChildRendering, fmt::Error> {
64
+ if entering {
65
+ if context.user.depth > context.user.max_depth {
66
+ context.user.exceeded = true;
67
+ }
68
+ context.user.depth += 1;
69
+ } else {
70
+ context.user.depth -= 1;
70
71
  }
72
+ html::format_node_default(context, node, entering)
73
+ }
71
74
 
72
- let comrak_options = comrak::Options {
73
- parse: comrak_parse_options,
74
- render: comrak_render_options,
75
- extension: comrak_extension_options,
76
- };
75
+ /// Everything a `Commonmarker` instance needs to parse and render, processed
76
+ /// once from the Ruby `options` and `plugins` hashes.
77
+ struct Config {
78
+ options: Options,
79
+ syntax_highlighter: Option<Arc<SyntectAdapter>>,
80
+ }
77
81
 
78
- let arena = Arena::new();
79
- let root = parse_document(&arena, commonmark_str, &comrak_options);
82
+ impl Config {
83
+ fn plugins(&self) -> comrak::options::Plugins<'_> {
84
+ comrak_plugins(self.syntax_highlighter.as_deref())
85
+ }
86
+ }
80
87
 
81
- CommonmarkerNode::new_from_comrak_node(root)
88
+ /// The Rust side of a `Commonmarker` instance.
89
+ ///
90
+ /// Ruby allocates it empty and `initialize` fills it through `commonmark_init`,
91
+ /// so the configuration is validated once and every later `parse`/`to_html`
92
+ /// call reuses it. It holds no Ruby objects, so there is nothing to mark.
93
+ #[derive(Default)]
94
+ #[magnus::wrap(class = "Commonmarker", free_immediately, size)]
95
+ struct Commonmarker {
96
+ config: OnceLock<Config>,
82
97
  }
83
98
 
84
- fn commonmark_to_html(ruby: &Ruby, args: &[Value]) -> Result<RString, magnus::Error> {
85
- let args = scan_args::scan_args::<_, (), (), (), _, ()>(args)?;
86
- let (rb_commonmark,): (RString,) = args.required;
99
+ impl Commonmarker {
100
+ /// `Commonmarker#commonmark_init(options, plugins)`, called from `initialize`.
101
+ fn init(
102
+ ruby: &Ruby,
103
+ rb_self: &Self,
104
+ rb_options: Value,
105
+ rb_plugins: Value,
106
+ ) -> Result<(), magnus::Error> {
107
+ let options = format_options(ruby, Some(rb_options))?;
108
+ let formatted_plugins = format_plugins(ruby, Some(rb_plugins))?;
109
+ let syntax_highlighter = construct_syntax_highlighter_from_plugin(ruby, formatted_plugins)?;
110
+
111
+ rb_self
112
+ .config
113
+ .set(Config {
114
+ options,
115
+ syntax_highlighter,
116
+ })
117
+ .map_err(|_| {
118
+ magnus::Error::new(
119
+ ruby.exception_runtime_error(),
120
+ "Commonmarker instance is already initialized",
121
+ )
122
+ })
123
+ }
87
124
 
88
- // SAFETY: We hold the GVL and rb_commonmark won't be modified until we return
89
- let commonmark_str = unsafe {
90
- rb_commonmark.as_str().map_err(|e| {
125
+ fn config(&self, ruby: &Ruby) -> Result<&Config, magnus::Error> {
126
+ self.config.get().ok_or_else(|| {
91
127
  magnus::Error::new(
92
- ruby.exception_encoding_error(),
93
- format!("invalid UTF-8: {}", e),
128
+ ruby.exception_runtime_error(),
129
+ "Commonmarker instance was not initialized; create it with Commonmarker.new",
94
130
  )
95
- })?
96
- };
97
-
98
- let kwargs = scan_args::get_kwargs::<
99
- _,
100
- (),
101
- (Option<RHash>, Option<RHash>, Option<RHash>, Option<RHash>),
102
- (),
103
- >(
104
- args.keywords,
105
- &[],
106
- &["render", "parse", "extension", "plugins"],
107
- )?;
108
- let (rb_render, rb_parse, rb_extension, rb_plugins) = kwargs.optional;
131
+ })
132
+ }
109
133
 
110
- let mut comrak_parse_options = comrak::options::Parse::default();
111
- let mut comrak_render_options = comrak::options::Render::default();
112
- let mut comrak_extension_options = comrak::options::Extension::default();
134
+ /// `Commonmarker#commonmark_parse(text)`.
135
+ fn parse(
136
+ ruby: &Ruby,
137
+ rb_self: &Self,
138
+ rb_commonmark: RString,
139
+ ) -> Result<CommonmarkerNode, magnus::Error> {
140
+ let config = rb_self.config(ruby)?;
141
+ let commonmark_str = commonmark_str(ruby, &rb_commonmark)?;
113
142
 
114
- if let Some(rb_parse) = rb_parse {
115
- iterate_parse_options(&mut comrak_parse_options, rb_parse);
116
- }
117
- if let Some(rb_render) = rb_render {
118
- iterate_render_options(&mut comrak_render_options, rb_render);
119
- }
120
- if let Some(rb_extension) = rb_extension {
121
- iterate_extension_options(&mut comrak_extension_options, rb_extension);
143
+ let arena = Arena::new();
144
+ let root = parse_document(&arena, commonmark_str, &config.options.comrak);
145
+
146
+ CommonmarkerNode::new_from_comrak_node(ruby, root, config.options.max_nesting_depth)
122
147
  }
123
148
 
124
- let mut comrak_plugins = comrak::options::Plugins::default();
149
+ /// `Commonmarker#commonmark_to_html(text)`.
150
+ fn to_html(
151
+ ruby: &Ruby,
152
+ rb_self: &Self,
153
+ rb_commonmark: RString,
154
+ ) -> Result<RString, magnus::Error> {
155
+ let config = rb_self.config(ruby)?;
156
+ let commonmark_str = commonmark_str(ruby, &rb_commonmark)?;
157
+
158
+ let arena = Arena::new();
159
+ let root = parse_document(&arena, commonmark_str, &config.options.comrak);
160
+
161
+ // Render and track nesting depth in one pass, eliminating a separate
162
+ // O(N) tree traversal for the nesting check.
163
+ let mut buffer = String::with_capacity(commonmark_str.len() * 2);
164
+ let depth_state = html::format_document_with_formatter(
165
+ root,
166
+ &config.options.comrak,
167
+ &mut buffer,
168
+ &config.plugins(),
169
+ format_node_with_depth_check,
170
+ DepthState {
171
+ depth: 0,
172
+ max_depth: config.options.max_nesting_depth,
173
+ exceeded: false,
174
+ },
175
+ )
176
+ .map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e.to_string()))?;
125
177
 
126
- let syntect_adapter = match construct_syntax_highlighter_from_plugin(ruby, rb_plugins) {
127
- Ok(Some(adapter)) => Some(adapter),
128
- Ok(None) => None,
129
- Err(err) => return Err(err),
130
- };
178
+ if depth_state.exceeded {
179
+ return Err(nesting::exceeded_error(
180
+ ruby,
181
+ config.options.max_nesting_depth,
182
+ ));
183
+ }
131
184
 
132
- match syntect_adapter {
133
- Some(ref adapter) => comrak_plugins.render.codefence_syntax_highlighter = Some(adapter),
134
- None => comrak_plugins.render.codefence_syntax_highlighter = None,
185
+ Ok(ruby.str_new(&buffer))
135
186
  }
136
187
 
137
- let comrak_options = comrak::Options {
138
- parse: comrak_parse_options,
139
- render: comrak_render_options,
140
- extension: comrak_extension_options,
141
- };
188
+ /// `Commonmarker#commonmark_to_commonmark(text)`: parses the text and
189
+ /// writes it back out as CommonMark.
190
+ fn to_commonmark(
191
+ ruby: &Ruby,
192
+ rb_self: &Self,
193
+ rb_commonmark: RString,
194
+ ) -> Result<RString, magnus::Error> {
195
+ let config = rb_self.config(ruby)?;
196
+ let commonmark_str = commonmark_str(ruby, &rb_commonmark)?;
197
+
198
+ let arena = Arena::new();
199
+ let root = parse_document(&arena, commonmark_str, &config.options.comrak);
200
+
201
+ nesting::check(ruby, root, config.options.max_nesting_depth)?;
202
+
203
+ let mut buffer = String::with_capacity(commonmark_str.len());
204
+ comrak::format_commonmark_with_plugins(
205
+ root,
206
+ &config.options.comrak,
207
+ &mut buffer,
208
+ &config.plugins(),
209
+ )
210
+ .map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e.to_string()))?;
142
211
 
143
- // Pre-allocate Ruby string with estimated capacity (assume HTML is typically 2x commonmark size)
144
- let output = ruby.str_with_capacity(commonmark_str.len() * 2);
145
- let mut writer = RStringWriter(output);
212
+ Ok(ruby.str_new(&buffer))
213
+ }
146
214
 
147
- // Parse and render directly to Ruby string, avoiding intermediate Rust String allocation
148
- let arena = Arena::new();
149
- let root = parse_document(&arena, commonmark_str, &comrak_options);
215
+ /// `Commonmarker#commonmark_render_html(node)`.
216
+ fn render_html(
217
+ ruby: &Ruby,
218
+ rb_self: &Self,
219
+ node: &CommonmarkerNode,
220
+ ) -> Result<String, magnus::Error> {
221
+ let config = rb_self.config(ruby)?;
150
222
 
151
- comrak::html::format_document_with_plugins(root, &comrak_options, &mut writer, &comrak_plugins)
152
- .map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e.to_string()))?;
223
+ node.render_html(ruby, &config.options, &config.plugins())
224
+ }
225
+
226
+ /// `Commonmarker#commonmark_render_commonmark(node)`.
227
+ fn render_commonmark(
228
+ ruby: &Ruby,
229
+ rb_self: &Self,
230
+ node: &CommonmarkerNode,
231
+ ) -> Result<String, magnus::Error> {
232
+ let config = rb_self.config(ruby)?;
153
233
 
154
- Ok(output)
234
+ node.render_commonmark(ruby, &config.options, &config.plugins())
235
+ }
155
236
  }
156
237
 
157
238
  #[magnus::init]
158
239
  fn init(ruby: &Ruby) -> Result<(), magnus::Error> {
159
- let m_commonmarker = ruby.define_module("Commonmarker")?;
240
+ let c_commonmarker = ruby.define_class("Commonmarker", ruby.class_object())?;
241
+
242
+ // Instances are allocated empty and configured by `initialize` (in Ruby),
243
+ // which hands the options and plugins to `commonmark_init`.
244
+ c_commonmarker.define_alloc_func::<Commonmarker>();
245
+ c_commonmarker.define_private_method("commonmark_init", method!(Commonmarker::init, 2))?;
246
+ c_commonmarker.define_private_method("commonmark_parse", method!(Commonmarker::parse, 1))?;
247
+ c_commonmarker
248
+ .define_private_method("commonmark_to_html", method!(Commonmarker::to_html, 1))?;
249
+ c_commonmarker.define_private_method(
250
+ "commonmark_to_commonmark",
251
+ method!(Commonmarker::to_commonmark, 1),
252
+ )?;
253
+ c_commonmarker.define_private_method(
254
+ "commonmark_render_html",
255
+ method!(Commonmarker::render_html, 1),
256
+ )?;
257
+ c_commonmarker.define_private_method(
258
+ "commonmark_render_commonmark",
259
+ method!(Commonmarker::render_commonmark, 1),
260
+ )?;
160
261
 
161
- m_commonmarker.define_module_function("commonmark_parse", function!(commonmark_parse, -1))?;
162
- m_commonmarker
163
- .define_module_function("commonmark_to_html", function!(commonmark_to_html, -1))?;
262
+ // Define Config module to hold constants
263
+ let m_config = c_commonmarker.define_module("Config")?;
264
+ m_config.const_set("OPTIONS", default_options_to_hash(ruby)?)?;
265
+ m_config.const_set("PLUGINS", default_plugins_to_hash(ruby)?)?;
164
266
 
165
- node::init(ruby, m_commonmarker).expect("cannot define Commonmarker::Node class");
267
+ node::init(ruby, c_commonmarker).expect("cannot define Commonmarker::Node class");
166
268
 
167
269
  Ok(())
168
270
  }
@@ -0,0 +1,52 @@
1
+ use comrak::arena_tree::NodeEdge;
2
+ use comrak::nodes::AstNode;
3
+ use magnus::{ExceptionClass, Module, RClass, Ruby};
4
+
5
+ /// Default for the `max_nesting_depth` parse option. Exposed to Ruby as
6
+ /// `Commonmarker::Config::OPTIONS[:parse][:max_nesting_depth]`, and also applies
7
+ /// when the option is passed as `nil`. The option is read alongside comrak's
8
+ /// in `crate::options::format_options`.
9
+ pub const DEFAULT_MAX_NESTING_DEPTH: usize = 1000;
10
+
11
+ /// The error raised when a document nests deeper than `max_nesting_depth`.
12
+ pub fn exceeded_error(ruby: &Ruby, max_nesting_depth: usize) -> magnus::Error {
13
+ let class = ruby
14
+ .class_object()
15
+ .const_get::<_, RClass>("Commonmarker")
16
+ .and_then(|class| class.const_get::<_, ExceptionClass>("NestingDepthExceededError"));
17
+
18
+ match class {
19
+ Ok(class) => magnus::Error::new(
20
+ class,
21
+ format!(
22
+ "nesting depth exceeds the max_nesting_depth parse option ({max_nesting_depth})"
23
+ ),
24
+ ),
25
+ Err(error) => error,
26
+ }
27
+ }
28
+
29
+ /// Fails if any node sits more than `max_nesting_depth` levels below the
30
+ /// document root. `traverse` is iterative, so this is safe on arbitrarily deep
31
+ /// trees.
32
+ pub fn check<'a>(
33
+ ruby: &Ruby,
34
+ root: &'a AstNode<'a>,
35
+ max_nesting_depth: usize,
36
+ ) -> Result<(), magnus::Error> {
37
+ let mut depth: usize = 0;
38
+
39
+ for edge in root.traverse() {
40
+ match edge {
41
+ NodeEdge::Start(_) => {
42
+ if depth > max_nesting_depth {
43
+ return Err(exceeded_error(ruby, max_nesting_depth));
44
+ }
45
+ depth += 1;
46
+ }
47
+ NodeEdge::End(_) => depth -= 1,
48
+ }
49
+ }
50
+
51
+ Ok(())
52
+ }