commit 44289836342d28ea01f13a439adc6a48675cc82f
parent 819afcb88377511de71e57f2297dd600ea08a473
Author: Virgil Dupras <hsoft@hardcoded.net>
Date: Fri, 31 Mar 2023 07:24:56 -0400
halcc: whilesum() dowhilesum()
Diffstat:
3 files changed, 34 insertions(+), 2 deletions(-)
diff --git a/fs/comp/c/fgen.fs b/fs/comp/c/fgen.fs
@@ -59,12 +59,29 @@ alias noop parseStatement ( tok -- ) \ forward declaration
: _continue [compile] ahead _conts :push read; ;
+: _while
+ _breaks :count >r _conts :count >r
+ here read( nextt parseExpression read)
+ Result :?>W$ W=0>Z, 0 Z) branchC,
+ nextt parseStatement ( tgt jmp )
+ r> resolvecontinues
+ swap [compile] again [compile] then r> resolvebreaks ;
+
+: _do
+ _breaks :count >r _conts :count >r
+ here nextt parseStatement ( tgt )
+ r> resolvecontinues
+ nextt S" while" s= _assert
+ read( nextt parseExpression read)
+ Result :?>W$ W=0>Z, NZ) branchC, drop
+ read; r> resolvebreaks ;
+
10 stringlist statementnames
"{" "return" "if" "for" "pspush" "break" "continue" "while" "do" "switch"
10 wordtbl statementhandler ( -- )
'w parseStatements 'w _return 'w _if 'w _for
-'w _pspush 'w _break 'w _continue 'w _err
-'w _err 'w _err
+'w _pspush 'w _break 'w _continue 'w _while
+'w _do 'w _err
0 value _laststmtid
: _ ( tok -- ) \ parseStatement
diff --git a/fs/tests/comp/c/cc.fs b/fs/tests/comp/c/cc.fs
@@ -65,6 +65,7 @@ typecast 1 #eq
testend \s
5 whilesum 15 #eq
5 dowhilesum 15 #eq
+testend \s
create mydata 42 , $12345678 , $23456789 ,
mydata structget $35 #eq
mydata $42 structset mydata 4 + @ $42345678 #eq
diff --git a/fs/tests/comp/c/test2.c b/fs/tests/comp/c/test2.c
@@ -235,3 +235,17 @@ int typecast() {
int y = 1;
return x == (char)(y-2);
}
+void whilesum(int n) {
+ int res = 0;
+ while (n) {
+ res = res + n--;
+ }
+ return res;
+}
+void dowhilesum(int n) {
+ int res = 0;
+ do {
+ res = res + n--;
+ } while (n);
+ return res;
+}