Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Numeric not handling trailing zeros #3371

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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", () => {
timotheeguerin marked this conversation as resolved.
Show resolved Hide resolved
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
Loading