What do "auto," "ansi," and "cil managed" do in CIL? - keyword

I'm learning CIL for various reasons, and it seems that classes are often defined similar to:
.class public auto ansi beforefieldinit [...] extends [mscorlib]System.Object
and functions defined as:
.method [...] (args) cil managed
I understand everything else, but I can't seem to find out what "auto" or "ansi" or "cil managed" do. The keywords are also too vague for me to get specific search results for (beforefieldinit came up nearly instantly).

ECMA-335 provides the information you seek,
under II.10.1 Type header(ClassHeader) you will find:
auto - Layout of fields is provided automatically. - §II.10.1.2
ansi - Marshal strings to platform as ANSI. - §II.10.1.5
Serge Lidin, in his book .Net IL Assembler writes in Chapter 1 under Class Declaration:
The keyword auto in this context defines the class layout style (automatic, the default), directing the loader to lay out this class however it sees fit. Alternatives are sequential (which preserves the specified sequence of the fields) and explicit (which explicitly specifies the offset for each field, giving the loader exact instructions for laying out the class). The keyword ansi defines the mode of string conversion within the class when interoperating with the unmanaged code. This keyword, the default, specifies that the strings will be converted to and from “normal” C-style strings of bytes. Alternative keywords are unicode (strings are converted to and from UTF-16 Unicode) and autochar (the underlying platform determines the mode of string conversion).
under II.23.1.11 Flags for methods [MethodImplAttributes] you can read:
IL - 0x0000 - Method impl is CIL
Managed - 0x0000 - Method impl is managed
Serge Lidin, describes this in Chapter 1 under Method Declaration:
The keywords cil and managed define so-called implementation flags of the MethodDef and indicate that the method body is represented in IL. A method represented in native code rather than in IL would carry the implementation flags native unmanaged.
I recommend you to get a book about this topic, there are a few i think. Its a lot faster than digging around in the ECMA-335 specs.

From ECMA CLI:
ansi Marshal strings to platform as ANSI. §II.10.1.5
auto Layout of fields is provided automatically. §II.10.1.2
beforefieldinit Need not initialize the type before a static method is
called.
§II.10.1.6
About 'cil managed', this method atrribute indicate that the nethod contains IL and all its code is managed.

Related

Roles of Delphi function name in Obj files

what is the roles of function name that's Delphi does when compiling pas file.
for example the following code
unit Hellopas;
interface
function HelloFromPas():Integer; stdcall;
will preduce this function name #Hellopas#HelloFromPas$qqsv
so what is the Delphi roles for that?
This is a decorated or mangled name. The name encodes the full scope for the function, and its parameters. The unit name is included because that is part of the fully qualified name. The parameters, return value and calling convention are encoded also, here as qqsv.
Wikipedia explains the need for mangling like this:
In compiler construction, name mangling (also called name decoration)
is a technique used to solve various problems caused by the need to
resolve unique names for programming entities in many modern
programming languages.
It provides a way of encoding additional information in the name of a
function, structure, class or another datatype in order to pass more
semantic information from the compilers to linkers.
The need arises where the language allows different entities to be
named with the same identifier as long as they occupy a different
namespace (where a namespace is typically defined by a module, class,
or explicit namespace directive) or have different signatures (such as
function overloading).
Any object code produced by compilers is usually linked with other
pieces of object code (produced by the same or another compiler) by a
type of program called a linker. The linker needs a great deal of
information on each program entity. For example, to correctly link a
function it needs its name, the number of arguments and their types,
and so on.

Difference between variable declaration and definition in Swift

