1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
|
//! Autolinks are a construct that occurs in the [text][] content type.
//!
//! It forms with the following BNF:
//!
//! ```bnf
//! autolink ::= '<' ( url | email ) '>'
//!
//! url ::= ascii_alphabetic 0*31( '+' '-' '.' ascii_alphanumeric ) ':' *( code - ascii_control - '\r' - '\n' - ' ')
//! email ::= 1*ascii_atext '@' domain *('.' domain)
//! ; Restriction: up to (including) 63 character are allowed in each domain.
//! domain ::= ascii_alphanumeric *( ascii_alphanumeric | '-' ascii_alphanumeric )
//! ascii_atext ::= ascii_alphanumeric | '#' .. '\'' | '*' | '+' | '-' | '/' | '=' | '?' | '^' .. '`' | '{' .. '~'
//! ```
//!
//! Autolinks relate to the `<a>` element in HTML.
//! See [*§ 4.5.1 The `a` element*][html-a] in the HTML spec for more info.
//! When an email autolink is used (so, without a protocol), the string
//! `mailto:` is prepended before the email, when generating the `href`
//! attribute of the hyperlink.
//!
//! The maximum allowed size of a scheme is `31` (inclusive), which is defined
//! in [`AUTOLINK_SCHEME_SIZE_MAX`][autolink_scheme_size_max].
//! The maximum allowed size of a domain is `63` (inclusive), which is defined
//! in [`AUTOLINK_DOMAIN_SIZE_MAX`][autolink_domain_size_max].
//!
//! The grammar for autolinks is quite strict and prohibits the use of ASCII control
//! characters or spaces.
//! To use non-ascii characters and otherwise impossible characters, in URLs,
//! you can use percent encoding:
//!
//! ```markdown
//! <https://example.com/alpha%20bravo>
//! ```
//!
//! Yields:
//!
//! ```html
//! <p><a href="https://example.com/alpha%20bravo">https://example.com/alpha%20bravo</a></p>
//! ```
//!
//! There are several cases where incorrect encoding of URLs would, in other
//! languages, result in a parse error.
//! In markdown, there are no errors, and URLs are normalized.
//! In addition, unicode characters are percent encoded
//! ([`sanitize_uri`][sanitize_uri]).
//! For example:
//!
//! ```markdown
//! <https://a👍b%>
//! ```
//!
//! Yields:
//!
//! ```html
//! <p><a href="https://a%F0%9F%91%8Db%25">https://a👍b%</a></p>
//! ```
//!
//! Interestingly, there are a couple of things that are valid autolinks in
//! markdown but in HTML would be valid tags, such as `<svg:rect>` and
//! `<xml:lang/>`.
//! However, because `CommonMark` employs a naïve HTML parsing algorithm, those
//! are not considered HTML.
//!
//! While `CommonMark` restricts links from occurring in other links in the
//! case of bracketed links, this restriction is not in place for autolinks
//! inside autolinks:
//!
//! ```markdown
//! [<https://example.com>](#)
//! ```
//!
//! Yields:
//!
//! ```html
//! <p><a href="#"><a href="https://example.com">https://example.com</a></a></p>
//! ```
//!
//! The generated output, in this case, is invalid according to HTML.
//! When a browser sees that markup, it will instead parse it as:
//!
//! ```html
//! <p><a href="#"></a><a href="https://example.com">https://example.com</a></p>
//! ```
//!
//! ## Tokens
//!
//! * [`Autolink`][TokenType::Autolink]
//! * [`AutolinkEmail`][TokenType::AutolinkEmail]
//! * [`AutolinkMarker`][TokenType::AutolinkMarker]
//! * [`AutolinkProtocol`][TokenType::AutolinkProtocol]
//!
//! ## References
//!
//! * [`autolink.js` in `micromark`](https://github.com/micromark/micromark/blob/main/packages/micromark-core-commonmark/dev/lib/autolink.js)
//! * [*§ 6.4 Autolinks* in `CommonMark`](https://spec.commonmark.org/0.30/#autolinks)
//!
//! [text]: crate::content::text
//! [autolink_scheme_size_max]: crate::constant::AUTOLINK_SCHEME_SIZE_MAX
//! [autolink_domain_size_max]: crate::constant::AUTOLINK_DOMAIN_SIZE_MAX
//! [sanitize_uri]: crate::util::sanitize_uri
//! [html-a]: https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element
//!
//! <!-- To do: add explanation of sanitation. -->
use crate::constant::{AUTOLINK_DOMAIN_SIZE_MAX, AUTOLINK_SCHEME_SIZE_MAX};
use crate::tokenizer::{Code, State, StateFnResult, TokenType, Tokenizer};
/// Start of an autolink.
///
/// ```markdown
/// a|<https://example.com>b
/// a|<user@example.com>b
/// ```
pub fn start(tokenizer: &mut Tokenizer, code: Code) -> StateFnResult {
match code {
Code::Char('<') => {
tokenizer.enter(TokenType::Autolink);
tokenizer.enter(TokenType::AutolinkMarker);
tokenizer.consume(code);
tokenizer.exit(TokenType::AutolinkMarker);
tokenizer.enter(TokenType::AutolinkProtocol);
(State::Fn(Box::new(open)), None)
}
_ => (State::Nok, None),
}
}
/// After `<`, before the protocol.
///
/// ```markdown
/// a<|https://example.com>b
/// a<|user@example.com>b
/// ```
fn open(tokenizer: &mut Tokenizer, code: Code) -> StateFnResult {
match code {
Code::Char(char) if char.is_ascii_alphabetic() => {
tokenizer.consume(code);
(State::Fn(Box::new(scheme_or_email_atext)), None)
}
Code::Char(char) if is_ascii_atext(char) => email_atext(tokenizer, code),
_ => (State::Nok, None),
}
}
/// After the first character of the protocol or email name.
///
/// ```markdown
/// a<h|ttps://example.com>b
/// a<u|ser@example.com>b
/// ```
fn scheme_or_email_atext(tokenizer: &mut Tokenizer, code: Code) -> StateFnResult {
// Whether this character can be both a protocol and email atext.
let unknown = match code {
Code::Char('+' | '-' | '.') => true,
Code::Char(char) if char.is_ascii_alphanumeric() => true,
_ => false,
};
if unknown {
scheme_inside_or_email_atext(tokenizer, code, 1)
} else {
email_atext(tokenizer, code)
}
}
/// Inside an ambiguous protocol or email name.
///
/// ```markdown
/// a<ht|tps://example.com>b
/// a<us|er@example.com>b
/// ```
fn scheme_inside_or_email_atext(
tokenizer: &mut Tokenizer,
code: Code,
size: usize,
) -> StateFnResult {
if let Code::Char(':') = code {
tokenizer.consume(code);
(State::Fn(Box::new(url_inside)), None)
} else {
// Whether this character can be both a protocol and email atext.
let unknown = match code {
Code::Char('+' | '-' | '.') if size < AUTOLINK_SCHEME_SIZE_MAX => true,
Code::Char(char) if char.is_ascii_alphanumeric() && size < AUTOLINK_SCHEME_SIZE_MAX => {
true
}
_ => false,
};
if unknown {
tokenizer.consume(code);
(
State::Fn(Box::new(move |t, c| {
scheme_inside_or_email_atext(t, c, size + 1)
})),
None,
)
} else {
email_atext(tokenizer, code)
}
}
}
/// Inside a URL, after the protocol.
///
/// ```markdown
/// a<https:|//example.com>b
/// ```
fn url_inside(tokenizer: &mut Tokenizer, code: Code) -> StateFnResult {
match code {
Code::Char('>') => {
tokenizer.exit(TokenType::AutolinkProtocol);
end(tokenizer, code)
}
Code::Char(char) if char.is_ascii_control() => (State::Nok, None),
Code::None | Code::CarriageReturnLineFeed | Code::VirtualSpace | Code::Char(' ') => {
(State::Nok, None)
}
Code::Char(_) => {
tokenizer.consume(code);
(State::Fn(Box::new(url_inside)), None)
}
}
}
/// Inside email atext.
///
/// ```markdown
/// a<user.na|me@example.com>b
/// ```
fn email_atext(tokenizer: &mut Tokenizer, code: Code) -> StateFnResult {
match code {
Code::Char('@') => {
tokenizer.consume(code);
(
State::Fn(Box::new(|t, c| email_at_sign_or_dot(t, c, 0))),
None,
)
}
Code::Char(char) if is_ascii_atext(char) => {
tokenizer.consume(code);
(State::Fn(Box::new(email_atext)), None)
}
_ => (State::Nok, None),
}
}
/// After an at-sign or a dot in the label.
///
/// ```markdown
/// a<user.name@|example.com>b
/// a<user.name@example.|com>b
/// ```
fn email_at_sign_or_dot(tokenizer: &mut Tokenizer, code: Code, size: usize) -> StateFnResult {
match code {
Code::Char(char) if char.is_ascii_alphanumeric() => email_value(tokenizer, code, size),
_ => (State::Nok, None),
}
}
/// In the label, where `.` and `>` are allowed.
///
/// ```markdown
/// a<user.name@ex|ample.com>b
/// ```
fn email_label(tokenizer: &mut Tokenizer, code: Code, size: usize) -> StateFnResult {
match code {
Code::Char('.') => {
tokenizer.consume(code);
(
State::Fn(Box::new(|t, c| email_at_sign_or_dot(t, c, 0))),
None,
)
}
Code::Char('>') => {
let index = tokenizer.events.len();
tokenizer.exit(TokenType::AutolinkProtocol);
// Change the token type.
tokenizer.events[index - 1].token_type = TokenType::AutolinkEmail;
tokenizer.events[index].token_type = TokenType::AutolinkEmail;
end(tokenizer, code)
}
_ => email_value(tokenizer, code, size),
}
}
/// In the label, where `.` and `>` are *not* allowed.
///
/// Though, this is also used in `email_label` to parse other values.
///
/// ```markdown
/// a<user.name@ex-|ample.com>b
/// ```
fn email_value(tokenizer: &mut Tokenizer, code: Code, size: usize) -> StateFnResult {
let ok = match code {
Code::Char('-') if size < AUTOLINK_DOMAIN_SIZE_MAX => true,
Code::Char(char) if char.is_ascii_alphanumeric() && size < AUTOLINK_DOMAIN_SIZE_MAX => true,
_ => false,
};
if ok {
tokenizer.consume(code);
let func = if let Code::Char('-') = code {
email_value
} else {
email_label
};
(State::Fn(Box::new(move |t, c| func(t, c, size + 1))), None)
} else {
(State::Nok, None)
}
}
/// At the `>`.
///
/// ```markdown
/// a<https://example.com|>b
/// a<user@example.com|>b
/// ```
fn end(tokenizer: &mut Tokenizer, code: Code) -> StateFnResult {
match code {
Code::Char('>') => {
tokenizer.enter(TokenType::AutolinkMarker);
tokenizer.consume(code);
tokenizer.exit(TokenType::AutolinkMarker);
tokenizer.exit(TokenType::Autolink);
(State::Ok, None)
}
_ => unreachable!("expected `>` at `end`"),
}
}
/// Check whether the character code represents an ASCII atext.
///
/// atext is an ASCII alphanumeric (see [`is_ascii_alphanumeric`][]), or a character in
/// the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),
/// U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F
/// SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E
/// CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE
/// (`{`) to U+007E TILDE (`~`).
///
/// See:
/// **\[RFC5322]**:
/// [Internet Message Format](https://tools.ietf.org/html/rfc5322).
/// P. Resnick.
/// IETF.
///
/// [`is_ascii_alphanumeric`]: char::is_ascii_alphanumeric
fn is_ascii_atext(x: char) -> bool {
matches!(x, '#'..='\'' | '*' | '+' | '-'..='9' | '=' | '?' | 'A'..='Z' | '^'..='~')
}
|