microsoft / typespec

https://typespec.io/
MIT License
4.3k stars 199 forks source link

Some float value would map to int in enum values e.g `1.0` -> `1` #2240

Open MaryGao opened 1 year ago

MaryGao commented 1 year ago

See the example for FloatEnum which has values 1.0, 2.0, 3.0 would be mapped to 1, 2, 3. I think this is incorrect.

enum FloatEnum {
  One: 1.0,
  Two: 2.0,
  Three: 3.0,
}

swagger spec:

FloatEnum:
      type: number
      enum:
        - 1
        - 2
        - 3

Another thing is I notice that the docs guides me following cases but it doesn't work, could you update the docs?

enum Hour {
  Zero = 0,
  Quarter = 0.25,
  Half = 0.5,
  ThreeQuarter = 0.75,
}

image

timotheeguerin commented 1 year ago

Seems like we have a typo in the docs, the example above show the correct syntax with : instead of =.

For the float part it is an a bit of a problem. We have numbers behind the scene in javascript, literals in typespec are just numeric it doesn't remember if it was defined with .0.

edit: we actually have valueAsString which "could" be used but is also not super clean and leave the job to every emitter to check if something is a float, int, etc.

MaryGao commented 1 year ago

@timotheeguerin Does that mean every emitter needs to check by themselves if they have requirement to distinguish 1.0 and 1?

model Result {
  prop: 1.0   // Here emitter may need to check if the devired type is int or float
}
timotheeguerin commented 1 year ago

yeah.. which is not ideal. Or we need to have at least an helper of the sort getNumericPrecision(numericType) // => int32, float64, etc.)

markcowl commented 1 year ago

fix the above doc

timotheeguerin commented 1 year ago

Doc fixed in https://github.com/microsoft/typespec/pull/2245, this can remain as a design discussion

ArcturusZhang commented 3 months ago

I opened this issue: https://github.com/microsoft/typespec/issues/2240 This would be an issue in csharp because adding a new value will cause breaking changes in C# for example, in one version we have:

enum Foo {
A: 1.0;
B: 2.0;
}

and everything will generate as integers. When they add a real float number, everything suddenly changed to generate as float:

enum Foo {
A: 1.0;
B: 2.0;
C: 3.3;
}