rescript-compiler icon indicating copy to clipboard operation
rescript-compiler copied to clipboard

Integrate embed lang

Open zth opened this issue 1 year ago • 0 comments

Experimenting with integrating https://github.com/zth/rescript-embed-lang into the compiler.

Instructions

Pass whatever extension points you want to treat as embeds to bsc via -embed when producing the .ast file via -bs-ast:

./bsc tst.res -bs-ast -embed sql.one -embed sql.many

Some examples. Imagine this ReScript file:

// tst.res
let query1 = %sql.one(`
  SELECT * FROM tst.res
  WHERE id = 1
`)

let q2 = %sql.many(`
  SELECT * FROM tst.res
  WHERE id > 1
`)

let q3 = %sql.one(`
  SELECT * FROM tst.res
  WHERE id = 2
`)

module Query = %sql.many(`
  SELECT * FROM tst.res
  WHERE id > 2
`)

Running ./bsc tst.res -bs-ast -embed sql.one -embed sql.many will do 2 things:

First, it'll produce a JSON file tst.embeds.json right next to the tst.ast file, with all embeds + info needed for them from the file:

[
  {
    "tag": "sql.one",
    "filename": "Tst__sql_one_1.res",
    "contents": "\n  SELECT * FROM tst.res\n  WHERE id = 1\n",
    "loc": {"start": {"line": 1, "col": 22}, "end": {"line": 4, "col": 64}}
  },
  {
    "tag": "sql.many",
    "filename": "Tst__sql_many_1.res",
    "contents": "\n  SELECT * FROM tst.res\n  WHERE id > 1\n",
    "loc": {"start": {"line": 6, "col": 86}, "end": {"line": 9, "col": 128}}
  },
  {
    "tag": "sql.one",
    "filename": "Tst__sql_one_2.res",
    "contents": "\n  SELECT * FROM tst.res\n  WHERE id = 2\n",
    "loc": {"start": {"line": 11, "col": 149}, "end": {"line": 14, "col": 191}}
  },
  {
    "tag": "sql.many",
    "filename": "Tst__sql_many_2.res",
    "contents": "\n  SELECT * FROM tst.res\n  WHERE id > 2\n",
    "loc": {"start": {"line": 16, "col": 219}, "end": {"line": 19, "col": 261}}
  }
]

Second, it'll rewrite the source to point to the generated file it expects:

// tst.res, the source as processed by the embed PPX
let query1 = Tst__sql_one_1.default

let q2 = Tst__sql_many_1.default

let q3 = Tst__sql_one_2.default

module Query = Tst__sql_many_2
  1. For extension points in the let binding position , the PPX transforms the let binding to access .default inside of the generated module.
  2. For extension points as modules, it transforms to access the full module.

TODO

  • [ ] Add tests

zth avatar Jun 21 '24 21:06 zth