The terms "declaration" and "definition" are being used synonymously in Apple's Swift documentation and it's getting me confused.
Under the "Initialization" section (which talks about class initializers), Apple states:
You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.
Further in a subsection they state:
You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the property’s declaration.
I thought a variable declaration was different than a variable definition.
You are right that those two mean different thing, THOUGH I think most of the people just use both of them in the same meaning and I think that is also the case of those AppleDocs. Here is great article on subject:
Summary
A declaration provides basic attributes of a symbol: its type and its
name. A definition provides all of the details of that symbol--if it's
a function, what it does; if it's a class, what fields and methods it
has; if it's a variable, where that variable is stored. Often, the
compiler only needs to have a declaration for something in order to
compile a file into an object file, expecting that the linker can find
the definition from another file. If no source file ever defines a
symbol, but it is declared, you will get errors at link time
complaining about undefined symbols.
After doing much searching across the web for legitimate explanations, I have seemed to have found an answer:
The problem is that the two terms overlap to some extent. Definitions also serve as declarations, because they inject an identifier of a certain type to a scope. However, a declaration isn't a definition because it doesn't entail storage allocation for the declared object. To add to the confusion, the semantics of definitions and declarations is slightly different when applied to types and functions, as I will show momentarily. So let's look at a more detailed analysis of these two terms.
Here is the article: Declarations and Definitions.
The article gives further explanation and examples.
Declaration of variable mean to tell compiler their is a var\funct\struct of particular data type. Definition of variable mean asking compiler to allocate memory to variable or define storage for that variable. you can define a variable only one time but you can declare it as many time you want.
I think Apple's Swift 4 Language Reference can be construed as the authoritative answer. From the Declarations section (emphasis mine):
A declaration introduces a new name or construct into your program.
For example, you use declarations to introduce functions and methods,
variables and constants, and to define new, named enumeration,
structure, class, and protocol types. You can also use a declaration
to extend the behavior of an existing named type and to import symbols
into your program that are declared elsewhere.
In Swift, most declarations are also definitions in the sense that
they are implemented or initialized at the same time they are
declared. That said, because protocols don’t implement their members,
most protocol members are declarations only. For convenience and
because the distinction isn’t that important in Swift, the term
declaration covers both declarations and definitions.

F# - Type augmentation VS Type extension

What exactly is the difference between F#'s type augmentation and type extension, and do we really need both?
Are there situations where one is better than the other, and vice-versa?
I'm asking because I recently had a lecture in F# where the lecturer talked about both, and afterwards commented that he couldn't see the reason why both were included in the F# language.
Update:
Ok, so Vladislav Zorov links to a page with examples of using type augmentation both when defining your own types, and extending (or augmenting?) an external type.
pad links to an MSDN page where they call it intrinsic and optional type extension.
Both seem to illustrate the same thing. Can someone come with a concrete example of type extension and another concrete example of type augmentation perhaps, in order to explicitly clarify what the two things are exactly?
The following bits from MSDN's Type Extensions page are relevant (emphasis mine):
There are two forms of type extensions that have slightly different
syntax and behavior. An intrinsic extension is an extension that
appears in the same namespace or module, in the same source file, and
in the same assembly (DLL or executable file) as the type being
extended. An optional extension is an extension that appears outside
the original module, namespace, or assembly of the type being
extended. Intrinsic extensions appear on the type when the type is
examined by reflection, but optional extensions do not. Optional
extensions must be in modules, and they are only in scope when the
module that contains the extension is open.
The purpose of optional extension is clear. It helps you inject new functionalities to types not belonging to your assemblies. For examples, FSharpx uses it to create various helpers for parsing primitive types:
open System
type Boolean with
static member parse x =
match bool.TryParse(x) with
| true,v -> Some v
| _ -> None
Why do you need intrinsic extension then? The answer is its convenience. I find it useful to break down type definitions to multiple sections with clear purposes.
In many F# libraries, I saw the use of the following pattern: type definition -> utility functions -> intrinsic extension. In this way, you can define sophisticated utility functions on your types, make them available in modules and still can use them directly in your member definitions. You can look at Complex type in F# PowerPack to see the pattern.
EDIT:
To be honest, I often use type extension and type augmentation interchangeably. The thing that matters is whether they are intrinsic or optional.
They are different things. Type augmentations, when defined in the same namespace, module and source file, actually become part of the type when compiled. Type extensions (a.k.a. type augmentations for types outside of the module and source file) are implemented with .NET extension methods.
They both use the same syntax, the only difference is whether the type you mention is in the same namespace and assembly, i.e. you're augmenting your own code and the additional methods can be added to your type before compilation.
Source: http://tomasp.net/blog/fsharp-iii-oop.aspx
Edit:
This is a terminology mix-up, they are both referring to the same thing - intrinsic extensions are type augmentations of the first kind (i.e. same namespace and assembly), optional extensions are type augmentations of the second kind (i.e. 3rd party assembly, in the blog post this is the List<T> augmentation example).
I assume when your lecturer is talking about type augmentations, he's referring to intrinsic extensions, i.e. first kind type augmentations, and when he's talking about type extensions, he's talking about optional extensions, or second kind type augmentations.

