DanielXMoore / Civet

A TypeScript superset that favors more types and less typing
https://civet.dev
MIT License
1.55k stars 33 forks source link

Indented calls in `if` conditions with explicit `then` clause (#1090) #1369

Closed edemaine closed 3 months ago

edemaine commented 3 months ago

Inspired by https://github.com/DanielXMoore/Civet/pull/1364#pullrequestreview-2244181171

There’s probably more we can do here eventually [...]

and specifically https://github.com/DanielXMoore/Civet/issues/1090#issuecomment-1981438104

Perhaps we could make an exception when there's an explicit then.

This PR allows for indented function calls in an if condition when there's an explicit then to indicate the then block. Unlike usual then, this one allows for an indented block after it, symmetric to else. This lets us write:

if (and)
  cond1
  cond2
then
  // match
else
  // no match

as well as #1090's original request:

return if (and)
  upper.test exactOrAny.toString()
  lower.test exactOrAny.toString()
then exactOrAny
else undefined

Performance

One potential issue is that this involves parsing each if twice, first with indentation calls enabled, but then failing if there isn't a then immediately after, and second with indentation calls disabled.

Running build/perf-compare.sh (modified here to parse the entire Civet codebase), the slowdown is a bit inconsistent but I'd say about 5% slowdown (from ~2.25s to ~2.4s parse time). Is this worth it? I'm not sure. (If not, I should cherry-pick some of the small improvements in this PR.)

If you see a way to make the common case more efficient, I'm all ears. Unfortunately, I think we need to check for the then-terminated condition before we check the "normal" case; otherwise, we misparse and can't recover.