kmyk-jikka / Jikka

an automated solver for problems of competitive programming
https://kmyk-jikka.github.io/Jikka/playground
Apache License 2.0
152 stars 11 forks source link

Use the same name in generated code when scopes of variables are distinct #239

Open kmyk opened 2 years ago

kmyk commented 2 years ago

Description / 説明

スコープに被りがなければ変数名に suffix を付けないでほしい

The current implementation avoids name conflicts of variables even when the scopes of them are distinct. For example, i and i2 are used in the following result:

int64_t solve(int64_t n, int64_t c, std::vector<int64_t> h) {
    ...
    for (int32_t i = 0; i < 1ll; ++ i) {
        ...
    }
    for (int32_t i2 = 0; i2 < n - 1ll; ++ i2) {
        ...
    }
    return x2[n - 1ll];
}

We want to use the same name, just i, for both variables in such cases.

Motivation / 動機

for more readability

Tutorial

This issue is not trivial (needs many implementation) but relatively easier than other issues, so marked as a good first issue.

For this issue, probably you need to do 3 steps:

(1.): Extend mapExprStatementExprM and mapExprStatementStatementM, mutual recursive functions to map exprs and statements in exprs and statements, to give current scopes to callback functions.

https://github.com/kmyk/Jikka/blob/f7a17bfac392712f08c857c0c7f25310093d698e/src/Jikka/CPlusPlus/Language/Util.hs#L140

https://github.com/kmyk/Jikka/blob/f7a17bfac392712f08c857c0c7f25310093d698e/src/Jikka/CPlusPlus/Language/Util.hs#L165

The mapSubExprM of core already did this.

https://github.com/kmyk/Jikka/blob/f7a17bfac392712f08c857c0c7f25310093d698e/src/Jikka/Core/Language/Util.hs#L123

(2.): Update mapVarNameProgramM in the similar manner to (1.).

https://github.com/kmyk/Jikka/blob/642b0fe3746bd4fdcdb813d96309ac6258494343/src/Jikka/CPlusPlus/Language/Util.hs#L297

(3.): Main part: Update rename function and chooseOccName function in src/Jikka/CPlusPlus/Convert/BurnFlavouredNames.hs to use information of current scopes. These functions decides strings which are used in the result code.

https://github.com/kmyk/Jikka/blob/f7a17bfac392712f08c857c0c7f25310093d698e/src/Jikka/CPlusPlus/Convert/BurnFlavouredNames.hs#L61

https://github.com/kmyk/Jikka/blob/f7a17bfac392712f08c857c0c7f25310093d698e/src/Jikka/CPlusPlus/Convert/BurnFlavouredNames.hs#L53