Safe to use Numeric.Complex with PInvoke? (It does not have LayoutKind.Sequential)

I want to use System.Numerics.Complex in an unmanaged PInvoke scenario. Using ILSpy, I noticed it does not have a LayoutKind.Sequential attribute assigned.
/// <summary>Represents a complex number.</summary>
[Serializable]
public struct Complex : IEquatable<Complex>, IFormattable
{
private double m_real;
private double m_imaginary;
...
Is it safe to give a pointer to an Complex[] array without conversion to a native function expecting the common memory layout, ie.: Real first, imaginary second? Or could the CLR possibly disorder its real and imaginary attributes for some reason?
LayoutKind.Sequential is default for all major .NET compiler: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx
Even if it wouldn't: theonly reason to alter the order of attributes would be for alignment issues. Since System.Numerics.Complex does only have two double members there would be no reason to exchange them. So IMO you are safe.
You are fine because this is a struct. It has an implied [StructLayout] that's sequential. Something you can see from typeof(Complex).IsLayoutSequential. The same is not true for a class, it requires an explicit declaration.
And yes, fields can get swapped in the internal representation of the object. But that won't matter since the pinvoke marshaller must marshal the object. There's an implied Marshal.StructureToPtr() built into the marshaller. Fwiw, this swapping won't happen because the packing for two doubles is already optimal. They fit without leaving any padding. So the marshaller just creates a pointer to the object and won't have to copy it.
All good news :)

What do underscore prefixed variable names in Objective-C mean?

I noticed that in many community Objective-C classes and in Apple's frameworks they name some of the variables using a convention that prefixes variables with an underscore, such as: _name. What is the reason for having the underscore. Should I be doing this in my own classes? If so where and when should I use it?
That's called uglification. The point is that you never use it, so no variable name or #define you create could ever interfere with Apple's code.
Ironically, many people create header guards with such names, because they see the system headers do it.
From C99 7.1.3 "Reserved identifiers":
All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
(They mean reserved for the system library.)
Note: I'm not sure of the exact relationship between C99 and Apple ObjC, but you might as well have naming conventions that work across the entire C language family. In particular ObjC++ would require valid C++ names, which have the additional requirement of no double underscores anywhere.
In Cocoa, it's a convention to indicate the something is private and shouldn't be used externally. However, it's unofficial convention, particularly in light of wording like this in the documentation:
Method names beginning with “_”, a single underscore character, are reserved for use by Apple.
However, that recommendation specifically applies to methods, not variables. So if you'd like to prefix your variables with underscores, go right ahead. That being said, if you're using the underscore prefix to indicate the private nature of some data, perhaps you shouldn't be exposing it in the first place...
Underscores get in the way of readability. Also with LLVM in place of GCC, I am getting rid of header side ivars and using header side properties. Be sure to make your properties non atomic unless you really want reads and writes synchronized for thread safety. unless you specify non atomic, it will default to atomic - which will deprive you of some performance.
also by convention, never start accessors with get. setters Should start with set but no getters with get. Read up on KVO and KVC for more about the conventions and what they are good for.
I do however like underscores in Enumeration naming list. Here the underscores help me pick out the suffix in 5 or more lines that all start with the same stem.
Like
typedef NSInteger COMPASS_DIRECTION;
enum {
COMPASS_DIRECTION_NORTH,
COMPASS_DIRECTION_EAST,
COMPASS_DIRECTION_SOUTH,
COMPASS_DIRECTION_WEST,
};

Resources