Poll

What method would you prefer to translate BASIC to a cross platform binary executable.

Daniel's uCalc Transform --> C++
1 (33.3%)
ScriptBasic --> Nimrod --> C (project abandoned by John)
0 (0%)
Nimrod --> C
0 (0%)
Python --> Nimrod --> C
1 (33.3%)
C BASIC (Charles Pegge's BASIC wrapper for C)
1 (33.3%)
Other (post your idea)
0 (0%)

Total Members Voted: 2

Author Topic: BAS2NIM  (Read 46099 times)

kryton9

  • Guest
Re: BAS2NIM
« Reply #60 on: October 16, 2013, 10:27:53 PM »
Works great John!
Quote
scriptbasic@nimrod:~/639761/projects/Kent/test-john-stuff $ scriba bas2nim.sb test1.bas
var A = "Hello BAS2NIM"
stdout.write(A,"\n")
scriptbasic@nimrod:~/639761/projects/Kent/test-john-stuff $ nimrod c -d:release test1.nim
config/nimrod.cfg(36, 2) Hint: added path: '/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/.babel/pkgs/babel-0.1.0' [Path]
config/nimrod.cfg(36, 2) Hint: added path: '/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/.babel/pkgs/' [Path]
Hint: used config file '/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/Nimrod/config/nimrod.cfg' [Conf]
Hint: system [Processing]
Hint: test1 [Processing]
gcc -c -w -O3 -fno-strict-aliasing -I/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/Nimrod/lib -o /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/nimcache/test-john-stuff_test1.o /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/nimcache/test-john-stuff_test1.c
gcc -c -w -O3 -fno-strict-aliasing -I/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/Nimrod/lib -o /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/nimcache/Nimrod_system.o /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/nimcache/Nimrod_system.c
gcc   -o /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/test1  /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/nimcache/Nimrod_system.o /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/projects/Kent/test-john-stuff/nimcache/test-john-stuff_test1.o  -ldl
Hint: operation successful (7680 lines compiled; 16.266 sec total; 9.922MB) [SuccessX]
scriptbasic@nimrod:~/639761/projects/Kent/test-john-stuff $ ./test1
Hello BAS2NIM
scriptbasic@nimrod:~/639761/projects/Kent/test-john-stuff $

Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #61 on: October 16, 2013, 10:28:09 PM »
Quote
The JavaScript target

Nimrod can also generate JavaScript code. However, the JavaScript code generator is experimental!

Nimrod targets JavaScript 1.5 which is supported by any widely used browser. Since JavaScript does not have a portable means to include another module, Nimrod just generates a long .js file.

Features or modules that the JavaScript platform does not support are not available. This includes:

    manual memory management (alloc, etc.)
    casting and other unsafe operations (cast operator, zeroMem, etc.)
    file management
    most modules of the Standard library
    proper 64 bit integer arithmetic
    unsigned integer arithmetic

However, the modules strutils, math, and times are available! To access the DOM, use the dom module that is only available for the JavaScript platform.

To compile a Nimrod module into a .js file use the js command; the default is a .js file that is supposed to be referenced in an .html file. However, you can also run the code with nodejs:

    nimrod js -d:nodejs -r examples/hallo.nim

hellojs.nim
Code: [Select]
echo "I'm a JavaScript Program!"

jrs@laptop:~/nimrod/nodejs$ nimrod js -d:nodejs -r hellojs.nim
config/nimrod.cfg(36, 11) Hint: added path: '/home/jrs/.babel/libs/' [Path]
Hint: used config file '/home/jrs/nimrod/config/nimrod.cfg' [Conf]
Hint: system [Processing]
Hint: hellojs [Processing]
Hint: operation successful (3511 lines compiled; 0.057 sec total; 3.307MB) [SuccessX]
node nodejs/nimcache/hellojs.js
I'm a JavaScript Program!
jrs@laptop:~/nimrod/nodejs$

hellojs.js
Code: [Select]
/* Generated by the Nimrod Compiler v0.9.2 */
/*   (c) 2013 Andreas Rumpf */


var Globals = this;
var framePtr = null;
var excHandler = null;
var NTI842 = {size: 0, kind: 17, base: null, node: null, finalizer: null};
var NTI103 = {size: 0,kind: 31,base: null,node: null,finalizer: null};
var NTI5851 = {size: 0, kind: 18, base: null, node: null, finalizer: null};
var NTI808 = {size: 0, kind: 17, base: null, node: null, finalizer: null};
var NTI139 = {size: 0,kind: 28,base: null,node: null,finalizer: null};
var NTI141 = {size: 0,kind: 29,base: null,node: null,finalizer: null};
var NTI893 = {size: 0,kind: 22,base: null,node: null,finalizer: null};
var NTI824 = {size: 0, kind: 17, base: null, node: null, finalizer: null};
var NTI828 = {size: 0, kind: 17, base: null, node: null, finalizer: null};
var NTI840 = {size: 0, kind: 17, base: null, node: null, finalizer: null};
var NTI844 = {size: 0, kind: 17, base: null, node: null, finalizer: null};
var NNI844 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []};
NTI844.node = NNI844;
var NNI840 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []};
NTI840.node = NNI840;
var NNI828 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []};
NTI828.node = NNI828;
NTI893.base = NTI824;
var NNI824 = {kind: 2, len: 4, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI893, name: "parent", sons: null},
{kind: 1, offset: "name", len: 0, typ: NTI141, name: "name", sons: null},
{kind: 1, offset: "message", len: 0, typ: NTI139, name: "msg", sons: null},
{kind: 1, offset: "trace", len: 0, typ: NTI139, name: "trace", sons: null}]};
NTI824.node = NNI824;
var NNI808 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []};
NTI808.node = NNI808;
NTI824.base = NTI808;
NTI828.base = NTI824;
NTI840.base = NTI828;
NTI844.base = NTI840;
var NNI5851 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI141, name: "Field0", sons: null},
{kind: 1, offset: "Field1", len: 0, typ: NTI103, name: "Field1", sons: null}]};
NTI5851.node = NNI5851;
var NNI842 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []};
NTI842.node = NNI842;
NTI842.base = NTI840;
var nim_program_result = 0;
var globalraisehook_5241 = null;
var localraisehook_5246 = null;
var outofmemhook_5249 = null;
function cstrToNimstr(c_6151) {
    var result = [];
    for (var i = 0; i < c_6151.length; ++i) {
      result[i] = c_6151.charCodeAt(i);
    }
    result[result.length] = 0; // terminating zero
    return result;
  }
