Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: compile-time conditionals and iterations #182

Open
epoberezkin opened this issue Nov 21, 2015 · 1 comment
Open

Feature: compile-time conditionals and iterations #182

epoberezkin opened this issue Nov 21, 2015 · 1 comment

Comments

@epoberezkin
Copy link
Collaborator

{{#?}} and {{#~}}

@strrchr
Copy link

strrchr commented Jan 7, 2016

The following is just a try (can copy and paste it to node REPL) for demonstration that how to implement compile-time conditionals:

let src3 = `
Hello!
{{& def.DEBUG }}
the debug version...
{{&& def.DEBUG2 }}
the debug2 version...
{{&&}}
the release version...
aaa
{::{& def.HAS_BBB }::}
bbb
{::{&}::}
ccc
{{&}}
`;

let def = {
  HAS_BBB: true,
};

function resolve_static_if(s) {
  return s.replace(/\{(:*)\{&\s*([\s\S]*?)\s*\}\1\}([\s\S]*?)\{\1\{&\s*\}\1\}/g, function (m, mark, if_cond, block) {
    console.log("GOT", if_cond);
    for (;;) {
      assert(mark !== undefined);
      assert(if_cond !== undefined);
      assert(block !== undefined);
      if_cond = if_cond === "" ? true : new Function("def", "return " + if_cond)(def);
      let p = new RegExp("^([\\s\\S]*?)(?:\\{"+mark+"\\{&&\\s*([\\s\\S]*?)\\s*\\}"+mark+"\\}([\\s\\S]*?))?$");
      console.log("PATTERN", p);
      console.log("BLOCK", block.length);
      m = p.exec(block);
      //console.log("m:", m);
      let if_part = m[1];
      if (if_cond) return resolve_static_if(if_part);
      if_cond = m[2];
      if (if_cond === undefined) return "";
      block = m[3];
    }
  });
}

let dst3 = resolve_static_if(src3);
console.log("----\n"+dst3+"\n----");

Features:

  • Just using recursion and replace(), no lexer and parser
  • Using {:::{& cond }:::} syntax to distinguish nesting, because no lexer and parser
  • Support elseif, using syntax {{&& cond }}
  • Empty condition means true

I think the core functionality can be used in resolveDefs() of doT, after resolving c.define, before resolving c.use.

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

No branches or pull requests

2 participants