Skip to content

Commit

Permalink
variable name check
Browse files Browse the repository at this point in the history
  • Loading branch information
LucaDillenburg committed Aug 20, 2020
1 parent 4818413 commit de5cd62
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 7 deletions.
2 changes: 2 additions & 0 deletions Assembler/config/generalConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ const AmntBitsCode = 8
const AmntBitsParam = 8

var Testing bool = false

const VariableNameRegex = "^[a-zA-Z][a-zA-Z0-9_]*$"
2 changes: 1 addition & 1 deletion Assembler/core/commandAssembler.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func getSecondWord(commandName string, words []string, acceptStringParam bool) (

strParam := words[1]

if utils.IsVariableName(strParam) {
if acceptStringParam && utils.IsValidVarName(strParam) {
param := data.NewStringParam(strParam)
return &param, nil
}
Expand Down
6 changes: 0 additions & 6 deletions Assembler/utils/validation.go

This file was deleted.

7 changes: 7 additions & 0 deletions Assembler/utils/validations.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
package utils

import (
"assembler/config"
"math"
"regexp"
)

func IsOverflow(num uint, availableBits int) bool {
largestNumber := math.Pow(2, float64(availableBits))
return num >= uint(math.Floor(largestNumber))
}

func IsValidVarName(str string) bool {
matched, err := regexp.MatchString(config.VariableNameRegex, str)
return matched && err == nil
}
35 changes: 35 additions & 0 deletions Assembler/utils/validations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,38 @@ func TestOverflow(t *testing.T) {
}
}
}

func TestIsValidVarName(t *testing.T) {
var tests = []struct {
param string
expected bool
}{
{"", false},
{"a", true},
{"var", true},
{"Var", true},
{"vaR", true},
{"VAR", true},
{"var_able", true},
{"var_Able", true},
{"var_ABLE", true},
{"va0r_4ABLE1", true},
{"va.", false},
{"va.r", false},
{"va-r", false},
{"va*r", false},
{"va^r", false},
{"va&r", false},
{"&var", false},
{"var&", false},
{"jmp", true},
}

for _, test := range tests {
got := IsValidVarName(test.param)

if test.expected != got {
t.Errorf("For var name '%s': Expected: %t, Got: %t", test.param, test.expected, got)
}
}
}

0 comments on commit de5cd62

Please sign in to comment.