function ArrayConstr(len_6863, value_6864, typ_6865) {
    var result = new Array(len_6863);
    for (var i = 0; i < len_6863; ++i) result[i] = NimCopy(value_6864, typ_6865);
    return result;
  }
function add_5263(x_5266, x_5266_Idx, y_5267) {
var F={procname:"system.add",prev:framePtr,filename:"lib/system.nim",line:0};
framePtr = F;
      var len = x_5266[0].length-1;
      for (var i = 0; i < y_5267.length; ++i) {
        x_5266[0][len] = y_5267.charCodeAt(i);
        ++len;
      }
      x_5266[0][len] = 0
    framePtr = framePtr.prev;
}
function auxwritestacktrace_5846(f_5848) {
var result_5849 = [null];
var it_5854 = f_5848;
var i_5855 = 0;
var total_5856 = 0;
var tempframes_5861 = ArrayConstr(64, {Field0: null, Field1: 0}, NTI5851);
L1: while (true) {
if (!(!((it_5854 == null)) && (i_5855 <= 63))) break L1;
tempframes_5861[i_5855].Field0 = it_5854.procname;
tempframes_5861[i_5855].Field1 = it_5854.line;
i_5855 += 1;
total_5856 += 1;
it_5854 = it_5854.prev;
}
L2: while (true) {
if (!!((it_5854 == null))) break L2;
total_5856 += 1;
it_5854 = it_5854.prev;
}
result_5849[0] = cstrToNimstr("");
if (!((total_5856 == i_5855))) {
result_5849[0] = (result_5849[0].slice(0,-1)).concat(cstrToNimstr("("));
result_5849[0] = (result_5849[0].slice(0,-1)).concat(cstrToNimstr(((total_5856 - i_5855))+""));
result_5849[0] = (result_5849[0].slice(0,-1)).concat(cstrToNimstr(" calls omitted) ...\x0A"));
}

var j_5940 = 0;
var X3Atmp_5945 = 0;
X3Atmp_5945 = (i_5855 - 1);
var res_5947 = X3Atmp_5945;
L3: while (true) {
if (!(0 <= res_5947)) break L3;
j_5940 = res_5947;
add_5263(result_5849, 0, tempframes_5861[j_5940].Field0);
if ((0 < tempframes_5861[j_5940].Field1)) {
result_5849[0] = (result_5849[0].slice(0,-1)).concat(cstrToNimstr(", line: "));
result_5849[0] = (result_5849[0].slice(0,-1)).concat(cstrToNimstr((tempframes_5861[j_5940].Field1)+""));
}

result_5849[0] = (result_5849[0].slice(0,-1)).concat(cstrToNimstr("\x0A"));
res_5947 -= 1;
}
return result_5849[0];
}
function rawwritestacktrace_5948() {
var result_5950 = null;
if ((framePtr == null)) {
result_5950 = cstrToNimstr("No stack traceback available\x0A");
}
else {
result_5950 = (cstrToNimstr("Traceback (most recent call last)\x0A").slice(0,-1)).concat(auxwritestacktrace_5846(framePtr));
framePtr = null;
}

return result_5950;
}
function eqStrings(a_6207, b_6208) {
    if (a_6207 == b_6208) return true;
    if ((!a_6207) || (!b_6208)) return false;
    var alen = a_6207.length;
    if (alen != b_6208.length) return false;
    for (var i = 0; i < alen; ++i)
      if (a_6207[i] != b_6208[i]) return false;
    return true;
  }
function toJSStr(s_6155) {
    var len = s_6155.length-1;
    var result = new Array(len);
    var fcc = String.fromCharCode;
    for (var i = 0; i < len; ++i) {
      result[i] = fcc(s_6155[i]);
    }
    return result.join("");
  }
