🐞️ Functions: Return position enforcement (#6)

* Parser

- Added a TODO in `wantsBody == true` case in `parseFuncDef()` to check for the return keyword's position

* Parser

- Added a check in `parseFuncDef()` which, is a `ReturnStmt` is found, then crash the parser if it is found anywhere besides the last statement

* Test cases

- Added test cases to test the `return` statement position enforcement
This commit is contained in:
Tristan B. Velloza Kildaire 2023-04-21 15:29:53 +02:00 committed by GitHub
parent dad185f96f
commit a4c010f27f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 54 additions and 0 deletions

View File

@ -100,6 +100,20 @@ jobs:
fi
- name: Simple string
run: ./tlang syntaxcheck source/tlang/testing/typecheck/simple_string.t
- name: Simple return (good)
run: |
./tlang syntaxcheck source/tlang/testing/return/simple_return_good.t
- name: Simple return (bad return position)
run: |
set +e
./tlang syntaxcheck source/tlang/testing/return/simple_return_bad.t
if [ $? = 255 ]
then
exit 0
else
exit 1
fi
typecheck:
needs: [build, unittests]

View File

@ -974,6 +974,22 @@ public final class Parser
/* Parse the body (and it leaves ONLY when it gets the correct symbol, no expect needed) */
statements = parseBody();
/* TODO: We should now run through the statements in the body and check for return */
for(ulong i = 0; i < statements.length; i++)
{
Statement curStatement = statements[i];
/* If we find a return statement */
if(cast(ReturnStmt)curStatement)
{
/* If it is not the last statement, throw an error */
if(i != statements.length-1)
{
expect("A return statement must be the last statement of a function's body");
}
}
}
nextToken();
}
/* If no body is requested */

View File

@ -0,0 +1,12 @@
module simple_return_bad;
int myFunction()
{
return 1;
}
int myFunction2()
{
return 2;
int j = 1;
}

View File

@ -0,0 +1,12 @@
module simple_return_good;
int myFunction()
{
return 1;
}
int myFunction2()
{
int j = 1;
return 2;
}