How does golang implement reflection? - reflection

Using reflection, we can get the type name, storage size and the function of the given type(such as uint64, user-defined struct and so on). Even, we can modify some fields of the given type.
How does golang implement reflections? I guess the following ways:
Every type in golang, including user-defined type, itself has the information about type name, fields name and the function name. Golang reflection just reads these information or call the function.
Through some mechanism, Golang can get the type name, storage size and so on. And the type itself doesn’t have these information.
I have read the golang reflection code roughly. I guessed that golang used the second way.
Who can describe the concrete implement of reflection? Or recommend me some documents? Reading all code is difficult for me.

This is just an overview and it might be not 100% accurate but hopefully you will find it helpful.
At build time Go linker will embed information about all types used by the application into the executable (https://github.com/golang/go/blob/master/src/runtime/symtab.go#L39)
Each interface value contains a pointer to the data type descriptor (https://github.com/golang/go/blob/master/src/runtime/type.go#L14)
During conversion from a type that is known at compile time to an interface value Go compiler will point type descriptor of this interface value to the concrete type descriptor (it is known at compile time!).
E.g. when you call reflect.TypeOf(uint(87)):
an interface value is created by the compiler that references uint type descriptor
this interface value is passed to reflect.TypeOf function as argument
reflect.TypeOf function uses type descriptor that has been stored by the linker in the executable to get the align (and other) information about uint type.

The description of interfaces is well described here: The Laws of Reflection.
A variable of interface type stores a pair: the concrete value
assigned to the variable, and that value's type descriptor.
Basically, type are known statically from your code. More flexible interface types keep the original underlying type for getting back to the original data type.

Related

How can I serialize and deserialize a private type?

I'm working with the GNAT.OS_Lib module to implement a process manager for Linux. I'm using the subprograms in that module to spawn processes and get back PIDs, and now I want to save those PIDs to a file so they can be retrieved later to kill the process, get its status, etc. The problem is, the Process_Id type is private:
type Process_Id is private; -- s-os_lib.ads, line 743
The module provides a Pid_To_Integer function, but not the inverse. How can I serialize and deserialize Process_Ids?
Study section K.2 "Language Defined Attributes" in the Ada Language Reference Manual http://www.ada-auth.org/standards/12rm/html/RM-K-2.html
The attributes to study are S'Read, S'Write.
Your file must be created as a stream file. The Process_Id'Write attribute will serialize and write to the stream file. The Process_Id'Read attribute will read and de-serialize the data in the file.
If S'Read and S'Write do not work for you because of the nature of a compound type you should use the S'Input and S'Output attributes, which will read and write any bounds or discriminants.
S'Input and S'Output will work correctly with all types.

Where is the mutability of Objects defined in ECMAScript?

In this question about the passing of arguments in JavaScript functions, we learn that everything is passed by value in JavaScript.
In Mozilla documents, it is mentioned that the primitive types are immutable, and objects are. Although I came from the procedural and structured programming school, I was able to quickly pick up the concepts.
In the ECMAScript standard, it is defined that "An Object is 'logically' a collection of properties". The standard also defines how objects may be compared, but left out on what happens when an object goes through the GetValue() pseudo-function that converts references into values.
So, I gave an answer in the question basically saying that this area had been left undefined.
My Question
I feel that by "left undefined", I meant, it wasn't philosophically thoroughly clear, what the value of an Object is. The standard had gone through a few revisions, and its size is ever increasing.
In short, an object is a collection, but what is the value of the collection? Is it the makeup of its content? Or is it individuality? Or have I been missing out on some important texts?
In the ECMAScript spec, every object is defined to have certain 'internal methods', some of which (e.g., [[DefineOwnProperty]] and [[Put]]) can change the state of the object. Ultimately, the mutability of objects is defined via the use of such internal methods.
GetValue() doesn't leave out what happens to objects -- step #1 is:
If Type(V) is not Reference, return V.
So it you pass it an object, you get back the same object.
(Which refutes one of your premises, but I'm not sure it resolves your question.)
See section 4.3.26 "property" of the 5.1 edition. The note says:
Depending upon the form of the property the value may be represented either directly as a data value (a primitive value, an object, or a function object) or indirectly by a pair of accessor functions.
We can take this as meaning a data value is one of the following:
Primitive Value: such as C language double, _Bool, ((void*)0), etc.
An object: which can be interpreted as a special C language structure containing the underlaying information about the object.
Function object: which is just a special case of 2, possibly the result of JIT compilation.
The reason this note for the definition of property is important, is because, everything - even function block scopes - are objects (or at least described in terms of one). Therefore, if we can determine that "the value of an object" is its individuality rather than its content makeup, then with the fact that every object accessible from a JavaScript program, is accessed as if its the property of some other object.
In section 4.2 "Language Overview", it says:
A primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of the remaining built-in type Object; and a function is a callable object.
Although this is an informal section, it can be seen that an object differs from a primitive value in a significant way.
As an interpretation, let's consider the value of an object is the object itself as we can infer from the "GetValue()" pseudo function - the overview says "an object is a member of the ... type Object - therefore, the value is the membership to the Object type.
To use a physics analogy to explain the relationship between membership and individuality, we see too electrons. They are identical in content, they're both the members of the Universe, yet they are two different individuals.
Therefore, we infer that - the value of a JavaScript Object, is its individuality.
Finally as to the question as asked in the title.
The mutibility of individual objects is defined in terms of a series of specificational pseudo functions, and immutability of other types is defined using the definition of value membership of types and specification pseudo functions operating on the primitive type values.

Fortran Derived Type - Public Pointer to a Private Array

I'm trying to define a Fortran derived type that has a private allocatable array. However, I would like to be able to access the array via a public pointer for use in other modules. E.g.
type,public :: test
private
real,allocatable :: a(:,:,:)
contains
real,pointer,dimension(:,:,:),public :: point => a
end type test
I just get a compiler error when attempting it like the above.
Is this possible without writing a subroutine that does the pointing for me?
No.
The syntax error is perhaps because you have the pointer component in the type bound procedure part of the type definition (after the contains), not in the component part (before the contains).
Beyond syntax, there are some problems with what you want to do:
You cannot associate a pointer with a component of a type definition. Pointers can be associated with components of objects (a subobject). Similarly, you cannot associate a pointer with something that doesn't have the target attribute. Types and components of types can't have the target attribute. Variables of that type, or objects pointed at by pointer components of an object may have the target attribute.
You cannot associate a pointer with something that isn't allocated. If something isn't allocated then there isn't anything to point at.
An initializer for a pointer component cannot refer to something that is allocatable. In addition to the target attribute the thing that it refers to must have the SAVE attribute. As the case with the TARGET attribute, variables have the save attribute, not type or component definitions.
Associating a pointer with a component of an object may defeat the point of making the component private in the first place. This leads to the question - what are you trying to do?

maps as anonymous struct members

I was stumbling over some behavior in go which I cannot make sense of completely and explainations of any kind would be wellcome:
type Test struct{
Name string // or other metadata to be stored along the core map element
map[string]string
}
The above code will fail to compile with an unexpected map error.
Which is probably because struct Field delarations must be types, however I fail to appriciate why map[string]string is not a type.
Changing it to
type Embedded map[string]string
type Test struct{
Name string
Embedded
}
get's arround the compiler error, but still Test["someKey"] raises the compiler error
invalid operation: Test["someKey"] (index of type Test).
Of course adressing the anoymous field directly with Test.Embedded["someKey"] works,
but my questions are:
Why are literal map declarations valid as types in non-anonymous field declarations but not valid in anonymous fields
Why does indexing the containing type not work? Why can't it work?
Thanks for clarifications.
Anonymous fields must be named types only. You're perhaps somewhat confusing Type, LiteralType and TypeName.
Referring to an anonymous field is presribed by the specs to be done always by its type name. Thus Test.Embedded[key] is the only legal form. Here you might be confusing the embedded field methods, which are inherited from embedded fields w/o need to use the field name and the field value, which must use it.

Qt: Pass pointer to QObject in QMimeData

Is it possible to pass a pointer to a QObject using QMimeData during drag-and-drop operation? QMimeData only has this function for storing data:
void QMimeData::setData(constQString &mimeType, const QByteArray &data)
but I can't find a way to safely encode a pointer into a QByteArray.
To clarify my goal: I need to pass a pointer to a QObject from a model to the target widget during the drag-and-drop operation.
Edit:
As far as I undrestand Mime data is all about passing application independent data from one place to another: urls, colors, html code. In my case I need to pass a pointer to a resource object eithin the application. How to you usually deal with this kind of drag-drops?
Thanks
Anton
You can subclass QMimeData and pass whatever you want.
To be on the safe & elegant side, I would come up with unique identifiers (e.g. strings, or numbers) for my objects and pass them as mime objects. Resolving a string back into the corresponding object using QHashmap is fast enough for your purpose.
The dirtiest (not recommended!) way would be that the identifier is the pointer address as int.
If you pass mime data with user interaction, you never know where it goes. If the user drops your pointer onto another application's window, it should fullfill the user's expectations best.
An application that gets a mangled up mime object and crashes for it is worst.
An application that gets a descriptive string and enables the user to understand what he was dropping is probably best.
I know that you can also, using the mime type, somewhat direct where the payload may be dropped and where not. the quintessence however is that you should stay within the mime concept. And that includes not passing a raw pointer.
As Kash said and the Qt docs suggest, subclass QMimeData.
Then, add the following:
text/plain data describing or representing the dragged object, so if you drop this data to notepad.exe, it results in something relevant
custom data type with an identifier or token that enables you to know that some dropped mime data is actually your subclass
add your own data in the subclass
You will still need to test the qobject_cast (or dynamic_cast), because some other program might have proxied your mime data object.

Resources