Delphi for .NET compiler preview - by John Kaster

zhaozj2021-02-16  53

Welcome zhang jinyuwww.borland.com

AppServer C Corba Delphi & Kylix Interbase Java Linux Teamsource DSP

Borland Developer Network Home> Delphi & Kylix> Platforms

Delphi for .NET Compiler Preview - by John Kaster

Abstract: a First Look at the delphi for .NET Compiler Features and Delphi's New Language Syntax

by John Kaster and Danny Thorpe At BorCon 2002, Borland started providing more technical details on our support under development for the .NET platform. This article introduces some of the planned enhancements to the Delphi language and introduces the prototype "Delphi for .NET" compiler . Unless otherwise indicated, the language features discussed here will first be seen in the Delphi for .NET compiler. Furthermore, all of the features discussed in this article may not be introduced in the preview release. When possible, features already implemented in the compiler will be listed, but since the compiler is in beta right now, not much emphasis will be placed on distinguishing what's currently implemented and what's not. For a good, brief overview of .NET and an introduction to some of the terms mentioned in this article See http://arstechnica.com/paedia/n/net/net-1.html. Dccil the delphi for .NET Compiler Produces Common Intermediate Language (CIL) Applications. The Applications CAN run anywhere the .NET runtime is available as fully managed applications. This means that Delphi applications can now move beyond their traditional Windows / Intel platform to any other platform that has a .NET runtime, such as the .NET compact framework available for tablet PCs, phones, and PDAs. The Delphi command line compiler for IL is dccil.exe. Here's what currently shows up when you run it without any parameters. (This output is guaranteed to change before we release the Delphi for .NET preview with Delphi 7.) Borland Delphi Version 16.0

Copyright (c) 1983, 2002 Borland Software Corporation

Confidential pre-release version built aug 2 2002 17:29:33

Syntax: dccil [options] filename [options]

-A = = set unit alias -lu = use package-b = build all units -m = make modified units

-Cc = console target -n = DCU Output Directory

-Cg = gui target -o = Object Directories

-D = define conditionals -p = Look for 8.3 File Names ALSO

-E = exe output directory -q = quiet compile

-F = Find Error -R = Resource Directories

-Gd = detailed map file -u = Unit Directories

-Gp = map file with publics -v = debug information in EXE

-Gs = map file with segments -vr = generate Remote Debug (RSM)

-H = Output hint messages -w = Output Warning Messages

-I = include Directories -z = Output 'NEVER Build' DCPS

-J = generate .obj file - $

= compiler Directive

-JP = generate C .obj file --help = show this help screen

-K = set image base addr --version = show name and version

Compiler Switches: - $ (Defaults Are Shown Below)

A8 Aligned Record Fields P Open String Params

B- Full Boolean Evaluation Q- Integer Overflow Checking

C Evaluate Assertions At Runtime R- Range Checking

D Debug Information T- Typed @ Operator

G Use Imported Data References U-Pentium (TM) -safe Divide

H Use long strings by Default V Strict Var-strings

I I / O Checking W- Generate Stack Frames

J-Writeable Structured Consts X Extended Syntaxl Local Debug Symbols Y Symbol Reference Info

M- Runtime Type Info Z1 Minimum Size of Enum Types

O Optimization

Product Version: Ver160

Debug Level: 2

