dotnet / dotnet/fsharp

Parsing ambiguity with numeric literals and calling methods

Open
#12,516 2 comments 0 reactions 0 assignees View on GitHub
Area-Diagnostics Area-LangService-Diagnostics Feature Improvement
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 11h
Merged PRs (30d)
131

Description

When calling methods on integer numeric literals (and possible other forms of literals that may be ambiguous), the user is presented with an error about a malformed numeric literal. While correct from the compiler's perspective, this appears trivially solvable to the user, so we should investigate changes to the error message or parser/checker enhancements to make this form understandable to the compiler.

**Repro steps**

Sample code where an extension method is added to the `int` type and then invoked on the `1` literal, causing a parsing error

```fsharp
open System.Runtime.CompilerServices

[]
type StringExtensions =
[]
static member A(x: int) = 0
[]
static member A(x: float) = 0
[]
static member A(x: bool) = 0

let intExtension = 1.A() // error on this line
let floatExt = 1.0.A()
let boolExt = true.A()
```

**Expected behavior**

The compiler should be able to interpret the right hand side of `intExtension` as `(1).A()`, that is calling the member `A` on the value `1`.

**Actual behavior**

The compiler tries to parse the numeric literal `1.A`, can't, and generates the following error:

```
error FS1156: This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0o1, 0b1, 1l (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger).
```

**Known workarounds**

Add parenthesis around the `1` literal to allow the compiler to parse the numeric literal before going ahead with method invocation.

**Related information**

* [Sharplab link](https://sharplab.io/#v2:DYLgZgzgPg9gDgUwHYAIDKBPCAXBBbAOgCUBXJbASzwQIGEY84LgEAnNNgNwoGMEIAsAChhAbQA8AUQAeuJBAowkAPgC6w7BkTpsrCkgDmMuQqUQUAXhTCUtlBOPJTK9ULsocAQ0o8U1PABGbCgAggAU0iAo+tgAlJYoAAw2dg6yToouKbZePn74QayhEVFgwDDe8VbJbqlS6fKZatke2N68+YHB4ZEoATAwwFVJLcIs2NHkjo1KCQCMBOGxYwgTZRXYxvMEiYthy0LjfQPAW1a6JDRLQA==)
* [Twitter thread](https://twitter.com/ChetHusk/status/1471147557447475208)

cc @KathleenDollard as co-discoverer

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.