function raiseException(e_5965, ename_5966) {
var Tmp1;
e_5965.name = ename_5966;
if (!((excHandler == null))) {
excHandler.exc = e_5965;
}
else {
var buf_6001 = [rawwritestacktrace_5948()];
if (!!(eqStrings(e_5965.message, null))) Tmp1 = false; else {Tmp1 = !((e_5965.message[0] == 0)); }if (Tmp1) {
buf_6001[0] = (buf_6001[0].slice(0,-1)).concat(cstrToNimstr("Error: unhandled exception: "));
buf_6001[0] = (buf_6001[0].slice(0,-1)).concat(e_5965.message);
}
else {
buf_6001[0] = (buf_6001[0].slice(0,-1)).concat(cstrToNimstr("Error: unhandled exception"));
}

buf_6001[0] = (buf_6001[0].slice(0,-1)).concat(cstrToNimstr(" ["));
add_5263(buf_6001, 0, ename_5966);
buf_6001[0] = (buf_6001[0].slice(0,-1)).concat(cstrToNimstr("]\x0A"));
console.log(toJSStr(buf_6001[0]));
}

throw e_5965;}
function raiseOverflow() {
var e_6040 = null;
e_6040 = {m_type: NTI844, parent: null, name: null, message: null, trace: null};
e_6040.message = cstrToNimstr("over- or underflow");
raiseException(e_6040, "EOverflow");
}
function raiseDivByZero() {
var e_6062 = null;
e_6062 = {m_type: NTI842, parent: null, name: null, message: null, trace: null};
e_6062.message = cstrToNimstr("divison by zero");
raiseException(e_6062, "EDivByZero");
}
function rawEcho() {
      var buf = "";
      for (var i = 0; i < arguments.length; ++i) {
        buf += toJSStr(arguments[i]);
      }
      console.log(buf);
    }
rawEcho(cstrToNimstr("I\'m a JavaScript Program!"));

Made my day!
« Last Edit: October 16, 2013, 10:56:28 PM by John »

Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #62 on: October 16, 2013, 10:31:39 PM »
I will be following your work closely to fill in the holes for the SB effort. Feel free to move that along if you like.




Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #63 on: October 16, 2013, 10:36:09 PM »
PowerBASIC Keywords (courtesy of Daniel)

