From 8684fab23cc79f29b3ff117429c6e3eabd936037 Mon Sep 17 00:00:00 2001 From: torque Date: Sun, 24 Sep 2023 14:45:01 -0700 Subject: [PATCH] build: add oneshot parsing example --- build.zig | 38 ++++++++++++++++++++++++++++++++++++++ examples/parse.zig | 29 +++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 examples/parse.zig diff --git a/build.zig b/build.zig index 8611504..2fcea8d 100644 --- a/build.zig +++ b/build.zig @@ -1,7 +1,45 @@ const std = @import("std"); pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const nice = b.addModule("nice", .{ .source_file = .{ .path = "src/config.zig" }, }); + + add_examples(b, .{ + .target = target, + .nice_mod = nice, + }); +} + +const ExampleOptions = struct { + target: std.zig.CrossTarget, + nice_mod: *std.Build.Module, +}; + +const Example = struct { + name: []const u8, + file: []const u8, +}; + +const examples = [_]Example{ + .{ .name = "parse", .file = "examples/parse.zig" }, +}; + +pub fn add_examples(b: *std.build, options: ExampleOptions) void { + const example_step = b.step("examples", "build examples"); + + inline for (examples) |example| { + const ex_exe = b.addExecutable(.{ + .name = example.name, + .root_source_file = .{ .path = example.file }, + .target = options.target, + .optimize = .Debug, + }); + + ex_exe.addModule("nice", options.nice_mod); + const install = b.addInstallArtifact(ex_exe, .{}); + example_step.dependOn(&install.step); + } } diff --git a/examples/parse.zig b/examples/parse.zig new file mode 100644 index 0000000..69a6bd2 --- /dev/null +++ b/examples/parse.zig @@ -0,0 +1,29 @@ +const std = @import("std"); + +const nice = @import("nice"); + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const args = try std.process.argsAlloc(allocator); + defer std.process.argsFree(allocator, args); + if (args.len < 2) return; + + const data = try std.fs.cwd().readFileAlloc(allocator, args[1], 4_294_967_295); + var needfree = true; + defer if (needfree) allocator.free(data); + + var parser = nice.Parser{ .allocator = allocator }; + + const document = try parser.parseBuffer(data); + defer document.deinit(); + + // free data memory to ensure that the parsed document is not holding + // references to it. + allocator.free(data); + needfree = false; + + document.printDebug(); +}