syntax-objects / Summer2021

Syntax Parse Bee 2021
11 stars 3 forks source link

`make-variable` - easily create "variables" for POSIX shell scripts #8

Open xgqt opened 3 years ago

xgqt commented 3 years ago

Macro

(define-syntax (make-variable stx)
  (syntax-parse stx
    [(_)
     #'"var=var"]  ; some placeholder
    [(_ name:id)
     #'(as-variable (symbol->string 'name) name)]
    [(_ str:string)
     #'(as-variable str str)]
    [(_ ((~literal quote) sym))
     #'(as-variable (symbol->string 'sym) 'sym)]))

If name is an identifier, then it is the name of variable and the value is what that name resolves to. If name is a string or a symbol then it is passed to both name and value of as-variable (symbol is converted to a string).

This probably makes more sense in the context of the as-variable function, described here: https://xgqt.gitlab.io/racket-ebuild/ebuild/ebuild-exported.html#%28def._%28%28lib._ebuild%2Febuild..rkt%29._as-variable%29%29

Examples

> (make-variable "this_variable_will_probably_change")
-> "this_variable_will_probably_change=\"this_variable_will_probably_change\""
> (define Z "Zzz...")
> (make-variable Z)
-> "Z=\"Zzz...\""

You can look into the racket-ebuild source code and see how this is exactly used there, but to summarize: it is later concatenated with other strings to make a complete POSIX-like shell script and output it into a file (https://gitlab.com/xgqt/racket-ebuild/-/blob/master/ebuild/ebuild.rkt#L142).

More examples in the macro's tests: https://gitlab.com/xgqt/racket-ebuild/-/blob/master/ebuild/private/ebuild/variable.rkt#L85

Before and After

Before the rewrite with syntax-parse a simple define-syntax-rule macro was used. It looked like this: https://gitlab.com/xgqt/racket-ebuild/-/blob/2286bd456f0b71cf715624123bedd91b2bba35ad/ebuild/private/ebuild/variable.rkt#L49

Was changed with commit: https://gitlab.com/xgqt/racket-ebuild/-/commit/78a2a2665ac90fc6ef0316e981e0cabb8ed85c20#696be2c6ced1eb02f3ac07043af0f9494a2546f1_49_59

Licence

The code I submit, and only this code here, I re-release here under the MIT license, for the growth of syntax-parse examples, that's why I allow to use a more permissive license. The rest of racket-ebuild still stays under the GPLv3 license.

The text of this GitHub issue I release under Creative Commons Attribution 4.0 International License.

spdegabrielle commented 3 years ago

Thank you for your contribution!

If you haven’t already please take the time to fill in the form https://forms.gle/Z5CN2xzK13dfkBnF7

Bw Stephen