Code: [Select]
!
#Bloat
#Compile
#Compiler
#Debug
#Dim
#Else
#ElseIf
#EndIf
#If
#Include
#Option
#PBForms
#Register
#Resource
#Stack
#Tools
$Bel
$Bloat
$Bs
$Compile
$Cr
$CrLf
$Debug
$Dim
$Dq
$Else
$ElseIf
$EndIf
$Eof
$Esc
$Ff
$If
$Include
$Lf
$Nul
$Option
$Register
$Resource
$Spc
$Stack
$Tab
$Tools
$Vt
%Black
%Blue
%Cyan
%Def
%Err_BadFileMode
%Err_BadFileName
%Err_BadFileNameOrNumber
%Err_BadRecordNumber
%Err_CommError
%Err_DeviceIoError
%Err_DeviceTimeout
%Err_DeviceUnavailable
%Err_DiskFull
%Err_DiskMediaError
%Err_DiskNotReady
%Err_DivisionByZero
%Err_FarHeapCorrupt
%Err_FileAlreadyExists
%Err_FileIsOpen
%Err_FileNotFound
%Err_GlobalMemoryCorrupt
%Err_IllegalFunctionCall
%Err_InputPastEnd
%Err_InternalError
%Err_NoError
%Err_ObjectError
%Err_OutOfMemory
%Err_Overflow
%Err_PathFileAccessError
%Err_PathNotFound
%Err_PermissionDenied
%Err_RenameAcrossDisks
%Err_StringSpaceCorrupt
%Err_SubscriptPointerOutOfRange
%Err_TooManyFiles
%Gray
%Green
%LtGray
%Magenta
%Mix_Blackness
%Mix_CopySrc
%Mix_MaskNotSrc
%Mix_MaskSrc
%Mix_MaskSrcNot
%Mix_MergeNotSrc
%Mix_MergeSrc
%Mix_MergeSrcNot
%Mix_Nop
%Mix_Not
%Mix_NotCopySrc
%Mix_NotMaskSrc
%Mix_NotMergeSrc
%Mix_NotXorSrc
%Mix_Whiteness
%Mix_XorSrc
%Pb_Cc32
%Pb_Dll16
%Pb_Dll32
%Pb_Exe
%Pb_Revision
%Pb_RevLetter
%Pb_Win32
%Red
%VarClass_Asc
%VarClass_Bit
%VarClass_Byt
%VarClass_Cur
%VarClass_Cux
%VarClass_Dbl
%VarClass_Dwd
%VarClass_Ext
%VarClass_Fix
%VarClass_Fld
%VarClass_Guid
%VarClass_IFac
%VarClass_Int
%VarClass_Lng
%VarClass_Qud
%VarClass_SBt
%VarClass_Sng
%VarClass_Str
%VarClass_Type
%VarClass_Vrnt
%VarClass_Wrd
%VT_Array
%VT_Blob
%VT_Blob_Object
%VT_Bool
%VT_BStr
%VT_ByRef
%VT_CArray
%VT_CF
%VT_ClsID
%VT_Cy
%VT_Date
%VT_Dispatch
%VT_Empty
%VT_Error
%VT_FileTime
%VT_HResult
%VT_I1
%VT_I2
%VT_I4
%VT_I8
%VT_Int
%VT_LPStr
%VT_LPWStr
%VT_Null
%VT_Ptr
%VT_R4
%VT_R8
%VT_Record
%VT_SafeArray
%VT_Storage
%VT_Stored_Object
%VT_Stream
%VT_Streamed_Object
%VT_UI1
%VT_UI2
%VT_UI4
%VT_UI8
%VT_UInt
%VT_Unknown
%VT_UserDefined
%VT_Variant
%VT_Vector
%VT_Void
%White
%Yellow
'
?
Abs
Accel
Accept
Access
ACode$
Add
Addr
Alias
All
And
Any
Append
Arc
Array
ArrayAttr
As
Asc
Ascend
Asciiz
Asciz
Asm
Assign
AssignAccel
At
Atn
Attach
Attrib
Bar
Base
Baud
BDecl
Beep
Begin
Bgr
Bin$
Binary
Bit
Bitmap
Bits
Bits%
Bits&
Bits?
Bits??
Bits???
Border
Box
Break
Button
ByCmd
ByCopy
ByRef
Byte
ByVal
Calc
Call
CallBack
CallStk
CallStk$
CallStkCount
Cancel
Case
Catch
CbCtl
CbCtlMsg
CbHndl
CbLParam
CbMsg
CbWParam
CByt
CCur
CCux
CD
CDbl
CDecl
CDwd
Ceil
Cext
ChDir
ChDrive
Check
Check3State
CheckBox
Choose
Choose$
Choose%
Choose&
Chr
Chr$
CInt
CLng
Class
CleanUp
Clear
Client
Close
Close#
ClsId$
CodePtr
Collate
Color
ComboBox
Comm
Command$
Con
Connect
Const
Const$
Constants
Control
Copy
Cos
CQud
Create
Created
CSet
CSet$
CSng
CtsFlow
Cur
CurDir$
Currency
CurrencyX
Cux
CvByt
CvCur
CvCux
Cvd
CvDwd
Cve
Cvi
Cvl
Cvq
Cvs
CvWrd
CWrd
Data
DataCount
Date$
DC
Declarations
Declare
Decr
Default
DefByt
DefCur
DefCux
DefDbl
DefDwd
DefExt
DefInt
DefLng
DefQud
DefSng
DefStr
DefWrd
Delete
Descend
Desktop
Dialog
Dim
Dir$
Disable
DiskFree
DiskSize
Dispatch
DispParams
Dll
DllMain
DllMain&
Do
DoEvents
Double
Draw
DsrFlow
DsrSens
DtrFlow
DtrLine
Dword
Ellipse
Else
ElseIf
Empty
Enable
End
Environ
Environ$
Eof
Eqv
Erase
ErL
Err
ErrApi
ErrClear
Error
Error$
Exe
Exit
Exp
Exp10
Exp2
Explicit
Export
Ext
Extended
Extract$
Field
Field#
FileAttr
FileCopy
FileName$
FileScan
Fill
Finally
Fix
Flow
Flush
Flush#
Focus
Font
For
Format$
FormFeed
Frac
Frame
FreeFile
From
FuncName$
Function
Get
Get#
Get$
GetAttr
Global
GoSub
GoTo
Graphic
Guid
Guid$
GuidTxt$
Handle
Handles
Hex$
Hi
HiByt
HiInt
HiWrd
Host
ICase
Icon
IDispatch
Idn
If
IFace
IIf
IIf$
IIf%
IIf&
Image
ImageX
ImgButton
ImgButtonX
Imp
In
Includes
Incr
InOut
Inp
Input
Input#
Input$
InputBox$
Insert
InStr
Int
Integer
Interface
Inv
Is
IsFalse
IsNothing
IsObject
IsTrue
Iterate
IUnknown
Join$
Kill
Label
LBound
LCase$
Left
Left$
Len
Let
Lib
LibMain
LibMain&
Line
Lines
ListBox
Lo
Load
LoByt
Loc
Local
Lock
Lock#
Lof
Log
Log10
Log2
LoInt
Long
Loop
LoWrd
LPrint
LPrint$
LSet
LSet$
LTrim$
Macro
MacroTemp
Main
Main&
Mak
MakDwd
MakInt
MakLng
MakPtr
MakWrd
Margin
Mat
Max
Max$
Max%
Max&
MCase$
Member
Menu
Mid$
Min
Min$
Min%
Min&
Mix
MkByt$
MkCur$
MkCux$
Mkd$
MkDir
MkDwd$
Mke$
Mki$
Mkl$
Mkq$
Mks$
MkWrd$
Mod
Modal
Modeless
MousePtr
MsgBox
Name
New
Next
None
Not
Nothing
Notify
Nul$
Null
ObjActive
Object
ObjPtr
ObjResult
Oct$
Of
Off
On
Open
Opt
Option
Optional
Or
Orientation
Out
Output
Paint
Parity
ParityChar
ParityRepl
ParityType
Parse
Parse$
ParseCount
PBLibMain
PBLibMain&
PBMain
PBMain&
PBWin
Peek
Peek$
Pie
Pixel
Pixels
Pointer
Poke
Poke$
Polygon
Polyline
PopUp
Port
Pos
Post
PPI
Preserve
Print
Print#
Printer$
PrinterCount
Private
Profile
ProgId$
Ptr
Put
Put#
Put$
Quad
Quality
Qword
Random
Randomize
Read
Read$
Records
Recv
ReDim
ReDraw
RegExpr
Register
RegRepl
Rem
Remain$
Remove$
Render
Repeat$
Replace
Reset
Resume
Retain$
Return
RGB
Right
Right$
Ring
Rlsd
RmDir
Rnd
Rotate
Round
RSet
RSet$
RTrim$
RtsFlow
RxBuffer
RxQue
Save
SBit
Scale
Scan
ScrollBar
SDecl
Seek
Seek#
Select
Send
Server
Set
SetAttr
SetEof
SetEof#
Sgn
Shared
Shell
Shift
Show
Signed
Sin
Single
Size
SizeOf
Sleep
Sort
Space$
Spc
Sqr
State
Static
Status
StdCall
Step
Stop
Str$
StrDelete$
Stretch
String
String$
StrInsert$
StrPtr
StrReverse$
Style
Sub
Suspend
Swap
Switch
Switch$
Switch%
Switch&
Tab
Tab$
TagArray
Tally
Tan
Tcp
Text
TextBox
Then
Thread
ThreadCount
Threaded
ThreadID
Time$
TimeOut
Timer
To
Toggle
Trace
Trim$
Trn
Try
TxBuffer
TxQue
Type
UBound
UCase
UCase$
UCode$
Udp
Union
Units
UnLock
UnLock#
Until
User
Using
Using$
Val
Variant
Variant#
Variant$
VariantVT
VarPtr
Verify
Version3
Version4
Version5
Wend
While
Width
Width#
Window
WinMain
WinMain&
With
Word
Write
Write#
XInpFlow
Xor
XOutFlow
XPrint
XPrint$
Zer

