niieani / bashscript

TypeScript to bash transpiler. Because.
MIT License
55 stars 0 forks source link

How would you define scopes in bash? #2

Open avierr opened 5 years ago

avierr commented 5 years ago

I have been working on a transpiler myself and came across this repo today. The specification in the README gives me some really good ideas! Thanks!

I am stuck at a point on how to implement variable scopes like:

let i = 10;
let z= 20;
while(i<10){
  console.log(i)
   i = i +1;
   let z = 40;
}

at the moment, translates to:

i=0

z=0

while  ((  $(($i < 10)) )) ; do 

  echo  "$i"
  i=$(($i + 1))
  z=$i

done

Let me know if you have any good idea for implementing scopes. Here is the one that I am working on https://github.com/evnix/BashType (very much a work in progress and the reason for building it exactly the same as yours 😛)

A JavaScript/TypeScript to bash transpiler. Work in progress.

Why? Mainly because I wanted to learn how to make a transpiler.

I also wanted to experiment with bash and how far we could stretch this old, yet widely cross-platform language.

niieani commented 5 years ago

Hi @avierr, we should collaborate ;)

There's a couple of things you could do:

  1. extract the body to function and transpile all declarations as locals
function run() {
  local -i i=0
  local -i z=0

  function extractedWhile() {
    echo "$i"
    i=$(($i + 1))
    local -i z="$i"
  }

  while (($i < 10)); do
    extractedWhile
  done

  echo "z is $z"
}

run

Works as in JavaScript and outputs:

0
1
2
3
4
5
6
7
8
9
z is 0
  1. You could also do variable renaming, like babel does. Since you already know the scope and which variables should be visible in which scope, you could simply rename the inner z local to a non-conflicting variable consistently within that scope:
function run() {
  local -i i=0
  local -i z=0
  local -i _z

  while (($i < 10)); do
    echo "$i"
    i=$(($i + 1))
    _z="$i"
  done

  echo "z is $z"
}

run

Some inspiring reading & tools here: