If statements

This commit is contained in:
2025-11-01 10:30:03 +11:00
parent 5e9c2273a9
commit 4bcbc6c650
5 changed files with 76 additions and 6 deletions

View File

@@ -79,6 +79,8 @@ def generateCode(line: list[str], offset: int) -> str:
line[3] = line[3][:(int(line[2])-len(line[3]))]
for char in line[3]:
returnval += '+' * ord(char) + '>'
for char in range(int(line[2])-len(line[3])):
returnval += '>'
else:
error(f'Invalid string: {line[3]}')
@@ -173,8 +175,14 @@ def generateCode(line: list[str], offset: int) -> str:
return returnval
elif keyword == 'inc':
if len(line) != 2:
error(f'Inc command requires 1 argument (got {len(line)-1})')
returnval = '>' * offset + '[>]'
idx = getIndex(line[1])
if variables[idx].type != 2:
error(f'Cannot increment {line[1]}: Invalid type')
for var in variables[:idx]:
if var.bytes > 0:
returnval += '>' * (var.bytes + 1)
@@ -236,5 +244,58 @@ def generateCode(line: list[str], offset: int) -> str:
returnval += '<[<]' + '<' * (offset-1)
return returnval
elif keyword == 'if':
if len(line) != 2:
error(f'If command requires 1 argument (got {len(line)-1})')
returnval = '>' * offset + '[>]'
idx = getIndex(line[1])
for var in variables[:idx]:
if var.bytes >= 0:
returnval += '>' * (var.bytes+1)
elif var.bytes == -1:
returnval += '>[>]'
else:
error()
returnval += '>[<+>->+<]<[>+<-]>>[<<'
for var in reversed(variables[:idx]):
if var.bytes >= 0:
returnval += '<' * (var.bytes+1)
elif var.bytes == -1:
returnval += '<[<]'
else:
error()
returnval += '<[<]<+>>[>]'
for var in variables[:idx]:
if var.bytes >= 0:
returnval += '>' * (var.bytes+1)
elif var.bytes == -1:
returnval += '>[>]'
else:
error()
returnval += '>>-]<<'
for var in reversed(variables[:idx]):
if var.bytes >= 0:
returnval += '<' * (var.bytes+1)
elif var.bytes == -1:
returnval += '<[<]'
else:
error()
returnval += '<[<]<[' + '<' * (offset-2) + '+' + '>' * (offset-2) + '-]' + '<' * (offset-2) + '[-'
return returnval
elif keyword == 'end':
if len(line) != 2:
error(f'End command requires 2 arguments (got {len(line)-1})')
if line[1] == 'if':
return ']'
else:
error(f'Invalid argument for end: {line[1]}')
else:
error(f'Invalid keyword: {line[0]}')

View File

@@ -19,7 +19,7 @@ def preprocess(code: str) -> list[list[str]]:
token += i
if (i == '\"'):
isString = not(isString)
else:
elif token != '':
tokenise[-1].append(token)
token = ''

View File

@@ -14,6 +14,13 @@ Print a string: `print name`
Increment an int: `inc name`
If statement:
```py
if bool
# Code here
end if
```
Example program (prints "Hello, World"):
```py
string var 13 "Hello, world!" # Or -1 bytes for a dynamic string

View File

@@ -1,5 +0,0 @@
string str1 13 "Hello, world!"
string str2 -1 "Testing dynamic string!"
int var -1
inc var
inc var

7
tests/test.basm Normal file
View File

@@ -0,0 +1,7 @@
string str1 -1 "Hello, world!"
int num 100
bool cond true
if cond
inc num
end if