Skip to content

Commit

Permalink
Add type checking for arithmetic operators
Browse files Browse the repository at this point in the history
  • Loading branch information
waleedyaseen committed Nov 24, 2023
1 parent ef0d431 commit f953a89
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## [Unreleased]
- Add support for `long` numeric type.
- Add `stylesheet` to the valid types list.
- Add type checking for arithmetic operators.

## [1.4.1] - 2023-10-16

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class RsTypeInferenceVisitor(private val myInferenceData: RsTypeInference) : RsV
if (unfoldedActualType != unfoldedExpectedType) {
if (reportError) {
context.error(
"Type mismatch: '%s' was given but '%s' was expected".format(
TYPE_MISMATCH_ERROR.format(
unfoldedActualType.representation,
unfoldedExpectedType.representation
)
Expand Down Expand Up @@ -511,6 +511,17 @@ class RsTypeInferenceVisitor(private val myInferenceData: RsTypeInference) : RsV

o.right.typeHint = o.typeHint ?: RsPrimitiveType.INT
o.right.accept(this)

val leftType = o.left.type.unfold()
val rightType = o.right.type.unfold()

if (leftType == null || rightType == null || leftType is RsErrorType || rightType == RsErrorType) return

val operator = o.arithmeticOp

if (leftType != rightType) {
o.error(INVALID_OPERATOR_ERROR.format(operator.text, leftType.representation, rightType.representation))
}
}

override fun visitArithmeticValueExpression(o: RsArithmeticValueExpression) {
Expand Down Expand Up @@ -665,10 +676,8 @@ class RsTypeInferenceVisitor(private val myInferenceData: RsTypeInference) : RsV
checkExpressionList(o, o.expressionList, expectedReturnList ?: emptyArray<RsType>())
}
companion object {
private val ALLOWED_RELATIONAL_TYPES = arrayOf(
RsPrimitiveType.INT,
RsPrimitiveType.LONG
)
private const val TYPE_MISMATCH_ERROR = "Type mismatch: '%s' was given but '%s' was expected"
private const val INVALID_OPERATOR_ERROR = "Operator '%s' cannot be applied to '%s', '%s'"
}
}

Expand Down

0 comments on commit f953a89

Please sign in to comment.