Skip to content

Commit

Permalink
async/await transpiller, wip
Browse files Browse the repository at this point in the history
  • Loading branch information
wpdas committed Mar 29, 2024
1 parent 96c92b9 commit d23d4cf
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/actions/transformSchemaToWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const transformImports = require("../parsers/transformImports");
const analyzeFunctionSignature = require("../parsers/analyzeFunctionSignature");
const removeFunctionParams = require("../parsers/removeFunctionParams");
const checkSyntaxError = require("../parsers/checkSyntaxError");
const transformAsyncAwait = require("../parsers/transformAsyncAwait");

/**
* @param {string} content
Expand Down Expand Up @@ -861,6 +862,14 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
);
});

// Faz transformação de async/await para o formato promisify
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
fileSchema.finalFileBundle = transformAsyncAwait(
fileSchema.finalFileBundle,
);
fileSchemas[fileSchemaIndex] = fileSchema;
});

return fileSchemas;
};

Expand Down
36 changes: 36 additions & 0 deletions lib/parsers/transformAsyncAwait.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Experimental: Gera uma estrutura entendível pelo Near VM a partir de um await
* @param {string} code
* @returns
*/
function transformAsyncAwait(code) {
// Primeiro, remove 'async ' de todas as funções
let transformedCode = code.replace(/async /g, "");

// Regex ajustada para capturar chamadas de função que abrangem múltiplas linhas
const pattern = /const (\w+) = await (.*?);/gs;

// Função para gerar o novo bloco de código substituto
function replaceWithPromisify(match, varName, asyncCall) {
// Removendo espaços em branco extras e quebras de linha do início e do fim do asyncCall
asyncCall = asyncCall.replace(/^\s+|\s+$/g, "");
return `let ${varName} = state.${varName};
if (!${varName}) {
// 1 - usa o promisify
promisify(
() => ${asyncCall},
(data) => State.update({ ${varName}: data }),
() => State.update({ ${varName}: null }),
);
return "";
}`;
}

// Realizando a substituição no código transformado
transformedCode = transformedCode.replace(pattern, replaceWithPromisify);

return transformedCode;
}

module.exports = transformAsyncAwait;

0 comments on commit d23d4cf

Please sign in to comment.