IN EFFORT TO MAINTAIN THE TREND OF ASKING ABOUT PRONUNCIATIONS ("Is IT 'DELF-EE' OR 'DELF-EYE'?" .NET GUI application As with Kylix, a basic step in our .NET support was getting a compiler that actually produces the appropriate "machine code" executable. in this case, that machine is .NET. A form designer is not currently available for Delphi For .NET, SO You Will Notice That The Following Code Actually Initializes The Menu Items, Button, Listbox, And Up / Down Control.

Program convelectritation;

Uses

SYSTEM.DRAWING,

Borland.delphi.sysUtils, borland.delphi.conversions, borland.vcl.controls;

Type

TFORM1 = Class (TFORM)

Private

DOITBUTTON: TBUTTON

Celsiusedit: tspinedit;

Resultlist: TListBox;

Mainmenu: TmainMenu;

FileItem: TMenuItem;

ExitItem: TMenuItem;

HelpItem: tMenuItem

AboutItem: TMenuItem

Procedure DOITBUTTONCLICK (Sender: Tobject; Args: teventargs);

Procedure ExitItemClick (Sender: Tobject; Args: TEVENTARGS);

Procedure AboutItemClick (Sender: Tobject; Args: teventargs);

protected

Function decimaltofloat (const avalue: decimal): Double;

Function Floattodecimal (Const Avalue: Double): Decimal

PROCEDURE READSTATE;

public

Constructor crete;

Procedure convers;

END;

VAR

FORM1: TFORM1;

Function TFORM1.DECIMALTOFLOAT (Const Avalue: Decimal): Double;

Begin

Result: = system.convert.todouble (avalue);

END;

Function TFORM1.FLOATTODECIMAL (Const Avalue: Double): Decimal

Begin

Result: = System.convert.todecimal (Avalue);

END;

Procedure TFORM1.CONVERT;

VAR

Lcelsius: double;

Function NTHDEGREE (Const Scale: String; Const Temperature: double): String;

Begin

Result: = format ('% s =% 8.2f', [scale, temperature]);

END;

Begin

Lcelsius: = DecimalTofloat (Celsiusedit.Value);

With resultlist.Items do

Begin

Clear;

Add (NTHDEGREE ('Celsius', Lcelsius);

Add (NTHDEGREE ('Fahrenheit', Celsiustofahrenheit (Lcelsius))

Add (NTHDEGREE ('Kelvin', Celsiustokelvin (Lcelsius));

Add (NTHDEGREE ('Rankine'));

Add (NTHDEGREE ('Reaumur'));

END;

END;

Procedure TFORM1.DOITBUTTONCLICK (Sender: Tobject; Args: teventargs);

Begin

CONVERT;

END;

Procedure TFORM1.EXITITEMCLICK (Sender: Tobject; Args: teventargs);

Begin

CLOSE;

END;

Procedure TFORM1.AboutitemClick (Sender: Tobject; Args: teventargs);

Begin

TMessageBox.show (Text 'Whatver');

END;

Constructor TFORM1.CREATE;

Begin

Inherited Create;

ReadState;

END;

Procedure TForm1.ReadState;

Begin

Mainmenu: = TmainMenu.create;

FileItem: = TMENUITEM.CREATE

EXITITEM: = TMENUITEM.CREATE

HelpItem: = TMENUITEM.CREATE

AboutItem: = tmenuitem.create;

Mainmenu.MenuItems.Add (fileItem);

Mainmenu.MenuItems.Add (HelpItem);

FileItem.MenuItems.Add (ExitItem);

FileItem.Text: = 'file';

EXITITEM.TEXT: = 'exit';

EXITITEM.ADD_CLICK (ExitItemClick);

Helpitem.MenuItems.Add (AboutItem);

HelpItem.Text: = 'help';

AboutItem.Text: = 'About ...';

Aboutitem.add_click (AboutItemClick);

DOITBUTTON: = TButton.create; with doitbutton do

Begin

LEFT: = 8;

TOP: = 8;

Width: = 33;

HEIGHT: = 25;

TEXT: = 'go';

Add_Click (DOITBUTTONCLICK);

END;

Celsiusedit: = tspinedit.create;

With Celsiusedit DO

Begin

LEFT: = 48;

TOP: = 8;

Width: = 177;

Value: = floattodecimal (100);

Maximum: = floattodecimal (10000);

Minimum: = floattodecimal (-1000);

Add_ValueChanged (DOITBUTTONCLICK);

END;

Resultlist: = tlistbox.create;

With resultlist do

Begin

LEFT: = 8;

TOP: = 40;

Width: = 217;

HEIGHT: = 217;

END;

Clientsize: = system.drawing.size.create (240, 270);

Menu: = mainmenu;

Controls.add (DOITButton);

Controls.add (celsiused);

Controls.add (resultlist);

TEXT: = 'Convertit!';

Controlbox: = true;

Minimizebox: = true;

CONVERT;

END;

Begin

Form1: = TFORM1.CREATE

Tapplication.run (Form1);

End.

Note! The unit Borland.Delphi.Conversions contains the various Celsius temperature conversion routines. The unit Borland.VCL.Controls is a preliminary version that will not be included with the initial preview release. The source code listed above is contained in ConvertIt.dpr , and is sure to change even before we ship the .NET Preview Compiler with delphi 7. IF We compile it:

[D: D4.NetConvert.Net] DCCIL Convertit.dpr

Borland Delphi Version 16.0

Copyright (c) 1983, 2002 Borland Software Corporation

Confidential pre-release version built aug 2 2002 17:29:33

Borland.delphi.conversions.pas (60)

Borland.vcl.controls.pas (38)

Convertit.dpr (159)

260 Lines, 0.64 Seconds, 12232 Bytes Code, 0 bytes Data.

After compiling the application, of course we should run it Here's what the application looks like after a little resizing to minimize the image size Fully Managed Code This application is a 100% managed code application, as the results of PEVerify show:.. [D : D4.NetConvert.net] Peverify Convertit.exe

Microsoft (R) .NET Framework PE Verifier Version 1.0.3705.0

Copyright (c) Microsoft Corporation 1998-2001. All Rights Reserved.

All classes and methods in controlitit.exe verified

You can use Microsoft IL Disassembler (ildasm) to examine the executable. ILDasm running on ConvertIt.exe You can examine the .NET assembler code for any module. .NET assembler code for function NthDegree Delphi for .NET code also works with Lutz Roeder's excellent utility, Reflector. (This link contains some other great .NET utilities as well.) ConvertIt examined in Reflector The .NET compiler The Delphi for .NET compiler is more than just a port of the existing Delphi compiler. There is a new code generator ., a new linker, significant new syntax, and a new runtime library Of course, it is also very important to maintain language compatibility, so you will see some familiar old friends in Delphi for .NET as well:

Strings & Arrays Records Classes Interfaces Properties & Events Sets Text files Local Procedures Variants Components Streams New, Dispose Readln, Writeln Format Component Streaming Random In order to fully embrace the CLR and make Delphi a first class citizen in the new world of managed code, some language features must be deprecated, and others are the subject of ongoing research. Though many of these details are still being researched and implemented, it is hoped that the following information will be useful for understanding the new language features of Delphi for .NET. Unsafe code warnings in Delphi Starting with Delphi 7, the compiler includes three new warnings that can help you locate code that is non-portable (ie it uses a deprecated language feature or type), or unsafe in the .NET Framework. in the .NET Framework, "unsafe" Simply Means That the code cannot be verified by the static analyysis performed by the clr ghen the code is loading. The compiler can warn there of unsafe types, unsafe code, and unsafe casts. Unsafe types PChar, PWideChar, and PAnsiChar Untyped pointers Untyped var and out parameters File of Real48 Variant records (records containing overlapping fields) Unsafe code Absolute variables Addr (), Ptr ( ), Hi (), lo (), swap () Standard Procedures Blockread (), And Blockwrite () Fail () getMem (), FreeMem (), ReallocMem () inline assembler the @

operator Unsafe casts Casting an object instance to a type that is not an ancestor or descendent of the instance type Casting a record type to anything else These new warnings are disabled by default. They can be enabled with the IDE Project Options dialog box, or with the compiler directive: {$ WARN UNSAFE_CODE ON} They can also be enabled with the -W command line switch: dcc32 -W UNSAFE_CODE Note there is no space before or after the ' ' character on the command line switch Note:. These new warnings are in the Delphi 7 (and beyond) compiler for Win32 (dcc32). They are not in the Delphi for .NET Preview compiler (dccil). Deprecated Language Features The dccil compiler will also deprecate some existing language features, listed in the Following table.

Keyword / Language FeatureNotesReal48 six byte floating type GetMem (), FreeMem (), and ReallocMem () Use dynamic arrays, or rely on automatic dispose pattern implementationBlockRead (), BlockWrite () Absolute directive, Addr, and @ Pre-Delphi object syntax ( type foo = object) TVarData, Variant internalsVariant semantics will be supported but not as TVarDataFile of This construct can not be implemented because the Delphi compiler can not know the size of on the target platform (eg a handheld device). The JIT compiler for the specific platform determines the size of intrinsic types. untyped var and out parametersUntyped const parameters are still supportedPCharIn a future release Delphi for .NET will support unsafe managed code (ie pointers). Unsafe, unmanaged pointers are not supported in the preview Release. Automated and Dispid Directives Inline Assembly - ASM Statement TinterFaceDObjectAddref, Queryinterface, And Release Are Deprecated. in The Preview Release TinterFaceDObjec t is an alias for TObject. Dynamic aggregationDynamic aggregation of interfaces is not supported by the CLR, because it can not be statically verified. In Delphi for .NET, all interfaces must be declared on the type. Dynamic aggregation is provided by the implements keyword, As The Following Code Illustrates.program project1;

Type

i = interface

Procedure Wombat;

END;

TA = Class (TinterFaceDObject, i)

Procedure Wombat;

END;

Tc = Class (TinterFaceDObject, i)

FA: TA;

Property A: Ta Read Fa IMPLEMENTS I;

END;

{Ta}

Procedure ta.wombat;

Begin

END;

Begin

End.

ExitProc CLR and Delphi The new Delphi compiler will provide access to the .NET CLR (Common Language Run-time). Delphi developers will be instantly familiar with the CLR not just because it resembles the VCL so closely, but also because compatibility type mappings will ......................

Delphi for .NET.NET CLRTObjectSystem.ObjectStringSystem.StringVariantSystem.ValueTypeRecordsSystem.ValueTypeExceptionSystem.ExceptionTComponentSystem.ComponentModel.ComponentDatabase connectivityADO.NET (and DataSnap direct drivers) RIO Web ServicesOn top of System.Web.ServicesGUISystem.Windows.Forms plus VCL Assemblies and Delphi The Delphi for .NET compiler treats CLR assemblies like Delphi packages. The compiler supports direct symbol importing from metadata. Header file translations are no longer needed. Symbols can be imported from any Common Language Specification (CLS) compliant .NET assembly, produced by any. NET language tool. Conceptually, every .NET assembly contains the equivalent of a DCP (which is a collection of DCUs) and a BPL, all lumped into one file. The compiler supports the -lu switch to specify which assemblies to link With or allow access to.......................... h no translations or conversions. Just as you use -lu for Delphi packages, you can use -lu for any CLR assembly. The Delphi package syntax produces assemblies. Furthermore, the package syntax will still provide the option of linking referred code directly into your exe, or making it an external reference. The .NET assemblies do not give you the option of internal or external linking of code. you can support internal or external linking by distributing the DCUs as well as DCPs

BPLs. You can not link code compiled in a package into an exe. You have to have a DCU (or source) to do that. The DCCIL compiler behaves the same as the DCC32 compiler. You should also know that Delphi for .NET will preserve the case for the namespaces you create. C # 's recognition of namespaces is case sensitive, so if you use a Delphi for .NET assembly with C #, you will need to match the original case of the namespace you created. Delphi's recognition of namespaces is not case sensitive, so if you do not keep this behavioral difference of the languages ​​in mind, you might run into problems later. Delphi Language Enhancements I'm sure you were all looking closely at the code above, even though I told you it would change . Some of the enhancements to Delphi are obvious by looking at the source code, but not all of them are demonstrated in the above code sample. Let's look at a partial list of Delphi language enhancements. Unit namespaces by examining the above source code, one Obvious chang E Should Be The Support for Unit Namespaces. Namespaces Allow You To Access Units with Fully Qualified Identifiers, Such as: Uses Borland.delphi.SysUtils;

The Delphi unit defines its own namespace with dotted names in the unit identifiers and file names. (The file name and unit name still match, with the ".pas" omitted from the unit name.) Project namespace You can configure project-specific namespace resolution. Project namespaces are a great way to eliminate uses clause iFDEFs. The project namespace will determine how the unit name references are fully resolved. Project namespace search path There will also be support for a project namespace search path, which supports searching the namespace path For UNQualified Unit Names on the search path; consider this Hypothetical Example: Uses form

This reference would resolve to Borland.VCL.Forms for a VCL project, and Borland.CLX.Forms for a CLX project. Clearly, this will make code for cross-platform development (such as .NET, Win32, and Linux) much easier To Write and Maintain. Default Project Namespace You Can Also Create Units That Can Be Compiled Into Multiple Project Namespaces. for Example,

Unit myControl;

would compile to Borland.VCL.MyControl.dcuil for a VCL project, and Borland.CLX.MyControl.dcuil for a CLX project Qualified identifiers Reserved words or keywords are allowed after the first identifier For example, in the following code..:

VAR

Foo: system.label;

Qualified identifiers can appear in type expressions, but not in identifier declarations. System.Label would be allowed as a valid type expression although label is a reserved word in Delphi. Future compiler plans for the extended identifier syntax include allowing the use of Unicode / UTF8 . identifiers after the first "standard" identifier The Common Language Specification includes this extended identifier syntax The dccil compiler will provide access to all CLS compliant symbols in CLR assemblies Nested types Consider the following code:.. type

TMYCLASS = Class

FDATA: Integer;

Const foo = 12;

TYPE TNESTEDCLASS = Class

Procedure hello;

END;

PROCEDURE GREEN

END;

...

VAR

Myclass: TMYCLASS;

Mynest: TMYCLASS.TNESTEDCLASS;

...

Begin

Myclass.fdata: = 15;

Mynest.tnestedclass: = tmyclass.tnestedclass.create;

Mynest.hello;

Myclass.green;

END;

The TNestedClass type is nested inside of the TMyClass type, but does not affect instances of TMyClass because data fields defined in TMyClass.TNestedClass do not occupy space in instances of TMyClass Nested types are an extension of the namespace idea;. Logical containment by naming convention, with no physical manifestation. In the above example, MyNest is not freed because it will be garbage-collected by the .NET runtime. Custom Attributes Delphi for .NET will support standard attributes, such as Conditional, Obsolete, Serializable, and web Methods. You will Also Be Able To Create Custom Attributes, Such As Those Displayed Here:

Type

[FooAttribute ('Hello', 23)]

TMYCLASS = Class

[SpecialDataTribute]

FDATA: Integer;

[WebMethod, Debuggerstepthrough]

Function Sample;

END;

Delphi allows you to create custom attributes you can use for any of your .net application source code

TQUANTUMATTRIBUTE = Class (TCUSTOMATTRIBUTE)

Constructor crete;

Constructor Create (name: string);

Property name: String ...

Property Spin: Double ...

Property color: tquarkcolor ...;

END;

A poster child for custom attributes might be the DLLImportAttribute. The Borland.Win32.Windows unit will be using that attribute for indicating the requirement for Windows run-time DLLs. CLR supports more options for referencing external DLL functions than regular old PE DLL Imports. Rather than add more special syntax to the language to cover those additional CLR-specific options, the additional info can be carried in an attribute. The compiler can remain blissfully ignorant of the payload for all but a handful of custom attributes. Class (static) .

Type

TMYCLASS = Class

Class fdata: integer;

Class Property foo: String ...

Class Procedure ONE;

Class Static Procedure TWO;

END;

Class properties Class properties work like class fields. The getters and setters must be class methods or class fields. Class static methods Class static methods work the same as traditional Delphi class methods, except that there is no "self" parameter available in the method body . This is a CLR requirement because some languages ​​do not support the hybrid behaviors Delphi has, where you can have routines that are not part of an object. Traditional Delphi class methods (which do have a "Self" in the body of the method) will also be supported. value types types can be "boxed" into object wrappers. These value types are not reference types. They are the actual instance of the type. value semantics are supported for assignment and copying data. Record types are an example of value types in Delphi. Records can inherit from other records, and records can contain non-virtual methods, properties, and nested types. When value types are boxed, a fresh copy of the value is made and a distinct o Bject Reference IS RETURNED. THIS DISTINCT OBJECT REFERENCE IS A Reference To Data That Is Completely Independent of The Underlying Value Type. for the Following Code, Tobject (12) .tostring

the code TObject (12) boxes an integer into an object. Boxing of value types in Delphi for .NET is a requirement. Boxing support is not planned for Win32 or Linux Delphi language implementations. Records with inheritance Delphi records will be implemented as value types in CLR. Record inheritance is an aspect of value types. Records with non-virtual methods is another aspect of value type support. Records with methods The declaration of methods on tRecord is supported. These behave as static non-virtual methods. Sealed classes A sealed class can not be inherited from. value types can only inherit from abstract value type classes, and only sealed value type classes can be instantiated. value types are highly deterministic, and decidedly non-polymorphic. Final methods The final directive on a virtual method ( OR OVERRIDE) INDICES THATED CANNODENTS. Descendents May Still Introduce New Virtual Methods with the Same Name As The inherited Method, But since they do not override the inherited method (occupy the same vmt slot as the inherited method), they do not participate in polymorphic calls to the inherited method. Possible Enhancements Multicast events With multicast events, you can have multiple listeners for each event. This event model is different from the Win32 event model, where an event is consumed and discarded by the first component responding to it. With event listeners, multiple components can respond to the same message (for example, all controls could respond to a "repaint"

. Event) In this event listener model, you can only remove your own listener Include () and Exclude () are standard procedures overloaded to operate on events for adding or removing an event listener Traditional singleton event semantics are supported through:.. = Assignments . If a singleton event is used with an assignment, it overrides Include () or other listeners. Support for multicast events in Delphi for .NET is a requirement. Support for multicast events may appear in future releases of Delphi for Win32 and Linux. Interface method resolution interface method resolution provides a convenient shorthand for implementing methods referenced in an interface. By default, the compiler attempts to bind a method name to a method of the same name in the class implementing the interface. With the following code, Type

TMYCLASS = Class (TBASECLASS, IFOO)

Procedure foobar (paramlist);

Procedure ifoo.bar = foobar;

END;

The New Version Would Be:

Type

TMYCLASS = Class (TBASECLASS, IFOO)

Procedure ifoo.bar (paramlist);

END;

A reference to tmyclass.ifoo.bar is the valid. When Multiple Interfaces Are Used, Interface Method Resolution Becomes Even More Valuable. The Following Code Illustrates:

Ifoo1 = interface

PROCEDURE BAR;

END;

Ifoo2 = interface

PROCEDURE BAR;

END;

TsomeClass = Class (TBASECLASS, IFOO1, IFOO2)

Procedure ifoo1.bar;

Procedure ifoo2.bar;

END;

Array Property Overloads Array Property Overloads Will Also Be Supported. The Following Example Shows The Probable Syntax for overloading Array Property References.

TsomeClass = Class

Property Item [index: string]: string

Read GetItem Write SetItem; Overload;

Property item [index: integer]: String

Read GetItem Write SETEM; OVERLOAD; Property Names: String Read GetNames Write setNames

OVERLOAD;

Property names [index: integer]: String

Readnnames Write setNames; Overload;

Function GetItem (INDEX: STRING): String; Overload;

Procedure setItem (INDEX: STRING; VALUE: String); OVERLOAD;

Function GetItem (INDEX: Integer): String;

OVERLOAD;

Procedure setItem (INDEX: Integer; Value: String);

OVERLOAD;

Function GetNames: String; OverLoad;

Procedure setNames (value: string); overload;

Function GetNames (INDEX: Integer): String;

OVERLOAD;

Procedure setNames (index: integer; value: string);

OVERLOAD;

END;

Overload of array properties is required for CLS compliance. For example, the CLR NameValueCollection overloads integer and string index references for the default Item property, as does this code snippet example above. Conclusion This document is intended to introduce some of the new features and concepts under research for the Delphi for .NET compiler. While every attempt has been made to keep this information accurate, all of it is subject to change. Compiler support for .NET has provided some exciting opportunities for enhancement to the Delphi language. The language enhancements Discussed Here Are for the delphi for .NET compiler unless. Hopefully Stated. Hopefully, you like what you see so far. Stay tuned to this Web site, as more articles on delphi for .NET Are COMING VERY SOON.

Add or View Comments On this Article Article ID: 28972 Publish Date: August 06, 2002 Last Modified: August 05, 2002

转载请注明原文地址:https://www.9cbs.com/read-28137.html

New Post(0)