Compare commits

...

14 Commits

Author SHA1 Message Date
Spencer Brower 5833b764a4 refactor: Replaced now object with iso string 2026-07-23 16:12:04 -04:00
Spencer Brower 23b0b3fa5f feat: format pipe can now accept custom formats as quoted strings. 2026-07-23 16:12:04 -04:00
Spencer Brower d35da93dcf feat: Added Go style date format configuration. 2026-07-23 16:12:03 -04:00
Spencer Brower 4560014954 feat: Pipes now have access to the full template context. 2026-07-23 11:45:37 -04:00
Spencer Brower b3608fe493 feat: Added date config to site. 2026-07-23 11:45:37 -04:00
Spencer Brower b2ff7038cb fix: Simplified logging. 2026-07-23 11:26:36 -04:00
Spencer Brower c648b600c7 refactor: Site now uses the default opengraph partial. 2026-07-23 11:26:36 -04:00
Spencer Brower 56e434210b feat: Added build time to output. 2026-07-23 11:26:36 -04:00
Spencer Brower 83f2dc18f9 perf(mustache): Improved performance. 2026-07-23 11:26:36 -04:00
Spencer Brower 986038f54c refactor(mustache): Simplified Node parser. 2026-07-23 11:26:36 -04:00
Spencer Brower 5960d3686c feat: Added a stress tester so we can benchmark the template rendering. 2026-07-23 11:26:36 -04:00
Spencer Brower 1856e29763 perf: Fixed leaks. 2026-07-23 11:26:36 -04:00
Spencer Brower cfd01a02d0 refactor: Changed Render_Error from Union to struct.
Also renamed it to `Error`.
2026-07-23 11:26:35 -04:00
Spencer Brower f04532229b feat: Added Rust-style error messages for template errors. 2026-07-23 11:26:32 -04:00
39 changed files with 3860 additions and 476 deletions
+96 -32
View File
@@ -5,7 +5,7 @@ Thor is a static site generator written in [Odin](https://odin-lang.org), replac
## Architecture
```
thor.json ← site config (title, base_url, params, modules)
thor.json ← site config (title, base_url, params, modules, og)
content/ ← markdown and HTML content files
layouts/ ← Mustache templates + partials (user overrides)
assets/ ← CSS (Tufte-based), JS, fonts, images
@@ -19,7 +19,7 @@ public/ ← build output (generated)
thor/
├── treesitter/ # FFI types + grammar management (standalone package)
├── markdown/ # Content transformation pipeline (imports ../treesitter)
├── mustache/ # Template engine with lambdas + pipe filters
├── mustache/ # Template engine with lambdas + pipe filters + diagnostics
├── content.odin # Page struct, scan_content, load_page
├── render.odin # Template rendering, data structs, RSS, sitemap
├── site.odin # Config (Flags, Config_File, Site), init_site
@@ -27,10 +27,12 @@ thor/
├── feed.odin # RSS + sitemap generation
├── vfs.odin # Union file system (defaults → modules → site)
├── assets.odin # VFS-based asset copying
├── opengraph.odin # Open_Graph struct + og_init/og_for_page
├── frontmatter.odin # JSON frontmatter parser
├── html.odin # HTML helpers: strip_html_tags, unescape_html, generate_summary
├── opengraph.odin # Open_Graph struct + og_for_site/og_for_page
├── frontmatter.odin # JSON frontmatter parser (supports nested og + lastmod)
├── defaults.odin # DEFAULTS_PATH constant (#directory)
├── main.odin # Entry point
├── bench/ # Template rendering benchmark
└── defaults/layouts/ # Bundled default templates
```
@@ -39,15 +41,16 @@ thor/
| File | Responsibility |
|---|---|
| `main.odin` | Entry point. Sets `context.logger`, calls `init_site`, `build_vfs`, `site_load_content`, `render_site`. Optional Spall profiling via `SPALL` config flag. |
| `site.odin` | `Flags` (CLI), `Config_File` (thor.json), `Site` (runtime state + arena + VFS + pages + modules). `Feature` enum. 5-step `init_site`. Imports `md "markdown"` for `Extension` enum. |
| `content.odin` | `Page` struct, `scan_content` (section-aware walk that handles leaf bundles), `load_page`, `infer_layout`. Calls `md.process()` for the markdown pipeline. |
| `site.odin` | `Flags` (CLI), `Config_File` (thor.json, includes `og: Open_Graph`), `Site` (runtime state + arena + VFS + pages + modules + `og`). `Feature` enum. 5-step `init_site`. Imports `md "markdown"` for `Extension` enum. |
| `content.odin` | `Page` struct (includes `lastmod`, `og`), `scan_content` (section-aware walk that handles leaf bundles), `load_page`, `infer_layout`. Calls `md.process()` for the markdown pipeline. |
| `render.odin` | Template rendering: `render_site`, `render_page_html`, `render_home_html`, `render_section`. Data structs (`Base_Data`, `Page_Data`, `Home_Data`, `Section_Data`). VFS-based template loading with fallback chain (`get_template`). |
| `minify.odin` | HTML/CSS minification via tree-sitter. Imports `ts "treesitter"`. |
| `feed.odin` | RSS feed + sitemap XML. Uses `page.url` for canonical URLs. |
| `vfs.odin` | Union file system: `VFS`, `build_vfs`, `mount_dir`, `mount_subdir`, `mount_recursive`, `vfs_get`. Layers defaults → modules → site. |
| `vfs.odin` | Union file system: `VFS`, `build_vfs`, `mount_dir`, `mount_subdir`, `mount_recursive`, `vfs_get`, `vfs_get_entry`, `vfs_entry_data`. Layers defaults → modules → site. |
| `assets.odin` | `copy_assets_dir` — iterates VFS entries with `assets/` prefix, minifies CSS, copies verbatim or via `os.copy_file`. |
| `opengraph.odin` | `Open_Graph` struct (fields ordered per OGP spec). `og_init(site)` for site defaults, `og_for_page(site, page, base)` for page-specific OG data. |
| `frontmatter.odin` | JSON frontmatter parser (`{ }` delimited). Supports `layout` field for template override. |
| `html.odin` | `strip_html_tags` (moved from render.odin), `unescape_html`, `generate_summary` (Hugo-style body summary for OG descriptions). |
| `opengraph.odin` | `Open_Graph` struct (fields ordered per OGP spec, `is_article: Maybe(bool)`). `og_for_site(site)` for site defaults (from config + derived), `og_for_page(site_og, page)` for page-specific (overlay page.og + derive from page data). |
| `frontmatter.odin` | JSON frontmatter parser (`{ }` delimited). Supports `layout`, `lastmod`, and nested `og` object (via `json_get_open_graph`). |
| `defaults.odin` | `DEFAULTS_PATH` constant, resolved at compile time via `#directory` so bundled templates ship in the binary. |
### Subpackages
@@ -62,6 +65,7 @@ thor/
| | `sectionate.odin` | `wrap_sections` — splits HTML at `<h2>` into `<section>` wrappers |
| | `highlight.odin` | Syntax highlighting via tree-sitter. Imports `../treesitter`. |
| `mustache/` | See [Mustache engine](#mustache-engine) below | Template engine |
| `bench/` | `bench.odin` + `templates/` | Standalone template rendering benchmark. Generates 500 posts + 100 comments, renders with indented partials + inheritance + pipes. `--dump <path>` for output validation, positional arg for iteration count (default 250). |
Icon SVGs live as HTML partials in `layouts/partials/icons/` (home, github, rss, chevron_up, star).
@@ -90,10 +94,12 @@ Page :: struct {
title: string,
description: string,
date: string,
lastmod: string,
menu: string,
body_html: string,
draft: bool,
is_starred: bool,
og: Open_Graph, // per-page OG overrides from frontmatter
_is_index: bool `private`,
}
```
@@ -112,8 +118,8 @@ No `Page_Type` enum — page type is inferred from section + `_is_index`. Layout
Config is split into three structs with a clear 5-step initialization flow:
- **`Flags`** — CLI args only. Parsed by `core:flags`. Includes path overrides (`--content`, `--assets`, `--output`, `--layouts`), build-mode toggles (`-drafts`, `-watch`, `-minify`), and `-ext`/`-no-ext` for markdown extension overrides.
- **`Config_File`** — parsed from `thor.json` via `json.unmarshal_string`. Holds title, paths, `markdown_extensions` (JSON), `params` (JSON), `modules` (JSON array of relative paths).
- **`Site`** — runtime state: arena, pages, modules, VFS, `features: bit_set[Feature]`, `markdown_extensions: bit_set[md.Extension]`.
- **`Config_File`** — parsed from `thor.json` via `json.unmarshal_string`. Holds title, paths, `markdown_extensions` (JSON), `params` (JSON), `modules` (JSON array of relative paths), `og` (`Open_Graph` struct for site-level OG defaults).
- **`Site`** — runtime state: arena, pages, modules, VFS, `features: bit_set[Feature]`, `markdown_extensions: bit_set[md.Extension]`, `og: Open_Graph` (resolved site-level OG).
**`Feature` enum** — `Drafts`, `Minify`, `Watch`. Checked with `.Minify in site.features`.
@@ -130,15 +136,11 @@ Config precedence: `CLI flags > thor.json values > hardcoded defaults`.
"title": "...",
"base_url": "...",
"modules": ["../path/to/module"],
"markdown_extensions": {
"emoji": true,
"sidenotes": true,
"alerts": true,
"highlight": true,
"sections": true
"og": {
"image": "https://example.com/og.png"
},
"markdown_extensions": { "emoji": true, "highlight": false },
"params": {
"author": "...",
"social": [
{ "name": "github", "url": "...", "icon": "icons/github" }
]
@@ -155,13 +157,33 @@ VFS :: struct { files: map[string]VFS_Entry }
VFS_Entry :: struct { fs_path: string, data: []byte }
```
`build_vfs` mounts in reverse precedence (defaults first, site last overwrites). `DEFAULTS_PATH` resolved at compile time via `#directory`, so bundled templates ship inside the binary. Modules configured via `"modules": ["../path"]` in `thor.json` — each module contributes `layouts/` and `assets/` subdirectories. `vfs_get` lazily reads file contents on first access.
`build_vfs` mounts in reverse precedence (defaults first, site last overwrites). `DEFAULTS_PATH` resolved at compile time via `#directory`, so bundled templates ship inside the binary. Modules configured via `"modules": ["../path"]` in `thor.json` — each module contributes `layouts/` and `assets/` subdirectories.
Three access patterns:
- `vfs_get(vfs, path) -> ([]byte, bool)` — data only (lazy-loaded from disk)
- `vfs_get_entry(vfs, path) -> (VFS_Entry, []byte, bool)` — entry + data (for callers that need `fs_path` for diagnostics)
- `vfs_entry_data(entry) -> ([]byte, bool)` — data from an entry already in hand (avoids redundant map lookup when iterating `vfs.files`)
Content is **not yet in the VFS**`scan_content` still uses direct filesystem reads. (See `TODOS.md`.)
## Open Graph
`Open_Graph` struct in `opengraph.odin` with fields ordered per [ogp.me](https://ogp.me/) spec. Site defaults set via `og_init(site)` (site_name, description, default image, locale). Page-specific fields via `og_for_page(site, page, base)` (copies base, overrides url/title/type/is_article/section/published_time). Templates access via `{{og.url}}`, `{{og.title}}`, `{{#og.is_article}}`, etc.
`Open_Graph` struct in `opengraph.odin` with fields ordered per [ogp.me](https://ogp.me/) spec. `is_article` is `Maybe(bool)` — nil means "unset" (distinguished from explicitly `false`).
**Site-level** (`og_for_site`): starts from `Config_File.og` (user-supplied defaults from `thor.json`), then fills empty fields derivable from `Site`:
- `site_name ← site.title`
- `locale ← "en_US"` (default if unset)
**Page-level** (`og_for_page`): copies site OG, derives page-specific fields, then overlays `Page.og` (from frontmatter):
- `url ← page.url`
- `title ← page.title` (falls back to `site_name` if empty)
- `type ← "article" if !page._is_index else "website"`
- `is_article ← !page._is_index`
- `section ← page.section`
- `published_time / modified_time ← page.date / page.lastmod`
- `description ← page.description`, else body summary (via `generate_summary`)
Paths through maps (e.g. `params.*`) are silently allowed — not validated. Templates access via `{{og.url}}`, `{{og.title}}`, `{{#og.is_article}}`, etc.
## Markdown pipeline
@@ -237,7 +259,7 @@ Section tags and interpolation tags may transform the resolved value before rend
<time datetime="{{date}}">{{date | format}}</time>
```
Currently implemented: `group_by <field>` (list → list-of-groups) and `format` (ISO date string → display string). Filter results live in `context.temp_allocator` (render-scoped). See `mustache/EXTENSIONS.md` for syntax details, caps (`MAX_PIPES`, `MAX_PIPE_ARGS`), and the `Group` struct shape.
Currently implemented: `group_by <field>` (list → list-of-groups) and `format` (ISO date string → display string like "15 Mar 2026"). Filter results live in `context.temp_allocator` (render-scoped). See `mustache/EXTENSIONS.md` for syntax details, caps (`MAX_PIPES`, `MAX_PIPE_ARGS`), and the `Group` struct shape.
### Comments
@@ -310,39 +332,76 @@ nix build # runs thor, outputs to ./result/
```bash
cd thor
odin test . # main package tests (site, frontmatter)
odin test . -all-packages # includes mustache specs, lambdas, pipes, markdown tests
odin test . -all-packages # includes mustache specs, lambdas, pipes, diagnostics, markdown tests
```
### Benchmark
```bash
cd thor
odin build bench -o:speed
./bench.bin # 250 iterations, prints timing
./bench.bin --dump output.html # render once, write to file for diff validation
./bench.bin 1000 # custom iteration count
```
## Mustache engine
Spec-compliant implementation at `mustache/`. See `mustache/SPEC.md` for the implementation specification and `mustache/EXTENSIONS.md` for non-standard extensions (pipes).
Spec-compliant implementation at `mustache/`. See `mustache/SPEC.md` for the implementation specification, `mustache/EXTENSIONS.md` for non-standard extensions (pipes), and `mustache/diagnostic.odin` for the rust-style error formatter.
### Files
| File | Responsibility |
|---|---|
| `mustache.odin` | Public API (`parse`, `render`, `Template`), parser (`parse_section` with allocator threading), renderer (`render_nodes`), template inheritance (`merge_block_overrides`), `delete_template`/`delete_partials` |
| `mustache.odin` | Public API (`parse`, `render`, `Template`), parser (`parse_section`), renderer (`render_nodes` with `Indent_State` for partial indentation), template inheritance (`merge_block_overrides`), `delete_template`/`delete_partials`. Pipe support in Variable/Unescaped/Section/Inverted tags. |
| `tokenizer.odin` | Tokenizer (template string → `[]Token`), standalone whitespace detection |
| `data.odin` | Reflection-based data model: `base_value` (peels union/any/nested-any layers), `lookup_in` (structs + maps, handles `Type_Info_Any` value kind in maps), `resolve_name`, `is_truthy`, `any_to_string`, `list_info`, `extract_list_element` (unwraps `[dynamic]any` element types so downstream lookups see the real value), `call_interp_lambda`/`call_section_lambda` |
| `pipes.odin` | Pipes extension: `Pipe_Filter` AST, `parse_pipeline`, `apply_pipeline`, `apply_filter` (switch dispatch), `apply_group_by`. Stored on `Node.filters`; render-scoped results in temp allocator. |
| `spec_test.odin` | JSON spec test runner — loads `spec/specs/*.json`, runs each test case |
| `data.odin` | Reflection-based data model: `base_value` (peels union/any/nested-any layers), `lookup_in` (structs + maps, handles `Type_Info_Any` value kind in maps), `resolve_name`, `is_truthy`, `any_to_string`, `list_info`, `extract_list_element`, `call_interp_lambda`/`call_section_lambda` |
| `pipes.odin` | Pipes extension: `Pipe_Filter` AST, `parse_pipeline` (takes `pos`), `apply_pipeline`, `apply_filter` (switch dispatch: `group_by` + `format`), `apply_group_by`, `apply_format`. Stored on `Node.filters`; render-scoped results in temp allocator. |
| `diagnostic.odin` | Rust-style error formatter: `format_error` (multi-line context, ANSI colors via `core:terminal/ansi`, `colorize` param), `format_render_error` (formats `Error`), `line_col`, `line_text`, `context_extent`, `count_lines`, `digit_count`, `should_colorize`. |
| `suggest.odin` | Strict-warning helpers: `validate_key_path` (walks dotted path, crosses maps silently), `suggest_correction` (Levenshtein via `core:strings/levenshtein_distance`), `collect_struct_keys` (via reflection, recurses into `using`), `struct_has_field` (distinguishes missing field from nil value — needed for `Maybe(bool)`), `collect_partial_names`, `collect_block_names`. |
| `spec_test.odin` | JSON spec test runner — loads `spec/specs/*.json`, runs each test case. Uses `log.nil_logger()` to suppress expected warnings. |
| `lambda_test.odin` | Spec lambda tests |
| `pipes_test.odin` | Pipe filter tests |
| `pipes_test.odin` | Pipe filter tests (`group_by` + `format`) |
| `diagnostic_test.odin` | Golden-output tests for `format_error` (multi-line context, edge cases, alignment, caret position, hint) + parser error message brace-escaping |
| `suggest_test.odin` | Tests for `validate_key_path`, `suggest_correction`, `struct_has_field` with `Maybe(bool)` and `using`-promoted fields |
### Architecture
```
parse(source) → tokenize → trim_standalone_whitespace → parse_section → Template
parse(source, path) → tokenize → trim_standalone_whitespace → parse_section → Template
render(tmpl, data, partials) → render_nodes (walks flat node array against context stack) → string
```
- **Two-phase API**: `parse()` produces a reusable `Template`, `render()` walks it against data. Templates parsed once, rendered many times.
- **Flat `[dynamic]Node` array** with `first_child`/`child_count` indices — pre-order layout.
- **Flat `[dynamic]Node` array** with `children: []Node` slices (pre-order layout; slices point into the backing array). Each `Node` carries `pos: int` (byte offset into source) for diagnostics.
- **`Template`** carries `source` and `path` — used by diagnostics to show file location and source context.
- **Context stack**: `^[dynamic]any` with `append`/`pop` for section push/pop.
- **`render_nodes` takes `Template` by value** (not `^Template`) — Odin's calling convention promotes to pointer when efficient. Eliminates "local copy" patterns at call sites.
- **`Block_Override.source: Template`** — carries the template that defined the override, so warnings inside block overrides point at the correct file.
- **`base_value`** peels Named/Distinct/Union layers (including `json.Value`). Also unwraps nested `any`-of-`any` (which occurs when `map[string]any` values are read via runtime map internals).
- **`lookup_in`** resolves keys on structs (via `reflect.struct_field_value_by_name` with `allow_using = true`) and maps. Detects `Type_Info_Any` value kind in maps and reads the inner any directly to avoid double-wrap.
- **Template inheritance**: `{{<parent}}` loads parent from partials, `{{$block}}` defines overridable sections. `merge_block_overrides` propagates overrides through multi-level chains.
- **Dynamic partial names**: `{{>*key}}` resolves partial name from data context at render time.
- **Render-time partial indentation**: `Indent_State` threads `at_line_start` through `render_nodes` so partial indent is applied at render time (via `write_indented` on Text nodes) instead of reparsing the partial's source. `render_template` writes initial indent, creates state, calls `render_nodes`. Data-injected newlines don't pick up indent (Variables don't update `at_line_start`).
### Diagnostics
Rust-style error messages with multi-line source context, caret underlines, and Levenshtein suggestions. ANSI colors via `core:terminal/ansi`, gated on `should_colorize()` (TTY detection on stderr).
**Error types**: `Error_Body{msg, pos, kind}` where `kind` is `Error_Kind.Syntax` (parse-time) or `Error_Kind.Data` (render-time). `Error` is a single-variant union wrapping `Error_Body` (nilable for `!= nil` / `or_return`).
**Strict-by-default warnings**`render_nodes` emits `log.warnf` diagnostics for:
- Unknown keys in `{{k}}`, `{{{k}}}`, `{{#k}}`, `{{^k}}` (via `validate_key_path` + `suggest_correction`)
- Missing partials (`{{> name}}` not in partials map)
- Missing parent templates (`{{<name}}` not in partials map)
- Unmatched block overrides (`{{$name}}` doesn't match any block in parent template)
**Exceptions** (no warning):
- `{{.}}` and dot-prefixed names (current context)
- Paths that cross a map (e.g., `params.*` — user-defined namespace)
- `Maybe(bool)` fields with nil value (field exists, value is nil — distinguished via `struct_has_field`)
**Block override source tracking**: `Block_Override.source: Template` ensures warnings inside block overrides point at the override's source file (e.g., `page.html`), not the parent template (`base.html`).
### Lambdas
@@ -353,11 +412,17 @@ Spec-compliant. Stored as `any` values in the data context.
### Pipes
`{{#key | op args…}}…{{/key}}`. Stored as `[dynamic; MAX_PIPES]Pipe_Filter` on each `Node` (fixed-cap inline storage, no per-tag heap allocation at parse time). Applied in the renderer via `apply_pipeline` before truthiness check. Currently only `group_by <field>` is implemented (returns `[dynamic]Group` where `Group{key, items}`). See `mustache/EXTENSIONS.md`.
`{{key | op args…}}` for interpolation, `{{#key | op args…}}…{{/key}}` for sections. Stored as `[dynamic; MAX_PIPES]Pipe_Filter` on each `Node`. Applied in the renderer via `apply_pipeline` before truthiness/interpolation. Implemented filters:
- `group_by <field>` — list → `[dynamic]Group` where `Group{key, items}`
- `format` — ISO 8601 date string → display string (e.g., "15 Mar 2026")
See `mustache/EXTENSIONS.md`.
### Not implemented
- Set delimiters (`{{= =}}`, `delimiters.json`)
- Partial invocation stack in diagnostics (warnings inside partials point at the partial file but don't show the `{{> name}}` invocation site — see TODOS.md)
## Known limitations
@@ -372,7 +437,6 @@ Spec-compliant. Stored as `any` values in the data context.
You may never, *ever* remove `TODO:` or `FIXME:` comments. Those are for humans, not machines.
See `HUGO.md` for analysis of why thor doesn't need Hugo's shortcode context isolation.
See `mustache/PARTIAL_INDENT.md` for whitespace handling analysis.
See `mustache/SPEC.md` for the original implementation specification.
See `mustache/EXTENSIONS.md` for non-standard extensions (pipes).
+36 -1
View File
@@ -13,6 +13,14 @@
- [ ] Not sure whether to use temp allocator or site_allocator in opengraph.odin.
- [ ] Not sure whether to use temp allocator or site_allocator in `site_load_content`.
- [ ] Might not need to allocate in `strip_html_tags`
- [ ] Fix `apply_filter`'s `format` case (`mustache/pipes.odin`) boxing `apply_format`'s
`string` result into `any` via bare `return`, which materializes a hidden
header temp in `apply_filter`'s own stack frame. Dangling once the frame
returns; caused the `-o:speed` segfault in `write_value`. Fix: box explicitly
with `any{new_clone(formatted, context.temp_allocator), typeid_of(string)}`.
- [ ] Same pattern in `apply_group_by` (`mustache/pipes.odin`): `return groups, nil`
boxes a freshly-built `[dynamic]Group` as bare `any` — same latent
stack-temp UB, hasn't crashed yet but should get the same treatment.
## Markdown
- [ ] Add overloads for every extension - accept ^strings.Builder.
@@ -20,13 +28,22 @@
- [ ] Add heading ids as a default on extension.
- [ ] Add opt-in deflist support.
- [ ] Decide if lambdas actually provide any value.
- [ ] configure date format as a partial
## Dates
- [x] Accept "strings"
- [x] Accept keys
- [ ] handle timezones
- [ ] display an error when no part of the date appears in the output.
- [x] use `date.format` as the default format.
- [ ] Handle 0 and whitespace padding i.e. "_2" -> " 2"
## General
- [ ] Integrity hash
- Allows users to verify their output didn't change after upgrading to a new version
- [ ] Content-hash fingerprinting for CSS and JS cache busting
- [ ] Avoid `json.Value` / `json.Object` where possible.
- [ ] Create a json schema file for `thor.json`.
- [ ] make `parse` an overload of `parse_text/parse_inline` and `parse_file`, or something.
- [ ] Add page params
- [ ] We must remove all mention of `posts` from the odin code.
At present, "posts" are a user-level construct defined as pages in a
@@ -45,6 +62,22 @@
- [x] Block-override source-template tracking: warnings inside overrides point at the override's source file, not the parent template
- [ ] Partial invocation stack in diagnostics: when an error fires inside a partial, show "invoked from" chain through `{{> name}}` calls. Currently warnings inside partials point at the partial (correct file) but don't show the invocation site.
- [ ] Could be better error message when missing a closing (or opening) brace
- [ ] Error message doesn't show position of faulty pipe name correctly.
- [ ] `render_template` (`render.odin`) blanks the *entire page* to `""` on any
mustache render error and only `log.errorf`s it — a single bad tag/pipe
anywhere on the page silently kills the whole output with no visible
signal outside the terminal log. Should at least be scoped to the
failing tag/section, or surfaced somewhere the person building the
site will actually see it.
```bash
[ERROR] --- [138:render_template()] unknown pipe op 'formats'
--> /home/spencer/github.com/sbrow.github.io/layouts/home.html:1:1
|
1 | {{<base}}
| ^^^^^^^^^
2 | {{$content}}
3 | <main>
```
- [ ] Block attributes on code fences (`{ #ex-1 }`) — hello-world.md
- [ ] include-code shortcode (`{{< include-code ... >}}`) — i-ported-fd-to-odin
- [ ] follow symlinks in `scan_content`?
@@ -111,6 +144,8 @@ these tasks.
- [ ] Review markdown.odin
- [x] Review sectionate.odin
- [x] Review sectionate_test.odin
- [ ] Review suggest.odin
- [ ] Review suggest_test.odin
- [x] Review opengraph.odin
- [ ] Review render.odin
- [x] Review site.odin
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+203
View File
@@ -0,0 +1,203 @@
package bench
import "core:fmt"
import "core:mem"
import "core:os"
import "core:strconv"
import "core:time"
import "../mustache"
Tag :: struct {
name: string,
slug: string,
}
Nav_Item :: struct {
url: string,
label: string,
}
Post :: struct {
title: string,
url: string,
date: string,
year: string,
excerpt: string,
author: string,
tags: [dynamic]Tag,
}
Comment :: struct {
author: string,
date: string,
body: string,
}
Page_Data :: struct {
title: string,
now: string,
posts: [dynamic]Post,
comments: [dynamic]Comment,
nav_items: [dynamic]Nav_Item,
}
TEMPLATE_DIR :: #directory
main :: proc() {
iterations := 250
dump_path := ""
i := 1
for i < len(os.args) {
if os.args[i] == "--dump" && i + 1 < len(os.args) {
dump_path = os.args[i + 1]
i += 2
} else {
n, ok := strconv.parse_int(os.args[i])
if ok && n > 0 {
iterations = n
}
i += 1
}
}
data_arena: mem.Dynamic_Arena
mem.dynamic_arena_init(&data_arena)
defer mem.dynamic_arena_destroy(&data_arena)
temp_arena: mem.Dynamic_Arena
mem.dynamic_arena_init(&temp_arena)
defer mem.dynamic_arena_destroy(&temp_arena)
context.allocator = mem.dynamic_arena_allocator(&data_arena)
context.temp_allocator = mem.dynamic_arena_allocator(&temp_arena)
base := parse_file("base.html")
page := parse_file("page.html")
defer mustache.delete_template(&base)
defer mustache.delete_template(&page)
partials := make(map[string]mustache.Template)
partials["base"] = base
partials["post"] = parse_file("partials/post.html")
partials["comment"] = parse_file("partials/comment.html")
defer mustache.delete_partials(partials)
data := generate_data()
if dump_path != "" {
result, err := mustache.render(page, data, partials, allocator = context.temp_allocator)
if err != nil {
b := mustache.body(err)
fmt.eprintln("render error:", b.msg)
os.exit(1)
}
werr := os.write_entire_file_from_string(dump_path, result)
if werr != nil {
fmt.eprintln("failed to write", dump_path, ":", werr)
os.exit(1)
}
fmt.println("wrote", len(result), "bytes to", dump_path)
return
}
for _ in 0..<3 {
_, _ = mustache.render(page, data, partials, allocator = context.temp_allocator)
mem.dynamic_arena_free_all(&temp_arena)
}
start := time.now()
for _ in 0..<iterations {
_, _ = mustache.render(page, data, partials, allocator = context.temp_allocator)
mem.dynamic_arena_free_all(&temp_arena)
}
elapsed := time.since(start)
seconds := time.duration_seconds(elapsed)
per_render_ms := seconds * 1000 / f64(iterations)
fmt.printfln("iterations=%d total=%.3fs per_render=%.3fms",
iterations, seconds, per_render_ms)
}
parse_file :: proc(name: string) -> mustache.Template {
path := fmt.aprintf("%s/templates/%s", TEMPLATE_DIR, name)
data, err := os.read_entire_file_from_path(path, context.allocator)
if err != nil {
fmt.eprintln("failed to read", path, ":", err)
os.exit(1)
}
source := string(data)
tmpl, perr := mustache.parse(source, path)
if perr != nil {
b := mustache.body(perr)
fmt.eprintln("parse error in", path, ":", b.msg)
os.exit(1)
}
return tmpl
}
generate_data :: proc() -> Page_Data {
years := []string{
"2025", "2024", "2023", "2022", "2021",
"2020", "2019", "2018", "2017", "2016",
}
posts := make([dynamic]Post, 0, 500)
for year in years {
for i in 0..<50 {
tags := make([dynamic]Tag, 0, 3)
append(&tags, Tag{name = fmt.aprintf("%s-notes", year), slug = fmt.aprintf("%s-notes", year)})
append(&tags, Tag{name = "writing", slug = "writing"})
append(&tags, Tag{name = "archive", slug = "archive"})
month := (i % 12) + 1
day := (i % 28) + 1
author := ""
if i % 3 != 0 {
author = fmt.aprintf("Author %d", i % 5)
}
append(&posts, Post{
title = fmt.aprintf("Post %d from %s", i, year),
url = fmt.aprintf("/%s/post-%d", year, i),
date = fmt.aprintf("%s-%02d-%02dT10:00:00Z", year, month, day),
year = year,
excerpt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
author = author,
tags = tags,
})
}
}
comments := make([dynamic]Comment, 0, 100)
for i in 0..<100 {
year := years[i % len(years)]
month := (i % 12) + 1
day := (i % 28) + 1
append(&comments, Comment{
author = fmt.aprintf("Commenter %d", i),
date = fmt.aprintf("%s-%02d-%02dT12:00:00Z", year, month, day),
body = fmt.aprintf("Great post! This is comment number %d.", i),
})
}
nav_items := make([dynamic]Nav_Item, 0, 8)
append(&nav_items, Nav_Item{url = "/", label = "Home"})
append(&nav_items, Nav_Item{url = "/archive", label = "Archive"})
append(&nav_items, Nav_Item{url = "/about", label = "About"})
append(&nav_items, Nav_Item{url = "/tags", label = "Tags"})
append(&nav_items, Nav_Item{url = "/feed.xml", label = "RSS"})
append(&nav_items, Nav_Item{url = "https://github.com/example", label = "GitHub"})
append(&nav_items, Nav_Item{url = "https://twitter.com/example", label = "Twitter"})
append(&nav_items, Nav_Item{url = "mailto:nobody@example.com", label = "Email"})
return Page_Data{
title = "Post Archive",
now = "2025-07-21T12:00:00Z",
posts = posts,
comments = comments,
nav_items = nav_items,
}
}
+130
View File
@@ -0,0 +1,130 @@
package main
import "base:runtime"
import "common"
import "core:fmt"
import "core:log"
import "core:os"
import "core:strings"
import "core:time"
import "inlined"
import "original"
DATES :: #load(#directory + os.Path_Separator_String + "dates.txt")
FORMATS :: #load(#directory + os.Path_Separator_String + "formats.txt")
ITERATIONS :: 1_000
dates: []common.Date_Components
formats: []string
formatter :: #type proc(
date: common.Date_Components,
format: string,
allocator: runtime.Allocator,
) -> string
benchmark :: #type proc(
options: ^time.Benchmark_Options,
allocator: runtime.Allocator,
) -> (
err: time.Benchmark_Error,
)
Version :: struct {
name: string,
bench: benchmark,
}
init :: proc() {
raw_dates := strings.split_lines(string(DATES))
raw_dates = raw_dates[:len(raw_dates) - 1]
formats = strings.split_lines(string(FORMATS))
dates = make([]common.Date_Components, len(raw_dates))
assert(to_parsed(raw_dates, &dates))
}
to_parsed :: proc(raw_dates: []string, dates: ^[]common.Date_Components) -> bool {
for date, i in raw_dates {
// log.debugf("parsing '%s'", date)
dates[i] = common.parse_iso_date(date) or_return
}
return true
}
main :: proc() {
logger_opts: log.Options =
(log.Default_Console_Logger_Opts - log.Full_Timestamp_Opts - {.Short_File_Path})
console_logger := log.create_console_logger(.Info, logger_opts)
context.logger = console_logger
defer log.destroy_console_logger(console_logger)
init()
versions := [?]Version {
{"original", to_benchmark(original.format_date)},
{"inlined", to_benchmark(inlined.format_date)},
}
fmt.printfln(
"%-10s %14s %10s %14s %12s %8s",
"version",
"total",
"calls",
"calls/s",
"time/call",
"MB/s",
)
for version in versions {
defer free_all(context.temp_allocator)
b: time.Benchmark_Options
b.bench = version.bench
if err := time.benchmark(&b, context.temp_allocator); err != nil {
fmt.panicf("%v", err)
}
// fmt.printfln("%v", b)
per_call := time.Duration(i64(b.duration) / i64(b.count))
fmt.printfln(
"%-10s %14v % 10d % 14.0f %12v % 8.2f",
version.name,
b.duration,
b.count,
b.rounds_per_second,
per_call,
b.megabytes_per_second,
)
}
}
to_benchmark :: proc($f: formatter) -> benchmark {
return(
proc(
opts: ^time.Benchmark_Options,
allocator: runtime.Allocator,
) -> (
err: time.Benchmark_Error,
) {
for _ in 0 ..< ITERATIONS {
for date in dates {
for format in formats {
f(date, format, allocator)
opts.count += 1
opts.processed += size_of(date) + size_of(format)
}
}
opts.rounds += 1
}
return err
} \
)
}
+44
View File
@@ -0,0 +1,44 @@
package common
Date_Components :: struct {
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int,
}
// TODO: Use some kind of scanner interface
parse_iso_date :: proc(iso: string) -> (c: Date_Components, ok: bool) {
if len(iso) < 10 {
return {}, false
}
c.year = parse_2_digits(iso, 0) * 100 + parse_2_digits(iso, 2)
c.month = parse_2_digits(iso, 5)
c.day = parse_2_digits(iso, 8)
if c.month < 1 || c.month > 12 {
return {}, false
}
if c.day < 1 || c.day > 31 {
return {}, false
}
if len(iso) >= 19 && (iso[10] == 'T' || iso[10] == 't') {
c.hour = parse_2_digits(iso, 11)
c.minute = parse_2_digits(iso, 14)
c.second = parse_2_digits(iso, 17)
}
return c, true
}
parse_2_digits :: proc(s: string, offset: int) -> int {
if offset + 1 >= len(s) {
return 0
}
return (int(s[offset]) - 0x30) * 10 + (int(s[offset + 1]) - 0x30)
}
+59
View File
@@ -0,0 +1,59 @@
2024-01-05
2024-02-14
2024-03-08
2024-04-22
2024-05-01
2024-06-19
2024-07-04
2024-08-30
2024-09-11
2024-10-31
2024-11-27
2024-12-25
2023-01-15T00:00:00-05:00
2023-02-14T09:30:15+01:00
2023-03-08T14:45:22-08:00
2023-04-22T23:59:59+05:30
2023-05-01T06:05:09-04:00
2023-06-19T18:20:33+09:00
2023-07-04T03:04:05-07:00
2023-08-30T11:11:11+00:00
2023-09-11T15:04:05-04:00
2023-10-31T20:15:30+02:00
2023-11-27T07:07:07-06:00
2023-12-25T12:30:45+03:00
2025-01-15T00:15:00-0500
2025-02-14T09:30:15+0100
2025-03-08T14:45:22-0800
2025-04-22T23:59:59+0530
2025-05-01T06:05:09-0400
2025-06-19T18:20:33+0900
2025-07-04T03:04:05-0700
2025-08-30T11:11:11+0000
2025-09-11T15:04:05-0400
2025-10-31T20:15:30+0200
2025-11-27T07:07:07-0600
2025-12-25T12:30:45+0300
2022-01-01T00:00:00Z
2022-02-14T01:30:00Z
2022-03-08T11:59:59Z
2022-04-22T12:00:00Z
2022-05-01T12:00:01Z
2022-06-19T13:15:00Z
2022-07-04T15:04:05Z
2022-08-30T18:45:30Z
2022-09-11T20:20:20Z
2022-10-31T22:10:10Z
2022-11-27T23:59:59Z
2022-12-25T09:09:09Z
2021-03-14t09:26:53
2021-07-20t23:00:00
2021-11-05t00:00:00
2020-06-15T15:04:05
2020-12-31T23:59:59
2020-01-01T00:00:00
2024-02-29T12:00:00Z
2000-02-29T00:00:00Z
1999-12-31T23:59:59Z
2026-01-01T00:00:00Z
2026-07-23T14:56:07-04:00
+46
View File
@@ -0,0 +1,46 @@
2006
06
January
Jan
Monday
Mon
01
02
03
04
05
15
1
2
3
4
5
PM
pm
MST
2006-01-02
2006-01-02 15:04:05
2 Jan 2006
Jan 2, 2006
January 2, 2006
Monday, January 2, 2006
Mon Jan 2 2006
Mon Jan 02 2006
Mon, 02 Jan 2006 15:04:05 MST
01/02/2006
02/01/2006
2006/01/02
1/2/06
1/2/06 3:04PM
1/2/2006
3:04:05 PM
3:04 pm
15:04:05
15:04
15:04:05 MST
January 2006
Jan 06
2 January 2006
Monday 2 Jan 2006 at 15:04
06-01-02
3:4:5
+126
View File
@@ -0,0 +1,126 @@
package inlined
import "../common"
import "core:fmt"
import "core:log"
import "core:strings"
import "core:time"
import "core:time/datetime"
format_date :: proc(
dt: common.Date_Components,
fmt: string,
allocator := context.temp_allocator,
) -> string {
b: strings.Builder
strings.builder_init_len(&b, len(fmt), allocator)
for i := 0; i < len(fmt); {
matched := match_token(&b, dt, fmt[i:])
if matched > 0 {
i += matched
} else {
strings.write_byte(&b, fmt[i])
i += 1
}
}
log.debugf("formatted date: '%s'", b.buf)
return strings.to_string(b)
}
match_token :: proc(b: ^strings.Builder, dt: common.Date_Components, s: string) -> int {
if strings.has_prefix(
s,
"January",
) {strings.write_string(b, fmt.tprintf("%s", time.Month(dt.month))); return 7}
if strings.has_prefix(s, "Monday") {emit_weekday(b, dt, full = true); return 6}
if strings.has_prefix(
s,
"2006",
) {strings.write_string(b, fmt.tprintf("%04d", dt.year)); return 4}
if strings.has_prefix(s, "MST") {strings.write_string(b, "UTC"); return 3}
if strings.has_prefix(s, "Jan") {emit_month_abbr(b, dt); return 3}
if strings.has_prefix(s, "Mon") {emit_weekday(b, dt, full = false); return 3}
if strings.has_prefix(
s,
"06",
) {strings.write_string(b, fmt.tprintf("%02d", dt.year % 100)); return 2}
if strings.has_prefix(s, "02") {strings.write_string(b, fmt.tprintf("%02d", dt.day)); return 2}
if strings.has_prefix(
s,
"15",
) {strings.write_string(b, fmt.tprintf("%02d", dt.hour)); return 2}
if strings.has_prefix(
s,
"04",
) {strings.write_string(b, fmt.tprintf("%02d", dt.minute)); return 2}
if strings.has_prefix(
s,
"05",
) {strings.write_string(b, fmt.tprintf("%02d", dt.second)); return 2}
if strings.has_prefix(
s,
"01",
) {strings.write_string(b, fmt.tprintf("%02d", dt.month)); return 2}
if strings.has_prefix(s, "03") {emit_hour_12(b, dt, pad = true); return 2}
if strings.has_prefix(s, "PM") {
strings.write_string(b, "PM" if dt.hour >= 12 else "AM")
return 2
}
if strings.has_prefix(s, "pm") {
strings.write_string(b, "pm" if dt.hour >= 12 else "am")
return 2
}
if len(s) >= 1 {
switch s[0] {
case '2':
strings.write_string(b, fmt.tprintf("%d", dt.day)); return 1
case '1':
strings.write_string(b, fmt.tprintf("%d", dt.month)); return 1
case '4':
strings.write_string(b, fmt.tprintf("%d", dt.minute)); return 1
case '5':
strings.write_string(b, fmt.tprintf("%d", dt.second)); return 1
case '3':
emit_hour_12(b, dt, pad = false); return 1
case:
return 0
}
}
return 0
}
emit_month_abbr :: proc(b: ^strings.Builder, dt: common.Date_Components) {
name := fmt.tprintf("%s", time.Month(dt.month))
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
emit_weekday :: proc(b: ^strings.Builder, dt: common.Date_Components, full: bool) {
date := datetime.Date {
year = i64(dt.year),
month = i8(dt.month),
day = i8(dt.day),
}
ordinal, err := datetime.date_to_ordinal(date)
if err != .None {
strings.write_string(b, "???")
return
}
weekday := datetime.day_of_week(ordinal)
name := fmt.tprintf("%s", weekday)
if full {
strings.write_string(b, name)
} else {
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
}
emit_hour_12 :: proc(b: ^strings.Builder, dt: common.Date_Components, pad: bool) {
h12 := dt.hour % 12
if h12 == 0 {h12 = 12}
format := "%02d" if pad else "%d"
fmt.sbprintf(b, format, h12)
}
+133
View File
@@ -0,0 +1,133 @@
package inplace
import "../common"
import "core:bytes"
import "core:fmt"
import "core:mem"
import "core:strings"
import "core:time"
import "core:time/datetime"
format_date :: proc(
dt: common.Date_Components,
fmt: string,
allocator := context.temp_allocator,
) -> string {
b := make([]byte, len(fmt), context.temp_allocator)
x := transmute([]byte)(fmt)
mem.copy_non_overlapping(&b[0], &x, len(fmt))
return string(b)
// for i := 0; i < len(fmt); {
// matched := match_token(&b, dt, fmt[i:])
// if matched > 0 {
// i += matched
// } else {
// strings.write_byte(&b, fmt[i])
// i += 1
// }
// }
// log.debugf("formatted date: '%s'", b.buf)
// return strings.to_string(b)
}
FULL_MONTH: string : "January"
match_token :: proc(s: []byte, dt: common.Date_Components) {
if bytes.equal(s[:len(FULL_MONTH)], transmute([]u8)FULL_MONTH) {
mo := fmt.tprintf("%s", time.Month(dt.month))
mem.copy_non_overlapping(&s[0], &(transmute([]u8)mo)[0], len(mo))
}
/*
if strings.has_prefix(s, "Monday") {emit_weekday(b, dt, full = true); return 6}
if strings.has_prefix(
s,
"2006",
) {strings.write_string(b, fmt.tprintf("%04d", dt.year)); return 4}
if strings.has_prefix(s, "MST") {strings.write_string(b, "UTC"); return 3}
if strings.has_prefix(s, "Jan") {emit_month_abbr(b, dt); return 3}
if strings.has_prefix(s, "Mon") {emit_weekday(b, dt, full = false); return 3}
if strings.has_prefix(
s,
"06",
) {strings.write_string(b, fmt.tprintf("%02d", dt.year % 100)); return 2}
if strings.has_prefix(s, "02") {strings.write_string(b, fmt.tprintf("%02d", dt.day)); return 2}
if strings.has_prefix(
s,
"15",
) {strings.write_string(b, fmt.tprintf("%02d", dt.hour)); return 2}
if strings.has_prefix(
s,
"04",
) {strings.write_string(b, fmt.tprintf("%02d", dt.minute)); return 2}
if strings.has_prefix(
s,
"05",
) {strings.write_string(b, fmt.tprintf("%02d", dt.second)); return 2}
if strings.has_prefix(
s,
"01",
) {strings.write_string(b, fmt.tprintf("%02d", dt.month)); return 2}
if strings.has_prefix(s, "03") {emit_hour_12(b, dt, pad = true); return 2}
if strings.has_prefix(s, "PM") {
strings.write_string(b, "PM" if dt.hour >= 12 else "AM")
return 2
}
if strings.has_prefix(s, "pm") {
strings.write_string(b, "pm" if dt.hour >= 12 else "am")
return 2
}
if len(s) >= 1 {
switch s[0] {
case '2':
strings.write_string(b, fmt.tprintf("%d", dt.day)); return 1
case '1':
strings.write_string(b, fmt.tprintf("%d", dt.month)); return 1
case '4':
strings.write_string(b, fmt.tprintf("%d", dt.minute)); return 1
case '5':
strings.write_string(b, fmt.tprintf("%d", dt.second)); return 1
case '3':
emit_hour_12(b, dt, pad = false); return 1
case:
return 0
}
}
*/
}
emit_month_abbr :: proc(b: ^strings.Builder, dt: common.Date_Components) {
name := fmt.tprintf("%s", time.Month(dt.month))
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
emit_weekday :: proc(b: ^strings.Builder, dt: common.Date_Components, full: bool) {
date := datetime.Date {
year = i64(dt.year),
month = i8(dt.month),
day = i8(dt.day),
}
ordinal, err := datetime.date_to_ordinal(date)
if err != .None {
strings.write_string(b, "???")
return
}
weekday := datetime.day_of_week(ordinal)
name := fmt.tprintf("%s", weekday)
if full {
strings.write_string(b, name)
} else {
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
}
emit_hour_12 :: proc(b: ^strings.Builder, dt: common.Date_Components, pad: bool) {
h12 := dt.hour % 12
if h12 == 0 {h12 = 12}
format := "%02d" if pad else "%d"
fmt.sbprintf(b, format, h12)
}
+128
View File
@@ -0,0 +1,128 @@
package original
import "../common"
import "core:fmt"
import "core:log"
import "core:strings"
import "core:time"
import "core:time/datetime"
format_date :: proc(
dt: common.Date_Components,
fmt: string,
allocator := context.temp_allocator,
) -> string {
b: strings.Builder
strings.builder_init(&b, allocator)
for i := 0; i < len(fmt); {
matched := match_token(&b, dt, fmt[i:])
if matched > 0 {
i += matched
} else {
strings.write_byte(&b, fmt[i])
i += 1
}
}
log.debugf("formatted date: '%s'", b.buf)
return strings.to_string(b)
}
match_token :: proc(b: ^strings.Builder, dt: common.Date_Components, s: string) -> int {
if strings.has_prefix(
s,
"January",
) {strings.write_string(b, fmt.tprintf("%s", time.Month(dt.month))); return 7}
if strings.has_prefix(s, "Monday") {emit_weekday(b, dt, full = true); return 6}
if strings.has_prefix(
s,
"2006",
) {strings.write_string(b, fmt.tprintf("%04d", dt.year)); return 4}
if strings.has_prefix(s, "MST") {strings.write_string(b, "UTC"); return 3}
if strings.has_prefix(s, "Jan") {emit_month_abbr(b, dt); return 3}
if strings.has_prefix(s, "Mon") {emit_weekday(b, dt, full = false); return 3}
if strings.has_prefix(
s,
"06",
) {strings.write_string(b, fmt.tprintf("%02d", dt.year % 100)); return 2}
if strings.has_prefix(s, "02") {strings.write_string(b, fmt.tprintf("%02d", dt.day)); return 2}
if strings.has_prefix(
s,
"15",
) {strings.write_string(b, fmt.tprintf("%02d", dt.hour)); return 2}
if strings.has_prefix(
s,
"04",
) {strings.write_string(b, fmt.tprintf("%02d", dt.minute)); return 2}
if strings.has_prefix(
s,
"05",
) {strings.write_string(b, fmt.tprintf("%02d", dt.second)); return 2}
if strings.has_prefix(
s,
"01",
) {strings.write_string(b, fmt.tprintf("%02d", dt.month)); return 2}
if strings.has_prefix(s, "03") {emit_hour_12(b, dt, pad = true); return 2}
if strings.has_prefix(s, "PM") {emit_am_pm(b, dt); return 2}
if strings.has_prefix(s, "pm") {emit_am_pm_lower(b, dt); return 2}
if len(s) >= 1 {
switch s[0] {
case '2':
strings.write_string(b, fmt.tprintf("%d", dt.day)); return 1
case '1':
strings.write_string(b, fmt.tprintf("%d", dt.month)); return 1
case '4':
strings.write_string(b, fmt.tprintf("%d", dt.minute)); return 1
case '5':
strings.write_string(b, fmt.tprintf("%d", dt.second)); return 1
case '3':
emit_hour_12(b, dt, pad = false); return 1
case:
return 0
}
}
return 0
}
emit_month_abbr :: proc(b: ^strings.Builder, dt: common.Date_Components) {
name := fmt.tprintf("%s", time.Month(dt.month))
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
emit_weekday :: proc(b: ^strings.Builder, dt: common.Date_Components, full: bool) {
date := datetime.Date {
year = i64(dt.year),
month = i8(dt.month),
day = i8(dt.day),
}
ordinal, err := datetime.date_to_ordinal(date)
if err != .None {
strings.write_string(b, "???")
return
}
weekday := datetime.day_of_week(ordinal)
name := fmt.tprintf("%s", weekday)
if full {
strings.write_string(b, name)
} else {
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
}
emit_hour_12 :: proc(b: ^strings.Builder, dt: common.Date_Components, pad: bool) {
h12 := dt.hour % 12
if h12 == 0 {h12 = 12}
format := "%02d" if pad else "%d"
fmt.sbprintf(b, format, h12)
}
emit_am_pm :: proc(b: ^strings.Builder, dt: common.Date_Components) {
strings.write_string(b, "PM" if dt.hour >= 12 else "AM")
}
emit_am_pm_lower :: proc(b: ^strings.Builder, dt: common.Date_Components) {
strings.write_string(b, "pm" if dt.hour >= 12 else "am")
}
+44
View File
@@ -0,0 +1,44 @@
package main
Date_Components :: struct {
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int,
}
// TODO: Use some kind of scanner interface
parse_iso_date :: proc(iso: string) -> (c: Date_Components, ok: bool) {
if len(iso) < 10 {
return {}, false
}
c.year = parse_2_digits(iso, 0) * 100 + parse_2_digits(iso, 2)
c.month = parse_2_digits(iso, 5)
c.day = parse_2_digits(iso, 8)
if c.month < 1 || c.month > 12 {
return {}, false
}
if c.day < 1 || c.day > 31 {
return {}, false
}
if len(iso) >= 19 && (iso[10] == 'T' || iso[10] == 't') {
c.hour = parse_2_digits(iso, 11)
c.minute = parse_2_digits(iso, 14)
c.second = parse_2_digits(iso, 17)
}
return c, true
}
parse_2_digits :: proc(s: string, offset: int) -> int {
if offset + 1 >= len(s) {
return 0
}
return (int(s[offset]) - 0x30) * 10 + (int(s[offset + 1]) - 0x30)
}
+127
View File
@@ -0,0 +1,127 @@
package returned
import "../common"
import "core:fmt"
import "core:log"
import "core:strings"
import "core:time"
import "core:time/datetime"
format_date :: proc(
dt: common.Date_Components,
fmt: string,
allocator := context.temp_allocator,
) -> string {
b: strings.Builder
// strings.builder_init_len(&b, len(fmt), allocator)
strings.builder_init(&b, allocator)
for i := 0; i < len(fmt); {
matched := match_token(&b, dt, fmt[i:])
if matched > 0 {
i += matched
} else {
strings.write_byte(&b, fmt[i])
i += 1
}
}
log.debugf("formatted date: '%s'", b.buf)
return strings.to_string(b)
}
match_token :: proc(b: ^strings.Builder, dt: common.Date_Components, s: string) -> int {
if strings.has_prefix(
s,
"January",
) {strings.write_string(b, fmt.tprintf("%s", time.Month(dt.month))); return 7}
if strings.has_prefix(s, "Monday") {emit_weekday(b, dt, full = true); return 6}
if strings.has_prefix(
s,
"2006",
) {strings.write_string(b, fmt.tprintf("%04d", dt.year)); return 4}
if strings.has_prefix(s, "MST") {strings.write_string(b, "UTC"); return 3}
if strings.has_prefix(s, "Jan") {emit_month_abbr(b, dt); return 3}
if strings.has_prefix(s, "Mon") {emit_weekday(b, dt, full = false); return 3}
if strings.has_prefix(
s,
"06",
) {strings.write_string(b, fmt.tprintf("%02d", dt.year % 100)); return 2}
if strings.has_prefix(s, "02") {strings.write_string(b, fmt.tprintf("%02d", dt.day)); return 2}
if strings.has_prefix(
s,
"15",
) {strings.write_string(b, fmt.tprintf("%02d", dt.hour)); return 2}
if strings.has_prefix(
s,
"04",
) {strings.write_string(b, fmt.tprintf("%02d", dt.minute)); return 2}
if strings.has_prefix(
s,
"05",
) {strings.write_string(b, fmt.tprintf("%02d", dt.second)); return 2}
if strings.has_prefix(
s,
"01",
) {strings.write_string(b, fmt.tprintf("%02d", dt.month)); return 2}
if strings.has_prefix(s, "03") {emit_hour_12(b, dt, pad = true); return 2}
if strings.has_prefix(s, "PM") {
strings.write_string(b, "PM" if dt.hour >= 12 else "AM")
return 2
}
if strings.has_prefix(s, "pm") {
strings.write_string(b, "pm" if dt.hour >= 12 else "am")
return 2
}
if len(s) >= 1 {
switch s[0] {
case '2':
strings.write_string(b, fmt.tprintf("%d", dt.day)); return 1
case '1':
strings.write_string(b, fmt.tprintf("%d", dt.month)); return 1
case '4':
strings.write_string(b, fmt.tprintf("%d", dt.minute)); return 1
case '5':
strings.write_string(b, fmt.tprintf("%d", dt.second)); return 1
case '3':
emit_hour_12(b, dt, pad = false); return 1
case:
return 0
}
}
return 0
}
emit_month_abbr :: proc(b: ^strings.Builder, dt: common.Date_Components) {
name := fmt.tprintf("%s", time.Month(dt.month))
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
emit_weekday :: proc(b: ^strings.Builder, dt: common.Date_Components, full: bool) {
date := datetime.Date {
year = i64(dt.year),
month = i8(dt.month),
day = i8(dt.day),
}
ordinal, err := datetime.date_to_ordinal(date)
if err != .None {
strings.write_string(b, "???")
return
}
weekday := datetime.day_of_week(ordinal)
name := fmt.tprintf("%s", weekday)
if full {
strings.write_string(b, name)
} else {
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
}
emit_hour_12 :: proc(b: ^strings.Builder, dt: common.Date_Components, pad: bool) {
h12 := dt.hour % 12
if h12 == 0 {h12 = 12}
format := "%02d" if pad else "%d"
fmt.sbprintf(b, format, h12)
}
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<title>{{$title}}{{/title}}</title>
{{$head}}{{/head}}
</head>
<body>
{{$nav}}{{/nav}}
{{$content}}{{/content}}
{{$sidebar}}{{/sidebar}}
{{$footer}}{{/footer}}
</body>
</html>
+45
View File
@@ -0,0 +1,45 @@
{{<base}}
{{$title}}Archive{{/title}}
{{$head}}
<meta name="description" content="Post archive">
{{/head}}
{{$nav}}
<nav>
<ul>
{{#nav_items}}
<li><a href="{{url}}">{{label}}</a></li>
{{/nav_items}}
</ul>
</nav>
{{/nav}}
{{$content}}
<main>
<h1>Archive</h1>
{{#posts | group_by year}}
<section class="year">
<h2>{{key}}</h2>
<ul>
{{#items}}
{{> post}}
{{/items}}
</ul>
</section>
{{/posts}}
</main>
{{/content}}
{{$sidebar}}
<aside>
<h3>Recent Comments</h3>
<ul>
{{#comments}}
{{> comment}}
{{/comments}}
</ul>
</aside>
{{/sidebar}}
{{$footer}}
<footer>
<p>Generated {{now}}</p>
</footer>
{{/footer}}
{{/base}}
+5
View File
@@ -0,0 +1,5 @@
<li class="comment">
<strong>{{author}}</strong>
<time datetime="{{date}}">{{date | format}}</time>
<p>{{body}}</p>
</li>
+9
View File
@@ -0,0 +1,9 @@
<li class="post">
<article>
<h3><a href="{{url}}">{{title}}</a></h3>
<time datetime="{{date}}">{{date | format}}</time>
<p class="excerpt">{{excerpt}}</p>
{{#author}}<address>{{author}}</address>{{/author}}
{{#tags}}<a href="/tag/{{slug}}" class="tag">{{name}}</a>{{/tags}}
</article>
</li>
+2
View File
@@ -149,6 +149,8 @@
cmark
tree-sitter
gdb
# IDE
unstable.helix
typescript-language-server
+5 -2
View File
@@ -1,7 +1,6 @@
package main
import "base:runtime"
import "core:fmt"
import "core:log"
import "core:os"
import "core:prof/spall"
@@ -33,12 +32,15 @@ main :: proc() {
defer spall.buffer_destroy(&spall_ctx, &spall_buffer)
}
console_logger := log.create_console_logger()
logger_opts: log.Options =
(log.Default_Console_Logger_Opts - log.Full_Timestamp_Opts - {.Short_File_Path})
console_logger := log.create_console_logger(.Info, logger_opts)
context.logger = console_logger
defer log.destroy_console_logger(console_logger)
for {
defer free_all(context.temp_allocator)
tick := time.tick_now()
site: Site
init_site(&site, os.args)
defer destroy_site(&site)
@@ -48,6 +50,7 @@ main :: proc() {
site_load_content(&site)
render_site(&site)
log.infof("Built site in %s", time.tick_since(tick))
(.Watch in site.features) or_break
time.sleep(5 * time.Second)
+5 -2
View File
@@ -56,13 +56,16 @@ Errors (returned as `Data_Error` at render time):
- Any element is missing the named field.
- Any element has an empty value for the named field.
#### `format` (no args yet)
#### `format`
Formats an ISO 8601 date string as a display string. Takes a string, returns a string (e.g. `"2026-03-15T08:49:54-04:00"``"15 Mar 2026"`). Invalid input (empty, too-short, non-string, or unparseable) returns a `Data_Error`. Templates that need to skip dateless pages should gate with a section — `{{#date}}<time datetime="{{.}}">{{. | format}}</time>{{/date}}` — so the section's truthiness check catches empty before the filter runs. Commonly used inline as `{{date | format}}` to render a display string while keeping the raw ISO available via `{{date}}` for the `datetime=` attribute.
Internally: parses the invariant `YYYY-MM-DD` prefix by char offset, stringifies `time.Month(month_num)` and slices `[:3]` for the abbreviation. Accepts any of these ISO 8601 forms (the date prefix is what matters): `2023-10-15T13:18:50-07:00`, `2023-10-15T13:18:50-0700`, `2023-10-15T13:18:50Z`, `2023-10-15T13:18:50`, `2023-10-15`.
Future: will accept Go reference-date format strings (e.g. `{{date | format "Mon Jan 2 2006"}}`) and pull default format/timezone from site configuration.
Takes an optional arg for the Go reference-date layout to use:
- A double-quoted literal, spaces allowed: `{{date | format "Mon Jan 2 2006"}}`.
- A bare key, resolved from context like any other field: `{{date | format long}}` uses the value of `long` (e.g. a site-config field) as the layout.
- No arg: falls back to the `date_format` context key (typically `date.format` from `thor.json`).
### Memory ownership
+323
View File
@@ -0,0 +1,323 @@
package mustache
import "core:fmt"
import "core:os"
import "core:strings"
import "core:terminal/ansi"
import "core:unicode/utf8"
// line_col returns the 1-indexed line and column for a byte offset in source.
// Newlines ('\n') separate lines; '\r' is treated as part of '\r\n'. Column is
// counted in bytes from the start of the line.
line_col :: proc(source: string, pos_in: int) -> (line: int, col: int) {
pos := pos_in
if pos < 0 {
return 1, 1
}
if pos > len(source) {
pos = len(source)
}
line = 1
col = 1
for i := 0; i < pos; i += 1 {
if source[i] == '\n' {
line += 1
col = 1
} else {
col += 1
}
}
return
}
// line_text returns the Nth (1-indexed) line of source, without the trailing
// newline. Returns "" if line is out of range.
line_text :: proc(source: string, line: int) -> string {
if line < 1 {
return ""
}
current := 1
start := 0
for i := 0; i < len(source); i += 1 {
if current == line {
end := i
for end < len(source) && source[end] != '\n' {
end += 1
}
return source[start:end]
}
if source[i] == '\n' {
current += 1
start = i + 1
}
}
if current == line {
return source[start:]
}
return ""
}
// context_extent returns the byte offset of the start of the line containing
// pos, plus the byte offsets of the start and end of the mustache tag at pos.
// Used to underline the offending tag. If pos is not inside a tag, the
// returned [token_start, token_end) is a single rune at pos.
context_extent :: proc(
source: string,
pos_in: int,
) -> (
line_start: int,
token_start: int,
token_end: int,
) {
pos := pos_in
if pos < 0 {
return 0, 0, 0
}
if pos >= len(source) {
pos = len(source) - 1
}
line_start = pos
for line_start > 0 && source[line_start - 1] != '\n' {
line_start -= 1
}
// Scan forward from line_start for `{{ ... }}` tags. If pos falls inside
// any tag's byte range, return that tag's extent.
i := line_start
for i + 1 < len(source) {
if source[i] == '{' && source[i + 1] == '{' {
tag_start := i
// Find closing }}
j := i + 2
depth := 1
for j + 1 < len(source) && depth > 0 {
if source[j] == '{' && source[j + 1] == '{' {
depth += 1
j += 2
} else if source[j] == '}' && source[j + 1] == '}' {
depth -= 1
j += 2
} else {
j += 1
}
}
tag_end := j
if pos >= tag_start && pos < tag_end {
return line_start, tag_start, tag_end
}
i = tag_end
} else {
i += 1
}
}
// Not inside a tag — underline a single rune at pos.
return line_start, pos, pos + 1
}
// should_colorize returns true if stderr is a TTY and color output is wanted.
should_colorize :: proc() -> bool {
return os.is_tty(os.stderr)
}
// count_lines returns the number of '\n'-separated lines in source.
// A trailing newline does not add an extra line.
count_lines :: proc(source: string) -> int {
if len(source) == 0 {
return 1
}
n := 1
for c in source {
if c == '\n' {
n += 1
}
}
// Drop phantom last line if source ends with '\n'.
if len(source) > 0 && source[len(source) - 1] == '\n' {
n -= 1
}
return n
}
// digit_count returns the number of decimal digits in n (min 1).
digit_count :: proc(n: int) -> int {
if n <= 0 {
return 1
}
c := 0
x := n
for x > 0 {
c += 1
x /= 10
}
return c
}
// display_width returns the number of terminal cells `s` occupies.
// For ASCII this is byte length; for UTF-8 we count runes (combining
// marks and wide CJK chars are still approximate).
display_width :: proc(s: string) -> int {
return utf8.rune_count_in_string(s)
}
// format_error produces a rust-style multi-line diagnostic string.
//
// <msg>
// --> <path>:<line>:<col>
// |
// N | <source line N-2>
// N | <source line N-1>
// N | <source line N — the error line>
// | ^^^^^^^^^^^ <hint>
// N | <source line N+1>
// N | <source line N+2>
// |
//
// `context_before`/`context_after` lines of context are shown around the
// error line. Line numbers are right-aligned to the width of the largest
// line number shown.
format_error :: proc(
path: string,
source: string,
pos: int,
msg: string,
hint: string = "",
context_before: int = 2,
context_after: int = 2,
colorize: bool = false,
) -> string {
line, col := line_col(source, pos)
total_lines := count_lines(source)
start_line := line - context_before
if start_line < 1 {
start_line = 1
}
end_line := line + context_after
if end_line > total_lines {
end_line = total_lines
}
// Width of the line-number column (right-align).
width := digit_count(end_line)
if width < 1 {
width = 1
}
sb := strings.builder_make(context.temp_allocator)
defer strings.builder_destroy(&sb)
color := colorize
red, faint, reset := "", "", ""
if color {
red = ansi.CSI + ansi.FG_RED + ansi.SGR
faint = ansi.CSI + ansi.FAINT + ansi.SGR
reset = ansi.CSI + ansi.RESET + ansi.SGR
}
// Header line: message.
strings.write_string(&sb, msg)
strings.write_byte(&sb, '\n')
// Location line: " --> path:line:col" (width spaces + arrow).
strings.write_string(&sb, faint)
for _ in 0 ..< width {
strings.write_byte(&sb, ' ')
}
strings.write_string(&sb, "--> ")
strings.write_string(&sb, reset)
strings.write_string(&sb, fmt.tprintf("%s:%d:%d\n", path, line, col))
// Top gutter line.
write_gutter(&sb, width, faint, reset)
// Caret extent for the error line.
_, token_start, token_end := context_extent(source, pos)
line_start, _, _ := context_extent(source, pos)
caret_start_col := token_start - line_start + 1
caret_end_col := token_end - line_start + 1
if caret_end_col <= caret_start_col {
caret_end_col = caret_start_col + 1
}
// Context lines.
for n in start_line ..= end_line {
// Line number (right-aligned, faint).
num_str := fmt.tprintf("%d", n)
strings.write_string(&sb, faint)
for _ in 0 ..< width - len(num_str) {
strings.write_byte(&sb, ' ')
}
strings.write_string(&sb, num_str)
strings.write_string(&sb, " | ")
strings.write_string(&sb, reset)
strings.write_string(&sb, line_text(source, n))
strings.write_byte(&sb, '\n')
// After the error line, emit the caret row.
if n == line {
strings.write_string(&sb, faint)
for _ in 0 ..< width + 1 {
strings.write_byte(&sb, ' ')
}
strings.write_string(&sb, "| ")
strings.write_string(&sb, reset)
for _ in 1 ..< caret_start_col {
strings.write_byte(&sb, ' ')
}
if color {
strings.write_string(&sb, red)
}
for _ in 0 ..< caret_end_col - caret_start_col {
strings.write_byte(&sb, '^')
}
if color {
strings.write_string(&sb, reset)
}
if hint != "" {
strings.write_byte(&sb, ' ')
if color {
strings.write_string(&sb, faint)
}
strings.write_string(&sb, hint)
if color {
strings.write_string(&sb, reset)
}
}
strings.write_byte(&sb, '\n')
}
}
// Trailing gutter line for visual closure.
write_gutter(&sb, width, faint, reset)
return strings.to_string(sb)
}
// write_gutter emits a faint pipe-only gutter line: `<width+1 spaces> |`.
write_gutter :: proc(sb: ^strings.Builder, width: int, faint: string, reset: string) {
strings.write_string(sb, faint)
for _ in 0 ..< width + 1 {
strings.write_byte(sb, ' ')
}
strings.write_string(sb, "|")
strings.write_string(sb, reset)
strings.write_byte(sb, '\n')
}
// format_render_error produces a diagnostic for an Error value using the
// template's path and source for context. Returns "" for nil errors.
format_render_error :: proc(err: Error, tmpl: Template, colorize: bool = false) -> string {
if err == nil {
return ""
}
path := tmpl.path
if path == "" {
path = "<input>"
}
b := body(err)
return format_error(path, tmpl.source, b.pos, b.msg, colorize = colorize)
}
+560
View File
@@ -0,0 +1,560 @@
#+test
package mustache
import "core:fmt"
import "core:strings"
import "core:testing"
// ---------------------------------------------------------------------------
// line_col / line_text / count_lines / digit_count — primitive helpers
// ---------------------------------------------------------------------------
@(test)
test_line_col_basic :: proc(t: ^testing.T) {
src := "abc\ndef\nghi"
cases := [?]struct {
pos: int,
line: int,
col: int,
}{{0, 1, 1}, {2, 1, 3}, {3, 1, 4}, {4, 2, 1}, {6, 2, 3}, {7, 2, 4}, {8, 3, 1}}
for c in cases {
l, col := line_col(src, c.pos)
testing.expect(t, l == c.line, fmt.tprintf("pos %d: line %d, want %d", c.pos, l, c.line))
testing.expect(t, col == c.col, fmt.tprintf("pos %d: col %d, want %d", c.pos, col, c.col))
}
}
@(test)
test_line_col_empty :: proc(t: ^testing.T) {
l, col := line_col("", 0)
testing.expect_value(t, l, 1)
testing.expect_value(t, col, 1)
}
@(test)
test_line_col_negative :: proc(t: ^testing.T) {
l, col := line_col("abc", -1)
testing.expect_value(t, l, 1)
testing.expect_value(t, col, 1)
}
@(test)
test_line_col_past_end :: proc(t: ^testing.T) {
l, col := line_col("abc", 100)
testing.expect_value(t, l, 1)
testing.expect_value(t, col, 4)
}
@(test)
test_line_text_first :: proc(t: ^testing.T) {
src := "first\nsecond\nthird"
testing.expect_value(t, line_text(src, 1), "first")
testing.expect_value(t, line_text(src, 2), "second")
testing.expect_value(t, line_text(src, 3), "third")
}
@(test)
test_line_text_trailing_newline :: proc(t: ^testing.T) {
src := "first\nsecond\n"
testing.expect_value(t, line_text(src, 1), "first")
testing.expect_value(t, line_text(src, 2), "second")
testing.expect_value(t, line_text(src, 3), "")
}
@(test)
test_line_text_out_of_range :: proc(t: ^testing.T) {
testing.expect_value(t, line_text("abc", 5), "")
testing.expect_value(t, line_text("abc", 0), "")
}
@(test)
test_count_lines :: proc(t: ^testing.T) {
testing.expect_value(t, count_lines(""), 1)
testing.expect_value(t, count_lines("abc"), 1)
testing.expect_value(t, count_lines("a\nb"), 2)
testing.expect_value(t, count_lines("a\nb\n"), 2)
testing.expect_value(t, count_lines("a\nb\nc"), 3)
}
@(test)
test_digit_count :: proc(t: ^testing.T) {
testing.expect_value(t, digit_count(0), 1)
testing.expect_value(t, digit_count(1), 1)
testing.expect_value(t, digit_count(9), 1)
testing.expect_value(t, digit_count(10), 2)
testing.expect_value(t, digit_count(99), 2)
testing.expect_value(t, digit_count(100), 3)
testing.expect_value(t, digit_count(-5), 1)
}
// ---------------------------------------------------------------------------
// format_error — golden output tests
// ---------------------------------------------------------------------------
@(test)
test_format_error_basic :: proc(t: ^testing.T) {
src := "line 1\nline 2\n{{bad}}\nline 4\nline 5"
out := format_error("p.html", src, 14, "unknown key 'bad'", "", colorize = false)
expected := `unknown key 'bad'
--> p.html:3:1
|
1 | line 1
2 | line 2
3 | {{bad}}
| ^^^^^^^
4 | line 4
5 | line 5
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_format_error_with_hint :: proc(t: ^testing.T) {
src := "line 1\nline 2\n{{titel}}\nline 4\nline 5"
out := format_error(
"post.html",
src,
14,
"unknown key 'titel'",
"did you mean 'title'?",
colorize = false,
)
expected := `unknown key 'titel'
--> post.html:3:1
|
1 | line 1
2 | line 2
3 | {{titel}}
| ^^^^^^^^^ did you mean 'title'?
4 | line 4
5 | line 5
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_format_error_no_hint_omits_trailing_space :: proc(t: ^testing.T) {
src := "{{bad}}"
out := format_error("p.html", src, 0, "msg", "", colorize = false)
// Caret line ends immediately after the carets — no trailing space.
testing.expect(t, strings.contains(out, "^^^^^^^\n"), out)
testing.expect(t, !strings.contains(out, "^^^^^^^ \n"), out)
}
// ---------------------------------------------------------------------------
// Edge cases — context window clamping
// ---------------------------------------------------------------------------
@(test)
test_format_error_first_line_only_after_context :: proc(t: ^testing.T) {
src := "{{bad}}\nline 2\nline 3\nline 4\nline 5"
out := format_error("p.html", src, 0, "msg", "", colorize = false)
expected := `msg
--> p.html:1:1
|
1 | {{bad}}
| ^^^^^^^
2 | line 2
3 | line 3
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_format_error_last_line_only_before_context :: proc(t: ^testing.T) {
src := "line 1\nline 2\nline 3\nline 4\n{{bad}}"
out := format_error("p.html", src, 28, "msg", "", colorize = false)
expected := `msg
--> p.html:5:1
|
3 | line 3
4 | line 4
5 | {{bad}}
| ^^^^^^^
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_format_error_short_source_clamped :: proc(t: ^testing.T) {
src := "x\n{{bad}}\ny"
out := format_error("p.html", src, 2, "msg", "", colorize = false)
expected := `msg
--> p.html:2:1
|
1 | x
2 | {{bad}}
| ^^^^^^^
3 | y
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_format_error_single_line_source :: proc(t: ^testing.T) {
src := "{{bad}}"
out := format_error("p.html", src, 0, "msg", "", colorize = false)
expected := `msg
--> p.html:1:1
|
1 | {{bad}}
| ^^^^^^^
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_format_error_two_digit_line_numbers :: proc(t: ^testing.T) {
// 12-line source; error on line 9. end_line=11 → width=2.
src := "l01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\n{{bad}}\nl10\nl11\nl12"
// Position of `{{bad}}`: 8 lines of "l0N\n" = 8*4 = 32 bytes.
out := format_error("p.html", src, 32, "msg", "", colorize = false)
testing.expect(t, strings.contains(out, " --> p.html:9:1\n"), out)
testing.expect(t, strings.contains(out, " |\n"), out)
testing.expect(t, strings.contains(out, " 7 | l07\n"), out)
testing.expect(t, strings.contains(out, " 9 | {{bad}}\n"), out)
testing.expect(t, strings.contains(out, "11 | l11\n"), out)
}
@(test)
test_format_error_three_digit_line_numbers :: proc(t: ^testing.T) {
// 102-line source; error on line 100. Width=3 because end_line=102 has 3 digits.
parts: [dynamic]string
defer delete(parts)
for i in 1 ..= 99 {
append(&parts, fmt.tprintf("l%03d", i))
}
append(&parts, "{{bad}}")
append(&parts, "l101")
append(&parts, "l102")
src := strings.join(parts[:], "\n", context.temp_allocator)
// Find byte position of "{{bad}}": after 99 lines.
pos := 0
for i in 1 ..= 99 {
pos += len(parts[i - 1]) + 1
}
out := format_error("p.html", src, pos, "msg", "", colorize = false)
testing.expect(t, strings.contains(out, " --> p.html:100:1\n"), out)
testing.expect(t, strings.contains(out, " |\n"), out)
testing.expect(t, strings.contains(out, " 98 | l098\n"), out)
testing.expect(t, strings.contains(out, "100 | {{bad}}\n"), out)
testing.expect(t, strings.contains(out, "102 | l102\n"), out)
}
// ---------------------------------------------------------------------------
// Caret position
// ---------------------------------------------------------------------------
@(test)
test_caret_at_column_1 :: proc(t: ^testing.T) {
src := "{{bad}} at start"
out := format_error("p.html", src, 0, "msg", "", colorize = false)
// Caret line should start with "^" right after "| " (no leading spaces).
testing.expect(t, strings.contains(out, " | ^^^^^^^\n"), out)
}
@(test)
test_caret_at_column_N :: proc(t: ^testing.T) {
src := " {{bad}}"
// pos=4 is the first '{'. Line 1, col 5.
out := format_error("p.html", src, 4, "msg", "", colorize = false)
// 4 leading spaces, then 7 carets.
testing.expect(t, strings.contains(out, " | ^^^^^^^\n"), out)
}
@(test)
test_caret_width_matches_token :: proc(t: ^testing.T) {
src := "{{x}}"
out := format_error("p.html", src, 0, "msg", "", colorize = false)
// {{x}} is 5 chars wide.
testing.expect(t, strings.contains(out, " | ^^^^^\n"), out)
}
// ---------------------------------------------------------------------------
// Context count
// ---------------------------------------------------------------------------
@(test)
test_context_before_zero :: proc(t: ^testing.T) {
src := "l1\nl2\nl3\n{{bad}}\nl5\nl6"
out := format_error(
"p.html",
src,
9,
"msg",
"",
context_before = 0,
context_after = 1,
colorize = false,
)
expected := `msg
--> p.html:4:1
|
4 | {{bad}}
| ^^^^^^^
5 | l5
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_context_after_zero :: proc(t: ^testing.T) {
src := "l1\nl2\nl3\n{{bad}}\nl5\nl6"
out := format_error(
"p.html",
src,
9,
"msg",
"",
context_before = 1,
context_after = 0,
colorize = false,
)
expected := `msg
--> p.html:4:1
|
3 | l3
4 | {{bad}}
| ^^^^^^^
|
`
testing.expect_value(t, out, expected)
}
@(test)
test_context_both_zero :: proc(t: ^testing.T) {
src := "l1\nl2\nl3\n{{bad}}\nl5\nl6"
out := format_error(
"p.html",
src,
9,
"msg",
"",
context_before = 0,
context_after = 0,
colorize = false,
)
expected := `msg
--> p.html:4:1
|
4 | {{bad}}
| ^^^^^^^
|
`
testing.expect_value(t, out, expected)
}
// ---------------------------------------------------------------------------
// Gutter/alignment
// ---------------------------------------------------------------------------
@(test)
test_gutter_pipes_align_with_source_pipe :: proc(t: ^testing.T) {
src := "l1\n{{bad}}\nl3"
out := format_error("p.html", src, 3, "msg", "", colorize = false)
// All "|" characters should appear at the same column.
// For width=1: source line is "N | ...", so "|" at col 2.
// Empty gutter is " |" (width+1 spaces + "|"), so "|" at col 2.
lines := strings.split(out, "\n", context.temp_allocator)
pipe_col := -1
for line in lines {
idx := strings.index(line, "|")
if idx < 0 {
continue
}
if pipe_col < 0 {
pipe_col = idx
} else {
testing.expect_value(t, idx, pipe_col)
}
}
}
@(test)
test_arrow_points_at_pipe :: proc(t: ^testing.T) {
src := "{{bad}}"
out := format_error("p.html", src, 0, "msg", "", colorize = false)
// For width=1: arrow line is " --> ..." so ">" at col 3.
// Pipe lines are " |" so "|" at col 2.
lines := strings.split(out, "\n", context.temp_allocator)
pipe_col := -1
for line in lines {
idx := strings.index(line, "|")
if idx >= 0 {
pipe_col = idx
break
}
}
testing.expect(t, pipe_col >= 0, "expected pipe in output")
// Find the arrow line specifically and verify its ">" column.
arrow_col := -1
for line in lines {
idx := strings.index(line, "-->")
if idx >= 0 {
arrow_col = idx + 2 // ">" is the last char of "-->"
break
}
}
testing.expect(t, arrow_col >= 0, "expected --> in output")
testing.expect_value(t, arrow_col, pipe_col + 1)
}
// ---------------------------------------------------------------------------
// format_render_error — dispatch
// ---------------------------------------------------------------------------
@(test)
test_format_render_error_dispatch :: proc(t: ^testing.T) {
src := "{{#unclosed}}\ncontent"
tmpl, parse_err := parse(src, "test.html")
testing.expect(t, parse_err != nil, "should fail to parse unclosed section")
if parse_err == nil {
return
}
b := body(parse_err)
out := format_error("test.html", src, b.pos, b.msg, colorize = false)
testing.expect(t, strings.contains(out, "unclosed section"), out)
testing.expect(t, strings.contains(out, "test.html:"), out)
}
@(test)
test_diagnostic_for_pipe_error :: proc(t: ^testing.T) {
src := "{{#name | group_by year}}x{{/name}}"
tmpl, perr := parse(src, "test.html")
testing.expect(t, perr == nil, "should parse")
if perr != nil {
return
}
defer delete_template(&tmpl)
Data :: struct {
name: string,
}
_, rerr := render(tmpl, Data{name = "hello"})
testing.expect(t, rerr != nil, "should fail to render")
if rerr == nil {
return
}
out := format_render_error(rerr, tmpl, colorize = false)
testing.expect(t, strings.contains(out, "group_by expects a list"), out)
testing.expect(t, strings.contains(out, "test.html:"), out)
}
// ---------------------------------------------------------------------------
// Parser error messages preserve double braces in tag syntax
// ---------------------------------------------------------------------------
@(test)
test_parse_error_expected_got_keeps_double_braces :: proc(t: ^testing.T) {
src := "{{#content}}body{{/cotent}}"
_, err := parse(src, "test.html")
testing.expect(t, err != nil, "should fail to parse")
if err == nil {
return
}
b := body(err)
testing.expect(
t,
strings.contains(b.msg, "{{/content}}"),
fmt.tprintf("msg should contain literal {{/content}}, got %q", b.msg),
)
testing.expect(
t,
strings.contains(b.msg, "{{/cotent}}"),
fmt.tprintf("msg should contain literal {{/cotent}}, got %q", b.msg),
)
}
@(test)
test_parse_error_unclosed_section_keeps_double_braces :: proc(t: ^testing.T) {
src := "{{#content}}body"
_, err := parse(src, "test.html")
testing.expect(t, err != nil, "should fail to parse")
if err == nil {
return
}
b := body(err)
testing.expect(
t,
strings.contains(b.msg, "{{#content}}"),
fmt.tprintf("msg should contain literal {{#content}}, got %q", b.msg),
)
}
@(test)
test_parse_error_unexpected_close_keeps_double_braces :: proc(t: ^testing.T) {
src := "text{{/content}}"
_, err := parse(src, "test.html")
testing.expect(t, err != nil, "should fail to parse")
if err == nil {
return
}
b := body(err)
testing.expect(
t,
strings.contains(b.msg, "{{/content}}"),
fmt.tprintf("msg should contain literal {{/content}}, got %q", b.msg),
)
}
@(test)
test_parse_error_pipe_in_close_tag_keeps_double_braces :: proc(t: ^testing.T) {
src := "{{#posts | group_by year}}x{{/posts | group_by year}}"
_, err := parse(src, "test.html")
testing.expect(t, err != nil, "should fail to parse")
if err == nil {
return
}
b := body(err)
testing.expect(
t,
strings.contains(b.msg, "{{/"),
fmt.tprintf("msg should contain literal '{{/', got %q", b.msg),
)
}
@(test)
test_parse_error_pipe_parse_in_section_keeps_double_braces :: proc(t: ^testing.T) {
src := "{{#posts |}}x{{/posts}}"
_, err := parse(src, "test.html")
testing.expect(t, err != nil, "should fail to parse")
if err == nil {
return
}
b := body(err)
testing.expect(
t,
strings.contains(b.msg, "{{#"),
fmt.tprintf("msg should contain literal '{{#', got %q", b.msg),
)
}
@(test)
test_parse_error_pipe_parse_in_inverted_keeps_double_braces :: proc(t: ^testing.T) {
src := "{{^posts |}}x{{/posts}}"
_, err := parse(src, "test.html")
testing.expect(t, err != nil, "should fail to parse")
if err == nil {
return
}
b := body(err)
testing.expect(
t,
strings.contains(b.msg, "{{^"),
fmt.tprintf("msg should contain literal '{{^', got %q", b.msg),
)
}
+169
View File
@@ -0,0 +1,169 @@
package mustache
import "core:fmt"
import "core:log"
import "core:strings"
import "core:time"
import "core:time/datetime"
Date_Components :: struct {
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int,
}
// TODO: Use some kind of scanner interface
parse_iso_date :: proc(iso: string) -> (c: Date_Components, ok: bool) {
if len(iso) < 10 {
return {}, false
}
c.year = parse_2_digits(iso, 0) * 100 + parse_2_digits(iso, 2)
c.month = parse_2_digits(iso, 5)
c.day = parse_2_digits(iso, 8)
if c.month < 1 || c.month > 12 {
return {}, false
}
if c.day < 1 || c.day > 31 {
return {}, false
}
if len(iso) >= 19 && (iso[10] == 'T' || iso[10] == 't') {
c.hour = parse_2_digits(iso, 11)
c.minute = parse_2_digits(iso, 14)
c.second = parse_2_digits(iso, 17)
}
return c, true
}
parse_2_digits :: proc(s: string, offset: int) -> int {
if offset + 1 >= len(s) {
return 0
}
return (int(s[offset]) - 0x30) * 10 + (int(s[offset + 1]) - 0x30)
}
format_date :: proc(
dt: Date_Components,
fmt: string,
allocator := context.temp_allocator,
) -> string {
b: strings.Builder
strings.builder_init(&b, allocator)
for i := 0; i < len(fmt); {
matched := match_token(&b, dt, fmt[i:])
if matched > 0 {
i += matched
} else {
strings.write_byte(&b, fmt[i])
i += 1
}
}
log.debugf("formatted date: '%s'", b.buf)
return strings.to_string(b)
}
match_token :: proc(b: ^strings.Builder, dt: Date_Components, s: string) -> int {
if strings.has_prefix(
s,
"January",
) {strings.write_string(b, fmt.tprintf("%s", time.Month(dt.month))); return 7}
if strings.has_prefix(s, "Monday") {emit_weekday(b, dt, full = true); return 6}
if strings.has_prefix(
s,
"2006",
) {strings.write_string(b, fmt.tprintf("%04d", dt.year)); return 4}
if strings.has_prefix(s, "MST") {strings.write_string(b, "UTC"); return 3}
if strings.has_prefix(s, "Jan") {emit_month_abbr(b, dt); return 3}
if strings.has_prefix(s, "Mon") {emit_weekday(b, dt, full = false); return 3}
if strings.has_prefix(
s,
"06",
) {strings.write_string(b, fmt.tprintf("%02d", dt.year % 100)); return 2}
if strings.has_prefix(s, "02") {strings.write_string(b, fmt.tprintf("%02d", dt.day)); return 2}
if strings.has_prefix(
s,
"15",
) {strings.write_string(b, fmt.tprintf("%02d", dt.hour)); return 2}
if strings.has_prefix(
s,
"04",
) {strings.write_string(b, fmt.tprintf("%02d", dt.minute)); return 2}
if strings.has_prefix(
s,
"05",
) {strings.write_string(b, fmt.tprintf("%02d", dt.second)); return 2}
if strings.has_prefix(
s,
"01",
) {strings.write_string(b, fmt.tprintf("%02d", dt.month)); return 2}
if strings.has_prefix(s, "03") {emit_hour_12(b, dt, pad = true); return 2}
if strings.has_prefix(s, "PM") {emit_am_pm(b, dt); return 2}
if strings.has_prefix(s, "pm") {emit_am_pm_lower(b, dt); return 2}
if len(s) >= 1 {
switch s[0] {
case '2':
strings.write_string(b, fmt.tprintf("%d", dt.day)); return 1
case '1':
strings.write_string(b, fmt.tprintf("%d", dt.month)); return 1
case '4':
strings.write_string(b, fmt.tprintf("%d", dt.minute)); return 1
case '5':
strings.write_string(b, fmt.tprintf("%d", dt.second)); return 1
case '3':
emit_hour_12(b, dt, pad = false); return 1
case:
return 0
}
}
return 0
}
emit_month_abbr :: proc(b: ^strings.Builder, dt: Date_Components) {
name := fmt.tprintf("%s", time.Month(dt.month))
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
emit_weekday :: proc(b: ^strings.Builder, dt: Date_Components, full: bool) {
date := datetime.Date {
year = i64(dt.year),
month = i8(dt.month),
day = i8(dt.day),
}
ordinal, err := datetime.date_to_ordinal(date)
if err != .None {
strings.write_string(b, "???")
return
}
weekday := datetime.day_of_week(ordinal)
name := fmt.tprintf("%s", weekday)
if full {
strings.write_string(b, name)
} else {
strings.write_string(b, name[:3 if len(name) >= 3 else len(name)])
}
}
emit_hour_12 :: proc(b: ^strings.Builder, dt: Date_Components, pad: bool) {
h12 := dt.hour % 12
if h12 == 0 {h12 = 12}
format := "%02d" if pad else "%d"
fmt.sbprintf(b, format, h12)
}
emit_am_pm :: proc(b: ^strings.Builder, dt: Date_Components) {
strings.write_string(b, "PM" if dt.hour >= 12 else "AM")
}
emit_am_pm_lower :: proc(b: ^strings.Builder, dt: Date_Components) {
strings.write_string(b, "pm" if dt.hour >= 12 else "am")
}
+164
View File
@@ -0,0 +1,164 @@
#+test
package mustache
import "core:testing"
// ---------------------------------------------------------------------------
// parse_iso_date
// ---------------------------------------------------------------------------
@(test)
test_parse_iso_date_extracts_time :: proc(t: ^testing.T) {
c, ok := parse_iso_date("2026-03-15T08:49:54-04:00")
testing.expect(t, ok, "should parse")
testing.expect_value(t, c.year, 2026)
testing.expect_value(t, c.month, 3)
testing.expect_value(t, c.day, 15)
testing.expect_value(t, c.hour, 8)
testing.expect_value(t, c.minute, 49)
testing.expect_value(t, c.second, 54)
}
@(test)
test_parse_iso_date_lowercase_t :: proc(t: ^testing.T) {
c, ok := parse_iso_date("2026-03-15t08:49:54Z")
testing.expect(t, ok, "should parse lowercase t separator")
testing.expect_value(t, c.hour, 8)
testing.expect_value(t, c.minute, 49)
testing.expect_value(t, c.second, 54)
}
@(test)
test_parse_iso_date_date_only_zero_time :: proc(t: ^testing.T) {
c, ok := parse_iso_date("2026-03-15")
testing.expect(t, ok, "should parse date-only")
testing.expect_value(t, c.hour, 0)
testing.expect_value(t, c.minute, 0)
testing.expect_value(t, c.second, 0)
}
@(test)
test_parse_iso_date_invalid_day_errors :: proc(t: ^testing.T) {
_, ok := parse_iso_date("2026-03-32")
testing.expect(t, !ok, "day > 31 should fail")
}
@(test)
test_parse_iso_date_too_short_errors :: proc(t: ^testing.T) {
_, ok := parse_iso_date("2026-03")
testing.expect(t, !ok, "input shorter than 10 chars should fail")
}
// ---------------------------------------------------------------------------
// format_date / match_token
// ---------------------------------------------------------------------------
@(test)
test_format_date_weekday_full :: proc(t: ^testing.T) {
// 2026-01-01 is a Thursday.
dt := Date_Components{year = 2026, month = 1, day = 1}
result := format_date(dt, "Monday")
testing.expect_value(t, result, "Thursday")
}
@(test)
test_format_date_weekday_abbr :: proc(t: ^testing.T) {
dt := Date_Components{year = 2026, month = 1, day = 1}
result := format_date(dt, "Mon")
testing.expect_value(t, result, "Thu")
}
@(test)
test_format_date_month_full_name :: proc(t: ^testing.T) {
dt := Date_Components{year = 2026, month = 3, day = 15}
result := format_date(dt, "January")
testing.expect_value(t, result, "March")
}
@(test)
test_format_date_two_digit_year :: proc(t: ^testing.T) {
dt := Date_Components{year = 2026, month = 3, day = 15}
result := format_date(dt, "06")
testing.expect_value(t, result, "26")
}
@(test)
test_format_date_hour24_padded :: proc(t: ^testing.T) {
midnight := Date_Components{year = 2026, month = 1, day = 1, hour = 0}
testing.expect_value(t, format_date(midnight, "15"), "00")
afternoon := Date_Components{year = 2026, month = 1, day = 1, hour = 13}
testing.expect_value(t, format_date(afternoon, "15"), "13")
}
@(test)
test_format_date_hour12_padded_am_pm_boundaries :: proc(t: ^testing.T) {
cases := [4]struct {
hour: int,
expected: string,
}{{0, "12 AM"}, {12, "12 PM"}, {13, "01 PM"}, {23, "11 PM"}}
for &c in cases {
dt := Date_Components{year = 2026, month = 1, day = 1, hour = c.hour}
result := format_date(dt, "03 PM")
testing.expect_value(t, result, c.expected)
}
}
@(test)
test_format_date_hour12_unpadded :: proc(t: ^testing.T) {
one_am := Date_Components{year = 2026, month = 1, day = 1, hour = 1}
testing.expect_value(t, format_date(one_am, "3"), "1")
one_pm := Date_Components{year = 2026, month = 1, day = 1, hour = 13}
testing.expect_value(t, format_date(one_pm, "3"), "1")
}
@(test)
test_format_date_am_pm_lowercase :: proc(t: ^testing.T) {
afternoon := Date_Components{year = 2026, month = 1, day = 1, hour = 13}
testing.expect_value(t, format_date(afternoon, "pm"), "pm")
morning := Date_Components{year = 2026, month = 1, day = 1, hour = 9}
testing.expect_value(t, format_date(morning, "pm"), "am")
}
@(test)
test_format_date_minute_second_padding :: proc(t: ^testing.T) {
dt := Date_Components{year = 2026, month = 1, day = 1, minute = 4, second = 5}
testing.expect_value(t, format_date(dt, "04:05"), "04:05")
testing.expect_value(t, format_date(dt, "4:5"), "4:5")
}
@(test)
test_format_date_month_day_numeric_padding :: proc(t: ^testing.T) {
dt := Date_Components{year = 2026, month = 3, day = 5}
testing.expect_value(t, format_date(dt, "01"), "03")
testing.expect_value(t, format_date(dt, "1"), "3")
testing.expect_value(t, format_date(dt, "02"), "05")
testing.expect_value(t, format_date(dt, "2"), "5")
}
@(test)
test_format_date_mst_always_utc :: proc(t: ^testing.T) {
// Date_Components carries no offset yet, so MST is a hardcoded
// placeholder until real timezone support lands.
dt := Date_Components{year = 2026, month = 1, day = 1, hour = 12}
result := format_date(dt, "MST")
testing.expect_value(t, result, "UTC")
}
@(test)
test_format_date_literal_passthrough :: proc(t: ^testing.T) {
dt := Date_Components{year = 2026, month = 1, day = 1}
result := format_date(dt, "Year: 2006!")
testing.expect_value(t, result, "Year: 2026!")
}
@(test)
test_format_date_combined_go_reference_layout :: proc(t: ^testing.T) {
// 2023-10-15 is a Sunday.
dt := Date_Components{year = 2023, month = 10, day = 15, hour = 13, minute = 18, second = 50}
result := format_date(dt, "Mon Jan 2 15:04:05 MST 2006")
testing.expect_value(t, result, "Sun Oct 15 13:18:50 UTC 2023")
}
+381 -170
View File
@@ -1,28 +1,35 @@
package mustache
import "core:fmt"
import "core:log"
import "core:reflect"
import "core:strings"
// ---------------------------------------------------------------------------
// Error types
// ---------------------------------------------------------------------------
Syntax_Error :: struct {
msg: string,
pos: int,
}
Data_Error :: struct {
msg: string,
}
Partial_Error :: struct {
name: string,
msg: string,
Error_Kind :: enum {
Syntax, // parse-time: malformed template
Data, // render-time: template fine, data wrong (e.g. filter misuse)
}
Render_Error :: union {
Syntax_Error,
Data_Error,
Partial_Error,
Error_Body :: struct {
msg: string,
pos: int,
kind: Error_Kind,
}
// Error is nil when no error occurred.
Error :: union { Error_Body }
// body unwraps the Error_Body from a non-nil Error.
// Precondition: err != nil.
body :: proc(err: Error) -> Error_Body {
switch e in err {
case Error_Body: return e
case: return {}
}
}
// ---------------------------------------------------------------------------
@@ -47,18 +54,18 @@ Node :: struct {
filters: [dynamic; MAX_PIPES]Pipe_Filter,
is_dynamic: bool,
indent: string,
first_child: int,
child_count: int,
children: []Node,
content: string,
pos: int,
}
// node_span returns the number of flat-array entries a node occupies:
// 1 for leaf nodes, 1 + child_count for container nodes (whose children
// 1 for leaf nodes, 1 + len(children) for container nodes (whose children
// are stored contiguously after them in the array).
node_span :: proc(n: Node) -> int {
#partial switch n.kind {
case .Section, .Inverted, .Parent, .Block:
return 1 + n.child_count
return 1 + len(n.children)
case:
return 1
}
@@ -67,12 +74,20 @@ node_span :: proc(n: Node) -> int {
Template :: struct {
nodes: [dynamic]Node,
source: string,
path: string,
}
Block_Override :: struct {
all_nodes: []Node,
first: int,
count: int,
nodes: []Node,
source: Template,
}
// Indent_State threads partial-indent tracking through render_nodes so
// the renderer can apply indentation at render time instead of reparsing
// the partial's source with indentation baked in.
Indent_State :: struct {
indent: string,
at_line_start: bool,
}
delete_template :: proc(tmpl: ^Template) {
@@ -94,11 +109,12 @@ delete_partials :: proc(partials: map[string]Template) {
parse :: proc(
source: string,
path := "",
allocator := context.allocator,
tokens_allocator := context.temp_allocator,
) -> (
tmpl: Template,
err: Render_Error,
err: Error,
) {
tokens, terr := tokenize(source, tokens_allocator)
if terr != nil {
@@ -111,7 +127,8 @@ parse :: proc(
return {}, err
}
tmpl.source = source
deindent_blocks(tmpl.nodes[:], 0, len(tmpl.nodes), allocator)
tmpl.path = path
deindent_blocks(tmpl.nodes[:], allocator)
return tmpl, nil
}
@@ -122,7 +139,7 @@ render :: proc(
allocator := context.allocator,
) -> (
result: string,
err: Render_Error,
err: Error,
) {
builder: strings.Builder
strings.builder_init(&builder, allocator)
@@ -133,7 +150,7 @@ render :: proc(
append(&ctx, data)
all_nodes := tmpl.nodes[:]
err = render_nodes(all_nodes, all_nodes, &ctx, partials, &builder)
err = render_nodes(tmpl, all_nodes, &ctx, partials, &builder)
if err != nil {
return result, err
}
@@ -154,11 +171,12 @@ parse_tokens :: proc(
allocator := context.allocator,
) -> (
nodes: [dynamic]Node,
err: Render_Error,
err: Error,
) {
nodes = make([dynamic]Node, 0, len(tokens), allocator)
pos := 0
err = parse_section(tokens, &pos, &nodes, "", source, allocator)
err = parse_section(tokens, &pos, &nodes, "", source, allocator, 0)
assert(len(nodes) <= cap(nodes))
return
}
@@ -169,23 +187,25 @@ parse_section :: proc(
end_tag: string,
source: string,
allocator := context.allocator,
) -> Render_Error {
open_pos: int = 0,
) -> Error {
for pos^ < len(tokens) {
tok := tokens[pos^]
switch tok.kind {
case .Text:
append(nodes, Node{kind = .Text, text = tok.value, first_child = -1})
append(nodes, Node{kind = .Text, text = tok.value, pos = tok.pos})
pos^ += 1
case .Variable:
idx := len(nodes)
append(nodes, Node{kind = .Variable, first_child = -1})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters)
append(nodes, Node{kind = .Variable})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters, tok.pos)
if perr != nil {
return Syntax_Error {
msg = fmt.tprintf("pipe parse error in '{{%s}}': %v", tok.value, perr),
return Error_Body {
msg = fmt.tprintf("pipe parse error in '{{{{%s}}}}': %v", tok.value, perr),
pos = tok.pos,
kind = .Syntax,
}
}
nodes[idx].key = pipe_key
@@ -193,12 +213,13 @@ parse_section :: proc(
case .Unescaped:
idx := len(nodes)
append(nodes, Node{kind = .Unescaped, first_child = -1})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters)
append(nodes, Node{kind = .Unescaped})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters, tok.pos)
if perr != nil {
return Syntax_Error {
msg = fmt.tprintf("pipe parse error in '{{&%s}}': %v", tok.value, perr),
return Error_Body {
msg = fmt.tprintf("pipe parse error in '{{{{&%s}}}}': %v", tok.value, perr),
pos = tok.pos,
kind = .Syntax,
}
}
nodes[idx].key = pipe_key
@@ -212,20 +233,20 @@ parse_section :: proc(
idx := len(nodes)
content_start := 0
if pos^ < len(tokens) {content_start = tokens[pos^].pos}
append(nodes, Node{kind = .Section, first_child = -1})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters)
append(nodes, Node{kind = .Section, pos = tok.pos})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters, tok.pos)
if perr != nil {
return Syntax_Error {
msg = fmt.tprintf("pipe parse error in '{{#%s}}': %v", tok.value, perr),
return Error_Body {
msg = fmt.tprintf("pipe parse error in '{{{{#%s}}}}': %v", tok.value, perr),
pos = tok.pos,
kind = .Syntax,
}
}
nodes[idx].key = pipe_key
parse_section(tokens, pos, nodes, pipe_key, source, allocator) or_return
parse_section(tokens, pos, nodes, pipe_key, source, allocator, tok.pos) or_return
close_pos := 0
if pos^ - 1 >= 0 && pos^ - 1 < len(tokens) {close_pos = tokens[pos^ - 1].pos}
nodes[idx].first_child = idx + 1
nodes[idx].child_count = len(nodes) - idx - 1
nodes[idx].children = nodes[idx + 1:len(nodes)]
nodes[idx].content = source[content_start:close_pos]
case .Inverted_Open:
@@ -233,30 +254,31 @@ parse_section :: proc(
idx := len(nodes)
content_start := 0
if pos^ < len(tokens) {content_start = tokens[pos^].pos}
append(nodes, Node{kind = .Inverted, first_child = -1})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters)
append(nodes, Node{kind = .Inverted, pos = tok.pos})
pipe_key, perr := parse_pipeline(tok.value, &nodes[idx].filters, tok.pos)
if perr != nil {
return Syntax_Error {
msg = fmt.tprintf("pipe parse error in '{{^%s}}': %v", tok.value, perr),
return Error_Body {
msg = fmt.tprintf("pipe parse error in '{{{{^%s}}}}': %v", tok.value, perr),
pos = tok.pos,
kind = .Syntax,
}
}
nodes[idx].key = pipe_key
parse_section(tokens, pos, nodes, pipe_key, source, allocator) or_return
parse_section(tokens, pos, nodes, pipe_key, source, allocator, tok.pos) or_return
close_pos := 0
if pos^ - 1 >= 0 && pos^ - 1 < len(tokens) {close_pos = tokens[pos^ - 1].pos}
nodes[idx].first_child = idx + 1
nodes[idx].child_count = len(nodes) - idx - 1
nodes[idx].children = nodes[idx + 1:len(nodes)]
nodes[idx].content = source[content_start:close_pos]
case .Section_Close:
if strings.contains(tok.value, "|") {
return Syntax_Error {
return Error_Body {
msg = fmt.tprintf(
"pipe expression not allowed in close tag '{{/%s}}' — use the bare key",
"pipe expression not allowed in close tag '{{{{/%s}}}}' — use the bare key",
tok.value,
),
pos = tok.pos,
kind = .Syntax,
}
}
if end_tag != "" && tok.value == end_tag {
@@ -264,14 +286,16 @@ parse_section :: proc(
return nil
}
if end_tag == "" {
return Syntax_Error {
msg = fmt.tprintf("unexpected {{/%s}}", tok.value),
return Error_Body {
msg = fmt.tprintf("unexpected {{{{/%s}}}}", tok.value),
pos = tok.pos,
kind = .Syntax,
}
}
return Syntax_Error {
msg = fmt.tprintf("expected {{/%s}}, got {{/%s}}", end_tag, tok.value),
return Error_Body {
msg = fmt.tprintf("expected {{{{/%s}}}}, got {{{{/%s}}}}", end_tag, tok.value),
pos = tok.pos,
kind = .Syntax,
}
case .Partial:
@@ -282,7 +306,7 @@ parse_section :: proc(
key = tok.value,
is_dynamic = tok.is_dynamic,
indent = tok.indent,
first_child = -1,
pos = tok.pos,
},
)
pos^ += 1
@@ -292,27 +316,39 @@ parse_section :: proc(
idx := len(nodes)
append(
nodes,
Node{kind = .Parent, key = tok.value, indent = tok.indent, first_child = -1},
Node {
kind = .Parent,
key = tok.value,
indent = tok.indent,
pos = tok.pos,
},
)
parse_section(tokens, pos, nodes, tok.value, source, allocator) or_return
nodes[idx].first_child = idx + 1
nodes[idx].child_count = len(nodes) - idx - 1
parse_section(tokens, pos, nodes, tok.value, source, allocator, tok.pos) or_return
nodes[idx].children = nodes[idx + 1:len(nodes)]
case .Block_Open:
pos^ += 1
idx := len(nodes)
append(
nodes,
Node{kind = .Block, key = tok.value, indent = tok.indent, first_child = -1},
Node {
kind = .Block,
key = tok.value,
indent = tok.indent,
pos = tok.pos,
},
)
parse_section(tokens, pos, nodes, tok.value, source, allocator) or_return
nodes[idx].first_child = idx + 1
nodes[idx].child_count = len(nodes) - idx - 1
parse_section(tokens, pos, nodes, tok.value, source, allocator, tok.pos) or_return
nodes[idx].children = nodes[idx + 1:len(nodes)]
}
}
if end_tag != "" {
return Syntax_Error{msg = fmt.tprintf("unclosed section '{{#%s}}'", end_tag)}
return Error_Body {
msg = fmt.tprintf("unclosed section '{{{{#%s}}}}'", end_tag),
pos = open_pos,
kind = .Syntax,
}
}
return nil
}
@@ -321,43 +357,38 @@ parse_section :: proc(
// Post-parse: de-indent block content
// ---------------------------------------------------------------------------
deindent_blocks :: proc(all_nodes: []Node, start: int, end: int, allocator := context.allocator) {
i := start
for i < end {
#partial switch all_nodes[i].kind {
deindent_blocks :: proc(nodes: []Node, allocator := context.allocator) {
i := 0
for i < len(nodes) {
#partial switch nodes[i].kind {
case .Block:
if all_nodes[i].child_count > 0 {
cs := all_nodes[i].first_child
ce := cs + all_nodes[i].child_count
deindent_blocks(all_nodes, cs, ce, allocator)
children := all_nodes[cs:ce]
if len(nodes[i].children) > 0 {
children := nodes[i].children
deindent_blocks(children, allocator)
common := find_common_indent(children)
if len(common) > 0 {
if len(all_nodes[i].indent) == 0 {
all_nodes[i].indent = common
if len(nodes[i].indent) == 0 {
nodes[i].indent = common
}
for j := cs; j < ce; {
if all_nodes[j].kind == .Text && len(all_nodes[j].text) > 0 {
all_nodes[j].text = remove_line_indent(
all_nodes[j].text,
for j := 0; j < len(children); {
if children[j].kind == .Text && len(children[j].text) > 0 {
children[j].text = remove_line_indent(
children[j].text,
common,
allocator,
)
}
j += node_span(all_nodes[j])
j += node_span(children[j])
}
}
}
case .Section, .Inverted, .Parent:
if all_nodes[i].child_count > 0 {
cs := all_nodes[i].first_child
ce := cs + all_nodes[i].child_count
deindent_blocks(all_nodes, cs, ce, allocator)
if len(nodes[i].children) > 0 {
deindent_blocks(nodes[i].children, allocator)
}
}
i += node_span(all_nodes[i])
i += node_span(nodes[i])
}
}
@@ -371,9 +402,16 @@ find_common_indent :: proc(children: []Node) -> string {
text := children[i].text
if len(text) > 0 {
line_start := 0
for j in 0 ..= len(text) {
if j == len(text) || text[j] == '\n' {
line := text[line_start:j]
for {
// Bulk-scan to next newline (AVX2-backed) instead of byte-by-byte.
rel := strings.index_byte(text[line_start:], '\n')
line_end: int
if rel < 0 {
line_end = len(text)
} else {
line_end = line_start + rel
}
line := text[line_start:line_end]
if len(strings.trim_space(line)) > 0 {
ws := leading_whitespace(line)
if !found {
@@ -383,8 +421,10 @@ find_common_indent :: proc(children: []Node) -> string {
common = ws
}
}
line_start = j + 1
if rel < 0 {
break
}
line_start = line_end + 1
}
}
}
@@ -420,17 +460,20 @@ remove_line_indent :: proc(s: string, indent: string, allocator := context.alloc
if at_line_start {
if i + len(indent) <= len(s) && s[i:i + len(indent)] == indent {
i += len(indent)
at_line_start = false
continue
}
at_line_start = false
}
append(&buf, s[i])
if s[i] == '\n' {
// Bulk-append up to and including the next newline (AVX2-backed).
rel := strings.index_byte(s[i:], '\n')
if rel < 0 {
append(&buf, s[i:])
break
}
next := i + rel
append(&buf, s[i:next + 1])
i = next + 1
at_line_start = true
}
i += 1
}
return string(buf[:])
}
@@ -439,34 +482,6 @@ remove_line_indent :: proc(s: string, indent: string, allocator := context.alloc
// Indentation helpers
// ---------------------------------------------------------------------------
indent_lines :: proc(source: string, indent: string) -> string {
if len(indent) == 0 || len(source) == 0 {
return source
}
b: strings.Builder
strings.builder_init(&b, context.temp_allocator)
write_indented(&b, indent, source)
return strings.to_string(b)
}
write_indented :: proc(b: ^strings.Builder, indent: string, content: string) {
if len(indent) == 0 || len(content) == 0 {
strings.write_string(b, content)
return
}
at_line_start := true
for i in 0 ..< len(content) {
if at_line_start {
strings.write_string(b, indent)
at_line_start = false
}
strings.write_byte(b, content[i])
if content[i] == '\n' {
at_line_start = true
}
}
}
render_template :: proc(
pt: Template,
ctx: ^[dynamic]any,
@@ -474,13 +489,37 @@ render_template :: proc(
b: ^strings.Builder,
blocks: map[string]Block_Override,
indent: string,
) -> Render_Error {
if len(indent) > 0 && len(pt.source) > 0 {
indented := indent_lines(pt.source, indent)
reparse := parse(indented, context.temp_allocator, context.temp_allocator) or_return
return render_nodes(reparse.nodes[:], reparse.nodes[:], ctx, partials, b, blocks)
) -> Error {
if len(indent) > 0 {
state := Indent_State{indent = indent, at_line_start = false}
strings.write_string(b, indent) // first line always gets indent
return render_nodes(pt, pt.nodes[:], ctx, partials, b, blocks, &state)
}
return render_nodes(pt, pt.nodes[:], ctx, partials, b, blocks, nil)
}
write_indented :: proc(b: ^strings.Builder, indent: string, content: string, at_line_start: ^bool) {
if len(indent) == 0 || len(content) == 0 {
strings.write_string(b, content)
return
}
i := 0
for i < len(content) {
if at_line_start^ {
strings.write_string(b, indent)
at_line_start^ = false
}
// Bulk-write up to and including the next newline (AVX2-backed).
rel := strings.index_byte(content[i:], '\n')
if rel < 0 {
strings.write_string(b, content[i:])
return
}
next := i + rel
strings.write_string(b, content[i:next + 1])
i = next + 1
at_line_start^ = true
}
return render_nodes(pt.nodes[:], pt.nodes[:], ctx, partials, b, blocks)
}
// ---------------------------------------------------------------------------
@@ -488,42 +527,60 @@ render_template :: proc(
// ---------------------------------------------------------------------------
render_nodes :: proc(
all_nodes: []Node,
current: Template,
nodes: []Node,
ctx: ^[dynamic]any,
partials: map[string]Template,
b: ^strings.Builder,
blocks: map[string]Block_Override = nil,
) -> Render_Error {
indent_state: ^Indent_State = nil,
) -> Error {
i := 0
for i < len(nodes) {
node := nodes[i]
switch node.kind {
case .Text:
if indent_state != nil {
write_indented(b, indent_state.indent, node.text, &indent_state.at_line_start)
} else {
strings.write_string(b, node.text)
}
i += 1
case .Variable:
if indent_state != nil && indent_state.at_line_start {
strings.write_string(b, indent_state.indent)
indent_state.at_line_start = false
}
val := resolve_name(node.key, ctx[:])
if val == nil {
warn_unknown_key(current, ctx[:], node)
}
if len(node.filters) > 0 {
transformed, perr := apply_pipeline(val, node.filters[:])
transformed, perr := apply_pipeline(val, node.filters[:], node.pos, ctx[:])
if perr != nil {
return perr
}
val = transformed
}
if result_str, ok := call_interp_lambda(val); ok {
sub_tpl, perr := parse(result_str, context.temp_allocator, context.temp_allocator)
sub_tpl, perr := parse(
result_str,
fmt.tprintf("<lambda output from '%s'>", node.key),
context.temp_allocator,
context.temp_allocator,
)
if perr == nil {
temp: strings.Builder
strings.builder_init(&temp, context.temp_allocator)
render_nodes(
sub_tpl.nodes[:],
sub_tpl,
sub_tpl.nodes[:],
ctx,
partials,
&temp,
blocks,
nil,
) or_return
write_value(b, strings.to_string(temp), escape = true)
}
@@ -533,26 +590,39 @@ render_nodes :: proc(
i += 1
case .Unescaped:
if indent_state != nil && indent_state.at_line_start {
strings.write_string(b, indent_state.indent)
indent_state.at_line_start = false
}
val := resolve_name(node.key, ctx[:])
if val == nil {
warn_unknown_key(current, ctx[:], node)
}
if len(node.filters) > 0 {
transformed, perr := apply_pipeline(val, node.filters[:])
transformed, perr := apply_pipeline(val, node.filters[:], node.pos, ctx[:])
if perr != nil {
return perr
}
val = transformed
}
if result_str, ok := call_interp_lambda(val); ok {
sub_tpl, perr := parse(result_str, context.temp_allocator, context.temp_allocator)
sub_tpl, perr := parse(
result_str,
fmt.tprintf("<lambda output from '%s'>", node.key),
context.temp_allocator,
context.temp_allocator,
)
if perr == nil {
temp: strings.Builder
strings.builder_init(&temp, context.temp_allocator)
render_nodes(
sub_tpl.nodes[:],
sub_tpl,
sub_tpl.nodes[:],
ctx,
partials,
&temp,
blocks,
nil,
) or_return
write_value(b, strings.to_string(temp), escape = false)
}
@@ -563,57 +633,76 @@ render_nodes :: proc(
case .Section:
val := resolve_name(node.key, ctx[:])
if val == nil {
warn_unknown_key(current, ctx[:], node)
}
if len(node.filters) > 0 {
transformed, perr := apply_pipeline(val, node.filters[:])
transformed, perr := apply_pipeline(val, node.filters[:], node.pos, ctx[:])
if perr != nil {
return perr
}
val = transformed
}
if result_str, ok := call_section_lambda(val, node.content); ok {
sub_tpl, perr := parse(result_str, context.temp_allocator, context.temp_allocator)
sub_tpl, perr := parse(
result_str,
fmt.tprintf("<lambda output from '%s'>", node.key),
context.temp_allocator,
context.temp_allocator,
)
if perr == nil {
render_nodes(
sub_tpl.nodes[:],
sub_tpl,
sub_tpl.nodes[:],
ctx,
partials,
b,
blocks,
nil,
) or_return
}
} else if is_truthy(val) {
children := all_nodes[node.first_child:node.first_child + node.child_count]
children := node.children
elem_info, count, data := list_info(val)
if elem_info != nil {
for j in 0 ..< count {
elem := extract_list_element(elem_info, data, j)
append(ctx, elem)
defer pop(ctx)
render_nodes(all_nodes, children, ctx, partials, b, blocks) or_return
render_nodes(
current,
children,
ctx,
partials,
b,
blocks,
indent_state,
) or_return
}
} else {
append(ctx, val)
defer pop(ctx)
render_nodes(all_nodes, children, ctx, partials, b, blocks) or_return
render_nodes(current, children, ctx, partials, b, blocks, indent_state) or_return
}
}
i += 1 + node.child_count
i += 1 + len(node.children)
case .Inverted:
val := resolve_name(node.key, ctx[:])
if val == nil {
warn_unknown_key(current, ctx[:], node)
}
if len(node.filters) > 0 {
transformed, perr := apply_pipeline(val, node.filters[:])
transformed, perr := apply_pipeline(val, node.filters[:], node.pos, ctx[:])
if perr != nil {
return perr
}
val = transformed
}
if !is_truthy(val) {
children := all_nodes[node.first_child:node.first_child + node.child_count]
render_nodes(all_nodes, children, ctx, partials, b, blocks) or_return
render_nodes(current, node.children, ctx, partials, b, blocks, indent_state) or_return
}
i += 1 + node.child_count
i += 1 + len(node.children)
case .Partial:
name := node.key
@@ -622,61 +711,74 @@ render_nodes :: proc(
name = any_to_string(val)
}
pt, found := partials[name]
if found {
if !found {
warn_missing_partial(current, partials, node, name)
} else {
render_template(pt, ctx, partials, b, nil, node.indent) or_return
if indent_state != nil {
indent_state.at_line_start = false
}
}
i += 1
case .Block:
content_nodes: []Node
content_pool: []Node
content_blocks := blocks
render_current := current
found_override := false
if blocks != nil {
if o, ok := blocks[node.key]; ok {
content_nodes = o.all_nodes[o.first:o.first + o.count]
content_pool = o.all_nodes
content_nodes = o.nodes
found_override = true
render_current = o.source
}
}
if !found_override {
content_nodes = all_nodes[node.first_child:node.first_child + node.child_count]
content_pool = all_nodes
content_nodes = node.children
}
if len(node.indent) > 0 {
temp: strings.Builder
strings.builder_init(&temp, context.temp_allocator)
render_nodes(
content_pool,
render_current,
content_nodes,
ctx,
partials,
&temp,
content_blocks,
nil,
) or_return
write_indented(b, node.indent, strings.to_string(temp))
at_ls := true
write_indented(b, node.indent, strings.to_string(temp), &at_ls)
} else {
render_nodes(
content_pool,
render_current,
content_nodes,
ctx,
partials,
b,
content_blocks,
indent_state,
) or_return
}
i += 1 + node.child_count
i += 1 + len(node.children)
case .Parent:
parent_children := all_nodes[node.first_child:node.first_child + node.child_count]
merged := merge_block_overrides(parent_children, all_nodes, blocks)
parent_children := node.children
merged := merge_block_overrides(parent_children, blocks, current)
pt, found := partials[node.key]
if found {
if !found {
warn_missing_partial(current, partials, node, node.key)
} else {
warn_unmatched_block_overrides(current, pt, parent_children)
render_template(pt, ctx, partials, b, merged, node.indent) or_return
if indent_state != nil {
indent_state.at_line_start = false
}
i += 1 + node.child_count
}
i += 1 + len(node.children)
}
}
return nil
@@ -684,8 +786,8 @@ render_nodes :: proc(
merge_block_overrides :: proc(
children: []Node,
all_nodes: []Node,
existing: map[string]Block_Override,
source: Template,
) -> map[string]Block_Override {
result := make(map[string]Block_Override, context.temp_allocator)
@@ -699,9 +801,8 @@ merge_block_overrides :: proc(
if child.kind == .Block {
if _, exists := result[child.key]; !exists {
result[child.key] = Block_Override {
all_nodes = all_nodes,
first = child.first_child,
count = child.child_count,
nodes = child.children,
source = source,
}
}
}
@@ -711,3 +812,113 @@ merge_block_overrides :: proc(
return result
}
// warn_unknown_key checks whether the missing key is a genuine typo (vs. a
// legitimate path through a user-defined map) and, if so, emits a diagnostic
// warning with the closest field-name suggestion via Levenshtein.
warn_unknown_key :: proc(current: Template, ctx: []any, node: Node) {
// `{{.}}` and dot-prefixed names refer to the current context — always valid.
if node.key == "." || (len(node.key) > 0 && node.key[0] == '.') {
return
}
path_ok, missing, available := validate_key_path(ctx, node.key)
if path_ok {
return
}
hint := ""
if len(available) > 0 {
suggestion := suggest_correction(available, missing)
if suggestion != "" {
hint = fmt.tprintf("did you mean '%s'?", suggestion)
}
}
msg := fmt.tprintf("unknown key '%s'", node.key)
path := current.path
if path == "" {
path = "<input>"
}
diag := format_error(path, current.source, node.pos, msg, hint, colorize = should_colorize())
log.warnf("%s", diag)
}
// warn_missing_partial emits a warning when a `{{> name}}` or `{{<name}}` tag
// references a partial that isn't in the partials map.
warn_missing_partial :: proc(
current: Template,
partials: map[string]Template,
node: Node,
name: string,
) {
hint := ""
available := collect_partial_names(partials)
suggestion := suggest_correction(available, name)
if suggestion != "" {
hint = fmt.tprintf("did you mean '%s'?", suggestion)
}
msg := fmt.tprintf("partial '%s' not found", name)
path := current.path
if path == "" {
path = "<input>"
}
diag := format_error(path, current.source, node.pos, msg, hint, colorize = should_colorize())
log.warnf("%s", diag)
}
// warn_unmatched_block_overrides checks each `{{$name}}...{{/name}}` block
// defined inside a `{{<parent}}` tag and warns when the name doesn't match
// any block in the parent template.
warn_unmatched_block_overrides :: proc(
current: Template,
parent: Template,
parent_children: []Node,
) {
if len(parent_children) == 0 {
return
}
available := collect_block_names(parent)
parent_path := parent.path
if parent_path == "" {
parent_path = "<input>"
}
for child in parent_children {
if child.kind != .Block {
continue
}
matched := false
for name in available {
if name == child.key {
matched = true
break
}
}
if matched {
continue
}
hint := ""
suggestion := suggest_correction(available, child.key)
if suggestion != "" {
hint = fmt.tprintf("did you mean '%s'?", suggestion)
}
msg := fmt.tprintf(
"block override '%s' has no match in parent template '%s'",
child.key,
parent_path,
)
path := current.path
if path == "" {
path = "<input>"
}
diag := format_error(
path,
current.source,
child.pos,
msg,
hint,
colorize = should_colorize(),
)
log.warnf("%s", diag)
}
}
+6 -1
View File
@@ -18,7 +18,12 @@ leak_parse_free_tokens :: proc(t: ^testing.T) {
mem.dynamic_arena_init(&arena)
defer mem.dynamic_arena_destroy(&arena)
tmpl, err := parse("Hello {{name}}!", context.allocator, mem.dynamic_arena_allocator(&arena))
tmpl, err := parse(
"Hello {{name}}!",
"<test>",
context.allocator,
mem.dynamic_arena_allocator(&arena),
)
testing.expect(t, err == nil)
defer delete_template(&tmpl)
}
+181 -52
View File
@@ -1,6 +1,7 @@
package mustache
import "core:fmt"
import "core:log"
import "core:reflect"
import "core:strings"
import "core:time"
@@ -12,6 +13,8 @@ MAX_PIPES :: 8
// No filter accepts more than 2 args.
MAX_PIPE_ARGS :: 2
DEFAULT_DATE_FORMAT :: "2 Jan 2006"
Pipe_Filter :: struct {
op: string,
args: [dynamic; MAX_PIPE_ARGS]string,
@@ -22,14 +25,60 @@ Group :: struct {
items: [dynamic]any,
}
// is_pipe_space reports whether c is whitespace for the purposes of
// tokenizing a filter segment.
is_pipe_space :: proc(c: u8) -> bool {
return c == ' ' || c == '\t' || c == '\n' || c == '\r'
}
// tokenize_fields splits seg on whitespace like strings.fields, but a
// double-quoted span (spaces allowed inside) becomes a single token. The
// quote characters are kept in the token (not stripped) so callers can
// distinguish a quoted literal from a bare key name. No escape sequences.
tokenize_fields :: proc(seg: string, pos: int) -> (tokens: [dynamic]string, err: Error) {
i := 0
for i < len(seg) {
for i < len(seg) && is_pipe_space(seg[i]) {
i += 1
}
if i >= len(seg) {
break
}
if seg[i] == '"' {
start := i
j := i + 1
for j < len(seg) && seg[j] != '"' {
j += 1
}
if j >= len(seg) {
return tokens, Error_Body {
msg = fmt.tprintf("unterminated string literal: %s", seg),
pos = pos,
kind = .Syntax,
}
}
append(&tokens, seg[start:j + 1])
i = j + 1
} else {
start := i
for i < len(seg) && !is_pipe_space(seg[i]) {
i += 1
}
append(&tokens, seg[start:i])
}
}
return tokens, nil
}
// Returned strings are slices into content — no cloning, lifetime bound to
// the caller's source.
parse_pipeline :: proc(
content: string,
filters_out: ^[dynamic; MAX_PIPES]Pipe_Filter,
pos: int,
) -> (
key: string,
err: Render_Error,
err: Error,
) {
if !strings.contains(content, "|") {
key = strings.trim_space(content)
@@ -40,18 +89,20 @@ parse_pipeline :: proc(
filter_count := len(segments) - 1
if filter_count > MAX_PIPES {
return "", Syntax_Error {
return "", Error_Body {
msg = fmt.tprintf(
"pipe expression has %d filters, max is %d",
filter_count,
MAX_PIPES,
),
pos = pos,
kind = .Syntax,
}
}
key = strings.trim_space(segments[0])
if len(key) == 0 {
return "", Syntax_Error{msg = "pipe expression missing key"}
return "", Error_Body{msg = "pipe expression missing key", pos = pos, kind = .Syntax}
}
if filter_count == 0 {
@@ -61,23 +112,29 @@ parse_pipeline :: proc(
for i in 0 ..< filter_count {
seg := strings.trim_space(segments[i + 1])
if len(seg) == 0 {
return "", Syntax_Error{msg = "empty filter"}
return "", Error_Body{msg = "empty filter", pos = pos, kind = .Syntax}
}
tokens := strings.fields(seg)
tokens, terr := tokenize_fields(seg, pos)
if terr != nil {
delete(tokens)
return "", terr
}
if len(tokens) == 0 {
return "", Syntax_Error{msg = "filter missing op name"}
return "", Error_Body{msg = "filter missing op name", pos = pos, kind = .Syntax}
}
arg_count := len(tokens) - 1
if arg_count > MAX_PIPE_ARGS {
return "", Syntax_Error {
return "", Error_Body {
msg = fmt.tprintf(
"filter '%s' has %d args, max is %d",
tokens[0],
arg_count,
MAX_PIPE_ARGS,
),
pos = pos,
kind = .Syntax,
}
}
@@ -94,77 +151,143 @@ parse_pipeline :: proc(
return key, nil
}
apply_pipeline :: proc(value: any, filters: []Pipe_Filter) -> (any, Render_Error) {
current := value
apply_pipeline :: proc(
value: any,
filters: []Pipe_Filter,
pos: int,
ctx: []any,
) -> (
current: any,
err: Error,
) {
current = value
for &filter in filters {
result, err := apply_filter(current, &filter)
if err != nil {
return nil, err
current = apply_filter(current, &filter, pos, ctx) or_return
log.debugf("applied: filter=%v before=%s after=%s pos=%d", filter, value, current, pos)
}
current = result
}
return current, nil
return
}
apply_filter :: proc(value: any, filter: ^Pipe_Filter) -> (any, Render_Error) {
// resolve_format_string looks up name as a context key and returns its
// string value. Used both for an explicit bare-key filter arg (e.g.
// `format long`) and for the implicit "date_format" fallback when no arg
// is given.
resolve_format_string :: proc(name: string, ctx: []any, pos: int) -> (string, Error) {
raw := resolve_name(name, ctx)
if raw == nil {
return "", Error_Body {
msg = fmt.tprintf("unable to resolve date format key '%s'", name),
pos = pos,
kind = .Data,
}
}
str, ok := reflect.as_string(raw)
if !ok {
return "", Error_Body {
msg = fmt.tprintf("date format key '%s' is not a string", name),
pos = pos,
kind = .Data,
}
}
return str, nil
}
// TODO: diagnostics don't show anything relevent
apply_filter :: proc(value: any, filter: ^Pipe_Filter, pos: int, ctx: []any) -> (any, Error) {
switch filter.op {
case "group_by":
return apply_group_by(value, filter.args[:])
return apply_group_by(value, filter.args[:], pos)
case "format":
str, ok := reflect.as_string(value)
if !ok {
return value, Data_Error{msg = "format may only be used on dates"}
return value, Error_Body {
msg = "format may only be used on dates",
pos = pos,
kind = .Data,
}
}
date_format: string
if len(filter.args) > 0 {
arg := filter.args[0]
if len(arg) >= 2 && arg[0] == '"' && arg[len(arg) - 1] == '"' {
date_format = arg[1:len(arg) - 1]
} else {
return apply_format(str, filter.args[:])
df, ferr := resolve_format_string(arg, ctx, pos)
if ferr != nil {
return value, ferr
}
date_format = df
}
} else {
df, ferr := resolve_format_string("date_format", ctx, pos)
if ferr != nil {
return value, ferr
}
date_format = df
}
str2, err := apply_format(str, filter.args[:], pos, date_format)
if err != nil {
return value, err
} else {
return any{new_clone(str2, context.temp_allocator), typeid_of(string)}, nil
}
case:
return nil, Data_Error{msg = fmt.tprintf("unknown pipe op '%s'", filter.op)}
return nil, Error_Body {
msg = fmt.tprintf("unknown pipe op '%s'", filter.op),
pos = pos,
kind = .Data,
}
}
}
// apply_format formats an ISO 8601 date string as a display string
// (e.g. "2026-03-15T08:49:54-04:00" → "15 Mar 2026"). Invalid input
// (empty, too-short, or unparseable) returns a `Data_Error`. Templates
// that need to skip dateless pages should gate with a section:
// {{#date}}<time datetime="{{.}}">{{. | format}}</time>{{/date}}
// The section's truthiness check catches empty before the filter runs.
//
// Currently ignores args; planned to accept Go reference-date format
// strings in the future.
//
// Accepts any of these ISO 8601 forms (date prefix is invariant):
// 2023-10-15T13:18:50-07:00
// 2023-10-15T13:18:50-0700
// 2023-10-15T13:18:50Z
// 2023-10-15T13:18:50
// 2023-10-15
apply_format :: proc(iso: string, args: []string) -> (result: any, err: Render_Error) {
if len(iso) < 10 {
return nil, Data_Error{msg = "format may only be used on dates"}
apply_format :: proc(
iso: string,
args: []string,
pos: int,
date_format: string,
) -> (
result: string,
err: Error,
) {
fmt_str := date_format
if fmt_str == "" {
log.errorf(
"format pipe used but no date format configured (set date.format in thor.json) Default will be used",
)
fmt_str = DEFAULT_DATE_FORMAT
}
year := iso[:4]
month_num := (int(iso[5]) - 0x30) * 10 + (int(iso[6]) - 0x30)
day_num := (int(iso[8]) - 0x30) * 10 + (int(iso[9]) - 0x30)
if month_num < 1 || month_num > 12 {
return nil, Data_Error{msg = fmt.tprintf("invalid date: \"%s\"", iso)}
components, ok := parse_iso_date(iso)
if !ok {
return "", Error_Body {
msg = fmt.tprintf("invalid date: \"%s\"", iso),
pos = pos,
kind = .Data,
}
}
month := fmt.tprintf("%s", time.Month(month_num))[:3]
return fmt.tprintf("%d %s %s", day_num, month, year), nil
log.debugf("date: '%s' format: '%s'", iso, date_format)
return format_date(components, fmt_str), nil
}
// Groups preserve first-appearance order from the input list.
apply_group_by :: proc(value: any, args: []string) -> (result: any, err: Render_Error) {
apply_group_by :: proc(value: any, args: []string, pos: int) -> (result: any, err: Error) {
if len(args) != 1 {
return nil, Data_Error{msg = fmt.tprintf("group_by expects 1 argument, got %d", len(args))}
return nil, Error_Body {
msg = fmt.tprintf("group_by expects 1 argument, got %d", len(args)),
pos = pos,
kind = .Data,
}
}
field := args[0]
elem_info, count, data := list_info(value)
if elem_info == nil {
return nil, Data_Error{msg = "group_by expects a list"}
return nil, Error_Body{msg = "group_by expects a list", pos = pos, kind = .Data}
}
groups := make([dynamic]Group, 0, 8, context.temp_allocator)
@@ -177,13 +300,19 @@ apply_group_by :: proc(value: any, args: []string) -> (result: any, err: Render_
key_val, found := lookup_in(elem, field)
if !found {
return nil, Data_Error {
return nil, Error_Body {
msg = fmt.tprintf("group_by: element missing field '%s'", field),
pos = pos,
kind = .Data,
}
}
key_str := any_to_string(key_val)
if len(key_str) == 0 {
return nil, Data_Error{msg = fmt.tprintf("group_by: field '%s' is empty", field)}
return nil, Error_Body {
msg = fmt.tprintf("group_by: field '%s' is empty", field),
pos = pos,
kind = .Data,
}
}
idx, exists := key_to_idx[key_str]
+134 -19
View File
@@ -66,13 +66,9 @@ test_pipe_group_by_missing_field_fails :: proc(t: ^testing.T) {
defer delete_template(&tpl)
_, err := render(tpl, data)
testing.expect(t, err != nil, "missing field should error")
is_data_err := false
#partial switch e in err {
case Data_Error:
is_data_err = len(e.msg) > 0
}
testing.expect(t, is_data_err, "error should be Data_Error")
b := body(err)
testing.expect(t, b.kind == .Data, "error should be Data kind")
testing.expect(t, len(b.msg) > 0, "error should have non-empty msg")
}
@(test)
@@ -212,11 +208,13 @@ test_delete_template_doesnt_leak :: proc(t: ^testing.T) {
test_interp_pipe_basic :: proc(t: ^testing.T) {
Scalar_Data :: struct {
name: string,
date_format: string,
}
data := Scalar_Data {
name = "2026-03-15T08:49:54-04:00",
date_format = "2 Jan 2006",
}
tpl, _ := parse("[{{name | format}}]", context.temp_allocator)
tpl, _ := parse("[{{name | format}}]", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "[15 Mar 2026]")
}
@@ -225,11 +223,13 @@ test_interp_pipe_basic :: proc(t: ^testing.T) {
test_interp_pipe_unescaped :: proc(t: ^testing.T) {
Scalar_Data :: struct {
name: string,
date_format: string,
}
data := Scalar_Data {
name = "2025-12-25T00:00:00Z",
date_format = "2 Jan 2006",
}
tpl, _ := parse("[{{&name | format}}]", context.temp_allocator)
tpl, _ := parse("[{{&name | format}}]", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "[25 Dec 2025]")
}
@@ -238,11 +238,13 @@ test_interp_pipe_unescaped :: proc(t: ^testing.T) {
test_interp_pipe_dot_current :: proc(t: ^testing.T) {
List_Data :: struct {
items: [3]string,
date_format: string,
}
data := List_Data {
items = {"2026-01-06T00:00:00Z", "2026-06-15T00:00:00Z", "2026-10-15T00:00:00Z"},
date_format = "2 Jan 2006",
}
tpl, _ := parse("{{#items}}[{{. | format}}]{{/items}}", context.temp_allocator)
tpl, _ := parse("{{#items}}[{{. | format}}]{{/items}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "[6 Jan 2026][15 Jun 2026][15 Oct 2026]")
}
@@ -253,14 +255,16 @@ test_interp_pipe_dot_current :: proc(t: ^testing.T) {
Format_Data :: struct {
date: string,
date_format: string,
}
@(test)
test_format_typical_iso :: proc(t: ^testing.T) {
data := Format_Data {
date = "2026-03-15T08:49:54-04:00",
date_format = "2 Jan 2006",
}
tpl, _ := parse("{{date | format}}", context.temp_allocator)
tpl, _ := parse("{{date | format}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "15 Mar 2026")
}
@@ -269,8 +273,9 @@ test_format_typical_iso :: proc(t: ^testing.T) {
test_format_short_date_only :: proc(t: ^testing.T) {
data := Format_Data {
date = "2026-06-06",
date_format = "2 Jan 2006",
}
tpl, _ := parse("{{date | format}}", context.temp_allocator)
tpl, _ := parse("{{date | format}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "6 Jun 2026")
}
@@ -279,8 +284,9 @@ test_format_short_date_only :: proc(t: ^testing.T) {
test_format_empty_input_errors :: proc(t: ^testing.T) {
data := Format_Data {
date = "",
date_format = "2 Jan 2006",
}
tpl, _ := parse("[{{date | format}}]", context.temp_allocator)
tpl, _ := parse("[{{date | format}}]", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "empty date should error")
@@ -290,8 +296,9 @@ test_format_empty_input_errors :: proc(t: ^testing.T) {
test_format_non_date_string_errors :: proc(t: ^testing.T) {
data := Format_Data {
date = "abc",
date_format = "2 Jan 2006",
}
tpl, _ := parse("[{{date | format}}]", context.temp_allocator)
tpl, _ := parse("[{{date | format}}]", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "non-date string should error")
@@ -305,7 +312,7 @@ test_format_non_string_value_errors :: proc(t: ^testing.T) {
data := Int_Data {
count = 42,
}
tpl, _ := parse("{{count | format}}", context.temp_allocator)
tpl, _ := parse("{{count | format}}", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "non-string value should error")
@@ -315,8 +322,9 @@ test_format_non_string_value_errors :: proc(t: ^testing.T) {
test_format_invalid_month_errors :: proc(t: ^testing.T) {
data := Format_Data {
date = "2023-13-15",
date_format = "2 Jan 2006",
}
tpl, _ := parse("{{date | format}}", context.temp_allocator)
tpl, _ := parse("{{date | format}}", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "invalid month should error")
@@ -328,10 +336,12 @@ test_format_inside_section_renders :: proc(t: ^testing.T) {
// partial uses {{.}} for ISO attr and {{. | format}} for display.
data := Format_Data {
date = "2025-12-25T00:00:00Z",
date_format = "2 Jan 2006",
}
tpl, _ := parse(
"{{#date}}<time datetime=\"{{.}}\">{{. | format}}</time>{{/date}}",
context.temp_allocator,
"<test>",
allocator = context.temp_allocator,
)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "<time datetime=\"2025-12-25T00:00:00Z\">25 Dec 2025</time>")
@@ -341,12 +351,101 @@ test_format_inside_section_renders :: proc(t: ^testing.T) {
test_format_inside_section_skips_when_empty :: proc(t: ^testing.T) {
data := Format_Data {
date = "",
date_format = "2 Jan 2006",
}
tpl, _ := parse("[{{#date}}<time>{{. | format}}</time>{{/date}}]", context.temp_allocator)
tpl, _ := parse("[{{#date}}<time>{{. | format}}</time>{{/date}}]", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "[]")
}
// ---------------------------------------------------------------------------
// format filter args: quoted literal strings and bare context keys
// ---------------------------------------------------------------------------
@(test)
test_format_quoted_literal_arg :: proc(t: ^testing.T) {
data := Format_Data {
date = "2026-03-15T08:49:54-04:00",
date_format = "2 Jan 2006",
}
tpl, _ := parse(`{{date | format "Jan 2, 2006"}}`, "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "Mar 15, 2026")
}
Key_Format_Data :: struct {
date: string,
long: string,
}
@(test)
test_format_bare_key_arg_resolves_from_context :: proc(t: ^testing.T) {
data := Key_Format_Data {
date = "2026-03-15T08:49:54-04:00",
long = "2 January 2006",
}
tpl, _ := parse("{{date | format long}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "15 March 2026")
}
@(test)
test_format_bare_key_arg_missing_errors :: proc(t: ^testing.T) {
data := Key_Format_Data {
date = "2026-03-15T08:49:54-04:00",
long = "2 January 2006",
}
tpl, _ := parse("{{date | format missing}}", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "unresolved format key should error")
}
@(test)
test_format_bare_key_arg_non_string_errors :: proc(t: ^testing.T) {
Int_Key_Data :: struct {
date: string,
count: int,
}
data := Int_Key_Data {
date = "2026-03-15T08:49:54-04:00",
count = 42,
}
tpl, _ := parse("{{date | format count}}", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "non-string format key should error")
}
@(test)
test_format_unterminated_quote_arg_is_parse_error :: proc(t: ^testing.T) {
src := `{{date | format "Jan 2, 2006}}`
_, err := parse(src)
testing.expect(t, err != nil, "unterminated string literal should fail to parse")
}
@(test)
test_format_context_date_format_weekday :: proc(t: ^testing.T) {
data := Format_Data {
date = "2026-01-01T00:00:00Z",
date_format = "Monday, January 2, 2006",
}
tpl, _ := parse("{{date | format}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "Thursday, January 1, 2026")
}
@(test)
test_format_context_date_format_time_of_day :: proc(t: ^testing.T) {
data := Format_Data {
date = "2026-01-01T15:30:00Z",
date_format = "3:04 PM",
}
tpl, _ := parse("{{date | format}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, "3:30 PM")
}
@(test)
test_format_handles_all_iso8601_variants :: proc(t: ^testing.T) {
cases := [5]struct {
@@ -361,10 +460,26 @@ test_format_handles_all_iso8601_variants :: proc(t: ^testing.T) {
for &c in cases {
data := Format_Data {
date = c.input,
date_format = "2 Jan 2006",
}
tpl, _ := parse("{{date | format}}", context.temp_allocator)
tpl, _ := parse("{{date | format}}", "<test>", allocator = context.temp_allocator)
result, _ := render(tpl, data, {}, context.temp_allocator)
testing.expect_value(t, result, c.expected)
}
}
@(test)
test_format_bare_numeric_arg_treated_as_key_not_literal :: proc(t: ^testing.T) {
// "2006" happens to also be a valid Go layout token — make sure an
// unquoted arg is still resolved as a context key (and fails, since
// no field is named "2006"), not silently used as the literal layout.
data := Format_Data {
date = "2026-03-15T08:49:54-04:00",
date_format = "2 Jan 2006",
}
tpl, _ := parse("{{date | format 2006}}", "<test>", allocator = context.temp_allocator)
defer delete_template(&tpl)
_, err := render(tpl, data, {}, context.temp_allocator)
testing.expect(t, err != nil, "bare numeric-looking arg should error as an unresolved key")
}
+7 -2
View File
@@ -3,6 +3,7 @@ package mustache
import "core:encoding/json"
import "core:fmt"
import "core:log"
import "core:os"
import "core:path/filepath"
import "core:testing"
@@ -54,6 +55,10 @@ run_one_test :: proc(
test: json.Object,
name, template_src, expected: string,
) -> bool {
// Spec tests deliberately exercise missing keys, missing partials, etc.
// Silence the warnings to keep test output readable.
context.logger = log.nil_logger()
partials := make_map(map[string]Template, context.temp_allocator)
if "partials" in test {
@@ -63,7 +68,7 @@ run_one_test :: proc(
psrc, ok := pval.(string)
assert(ok)
pt, perr := parse(psrc, context.temp_allocator)
pt, perr := parse(psrc, "<spec>", context.temp_allocator)
if perr != nil {
testing.expectf(t, false, "[%s] partial '%s' parse error", name, pname)
return false
@@ -72,7 +77,7 @@ run_one_test :: proc(
}
}
tmpl, terr := parse(template_src, context.temp_allocator)
tmpl, terr := parse(template_src, "<spec>", context.temp_allocator)
if terr != nil {
testing.expectf(t, false, "[%s] template parse error", name)
return false
+206
View File
@@ -0,0 +1,206 @@
package mustache
import "base:runtime"
import "core:strings"
// collect_struct_keys enumerates the visible field names of a struct value,
// including fields promoted via `using`-embedded structs.
collect_struct_keys :: proc(val: any, allocator := context.temp_allocator) -> []string {
out := make([dynamic]string, 0, 0, allocator)
collect_struct_keys_into(val, &out, allocator)
return out[:]
}
collect_struct_keys_into :: proc(val: any, out: ^[dynamic]string, allocator := context.allocator) {
v, info := base_value(val)
if info == nil {
return
}
s, ok := info.variant.(runtime.Type_Info_Struct)
if !ok {
return
}
for i in 0 ..< int(s.field_count) {
name := s.names[i]
if len(name) == 0 {
continue
}
if name[0] == '_' {
continue
}
append(out, name)
// Recurse into using-embedded struct fields to surface promoted names.
if s.usings[i] {
field_info := type_info_of(s.types[i].id)
if field_info != nil {
collect_struct_keys_into(any{v.data, s.types[i].id}, out, allocator)
}
}
}
}
// struct_has_field reports whether a struct value has a named field,
// independent of whether that field's value is currently nil. This matters
// for fields like `Maybe(bool)` which can be nil but still exist.
struct_has_field :: proc(val: any, key: string) -> bool {
v, info := base_value(val)
if info == nil {
return false
}
s, ok := info.variant.(runtime.Type_Info_Struct)
if !ok {
return false
}
for i in 0 ..< int(s.field_count) {
if s.names[i] == key {
return true
}
// Recurse into using-embedded fields.
if s.usings[i] {
if struct_has_field(any{v.data, s.types[i].id}, key) {
return true
}
}
}
return false
}
// validate_key_path walks a dotted key path against the context stack and
// reports where (if anywhere) the lookup fails. Returns:
// - ok: true if the entire path resolves, OR if the path crosses a map
// (map keys are user-defined and not validated)
// - missing_segment: the segment that failed (empty when ok)
// - available: keys available at the failing level, for suggestions
validate_key_path :: proc(
ctx: []any,
key: string,
allocator := context.temp_allocator,
) -> (
ok: bool,
missing_segment: string,
available: []string,
) {
parts: [16]string
part_count := 0
start := 0
for i in 0 ..< len(key) {
if key[i] == '.' {
if part_count < len(parts) {
parts[part_count] = key[start:i]
part_count += 1
}
start = i + 1
}
}
if part_count < len(parts) {
parts[part_count] = key[start:]
part_count += 1
}
if part_count == 0 {
return true, "", nil
}
current: any = nil
found := false
for i := len(ctx) - 1; i >= 0; i -= 1 {
current, found = lookup_in(ctx[i], parts[0])
if found {
break
}
}
if !found {
keys := make([dynamic]string, 0, 4, allocator)
for i := len(ctx) - 1; i >= 0; i -= 1 {
collect_struct_keys_into(ctx[i], &keys, allocator)
}
return false, parts[0], keys[:]
}
for i in 1 ..< part_count {
v, info := base_value(current)
if info == nil {
return false, parts[i], nil
}
if _, is_map := info.variant.(runtime.Type_Info_Map); is_map {
return true, "", nil
}
if _, is_struct := info.variant.(runtime.Type_Info_Struct); is_struct {
if !struct_has_field(current, parts[i]) {
return false, parts[i], collect_struct_keys(current, allocator)
}
// Field exists — descend into it. If the value is nil, stop here
// (further segments can't be resolved but the current field is
// legitimately present).
next, found := lookup_in(current, parts[i])
if !found {
return true, "", nil
}
current = next
continue
}
return false, parts[i], nil
}
return true, "", nil
}
// suggest_correction returns the closest match from `available` to `missing`
// using Levenshtein distance, or "" if no good match exists. The threshold
// scales with the length of the missing key.
suggest_correction :: proc(available: []string, missing: string) -> string {
if len(available) == 0 || len(missing) == 0 {
return ""
}
threshold := 2
if len(missing) > 8 {
threshold = len(missing) / 4
}
best: string
best_dist := threshold + 1
for candidate in available {
if abs(len(candidate) - len(missing)) > threshold {
continue
}
d := strings.levenshtein_distance(missing, candidate)
if d <= threshold && d < best_dist {
best = candidate
best_dist = d
}
}
return best
}
// collect_partial_names enumerates the keys of the partials map.
collect_partial_names :: proc(
partials: map[string]Template,
allocator := context.temp_allocator,
) -> []string {
out := make([dynamic]string, 0, 0, allocator)
for name in partials {
append(&out, name)
}
return out[:]
}
// collect_block_names enumerates the unique `{{$name}}` block definitions in
// a template's node array.
collect_block_names :: proc(
tmpl: Template,
allocator := context.temp_allocator,
) -> []string {
out := make([dynamic]string, 0, 0, allocator)
seen := make(map[string]bool, allocator)
defer delete(seen)
for &node in tmpl.nodes {
if node.kind == .Block {
if !seen[node.key] {
seen[node.key] = true
append(&out, node.key)
}
}
}
return out[:]
}
+195
View File
@@ -0,0 +1,195 @@
#+test
#+feature dynamic-literals
package mustache
import "core:fmt"
import "core:testing"
Inner :: struct {
foo: string,
bar: int,
}
Outer :: struct {
title: string,
page_title: string,
inner: Inner,
numbers: [3]int,
}
@(test)
test_validate_simple_found :: proc(t: ^testing.T) {
data := Outer {
title = "hi",
}
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
ok, missing, _ := validate_key_path(ctx[:], "title")
testing.expect_value(t, ok, true)
testing.expect(t, missing == "", fmt.tprintf("expected empty missing, got %q", missing))
}
@(test)
test_validate_simple_missing :: proc(t: ^testing.T) {
data := Outer {
title = "hi",
}
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
ok, missing, available := validate_key_path(ctx[:], "page_titel")
testing.expect_value(t, ok, false)
testing.expect_value(t, missing, "page_titel")
testing.expect(t, len(available) > 0, "should have suggestions")
}
@(test)
test_validate_dotted_found :: proc(t: ^testing.T) {
data := Outer {
inner = Inner{foo = "x"},
}
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
ok, missing, _ := validate_key_path(ctx[:], "inner.foo")
testing.expect_value(t, ok, true)
testing.expect_value(t, missing, "")
}
@(test)
test_validate_dotted_missing :: proc(t: ^testing.T) {
data := Outer {
inner = Inner{foo = "x"},
}
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
ok, missing, available := validate_key_path(ctx[:], "inner.fooo")
testing.expect_value(t, ok, false)
testing.expect_value(t, missing, "fooo")
testing.expect(t, len(available) > 0, "should have inner field suggestions")
}
Params_Data :: struct {
params: map[string]string,
}
Maybe_Bool_Data :: struct {
flag: Maybe(bool),
name: string,
}
Inner_For_Using :: struct {
flag: Maybe(bool),
label: string,
}
Outer_With_Using :: struct {
using inner: Inner_For_Using,
other: int,
}
@(test)
test_validate_path_through_using_to_maybe_bool :: proc(t: ^testing.T) {
data := Outer_With_Using {
inner = Inner_For_Using{label = "hi"},
other = 42,
}
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
// `flag` is promoted via using; field exists even when Maybe is nil.
ok, missing, _ := validate_key_path(ctx[:], "flag")
testing.expect_value(t, ok, true)
testing.expect_value(t, missing, "")
// `label` is also promoted via using.
ok2, missing2, _ := validate_key_path(ctx[:], "label")
testing.expect_value(t, ok2, true)
testing.expect_value(t, missing2, "")
}
@(test)
test_struct_has_field_with_maybe_bool :: proc(t: ^testing.T) {
data := Maybe_Bool_Data {
name = "hi",
} // flag is nil Maybe
testing.expect_value(t, struct_has_field(data, "flag"), true)
testing.expect_value(t, struct_has_field(data, "name"), true)
testing.expect_value(t, struct_has_field(data, "missing"), false)
}
@(test)
test_validate_path_through_maybe_bool :: proc(t: ^testing.T) {
data := Maybe_Bool_Data {
name = "hi",
}
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
// `flag` exists as a field even when its Maybe value is nil — should NOT warn.
ok, missing, _ := validate_key_path(ctx[:], "flag")
testing.expect_value(t, ok, true)
testing.expect_value(t, missing, "")
}
@(test)
test_validate_map_path_silent :: proc(t: ^testing.T) {
data := Params_Data {
params = {"social" = "x"},
}
defer delete(data.params)
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, data)
// `params` exists and is a map — subsequent segments are user-defined.
ok, _, _ := validate_key_path(ctx[:], "params.anything_here")
testing.expect_value(t, ok, true)
}
@(test)
test_suggest_correction_exact :: proc(t: ^testing.T) {
available := []string{"title", "page_title", "body"}
testing.expect_value(t, suggest_correction(available, "page_titel"), "page_title")
}
@(test)
test_suggest_correction_close :: proc(t: ^testing.T) {
available := []string{"title", "body", "now"}
testing.expect_value(t, suggest_correction(available, "titel"), "title")
}
@(test)
test_suggest_correction_no_match :: proc(t: ^testing.T) {
available := []string{"completely_different", "unrelated"}
testing.expect_value(t, suggest_correction(available, "page_titel"), "")
}
@(test)
test_suggest_correction_empty :: proc(t: ^testing.T) {
testing.expect_value(t, suggest_correction([]string{}, "anything"), "")
testing.expect_value(t, suggest_correction([]string{"a"}, ""), "")
}
@(test)
test_warn_no_false_positive_for_valid_keys :: proc(t: ^testing.T) {
Data :: struct {
name: string,
}
src := "Hello {{name}}"
tmpl, err := parse(src, "<test>", context.temp_allocator)
testing.expect(t, err == nil, "should parse")
if err != nil {
return
}
// We can't easily capture log output in tests, but we can verify the
// validation procs agree the key exists.
ctx := make([dynamic]any, 0, 1, context.temp_allocator)
append(&ctx, Data{name = "World"})
ok, missing, _ := validate_key_path(ctx[:], "name")
testing.expect_value(t, ok, true)
}
+22 -7
View File
@@ -28,7 +28,7 @@ tokenize :: proc(
allocator := context.allocator,
) -> (
tokens: [dynamic]Token,
err: Render_Error,
err: Error,
) {
tokens = make([dynamic]Token, 0, 8, allocator)
@@ -36,7 +36,20 @@ tokenize :: proc(
text_start := 0
for i < len(src) {
if src[i] == '{' && i + 1 < len(src) && src[i + 1] == '{' {
// Find next '{' via AVX2/SSE-backed memchr instead of byte-by-byte scan.
rel := strings.index_byte(src[i:], '{')
if rel < 0 {
i = len(src)
break
}
next := i + rel
// Single '{' (not '{{') — advance past it and keep scanning.
if next + 1 >= len(src) || src[next + 1] != '{' {
i = next + 1
continue
}
i = next
if i > text_start {
append(&tokens, Token{kind = .Text, value = src[text_start:i], pos = text_start})
}
@@ -47,9 +60,10 @@ tokenize :: proc(
content_start := i + 3
idx := strings.index(src[content_start:], "}}}")
if idx < 0 {
return tokens, Syntax_Error {
return tokens, Error_Body {
msg = "unclosed triple mustache '{{{'",
pos = tag_pos,
kind = .Syntax,
}
}
close := content_start + idx
@@ -90,7 +104,11 @@ tokenize :: proc(
close_idx := strings.index(src[key_start:], "}}")
if close_idx < 0 {
return tokens, Syntax_Error{msg = "unclosed tag '{{'", pos = tag_pos}
return tokens, Error_Body {
msg = "unclosed tag '{{'",
pos = tag_pos,
kind = .Syntax,
}
}
close := key_start + close_idx
@@ -124,9 +142,6 @@ tokenize :: proc(
i = close + 2
text_start = i
}
} else {
i += 1
}
}
if i > text_start {
+45 -17
View File
@@ -19,12 +19,13 @@ Page_Context :: struct {
}
Base_Data :: struct {
now: datetime.DateTime,
now: string,
params: json.Value,
body: string,
title: string,
description: string,
og: Open_Graph,
date_format: string,
}
Page_Data :: struct {
@@ -55,14 +56,26 @@ build_page_context :: proc(page: Page) -> Page_Context {
}
load_template :: proc(vfs: ^VFS, virtual_path: string) -> mustache.Template {
data, ok := vfs_get(vfs, virtual_path)
entry, data, ok := vfs_get_entry(vfs, virtual_path)
if !ok {
log.warnf("template %s not found", virtual_path)
return mustache.Template{}
log.fatalf("template %s not found", virtual_path)
os.exit(1)
}
tpl, err := mustache.parse(string(data))
source := string(data)
tpl, err := mustache.parse(source, entry.fs_path)
if err != nil {
log.warnf("failed to parse template %s: %v", virtual_path, err)
b := mustache.body(err)
log.errorf(
"%s",
mustache.format_error(
entry.fs_path,
source,
b.pos,
b.msg,
colorize = mustache.should_colorize(),
),
)
os.exit(1)
}
return tpl
}
@@ -122,13 +135,17 @@ render_template :: proc(
) -> string {
result, err := mustache.render(content_tpl, data, partials)
if err != nil {
fmt.eprintfln("mustache error: %v", err)
log.errorf(
"%s",
mustache.format_render_error(err, content_tpl, colorize = mustache.should_colorize()),
)
return ""
}
return result
}
render_site :: proc(site: ^Site) {
allocator := site_allocator(site)
pages := site.pages[:]
sort_pages_by_date(pages)
@@ -139,7 +156,9 @@ render_site :: proc(site: ^Site) {
template_cache: map[string]mustache.Template
defer delete(template_cache)
now, ok := time.time_to_datetime(time.now())
// TODO: CAlculate offset
offset := 0
now, ok := time.time_to_rfc3339(time.now(), offset, false, allocator)
assert(ok)
// Build base data once
@@ -148,6 +167,7 @@ render_site :: proc(site: ^Site) {
params = site.params,
description = site.description,
og = site.og,
date_format = site.date.format,
}
// Find home page
@@ -241,7 +261,7 @@ render_site :: proc(site: ^Site) {
if !has_home {
total += 1
}
fmt.printfln("Rendered %d pages to %s", total, site.output_dir)
log.infof("Rendered %d pages to %s", total, site.output_dir)
}
render_page_html :: proc(
@@ -331,7 +351,7 @@ render_section :: proc(
load_partials :: proc(vfs: ^VFS) -> map[string]mustache.Template {
partials: map[string]mustache.Template
prefix := "layouts/partials/"
for virtual_path in vfs.files {
for virtual_path, entry in vfs.files {
if !strings.has_prefix(virtual_path, prefix) {
continue
}
@@ -342,14 +362,22 @@ load_partials :: proc(vfs: ^VFS) -> map[string]mustache.Template {
stripped := virtual_path[len(prefix):]
key := stripped[:len(stripped) - len(".html")]
data, ok := vfs_get(vfs, virtual_path)
if !ok {
continue
}
tpl, err := mustache.parse(string(data))
data := vfs_entry_data(entry) or_continue
source := string(data)
tpl, err := mustache.parse(source, entry.fs_path)
if err != nil {
log.warnf("failed to parse partial %s: %v", key, err)
continue
b := mustache.body(err)
log.errorf(
"%s",
mustache.format_error(
entry.fs_path,
source,
b.pos,
b.msg,
colorize = mustache.should_colorize(),
),
)
os.exit(1)
}
partials[key] = tpl
}
+8
View File
@@ -29,6 +29,12 @@ Site :: struct {
features: bit_set[Feature],
markdown_extensions: bit_set[md.Extension],
og: Open_Graph,
date: Date_Preferences,
}
Date_Preferences :: struct {
format: string,
timezone: string,
}
Feature :: enum {
@@ -51,6 +57,7 @@ Config_File :: struct {
params: json.Value,
modules: json.Value,
og: Open_Graph,
date: Date_Preferences,
}
// Configuration loaded from command line arguments. Gets folded in to Site
@@ -163,6 +170,7 @@ site_apply_config :: proc(site: ^Site, config: Config_File, config_dir: string)
}
site.og = config.og
site.date = config.date
}
site_apply_path_defaults :: proc(site: ^Site, config_dir: string) {
+32
View File
@@ -78,3 +78,35 @@ vfs_get :: proc(vfs: ^VFS, virtual_path: string) -> ([]byte, bool) {
return data, true
}
// vfs_get_entry returns both the VFS_Entry (for fs_path) and the lazily-loaded
// data. Use this instead of vfs_get when you need the entry's metadata along
// with the contents.
vfs_get_entry :: proc(vfs: ^VFS, virtual_path: string) -> (VFS_Entry, []byte, bool) {
entry, ok := vfs.files[virtual_path]
if !ok {
return {}, nil, false
}
if entry.data != nil {
return entry, entry.data, true
}
data, err := os.read_entire_file_from_path(entry.fs_path, context.allocator)
if err != nil {
return entry, nil, false
}
return entry, data, true
}
// vfs_entry_data returns the data for a VFS_Entry, reading from disk if it
// hasn't been loaded yet. Useful when iterating vfs.files directly (where you
// already have the entry and don't want a redundant map lookup).
vfs_entry_data :: proc(entry: VFS_Entry) -> ([]byte, bool) {
if entry.data != nil {
return entry.data, true
}
data, err := os.read_entire_file_from_path(entry.fs_path, context.allocator)
if err != nil {
return nil, false
}
return data, true
}