kryton9

  • Guest
Re: BAS2NIM
« Reply #64 on: October 16, 2013, 10:44:53 PM »
Daniels work is daunting. But think of all the PowerBasic users looking for a way out. His work will be used by many that is for sure!

kryton9

  • Guest
Re: BAS2NIM
« Reply #65 on: October 16, 2013, 10:47:21 PM »
I will tinker with it tomorrow as I want to learn SB better.
Just the little bit we have done makes you appreciate language developers, wow talk about work!

kryton9

  • Guest
Re: BAS2NIM
« Reply #66 on: October 17, 2013, 03:54:07 PM »
John, as you know I get confused easily, so am not following well... I will get on and look at the code and then perhaps get a better picture.
Looking forward to hearing you ideas.

Perhaps we need a list of BASICS and what they can do and are planning to do and which would benefit from such a project.

For example:
ScriptBasic - already cross-platform and can output to C. So, no need for translator.
OxygenBasic - planned to be cross-platform and output to C, So, no need for translator.
PowerBasic - windows only. I don't know if it can output to C, need for translator to be cross platform
...
« Last Edit: October 17, 2013, 04:11:34 PM by kryton9 »

Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #67 on: October 17, 2013, 04:35:13 PM »
I don't think a BAS2NIM utility would be much value if it couldn't at least translate PowerBASIC Console Compiler 5 BASIC. Beyond that creating a BASIC seems to be a life long dream of most that have used the language. I think this effort will help others understand the benefits of high level languages and what is going on under the covers.

I'm still waiting to see what Daniel has up his sleeve. I'm just trying to keep some momentum going with my SB efforts. As you can see, it doesn't take much SB code/time to show a concept. I encourage anyone with an idea how to save BASIC and make it more cross platform to come forward and tell us your ideas.

Good to solve the mystery of the other vote. I should of guessed AIR was going to do some of his Python magic for us.  8)
« Last Edit: October 17, 2013, 09:47:40 PM by John »

Offline AIR

  • BASIC Developer
  • Posts: 932
  • Coder
Re: BAS2NIM
« Reply #68 on: October 17, 2013, 05:22:10 PM »
You'll need the pyparsing module (sudo easy_install pyparsing, to get it).

Just a rudimentary, quickly thrown together attempt.  The "test" variable holds a sample, and as you can see it is NOT case sensitive.

Code: [Select]
#!/usr/bin/env python

from pyparsing import *

test = """
let g = 10
LET A = "Hello BAS2NIM"
PRINT A
print "Howya Doin? " & A
for x = 0 to g-1
    print x
next

If g = 10 then
    print "OK"
end if

while g > 0
    print g
    g = g - 1
wend

""".split('\n')


IDENT = Word(alphas, alphanums+"_")

# KEYWORDS
LET = Keyword('Let',  caseless=True)
PRINT = Keyword('print',  caseless=True)
FOR = Keyword('for',  caseless=True)
TO = Keyword('to',  caseless=True)
NEXT = Keyword('next',  caseless=True)
IF = Keyword('if',  caseless=True)
THEN = Keyword('then',  caseless=True)
ELSE = Keyword('else',  caseless=True)
WHILE = Keyword('while',  caseless=True)
WEND = Keyword('wend',  caseless=True)
END = Keyword('end',  caseless=True)
ASC = Keyword('asc',  caseless=True)
VAL = Keyword('val',  caseless=True)
STR = Keyword('str',  caseless=True)
MID = Keyword('mid',  caseless=True)
LEFT = Keyword('left',  caseless=True)
UCASE = Keyword('ucase',  caseless=True)
LCASE = Keyword('lcase',  caseless=True)
UBOUND = Keyword('ubound', caseless=True)
LBOUND = Keyword('lbound', caseless=True)
ENDIF = END + IF


# KEYWORD REPLACEMENT ACTIONS
PRINT.setParseAction(replaceWith('echo'))
LET.setParseAction(replaceWith('var'))
TO.setParseAction(replaceWith('..'))
NEXT.setParseAction(replaceWith(None))
UBOUND.setParseAction(replaceWith('high'))
LBOUND.setParseAction(replaceWith('low'))
WEND.setParseAction(replaceWith(None))



