lundi 20 mai 2019

Why is this substitution failure occuring in SFINAE-based reflection?

I have written code that detects if one object can be streamed into an std::ostream. However, while it works in clang, it fails in gcc. After simplifying the code, the problem seems to occur when two classes have operator<< defined in different namespaces.

Below is the (simplified) code (and here it is on godbolt):

#include <iostream>

namespace test_ns {
  // Define two (trivial) classes.
  class Class1 { };
  class Class2 { };

  // First class has ostream operator defined in namespace test_ns
  std::ostream & operator<<(std::ostream & out, const Class1 & v) {
    return out << "Class1 Output!";
  }
}

// Second class as ostream operator defined in global namespace.
std::ostream & operator<<(std::ostream & out, const test_ns::Class2 & v) {
  return out << "Class2 Output!";
}

namespace test_ns {
  // Simple template that always evaluates to bool (for SFINAE-based reflection)
  template <typename EVAL_TYPE> using bool_decoy = bool;

  // Two version of HasPrint that test the operator<< into ostream.
  // First version preferred if << works...
  template <typename T>
  bool HasPrint(bool_decoy<decltype( std::declval<std::ostream&>() << std::declval<T>() )>) {
    return true;
  }

  // Second version as a fallback.
  template <typename T>
  bool HasPrint(...) {
    return false;
  }

}

int main()
{
  std::cout << test_ns::HasPrint<test_ns::Class2>(true) << std::endl;
}

Here is the error I receive in gcc 9.1:

<source>: In instantiation of 'bool test_ns::HasPrint(test_ns::bool_decoy<decltype ((declval<std::basic_ostream<char, std::char_traits<char> >&>() << declval<T>()))>) [with T = test_ns::Class2; test_ns::bool_decoy<decltype ((declval<std::basic_ostream<char, std::char_traits<char> >&>() << declval<T>()))> = <type error>]':

<source>:40:55:   required from here

<source>:26:68: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'test_ns::Class2')

   26 |   bool HasPrint(bool_decoy<decltype( std::declval<std::ostream&>() << std::declval<T>() )>) {

      |                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~


(followed by a long list of candidates)

While I can (and will) refactor the code to circumvent this issue, I don't fully understand what is going wrong here. Am I improperly defining the operators, or is this a problem with gcc?





Baking a byte array into dynamic IL

I am writing a performance-oriented data deserializer by emitting IL. The serialized data is UTF8, and the fields are denoted as strings.

[FieldA]: 22
[FieldB]: 16

I have already written a custom reader that properly tokenizes the serialized data and provides a ReadOnlySpan<byte> as it steps through the serialized data.

I would like to have a static, inline deserializer that is able to have the byte signatures of the fields packed in so that I can easily create a jump table and set the appropriate fields.

How non-dynamic code might look:

// byteSpan is a ReadOnlySpan<byte> containing the signature

var signatureA = Encoding.UTF8.GetBytes( "FieldA" );
var signatureB = Encoding.UTF8.GetBytes( "FieldB" );
if( byteSpan.SequenceEqual( signatureA ) )
  DoSomething();
else if ( byteSpan.SequenceEqual( signatureB ) )
  DoSomething();
...

How the jump table is being emitted:

var fieldSignatures = GetTypeSignatures<T>(); // Returns a Tuple<byte[], FieldInfo>
var setFieldLabels = new List<Tuple<FieldInfo, Label>>();

foreach( (byte[] signature, FieldInfo field) in fieldSignatures )
{
  var setFieldLabel = il.DefineLabel();
  setFieldLabels.Add( Tuple.Create( field, setFieldLabel ) );

  il.Emit( OpCodes.Ldloc_1 ); // Load the current ReadOnlySpan<byte>
  // Inline load byte[] signature here
  il.Emit( OpCodes.Call, METHOD_SEQUENCEEQUAL );
  il.Emit( OpCodes.Brtrue, setFieldLabel );
}

EmitFieldSetters( setFieldLabels, ref il );

Is there a way I can bake the signature byte arrays directly into the IL that I am emitting so that they are a part of the delegate?

These signatures are generated at runtime based on type information, so manually defining them in a static class isn't feasible. A workaround could be to define a new dynamic Assembly and Type and store the bytes in there, but I would like to avoid having to do that if possible.





How do I dynamically create a graphene Object? For example, I want to at run time add fields and resolvers based off of a configuration file

I want to be able to create a GraphQL Server dynamically from a given configuration file. So for example, my configuration file will include what fields should exist, and some of the fields will have a flag indicating them as the primary key or secondary key which will map to them getting a resolver. How would I achieve dynamically creating a graphene object type?

I tried taking graphene's example code and adding fields to it. But it won't accept them. I tried diving into the meta data and updating some options, but that hasn't panned out either.

class User(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()


class Query(graphene.ObjectType):
    me = graphene.Field(User)

    def resolve_me(self, info):
        return info.context["user"]

schema = graphene.Schema(query=Query)
query = """
    query something{
      me {
        name
        temp
      }
    }
"""

if __name__ == "__main__":
    userobj = User
    print(dir(userobj._meta.fields))
    setattr(userobj,"temp", graphene.String())
    print((userobj._meta.fields))

    userobj._meta.fields.update({"temp": graphene.String()})
    print(userobj._meta.fields)

    print((userobj._meta.fields))
    result = schema.execute(query, context={"user": userobj(id="X", name="Console", temp="hey")})
    print(result.data)
    print(result.data["me"])

Currently I get None with this attempt. Taking out the portion where I update _meta.fields, I get 'temp isn't a valid argument' for creating a userobj. 'temp' is an invalid keyword argument for User





Object in Object to HashMap with reflection

Project:

I am currently using a tool called Netuno to develop an api, so to do the export of objects to json it is necessary to do the transformation of the object to HashMap, for this a method was developed in a parent class to export the object.

The method:
   public Map<String, Object> export() {
        Object obj = this;
        Map<String, Object> map = new HashMap<>();
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(obj));
            } catch (Exception e) {
                //todo e
            }
        }
        return map;
    }

