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
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const Lexed = @import("lexer/Lexed.zig");
const Lexer = @import("lexer/Lexer.zig");
const Element = @import("dom/Element.zig");
const paragraph = @import("paragraph.zig");
const title = @import("title.zig");
const link = @import("link.zig");
pub const Error = error{
FeatureNotSupported,
} || Lexer.Error || paragraph.Error || title.Error || link.Error;
pub fn parse(parent: Allocator, content: []const u8) Error![]const u8 {
var arena = std.heap.ArenaAllocator.init(parent);
defer arena.deinit();
const alloc = arena.allocator();
var elements = try std.ArrayList(Element).initCapacity(alloc, 2);
var l = try Lexer.init(content);
base: while (l.nextKind()) |it| {
try elements.append(alloc, switch (it) {
.literal, .bold, .italic, .code, .link => try paragraph.parse(alloc, &l),
.title => try title.parse(alloc, &l),
.weak_delimiter, .strong_delimiter => {
var v = (try l.next(alloc)).?;
v.deinit();
continue :base;
},
else => return Error.FeatureNotSupported,
});
}
var res = try std.ArrayList(u8).initCapacity(parent, elements.items.len);
errdefer res.deinit(parent);
for (elements.items) |it| {
var v = it;
try res.appendSlice(parent, try v.render(alloc));
}
return res.toOwnedSlice(parent);
}
fn doTest(alloc: Allocator, t: []const u8, v: []const u8) !void {
const g = try parse(alloc, t);
defer alloc.free(g);
std.testing.expect(std.mem.eql(u8, g, v)) catch |err| {
std.debug.print("{s}\n", .{g});
return err;
};
}
test "parse multilines" {
var arena = std.heap.DebugAllocator(.{}).init;
defer if (arena.deinit() == .leak) std.debug.print("leaking!\n", .{});
const alloc = arena.allocator();
try doTest(alloc,
\\hello
\\world
\\
\\foo bar
\\in new paragraph
, "<p>hello world</p><p>foo bar in new paragraph</p>");
try doTest(alloc,
\\# title
\\hello world ;3
\\## subtitle
\\hehe
, "<h1>title</h1><p>hello world ;3</p><h2>subtitle</h2><p>hehe</p>");
}
|