Skip to content

Commit

Permalink
Numeric not handling trailing zeros (#3371)
Browse files Browse the repository at this point in the history
```tsp
const a = 100.0
```

was getting into an infinite loop
  • Loading branch information
timotheeguerin authored May 16, 2024
1 parent 69d6cb7 commit aa91dcd
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: fix
packages:
- "@typespec/compiler"
---

Numeric not handling trailing zeros and causing freeze(e.g. `const a = 100.0`)
10 changes: 3 additions & 7 deletions packages/compiler/src/core/numeric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,10 @@ function parse(original: string): InternalData {
}

let end = stringValue.length;
while (stringValue[end - 1] === "0") {
if (end < adjustedPointIndex) {
// if we are looking at a zero before the decimal point, we need to decrease the exponent
exp++;
} else {
end--;
}
while (stringValue[end - 1] === "0" && end > adjustedPointIndex) {
end--;
}

try {
stringValue = stringValue.slice(0, end);
stringValue = stringValue + "0".repeat(Math.max(exp - stringValue.length, 0)); // add remaining zeros for cases like 3e30
Expand Down
20 changes: 19 additions & 1 deletion packages/compiler/test/core/numeric.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ describe("parsing", () => {

describe("invalid number", () => {
// cspell: ignore babc
it.each(["0babc", "0xGHI", "0o999", "a123", "1d.3"])("%s", (a) => {
it.each(["0babc", "0xGHI", "0o999", "a123", "1d.3", "1.2.3"])("%s", (a) => {
expect(() => Numeric(a)).toThrow(`Invalid numeric value: ${a}`);
});
});
Expand All @@ -39,6 +39,24 @@ describe("parsing", () => {
it("simple decimal", () => {
expectNumericData("123.456", 123456n, 3);
});

describe("decimal with trailing zeros", () => {
it.each([
["1.0", 1n, 1],
["10", 10n, 2],
["10.0", 10n, 2],
["10.00000", 10n, 2],
["100.0", 100n, 3],
["100", 100n, 3],
["1000.0", 1000n, 4],
["1000000000", 1000000000n, 10],
["1000000000.0", 1000000000n, 10],
["1000000000.00000", 1000000000n, 10],
])(`%s`, (a, b, c) => {
expectNumericData(a, b, c);
});
});

it("negative decimal", () => {
expectNumericData("-123.456", 123456n, 3, -1);
});
Expand Down

0 comments on commit aa91dcd

Please sign in to comment.