Skip to content

Instantly share code, notes, and snippets.

@repeatedly
Created October 17, 2014 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save repeatedly/96e20abfd0f639f42185 to your computer and use it in GitHub Desktop.
Save repeatedly/96e20abfd0f639f42185 to your computer and use it in GitHub Desktop.
テンプレートエンジンnight

D言語の話

テンプレートエンジン書くのに便利な機能がいくつかある.

CTFE

コンパイル時に関数が実行出来る.標準ライブラリの有名所は大抵コンパイル時にも動く(std.algorithm, std.range, std.string, etc...).

import std.random, std.stdio;

size_t r()
{
    auto r = new Random;
    scope (exit) { r.destroy; }
    r.popFront();
    return r.front;
}

pragma(msg, r());

void main() {}

__ctfe

CTFE時にtrueになる特殊変数.コンパイル時とランタイムで処理を分岐できる.

import("file")

コンパイル時にファイル読み込める

#!/usr/bin/env rdmd -J.

import std.stdio;

enum fileContent = import("ctfe.d");

void main()
{
    writeln(fileContent);
}

string mixin

文字列をD言語のコードとしてそこに埋め込める機能

import std.stdio;

void main()
{
    mixin("
struct Hoge
{
    int a = 100;
}
");

    Hoge hoge;
    writeln(hoge.a);
}

CTFE + string mixin

これで大抵なんとかなる.

D言語でコンパイルタイムに色々やるライブラリ

D言語のテンプレートエンジン

mustache

ランタイムに普通にパースして,普通に値をテンプレートに適用していく.コンパイル時に動くように多分出来るけど,やってない.

diet

コンパイル時にテンプレートをパースしてHTMLやフィルターの変換処理を施し,結果をD言語のコードとして埋め込む.

import("file") -> HTML変換 -> フィルター適用(markdown変換,D言語コード埋め込み) -> 文字列 -> mixinで埋め込む

https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/textfilter/markdown.d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment