Unable to compile variant record

Issue #197 new
Nikola Dimitrov created an issue

When trying to compile a variant record I get an error Syntax Error: Name expected [line: X, column: Y, file: FileName]. As a simple example, consider this:

TCustomType = record
  case Tag: Integer of
    0: (Value1: String);
    1: (Value2: Integer);
end;

Putting this bug aside for a moment my intentions are to emulate the Algebraic Data Types commonly found in functional programming languages. The need to do so arises, because a JavaScript library I’m currently wrapping is using POJOs to pass around a bunch of options. But those POJOs have members with disjoint types, e.g. RegExp and String, String and Function. What I’m looking for is the DWScript equivalent of a type that can be both String and Function, for example, and need not be explicitly unpacked before passing it to the external functions.

Comments (4)

  1. Eric Grange repo owner

    This is not supported because this would be unsafe, however if I understood correctly, you should be able to use the Variant type for that purpose, for the JS codegen it’s an untyped black box.

    If you don’t want to expose the internal Variant field, you could scope it as private, and only expose typed properties, using accessors to implement casts or checks.

  2. Nikola Dimitrov reporter

    @Eric Grange Hello, Eric! Thank you for taking the time! Yes, I suspected it is not supported after not finding any examples in the Smart Mobile Studio RTL ^^ I avoided using Variant on purpose as it is a catch-all type. I wanted to use as much of the specified type-safe goodness of DWScript as possible. This brought me to create a “Frankenstein” class ridden with macros that add/remove methods from its declaration.

    Sounds like you did – There’s a function in the JS library that more or less looks like this https://jsfiddle.net/vmse17uc/1/ It has a single parameter, a POJO, that has various properties, many of them with Sum types, e.g. String|RegExp, Integer|String, String|Function. I wanted to wrap it in DWScript, thus created a new class and a new record holding the atomic data types, but not the sum typed ones.

  3. Eric Grange repo owner

    Hmm, fiddle contains only this

    function Classic(options) {
            return { };
    }
    

    which if that’s what you are after would be equivalent to

    exit Variant(new JObject)
    

    so an empty object/dictionary where fields will get added on the fly.

    Not much typing can happen with libraries having such constructs IME, even if they start with good intents, it often ends up in a free-for-all :/

  4. Nikola Dimitrov reporter

    Yes, that’s the only function in the fiddle, but it’s the JSDoc comments that are of value. That options object has a field grep that has a sum type of RegExp|String. It is this elusive type that I’m after.

  5. Log in to comment