all_keywords = FOR|NEXT|IF|THEN|ELSE|WHILE|WEND|LET \
   |PRINT|END|ASC|VAL|STR|MID|LEFT|UCASE \
   |LCASE|UBOUND|LBOUND|TO

for line in test:
if "for" in line.lower():
line = line.replace('=','in')+':'
elif "then" in line.lower():
line = line.replace(' then',':').replace('=','==')
elif "while" in line.lower():
line = line.replace('=','==')+':'
elif "end if" or "endif" in line.lower():
line = line.replace('end if','')


print all_keywords.transformString(line)

Quote from: CONVERTED OUTPUT
var g = 10
var A = "Hello BAS2NIM"
echo A
echo "Howya Doin? " & A
for x in 0 .. g-1:
    echo x


if g == 10:
    echo "OK"


while g > 0:
    echo g
    g = g - 1

Just playing around with this, I probably won't have time to do this properly....

A.
« Last Edit: October 17, 2013, 05:25:39 PM by AIR »

Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #69 on: October 17, 2013, 05:50:31 PM »
Looks great AIR!

I'm sure if you could get enough of a framework going others would jump in and help. I'm not a Python guy but willing to learn if this is a better solution.

I installed pyparsing via synaptic. It doesn't look like it's available on the C9 IDE enviroment. I'll ask the C9 guys if they have a c9pm package available for it.

Code: [Select]
from pyparsing import Word, alphas
greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
hello = "Hello, World!"
print (hello, "->", greet.parseString( hello ))

jrs@laptop:~/bas2nim$ python pyparse.py
('Hello, World!', '->', (['Hello', ',', 'World', '!'], {}))
jrs@laptop:~/bas2nim$
« Last Edit: October 17, 2013, 06:32:38 PM by John »

Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #70 on: October 17, 2013, 07:06:55 PM »
I got pyparsing 2.01 installed on the Cloud9 IDE Nimrod site.

Code: [Select]
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1 $ python setup.py install
running install
running build
running build_py
creating build
creating build/lib
copying pyparsing.py -> build/lib
running install_lib
copying build/lib/pyparsing.py -> /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/lib/python/site-packages
byte-compiling /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/lib/python/site-packages/pyparsing.py to pyparsing.pyc
running install_egg_info
Writing /var/lib/stickshift/525387a75973caafd40003a0/app-root/data/lib/python/site-packages/pyparsing-2.0.1-py2.6.egg-info
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1 $
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1 $ ls -l
total 876
drwxr-xr-x. 3 525387a75973caafd40003a0 525387a75973caafd40003a0   4096 Oct 17 22:02 build/
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  73858 Jul 17 00:49 CHANGES
drwxr-xr-x. 2 525387a75973caafd40003a0 525387a75973caafd40003a0   4096 Jul 17 03:38 docs/
drwxr-xr-x. 2 525387a75973caafd40003a0 525387a75973caafd40003a0   4096 Jul 17 03:38 examples/
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  69524 Jul 17 02:30 HowToUsePyparsing.html
drwxr-xr-x. 2 525387a75973caafd40003a0 525387a75973caafd40003a0   4096 Jul 17 03:38 htmldoc/
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1041 Oct 15  2007 LICENSE
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    994 Jul 17 03:38 PKG-INFO
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0 236402 Apr 13  2009 pyparsingClassDiagram.JPG
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0 141354 Apr 13  2009 pyparsingClassDiagram.PNG
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0 154099 Jul 17 03:08 pyparsing.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0 173787 Oct 17 22:02 pyparsing.pyc
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1947 Sep 13  2005 README
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0     35 May  5  2006 robots.txt
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1320 Jul 17 00:52 setup.py
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1 $ cd examples
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1/examples $ ls -l
total 780
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  12027 Oct 18  2012 0README.html
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  39137 Feb 28  2003 AcManForm.dfm
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  20595 Nov 23  2012 adventureEngine.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  10733 Nov 23  2012 antlr_grammar.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2499 Sep  7  2010 antlr_grammar_tests.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2170 Nov 23  2012 apicheck.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   4374 Nov 23  2012 btpyparse.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    885 Nov 23  2012 builtin_parse_action_demo.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2062 Nov 23  2012 chemicalFormulas.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    806 Nov 23  2012 cLibHeader.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    744 Nov 23  2012 commasep.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2054 Nov 23  2012 configParse.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1342 Nov 23  2012 cpp_enum_parser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1582 Nov 23  2012 datetimeParseActions.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7051 Nov 23  2012 deltaTime.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   6933 Nov 23  2012 dfmparse.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3164 Nov 23  2012 dhcpd_leases_parser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2198 Nov 23  2012 dictExample2.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1612 Nov 23  2012 dictExample.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   4247 Mar  9  2004 ebnf.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2322 Nov 23  2012 ebnftest.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7102 Nov 23  2012 eval_arith.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2326 Nov 23  2012 excelExpr.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7196 Nov 23  2012 fourFn.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   5175 Nov 23  2012 gen_ctypes.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1311 Nov 23  2012 getNTPserversNew.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1101 Nov 23  2012 getNTPservers.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    434 Nov 23  2012 greetingInGreek.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    479 Nov 23  2012 greetingInKorean.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    372 Nov 23  2012 greeting.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    502 Nov 23  2012 groupUsingListAllMatches.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1075 Nov 23  2012 holaMundo.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1251 Nov 23  2012 htmlStripper.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3577 Nov 23  2012 httpServerLogParser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   8082 Nov 23  2012 idlParse.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1928 Nov 23  2012 indentedGrammarExample.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7652 Nov 23  2012 invRegex.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3525 Nov 23  2012 jsonParser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  18475 Nov 23  2012 LAparser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1531 Nov 23  2012 linenoExample.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1658 Nov 23  2012 list1.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1788 Nov 23  2012 listAllMatches.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7326 Nov 23  2012 lucene_grammar.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1844 Nov 23  2012 macroExpander.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    796 Nov 23  2012 makeHTMLTagExample.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    587 Nov 23  2012 matchPreviousDemo.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2700 Nov 23  2012 mozillaCalendarParser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    752 Jul 16  2004 mozilla.ics
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    609 Nov 23  2012 nested.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3871 Nov 23  2012 oc.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3863 Nov 23  2012 parseListString.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2167 Nov 23  2012 parsePythonValue.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    827 Nov 23  2012 parseResultsSumExample.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3310 Nov 23  2012 partial_gene_match.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3498 Nov 23  2012 pgn.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2217 Nov 23  2012 position.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3565 Nov 23  2012 protobuf_parser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  60603 Nov 23  2012 pymicko.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   8230 Nov 23  2012 pythonGrammarParser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2562 Nov 23  2012 rangeCheck.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0 123643 Nov 23  2012 readJson.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1524 Nov 23  2012 removeLineBreaks.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2366 Nov 23  2012 romanNumerals.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2363 Nov 23  2012 scanExamples.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    452 Nov 23  2012 scanYahoo.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    935 Nov 23  2012 searchParserAppDemo.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  10737 Nov 23  2012 searchparser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   6371 Nov 23  2012 select_parser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   5504 Nov 23  2012 sexpParser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1715 Nov 23  2012 shapes.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2323 Nov 23  2012 simpleArith.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   2220 Nov 23  2012 simpleBool.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3115 Nov 23  2012 SimpleCalc.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   4760 Nov 23  2012 simpleSQL.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1082 Nov 23  2012 simpleWiki.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  43730 Feb 28  2003 SingleForm.dfm
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  13282 Nov 23  2012 sparser.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3033 Nov 23  2012 sql2dot.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3000 Nov 23  2012 stackish.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   8825 Nov 23  2012 stateMachine2.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1027 Nov 23  2012 tagCapture.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7467 Nov 23  2012 TAP.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   7867 Jan  4  2011 test_bibparse.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1475 Nov 23  2012 urlExtractorNew.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   1794 Nov 23  2012 urlExtractor.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0  31847 Nov 23  2012 verilogParse.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0    887 Nov 23  2012 withAttribute.py
-rw-r--r--. 1 525387a75973caafd40003a0 525387a75973caafd40003a0   3259 Nov 23  2012 wordsToNum.py
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1/examples $ python searchParserAppDemo.py
/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/install/pyparsing-2.0.1/examples/searchparser.py:61: DeprecationWarning: the sets module is deprecated
  from sets import Set
