ASM Blocks

Top  Previous  Next

ASM blocks

In the world of Delphi or free pascal, itís quite rare to find people that write assembler side by side with their pascal code anymore. Real assembler is complex, error prone and tricky to master (which is why so few people are good at it). But under Smart assembler is pure fun Ė because to a browser assembler is JavaScript! Unlike x86 assembler, JavaScript is reasonably easy to work with (although abhorrently difficult to get right beyond 20.000 lines) and if you want to interface more closely with the browser Ė you have no other option but to use an ASM section. So ASM sections contain normal JavaScript, not machine instructions. Let us have a look at the ground rules:

procedure TMyObject.Testing;
var
mRefTObject;
begin
  mRef := tagRef;
   asm
    (@mRef).style.width=100 + "px";
   end;
end;

 

What we do here is to first get a handle to the our tag (the tagRef is a public property of TW3TagObject, the base class for all our controls and components). We then enter the ASM section, use that reference to access and alter the width style property of our control. Of-course you donít have to do things this way, our RTL is quite rich in functions to deal with such simple tasks. But learning how to benefit from your JavaScript skills is a great bonus. You get the best of both worlds. The same could easily be achieved with a function from our w3systems.pas RTL unit:

procedure TMyObject.Testing;
asm
w3_setStyle(tagRef,'width',w3_intToPxStr(100));
end;
 

There is one important rule when mixing raw JavaScript with Object Pascal code though, and that is that you must prefix any variables comming from the pascal side with the @ character. The reason is that when our obfuscator (a process that makes the generated sourcecode "unreadable" to human eyes) examines your code, all the names, variables and tokens are altered. As such, the compiler needs something extra to distinguish pascal symbols from raw JavaScript symbols. So all Object Pascal variables (or references) must be prefixed. Due to the nature of JavaScript, in some cases you also have to isolate references inside a ( .. ) block, like this:
procedure TMyObject.Testing;
asm
(@self.FWidth) = parseInt( (@mRef).style.width );
end;
 

Of-course, you can use functions in w3system.pas to achieve the exact same thing:
procedure TMyObject.Testing;
begin
 self.width := w3_getStyleAsInt(tagRef,'width');
end;
 

Note: The above is not an example of how to size a control. TW3CustomControl have ample properties and methods for moving and resizing, just like TCustomControl have in Delphi.

 

How would you "export" a function created in Smart Pascal to use outside of Pas2JS closure?

procedure Myfunction();
begin
 WriteLn('test');
end;
 
initialization
asm
 window.Myfunction = @Myfunction;
end;