This works, but only for simple objects.

My problem:

If the object has complex objects inside my method it has no ability to export them to HashMap either.

Example structure:

public abstract class Master {
 public Map < String, Object >
  export () {
   Object obj = this;
   Map < String, Object > map = new HashMap < > ();
   for (Field field: obj.getClass().getDeclaredFields()) {
    field.setAccessible(true);
    try {
     map.put(field.getName(), field.get(obj));
    } catch (Exception e) {
     //todo e
    }
   }
   return map;
  }
}

public class Foo extends Master {
 private int a;
 private int b;
 private String c;
 private Bar bar;
//...
}

public class Bar extends Master {
 private int q;
 private int w;
 private String e;
//...
}


I use it this way:

return new Bar(/*data*/).export();

Output:

{
  "a": 2,
  "b": 5,
  "c": "abc",
  "bar": "myproject.myPackage.Bar@XXXXX"
}

Expected Output:

{
  "a": 2,
  "b": 5,
  "c": "abc",
  "bar": {
    "q": 10,
    "w": 15,
    "e": "it works"
  }
}





dimanche 19 mai 2019

Invoke arithmetic operator dynamically

Powershell has arithmetic operators like addition (+), substraction (-) and bitwise and (-band). I'm making a simple calculator program, and I want to dynamically perform arithmetic calculations based on the user input, without needing to write a lot of if-else statements. Is there a way to dynamically invoke powershell operators? E.g. if $method=="plus" do "6+6".

I know there is Invoke-Expression, but that doesn't really operate on the operator alone (you also need to supply the operands in the expression string). Is there some way to define the operator as a variable? E.g. $method="-band", $result=6 $method 6;





C#: Construct Type Constrained Half-Closed Generic Implementations of Open Generic Interface via Open Generic Method/Class

I am trying to construct instances of an open generic repository interface whereby the implementations impose more strict type constraints than the interface. Each implementation of the repository interface needs a specific implementation of the generic type to handle certain methods/operations based on the passed type's properties (not shown for the sake of brevity).

Here is a comprehensive example of the scenario:

public interface IRepository<T> where T : class
{
    //...
}

public class BaseRepository<T> : IRepository<T> where T : DbModel
{
    //...
}

public class SqlServerDbRepository<T> : BaseRepository<T> where T : SqlServerDbModel
{
    //...
}

public abstract class DbModel
{
    //...
}

// is further derived by other models
public class SqlServerDbModel : DbModel
{
    //...
}

public class User : SqlServerDbModel
{
}


// CLIENT CODE

public static IRepository<T> BuildRepository<T>()
    where T : class
{
    if (typeof(T) == typeof(SqlServerDbModel)) // "is" keyword will not work here (according to IDE, have not checked)
    {
        return new SqlServerDbRepository<T>(); // How can T be converted or accepted as an input of type "SqlServerDbModel" (the check already confirms it, so we know it should work)
    }
    else if (typeof(T) == typeof(DbModel))
    {
        return new BaseRepository<T>(); // How can T be converted or accepted as an input of type "DbModel" (the check already confirms it, so we know it should work)
    }
    //... else throw error or just return default...
}

// USAGE
public static void TestBuildRepository()
{
    var userRepository = BuildRepository<User>();
}

I tried initially running the scenario through an IOC container (Castle Windsor in case anybody is wondering) figuring it would figure out the type constraints automatically, however, this was not possible (or at least not with the way it handles open generics and dependency injection). I figured I could use a custom factory to build the interface implementations.

The problem is in the lines matching the pattern return new XYZRepository<T>(); whereby I am not sure how to get the c# compiler to take the generic type "T" passed to it, knowing it will fully satisfy the type constraint. I am sure this could be done through reflection, but I only found information on how to build methods and properties, not generic classes. How could this be achieved?

P.S.

I cannot make any changes to the interfaces, repository implementations, or models...just in case anyone was going to make that suggestion.

Please and thanks!





Dictionary

How do I convert a Dictionary to class and subclasses recursively? These are my classes: class Program { class Provider { public string Id { get; set; } public Address Address { get; set; } public Address Address2 { get; set; } public List Specalities; }

class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

class Speciality
{
    public string Description { get; set; }
}

}