/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/install/pyparsing-2.0.1/examples/searchparser.py:99: DeprecationWarning: Operator '<<' is deprecated, use '<<=' instead
  (operatorWord + operatorQuotesContent) | operatorWord
/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/install/pyparsing-2.0.1/examples/searchparser.py:113: DeprecationWarning: Operator '<<' is deprecated, use '<<=' instead
  ).setResultsName("not") | operatorParenthesis)
/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/install/pyparsing-2.0.1/examples/searchparser.py:120: DeprecationWarning: Operator '<<' is deprecated, use '<<=' instead
  ).setResultsName("and") | operatorNot)
/var/lib/stickshift/525387a75973caafd40003a0/app-root/data/639761/install/pyparsing-2.0.1/examples/searchparser.py:124: DeprecationWarning: Operator '<<' is deprecated, use '<<=' instead
  ).setResultsName("or") | operatorAnd)
grape or orange
set(['orange juice', 'grape juice', 'orange marmalade', 'orange jujubees', 'grape jelly'])
()
grape*
set(['grapefruit juice', 'grape juice', 'grape jelly'])
()
not(grape*)
set(['orange jujubees', 'orange juice', 'prune butter', 'orange marmalade', 'strawberry jam', 'prune juice'])
()
prune and grape
set([])
()
scriptbasic@nimrod:~/639761/install/pyparsing-2.0.1/examples $

Offline AIR

  • BASIC Developer
  • Posts: 932
  • Coder
Re: BAS2NIM
« Reply #71 on: October 17, 2013, 07:30:22 PM »
I just did:  easy_install pyparsing (without the sudo) and it installed fine in my c9 test instance.

Offline John

  • Forum Support / SB Dev
  • Posts: 3597
    • ScriptBasic Open Source Project
Re: BAS2NIM
« Reply #72 on: October 17, 2013, 07:33:33 PM »
Excellent!

It would be great if you could setup a github project for BAS2NIM using Python.

Building Recursive Descent Parsers with Python

Quote
Pyparsing provides a basic framework for creating recursive-descent parsers, taking care of the overhead functions of scanning the input string, handling expression mismatches, selecting the longest of matching alternatives, invoking callback functions, and returning the parsed results. This leaves developers free to focus on their grammar design and the design and implementation of corresponding token processing. Pyparsing's nature as a combinator allows developers to scale their applications from simple tokenizers up to complex grammar processors. It is a great way to get started with your next parsing project!

