Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix/better call argument with string literal #42

Merged
merged 2 commits into from
Apr 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 7 additions & 4 deletions example/example-function.jaksel
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ so about fungsi_param a
thats it sih

so about fungsiMultiParam a b c
spill "a: " + a
spill "b: " + b
spill "c: " + c
spill "argumen pertama: " + a
spill "argumen kedua: " + b
spill "argumen ketiga: " + c
thats it sih

call my_story
Expand All @@ -34,6 +34,9 @@ literally nama itu "adi"
call fungsi_param nama
spill "\n"

call fungsi_param "Rayhan"
spill "\n"

call fungsi_param 3
spill "\n"

Expand All @@ -42,5 +45,5 @@ spill "\n"

literally nama2 itu "budi"

call fungsiMultiParam nama nama2 4
call fungsiMultiParam 2 nama2 "and then Romeo says \"I love you\" to Juliet"
spill "\n"
42 changes: 24 additions & 18 deletions lib/logics/parser/functionCall.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,37 @@
* @param msg {string}
*/
const functionCall = (msg) => {
let format = /call (\w+)((\s\w+)*)?/;
let format = /call (\w+)((\s(\w+|\".*\"))*)/;
let match = msg.match(format);
if (!match) return null;

const [, funcName, paramValues] = match;
const [, funcName, argValues = ''] = match;

/**
* if function doesn't have arguments
*/
if (argValues.trim() === '') {
return {
exp: `${funcName}();`
}
}


/**
* Match arg1, arg2, ..., argN on function call.
* Argument can be variable, string literal, native boolean literal (true and false), or number.
* e.g:
* call helloFunction "a string literal" aVariable 4
*
* we can even have string literal with escaped quotes
* e.g:
* call tellNextStory "and then Romeo says \"I love you\" to Juliet"
*/
let paramFormat = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|[^\s]+/g;
let params = argValues.trim().match(paramFormat);

return {
exp: `${funcName}(${paramsStringified(paramValues) || ifItisAString(msg)});`
exp: `${funcName}(${params.join()});`
}
};

const paramsStringified = (paramValues)=>{
return (paramValues?.trim().split(/\s+/) ?? []).reduce((p, c, idx, arr) => idx !== arr.length - 1 ? `${p} ${c},` : `${p} ${c}`,'').trim()

}

const ifItisAString = (msg)=>{
const cmnds = msg.split(" ")
var cmnd = ""
for (let index = 2; index < cmnds.length; index++) {
cmnd += `${cmnds[index]}, `
};
return msg.split(" ")[2]
}

module.exports = functionCall;