paxCompiler for Delphi. Evaluate expression.


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, PaxCompiler;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    arr_x, arr_y: array[1..3] of Double;
    h_norm, h_x, h_y: Integer;

    buff: array[1..4096] of Byte;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function Norm(x, y: Double): Double;
begin
  result := Sqrt(x * x + y * y);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  PaxCompiler1: TPaxCompiler;
  PaxPascalLanguage1: TPaxPascalLanguage;
  PaxProgram1: TPaxProgram;
  I: Integer;
begin
  PaxCompiler1 := TPaxCompiler.Create(nil);
  PaxPascalLanguage1 := TPaxPascalLanguage.Create(nil);
  PaxProgram1 := TPaxProgram.Create(nil);

  try
    PaxCompiler1.Reset;
    PaxCompiler1.RegisterLanguage(PaxPascalLanguage1);

    h_norm := PaxCompiler1.RegisterRoutine(0, 'Norm', _typeDOUBLE, _ccREGISTER);
    PaxCompiler1.RegisterParameter(h_norm, _typeDOUBLE, Unassigned);
    PaxCompiler1.RegisterParameter(h_norm, _typeDOUBLE, Unassigned);

    h_x := PaxCompiler1.RegisterVariable(0, 'x', _typeDOUBLE);
    h_y := PaxCompiler1.RegisterVariable(0, 'y', _typeDOUBLE);

    if PaxCompiler1.CompileExpression('Norm(x, y)', PaxProgram1) then
    begin
      PaxProgram1.SaveToBuff(buff);
      ShowMessage('Compiled expression has been created!');
    end
    else
      for I:=0 to PaxCompiler1.ErrorCount - 1 do
        ShowMessage(PaxCompiler1.ErrorMessage[I]);
  finally
    PaxCompiler1.Free;
    PaxPascalLanguage1.Free;
    PaxProgram1.Free;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  PaxProgram1: TPaxProgram;
  ResValue: Double;
  I: Integer;
begin
{$O-}
  if h_x <> 0 then
  begin
    PaxProgram1 := TPaxProgram.Create(nil);
    try
      PaxProgram1.LoadFromBuff(buff);

      PaxProgram1.SetAddress(h_norm, @norm);

      for I:=1 to 3 do
      begin
        PaxProgram1.SetAddress(h_x, @arr_x[I]);
        PaxProgram1.SetAddress(h_y, @arr_y[I]);

        PaxProgram1.Run;

        ResValue := Double(PaxProgram1.ResultPtr^);
        ShowMessage(FloatToStr(ResValue));
      end;

    finally
      PaxProgram1.Free;
    end;
  end
  else
    ShowMessage('Press the first button to create compiled script.');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  h_x := 0; h_y := 0; h_norm := 0;
  arr_x[1] := 4.2;   arr_y[1] := -5.2;
  arr_x[2] := -0.4;  arr_y[2] := 3.2;
  arr_x[3] := 2.0;   arr_y[3] := 3;
end;

end.


Copyright © 2006-2017 Alexander Baranovsky. All rights reserved.