Code: [Select]
#
# simpleArith.py
#
# Example of defining an arithmetic expression parser using
# the operatorPrecedence helper method in pyparsing.
#
# Copyright 2006, by Paul McGuire
#

from pyparsing import *

integer = Word(nums).setParseAction(lambda t:int(t[0]))
variable = Word(alphas,exact=1)
operand = integer | variable

expop = Literal('^')
signop = oneOf('+ -')
multop = oneOf('* /')
plusop = oneOf('+ -')
factop = Literal('!')

# To use the operatorPrecedence helper:
#   1.  Define the "atom" operand term of the grammar.
#       For this simple grammar, the smallest operand is either
#       and integer or a variable.  This will be the first argument
#       to the operatorPrecedence method.
#   2.  Define a list of tuples for each level of operator
#       precendence.  Each tuple is of the form
#       (opExpr, numTerms, rightLeftAssoc, parseAction), where
#       - opExpr is the pyparsing expression for the operator;
#          may also be a string, which will be converted to a Literal
#       - numTerms is the number of terms for this operator (must
#          be 1 or 2)
#       - rightLeftAssoc is the indicator whether the operator is
#          right or left associative, using the pyparsing-defined
#          constants opAssoc.RIGHT and opAssoc.LEFT.
#       - parseAction is the parse action to be associated with
#          expressions matching this operator expression (the
#          parse action tuple member may be omitted)
#   3.  Call operatorPrecedence passing the operand expression and
#       the operator precedence list, and save the returned value
#       as the generated pyparsing expression.  You can then use
#       this expression to parse input strings, or incorporate it
#       into a larger, more complex grammar.
#       
expr = operatorPrecedence( operand,
    [("!", 1, opAssoc.LEFT),
     ("^", 2, opAssoc.RIGHT),
     (signop, 1, opAssoc.RIGHT),
     (multop, 2, opAssoc.LEFT),
     (plusop, 2, opAssoc.LEFT),]
    )

test = ["9 + 2 + 3",
        "9 + 2 * 3",
        "(9 + 2) * 3",
        "(9 + -2) * 3",
        "(9 + -2) * 3^2^2",
        "(9! + -2) * 3^2^2",
        "M*X + B",
        "M*(X + B)",
        "1+2*-3^4*5+-+-6",]
for t in test:
    print(t)
    print(expr.parseString(t))
    print()

jrs@laptop:~/bas2nim/pyparsing-2.0.1/examples$ python simpleArith.py
9 + 2 + 3
[[9, '+', 2, '+', 3]]
()
9 + 2 * 3
[[9, '+', [2, '*', 3]]]
()
(9 + 2) * 3
[[[9, '+', 2], '*', 3]]
()
(9 + -2) * 3
[[[9, '+', ['-', 2]], '*', 3]]
()
(9 + -2) * 3^2^2
[[[9, '+', ['-', 2]], '*', [3, '^', [2, '^', 2]]]]
()
(9! + -2) * 3^2^2
[[[[9, '!'], '+', ['-', 2]], '*', [3, '^', [2, '^', 2]]]]
()
M*X + B
[[['M', '*', 'X'], '+', 'B']]
()
M*(X + B)
[['M', '*', ['X', '+', 'B']]]
()
1+2*-3^4*5+-+-6
[[1, '+', [2, '*', ['-', [3, '^', 4]], '*', 5], '+', ['-', ['+', ['-', 6]]]]]
()
jrs@laptop:~/bas2nim/pyparsing-2.0.1/examples$

Code: [Select]
#
# cLibHeader.py
#
# A simple parser to extract API doc info from a C header file
#
# Copyright, 2012 - Paul McGuire
#

from pyparsing import Word, alphas, alphanums, Combine, oneOf, Optional, delimitedList, Group, Keyword

testdata = """
  int func1(float *vec, int len, double arg1);
  int func2(float **arr, float *vec, int len, double arg1, double arg2);
  """
 
ident = Word(alphas, alphanums + "_")
vartype = Combine( oneOf("float double int char") + Optional(Word("*")), adjacent = False)
arglist = delimitedList(Group(vartype("type") + ident("name")))

functionCall = Keyword("int") + ident("name") + "(" + arglist("args") + ")" + ";"

for fn,s,e in functionCall.scanString(testdata):
    print(fn.name)
    for a in fn.args:
        print(" - %(name)s (%(type)s)" % a)

jrs@laptop:~/bas2nim/pyparsing-2.0.1/examples$ python cLibHeader.py
func1
 - vec (float*)
 - len (int)
 - arg1 (double)
func2
 - arr (float**)
 - vec (float*)
 - len (int)
 - arg1 (double)
 - arg2 (double)
jrs@laptop:~/bas2nim/pyparsing-2.0.1/examples$
« Last Edit: October 17, 2013, 09:36:11 PM by John »

Offline AIR

  • BASIC Developer
  • Posts: 932
  • Coder
Re: BAS2NIM
« Reply #73 on: October 17, 2013, 10:50:09 PM »
Good to solve the mystery of the other vote. I should of guessed AIR was going to do some of his Python magic for us.  8)

I knew that was gonna make you wonder!   ;D

A.

kryton9

  • Guest
Re: BAS2NIM
« Reply #74 on: October 17, 2013, 11:36:42 PM »
AIR + PYTHON = MAGIC TRANSLATOR

My latest updates here:
http://www.allbasic.info/forum/index.php?topic=249.msg2826#msg2826
« Last Edit: October 18, 2013, 12:15:08 AM by kryton9 »