Reputation: 872
I'm writing a bison/flex parser, with multiple data types, all compatible with ANSI C. It won't be a C language, but will retain its data types. Thing is... I am not sure how to do this correctly.
For example, in an expression, say 'n1' + 'n2', if 'n1' is double and 'n2' is a 32 bit integer, I will need to do type conversion right? How to do it correctly? i.e. I will logically need to evaluate which type is bigger (here it's double), then convert the int32 to double and then perform the add operation, which would result in a double of value n1 + n2.
I also want to provide support for type casting.
What's the best way to do it correctly? Is there a way to do it nicely or will I have to put a billion of conversion functions like uint32todouble, int32todouble, int32tolongdouble, int64tolongdouble, etc etc.
Thanks!
EDIT: I have been asked to clarify my question, so I will. I agree this is not directly related to bison/flex, but I would like people experienced in this context to hint me.
Say I have such an operation in my own 'programming' language (i would say it's more scripting, but anyways) i.e. the one I would parse :
int64 b = 237847823435ll
int64 a = int64(82 + 3746.3746434 * 265.345 + b)
Here, the int64() pseudo-function is a type cast. First, we can see the 82 is an int constant, followed by 3746.3746434 and 265.345, and b is an int64. So when I do the operation at A, I will have to :
As you see, it's quite lots of type changes... And I wonder how I can for example do them in the most elegant and less work possible. I'm talking about the internal implementation. I could for example write things like :
int64_t double_to_int64(double k) {
return (int64_t) k; // make specific double to int64 conversion
}
For each of the types, so I'd have functions specific to each conversion, but it would take quite lots of time to achieve it and bsides it's an ugly way of doing things. Since some of the variables and number tokens in my parser/lexer are stored in buffers (for different reasons), I don't see really how I could find a way to convert from a type to another without doing such functions. Not to mention with all the unsigned/signed types, it will double the number of required functions.
Thanks
Upvotes: 0
Views: 902
Reputation: 311054
This has nothing to do with flex or bison. It is a language design question.
I suggest you have a look at the type promotion features of other languages. For example, C and Java promote byte, char, and short to int whenever used in an expression. So that cuts a lot of cackle straight away.
These operations are single instructions on the hardware. You don't need to write any functions at all; just generate the appropriate code. If you're designing an interpretive system, design the p-code accordingly.
Upvotes: 1