Merge pull request #333 from Tass/master

EcmaScript => Js
This commit is contained in:
Araq 2013-02-15 12:37:09 -08:00
commit fb6747a55e
25 changed files with 127 additions and 126 deletions

View file

@ -20,22 +20,22 @@ import
# implementation # implementation
type type
TEcmasGen = object of TPassContext TJSGen = object of TPassContext
module: PSym module: PSym
BModule = ref TEcmasGen BModule = ref TJSGen
TEcmasTypeKind = enum # necessary JS "types" TJSTypeKind = enum # necessary JS "types"
etyNone, # no type etyNone, # no type
etyNull, # null type etyNull, # null type
etyProc, # proc type etyProc, # proc type
etyBool, # bool type etyBool, # bool type
etyInt, # Ecmascript's int etyInt, # JavaScript's int
etyFloat, # Ecmascript's float etyFloat, # JavaScript's float
etyString, # Ecmascript's string etyString, # JavaScript's string
etyObject, # Ecmascript's reference to an object etyObject, # JavaScript's reference to an object
etyBaseIndex # base + index needed etyBaseIndex # base + index needed
TCompRes{.final.} = object TCompRes{.final.} = object
kind: TEcmasTypeKind kind: TJSTypeKind
com: PRope # computation part com: PRope # computation part
# address if this is a (address, index)-tuple # address if this is a (address, index)-tuple
res: PRope # result part; index if this is an res: PRope # result part; index if this is an
@ -91,7 +91,7 @@ const
MappedToObject = {tyObject, tyArray, tyArrayConstr, tyTuple, tyOpenArray, MappedToObject = {tyObject, tyArray, tyArrayConstr, tyTuple, tyOpenArray,
tySet, tyVar, tyRef, tyPtr, tyBigNum, tyVarargs} tySet, tyVar, tyRef, tyPtr, tyBigNum, tyVarargs}
proc mapType(typ: PType): TEcmasTypeKind = proc mapType(typ: PType): TJSTypeKind =
var t = skipTypes(typ, abstractInst) var t = skipTypes(typ, abstractInst)
case t.kind case t.kind
of tyVar, tyRef, tyPtr: of tyVar, tyRef, tyPtr:
@ -605,8 +605,8 @@ proc genCaseStmt(p: var TProc, n: PNode, r: var TCompRes) =
if cond.com != nil: appf(r.com, "$1;$n", [cond.com]) if cond.com != nil: appf(r.com, "$1;$n", [cond.com])
stringSwitch = skipTypes(n.sons[0].typ, abstractVar).kind == tyString stringSwitch = skipTypes(n.sons[0].typ, abstractVar).kind == tyString
if stringSwitch: if stringSwitch:
useMagic(p, "toEcmaStr") useMagic(p, "toJSStr")
appf(r.com, "switch (toEcmaStr($1)) {$n", [cond.res]) appf(r.com, "switch (toJSStr($1)) {$n", [cond.res])
else: else:
appf(r.com, "switch ($1) {$n", [cond.res]) appf(r.com, "switch ($1) {$n", [cond.res])
for i in countup(1, sonsLen(n) - 1): for i in countup(1, sonsLen(n) - 1):
@ -619,17 +619,17 @@ proc genCaseStmt(p: var TProc, n: PNode, r: var TCompRes) =
v = copyNode(e.sons[0]) v = copyNode(e.sons[0])
while (v.intVal <= e.sons[1].intVal): while (v.intVal <= e.sons[1].intVal):
gen(p, v, cond) gen(p, v, cond)
if cond.com != nil: internalError(v.info, "ecmasgen.genCaseStmt") if cond.com != nil: internalError(v.info, "jsgen.genCaseStmt")
appf(r.com, "case $1: ", [cond.res]) appf(r.com, "case $1: ", [cond.res])
Inc(v.intVal) Inc(v.intVal)
else: else:
gen(p, e, cond) gen(p, e, cond)
if cond.com != nil: internalError(e.info, "ecmasgen.genCaseStmt") if cond.com != nil: internalError(e.info, "jsgen.genCaseStmt")
if stringSwitch: if stringSwitch:
case e.kind case e.kind
of nkStrLit..nkTripleStrLit: appf(r.com, "case $1: ", of nkStrLit..nkTripleStrLit: appf(r.com, "case $1: ",
[makeJSString(e.strVal)]) [makeJSString(e.strVal)])
else: InternalError(e.info, "ecmasgen.genCaseStmt: 2") else: InternalError(e.info, "jsgen.genCaseStmt: 2")
else: else:
appf(r.com, "case $1: ", [cond.res]) appf(r.com, "case $1: ", [cond.res])
genStmt(p, lastSon(it), stmt) genStmt(p, lastSon(it), stmt)
@ -637,7 +637,7 @@ proc genCaseStmt(p: var TProc, n: PNode, r: var TCompRes) =
of nkElse: of nkElse:
genStmt(p, it.sons[0], stmt) genStmt(p, it.sons[0], stmt)
appf(r.com, "default: $n$1break;$n", [mergeStmt(stmt)]) appf(r.com, "default: $n$1break;$n", [mergeStmt(stmt)])
else: internalError(it.info, "ecmasgen.genCaseStmt") else: internalError(it.info, "jsgen.genCaseStmt")
appf(r.com, "}$n", []) appf(r.com, "}$n", [])
proc genStmtListExpr(p: var TProc, n: PNode, r: var TCompRes) proc genStmtListExpr(p: var TProc, n: PNode, r: var TCompRes)
@ -692,7 +692,7 @@ proc genAsmStmt(p: var TProc, n: PNode, r: var TCompRes) =
case n.sons[i].Kind case n.sons[i].Kind
of nkStrLit..nkTripleStrLit: app(r.com, n.sons[i].strVal) of nkStrLit..nkTripleStrLit: app(r.com, n.sons[i].strVal)
of nkSym: app(r.com, mangleName(n.sons[i].sym)) of nkSym: app(r.com, mangleName(n.sons[i].sym))
else: InternalError(n.sons[i].info, "ecmasgen: genAsmStmt()") else: InternalError(n.sons[i].info, "jsgen: genAsmStmt()")
proc genIfStmt(p: var TProc, n: PNode, r: var TCompRes) = proc genIfStmt(p: var TProc, n: PNode, r: var TCompRes) =
var var
@ -1276,7 +1276,7 @@ proc genMagic(p: var TProc, n: PNode, r: var TCompRes) =
binaryStmt(p, n, r, "", "$1 += $2") binaryStmt(p, n, r, "", "$1 += $2")
else: else:
binaryStmt(p, n, r, "", "$1 = ($1.slice(0,-1)).concat($2)") binaryStmt(p, n, r, "", "$1 = ($1.slice(0,-1)).concat($2)")
# XXX: make a copy of $2, because of ECMAScript's sucking semantics # XXX: make a copy of $2, because of Javascript's sucking semantics
of mAppendSeqElem: binaryStmt(p, n, r, "", "$1.push($2)") of mAppendSeqElem: binaryStmt(p, n, r, "", "$1.push($2)")
of mConStrStr: genConStrStr(p, n, r) of mConStrStr: genConStrStr(p, n, r)
of mEqStr: binaryExpr(p, n, r, "eqStrings", "eqStrings($1, $2)") of mEqStr: binaryExpr(p, n, r, "eqStrings", "eqStrings($1, $2)")
@ -1395,8 +1395,8 @@ proc convStrToCStr(p: var TProc, n: PNode, r: var TCompRes) =
else: else:
gen(p, n.sons[0], r) gen(p, n.sons[0], r)
if r.res == nil: InternalError(n.info, "convStrToCStr") if r.res == nil: InternalError(n.info, "convStrToCStr")
useMagic(p, "toEcmaStr") useMagic(p, "toJSStr")
r.res = ropef("toEcmaStr($1)", [r.res]) r.res = ropef("toJSStr($1)", [r.res])
proc convCStrToStr(p: var TProc, n: PNode, r: var TCompRes) = proc convCStrToStr(p: var TProc, n: PNode, r: var TCompRes) =
# we do an optimization here as this is likely to slow down # we do an optimization here as this is likely to slow down
@ -1660,10 +1660,10 @@ proc myClose(b: PPassContext, n: PNode): PNode =
discard writeRopeIfNotEqual(con(genHeader(), code), outfile) discard writeRopeIfNotEqual(con(genHeader(), code), outfile)
proc myOpenCached(s: PSym, rd: PRodReader): PPassContext = proc myOpenCached(s: PSym, rd: PRodReader): PPassContext =
InternalError("symbol files are not possible with the Ecmas code generator") InternalError("symbol files are not possible with the JS code generator")
result = nil result = nil
proc myOpen(s: PSym): PPassContext = proc myOpen(s: PSym): PPassContext =
result = newModule(s) result = newModule(s)
const ecmasgenPass* = makePass(myOpen, myOpenCached, myProcess, myClose) const JSgenPass* = makePass(myOpen, myOpenCached, myProcess, myClose)

View file

@ -322,7 +322,7 @@ proc generateThunk(prc: PNode, dest: PType): PNode =
# we cannot generate a proper thunk here for GC-safety reasons (see internal # we cannot generate a proper thunk here for GC-safety reasons (see internal
# documentation): # documentation):
if gCmd == cmdCompileToEcmaScript: return prc if gCmd == cmdCompileToJS: return prc
result = newNodeIT(nkClosure, prc.info, dest) result = newNodeIT(nkClosure, prc.info, dest)
var conv = newNodeIT(nkHiddenStdConv, prc.info, dest) var conv = newNodeIT(nkHiddenStdConv, prc.info, dest)
conv.add(emptyNode) conv.add(emptyNode)
@ -543,7 +543,7 @@ proc transformOuterProc(o: POuterContext, n: PNode): PNode =
if x != nil: n.sons[i] = x if x != nil: n.sons[i] = x
proc liftLambdas*(fn: PSym, body: PNode): PNode = proc liftLambdas*(fn: PSym, body: PNode): PNode =
if body.kind == nkEmpty or gCmd == cmdCompileToEcmaScript: if body.kind == nkEmpty or gCmd == cmdCompileToJS:
# ignore forward declaration: # ignore forward declaration:
result = body result = body
else: else:
@ -566,7 +566,7 @@ proc liftLambdas*(fn: PSym, body: PNode): PNode =
result = ex result = ex
proc liftLambdasForTopLevel*(module: PSym, body: PNode): PNode = proc liftLambdasForTopLevel*(module: PSym, body: PNode): PNode =
if body.kind == nkEmpty or gCmd == cmdCompileToEcmaScript: if body.kind == nkEmpty or gCmd == cmdCompileToJS:
result = body result = body
else: else:
var o = newOuterContext(module) var o = newOuterContext(module)

View file

@ -14,7 +14,7 @@ import
llstream, strutils, ast, astalgo, lexer, syntaxes, renderer, options, msgs, llstream, strutils, ast, astalgo, lexer, syntaxes, renderer, options, msgs,
os, lists, condsyms, rodread, rodwrite, ropes, trees, times, os, lists, condsyms, rodread, rodwrite, ropes, trees, times,
wordrecg, sem, semdata, idents, passes, docgen, extccomp, wordrecg, sem, semdata, idents, passes, docgen, extccomp,
cgen, ecmasgen, cgendata, cgen, jsgen, cgendata,
platform, nimconf, importer, passaux, depends, evals, types, idgen, platform, nimconf, importer, passaux, depends, evals, types, idgen,
tables, docgen2, service, magicsys, parser, crc, ccgutils tables, docgen2, service, magicsys, parser, crc, ccgutils
@ -301,14 +301,15 @@ when has_LLVM_Backend:
#registerPass(cleanupPass()) #registerPass(cleanupPass())
compileProject() compileProject()
proc CommandCompileToEcmaScript = proc CommandCompileToJS =
#incl(gGlobalOptions, optSafeCode) #incl(gGlobalOptions, optSafeCode)
setTarget(osEcmaScript, cpuEcmaScript) setTarget(osJS, cpuJS)
#initDefines() #initDefines()
DefineSymbol("nimrod") # 'nimrod' is always defined DefineSymbol("nimrod") # 'nimrod' is always defined
DefineSymbol("ecmascript") DefineSymbol("ecmascript") # For backward compatibility
DefineSymbol("js")
semanticPasses() semanticPasses()
registerPass(ecmasgenPass) registerPass(jsgenPass)
compileProject() compileProject()
proc InteractivePasses = proc InteractivePasses =
@ -481,10 +482,10 @@ proc MainCommand =
CommandCompileToC() CommandCompileToC()
else: else:
rawMessage(errInvalidCommandX, command) rawMessage(errInvalidCommandX, command)
of "js", "compiletoecmascript": of "js", "compiletojs":
gCmd = cmdCompileToEcmaScript gCmd = cmdCompileToJS
wantMainModule() wantMainModule()
CommandCompileToEcmaScript() CommandCompileToJS()
of "compiletollvm": of "compiletollvm":
gCmd = cmdCompileToLLVM gCmd = cmdCompileToLLVM
wantMainModule() wantMainModule()

View file

@ -472,32 +472,32 @@ cgen -> wordrecg;
cgen -> rnimsyn; cgen -> rnimsyn;
cgen -> treetab; cgen -> treetab;
cgen -> cgmeth; cgen -> cgmeth;
ecmasgen -> ast; jsgen -> ast;
ecmasgen -> astalgo; jsgen -> astalgo;
ecmasgen -> strutils; jsgen -> strutils;
ecmasgen -> nhashes; jsgen -> nhashes;
ecmasgen -> trees; jsgen -> trees;
ecmasgen -> platform; jsgen -> platform;
ecmasgen -> magicsys; jsgen -> magicsys;
ecmasgen -> extccomp; jsgen -> extccomp;
ecmasgen -> options; jsgen -> options;
ecmasgen -> nversion; jsgen -> nversion;
ecmasgen -> nimsets; jsgen -> nimsets;
ecmasgen -> msgs; jsgen -> msgs;
ecmasgen -> crc; jsgen -> crc;
ecmasgen -> bitsets; jsgen -> bitsets;
ecmasgen -> idents; jsgen -> idents;
ecmasgen -> lists; jsgen -> lists;
ecmasgen -> types; jsgen -> types;
ecmasgen -> os; jsgen -> os;
ecmasgen -> times; jsgen -> times;
ecmasgen -> ropes; jsgen -> ropes;
ecmasgen -> math; jsgen -> math;
ecmasgen -> passes; jsgen -> passes;
ecmasgen -> ccgutils; jsgen -> ccgutils;
ecmasgen -> wordrecg; jsgen -> wordrecg;
ecmasgen -> rnimsyn; jsgen -> rnimsyn;
ecmasgen -> rodread; jsgen -> rodread;
interact -> llstream; interact -> llstream;
interact -> strutils; interact -> strutils;
interact -> ropes; interact -> ropes;
@ -561,7 +561,7 @@ main -> passes;
main -> docgen; main -> docgen;
main -> extccomp; main -> extccomp;
main -> cgen; main -> cgen;
main -> ecmasgen; main -> jsgen;
main -> platform; main -> platform;
main -> interact; main -> interact;
main -> nimconf; main -> nimconf;

View file

@ -84,7 +84,7 @@ Files: "lib/wrappers/zip/libzip_all.c"
Files: "lib/windows/*.nim" Files: "lib/windows/*.nim"
Files: "lib/posix/*.nim" Files: "lib/posix/*.nim"
Files: "lib/ecmas/*.nim" Files: "lib/js/*.nim"
[Other] [Other]

View file

@ -60,7 +60,7 @@ proc HandleCmdLine() =
if gCmd == cmdRun: if gCmd == cmdRun:
tccgen.run() tccgen.run()
if optRun in gGlobalOptions: if optRun in gGlobalOptions:
if gCmd == cmdCompileToEcmaScript: if gCmd == cmdCompileToJS:
var ex = quoteIfContainsWhite( var ex = quoteIfContainsWhite(
completeCFilePath(changeFileExt(gProjectFull, "js").prependCurDir)) completeCFilePath(changeFileExt(gProjectFull, "js").prependCurDir))
execExternalProgram("node " & ex & ' ' & service.arguments) execExternalProgram("node " & ex & ' ' & service.arguments)

View file

@ -68,7 +68,7 @@ type # please make sure we have under 32 options
TCommands* = enum # Nimrod's commands TCommands* = enum # Nimrod's commands
# **keep binary compatible** # **keep binary compatible**
cmdNone, cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdNone, cmdCompileToC, cmdCompileToCpp, cmdCompileToOC,
cmdCompileToEcmaScript, cmdCompileToLLVM, cmdInterpret, cmdPretty, cmdDoc, cmdCompileToJS, cmdCompileToLLVM, cmdInterpret, cmdPretty, cmdDoc,
cmdGenDepend, cmdDump, cmdGenDepend, cmdDump,
cmdCheck, # semantic checking for whole project cmdCheck, # semantic checking for whole project
cmdParse, # parse a single file (for debugging) cmdParse, # parse a single file (for debugging)

View file

@ -21,7 +21,7 @@ type
# conditionals to condsyms (end of module). # conditionals to condsyms (end of module).
osNone, osDos, osWindows, osOs2, osLinux, osMorphos, osSkyos, osSolaris, osNone, osDos, osWindows, osOs2, osLinux, osMorphos, osSkyos, osSolaris,
osIrix, osNetbsd, osFreebsd, osOpenbsd, osAix, osPalmos, osQnx, osAmiga, osIrix, osNetbsd, osFreebsd, osOpenbsd, osAix, osPalmos, osQnx, osAmiga,
osAtari, osNetware, osMacos, osMacosx, osHaiku, osEcmaScript, osNimrodVM, osAtari, osNetware, osMacos, osMacosx, osHaiku, osJS, osNimrodVM,
osStandalone osStandalone
type type
@ -136,7 +136,7 @@ const
objExt: ".o", newLine: "\x0A", pathSep: ":", dirSep: "/", objExt: ".o", newLine: "\x0A", pathSep: ":", dirSep: "/",
scriptExt: ".sh", curDir: ".", exeExt: "", extSep: ".", scriptExt: ".sh", curDir: ".", exeExt: "", extSep: ".",
props: {ospNeedsPIC, ospPosix, ospLacksThreadVars}), props: {ospNeedsPIC, ospPosix, ospLacksThreadVars}),
(name: "EcmaScript", parDir: "..", (name: "JS", parDir: "..",
dllFrmt: "lib$1.so", altDirSep: "/", dllFrmt: "lib$1.so", altDirSep: "/",
objExt: ".o", newLine: "\x0A", objExt: ".o", newLine: "\x0A",
pathSep: ":", dirSep: "/", pathSep: ":", dirSep: "/",
@ -155,7 +155,7 @@ type
# alias conditionals to condsyms (end of module). # alias conditionals to condsyms (end of module).
cpuNone, cpuI386, cpuM68k, cpuAlpha, cpuPowerpc, cpuPowerpc64, cpuNone, cpuI386, cpuM68k, cpuAlpha, cpuPowerpc, cpuPowerpc64,
cpuSparc, cpuVm, cpuIa64, cpuAmd64, cpuMips, cpuArm, cpuSparc, cpuVm, cpuIa64, cpuAmd64, cpuMips, cpuArm,
cpuEcmaScript, cpuNimrodVM, cpuAVR cpuJS, cpuNimrodVM, cpuAVR
type type
TEndian* = enum TEndian* = enum
@ -177,7 +177,7 @@ const
(name: "amd64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64), (name: "amd64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64),
(name: "mips", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32), (name: "mips", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32),
(name: "arm", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32), (name: "arm", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32),
(name: "ecmascript", intSize: 32, endian: bigEndian,floatSize: 64,bit: 32), (name: "js", intSize: 32, endian: bigEndian,floatSize: 64,bit: 32),
(name: "nimrodvm", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32), (name: "nimrodvm", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32),
(name: "avr", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16)] (name: "avr", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16)]

View file

@ -526,7 +526,7 @@ proc cmdChangeTriggersRecompilation(old, new: TCommands): bool =
# new command forces us to consider it here :-) # new command forces us to consider it here :-)
case old case old
of cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, of cmdCompileToC, cmdCompileToCpp, cmdCompileToOC,
cmdCompileToEcmaScript, cmdCompileToLLVM: cmdCompileToJS, cmdCompileToLLVM:
if new in {cmdDoc, cmdCheck, cmdIdeTools, cmdPretty, cmdDef, if new in {cmdDoc, cmdCheck, cmdIdeTools, cmdPretty, cmdDef,
cmdInteractive}: cmdInteractive}:
return false return false

View file

@ -29,7 +29,7 @@ path="$lib/wrappers/x11"
path="$lib/wrappers/zip" path="$lib/wrappers/zip"
path="$lib/windows" path="$lib/windows"
path="$lib/posix" path="$lib/posix"
path="$lib/ecmas" path="$lib/js"
path="$lib/pure/unidecode" path="$lib/pure/unidecode"
@if nimbabel: @if nimbabel:

View file

@ -328,7 +328,7 @@ Modules for JS backend
--------------------------- ---------------------------
* `dom <dom.html>`_ * `dom <dom.html>`_
Declaration of the Document Object Model for the ECMAScript backend. Declaration of the Document Object Model for the JS backend.
Impure libraries Impure libraries

View file

@ -4720,7 +4720,7 @@ Foreign function interface
========================== ==========================
Nimrod's `FFI`:idx: (foreign function interface) is extensive and only the Nimrod's `FFI`:idx: (foreign function interface) is extensive and only the
parts that scale to other future backends (like the LLVM/EcmaScript backends) parts that scale to other future backends (like the LLVM/JavaScript backends)
are documented here. are documented here.

View file

@ -190,7 +190,7 @@ Define Effect
``useRealtimeGC`` Enables support of Nimrod's GC for *soft* realtime ``useRealtimeGC`` Enables support of Nimrod's GC for *soft* realtime
systems. See the documentation of the `gc <gc.html>`_ systems. See the documentation of the `gc <gc.html>`_
for further information. for further information.
``nodejs`` The EcmaScript target is actually ``node.js``. ``nodejs`` The JS target is actually ``node.js``.
``ssl`` Enables OpenSSL support for the sockets module. ``ssl`` Enables OpenSSL support for the sockets module.
``memProfiler`` Enables memory profiling for the native GC. ``memProfiler`` Enables memory profiling for the native GC.
================== ========================================================= ================== =========================================================
@ -549,17 +549,17 @@ efficient:
else: quit(errorStr(p, "unknown variable: " & k.key)) else: quit(errorStr(p, "unknown variable: " & k.key))
The ECMAScript target The JavaScript target
===================== =====================
Nimrod can also generate `ECMAScript`:idx: (also known as `JavaScript`:idx:) Nimrod can also generate `JavaScript`:idx: code. However, the
code. However, the ECMAScript code generator is experimental! JavaScript code generator is experimental!
Nimrod targets ECMAScript 1.5 which is supported by any widely used browser. Nimrod targets JavaScript 1.5 which is supported by any widely used browser.
Since ECMAScript does not have a portable means to include another module, Since JavaScript does not have a portable means to include another module,
Nimrod just generates a long ``.js`` file. Nimrod just generates a long ``.js`` file.
Features or modules that the ECMAScript platform does not support are not Features or modules that the JavaScript platform does not support are not
available. This includes: available. This includes:
* manual memory management (``alloc``, etc.) * manual memory management (``alloc``, etc.)
@ -571,7 +571,7 @@ available. This includes:
However, the modules `strutils`:idx:, `math`:idx:, and `times`:idx: are However, the modules `strutils`:idx:, `math`:idx:, and `times`:idx: are
available! To access the DOM, use the `dom`:idx: module that is only available! To access the DOM, use the `dom`:idx: module that is only
available for the ECMAScript platform. available for the JavaScript platform.
To compile a Nimrod module into a ``.js`` file use the ``js`` command; the 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`` default is a ``.js`` file that is supposed to be referenced in an ``.html``

View file

@ -69,7 +69,7 @@ if [ $# -eq 1 ] ; then
mkdir -p $libdir/wrappers/zip mkdir -p $libdir/wrappers/zip
mkdir -p $libdir/windows mkdir -p $libdir/windows
mkdir -p $libdir/posix mkdir -p $libdir/posix
mkdir -p $libdir/ecmas mkdir -p $libdir/js
cp bin/nimrod $bindir/nimrod cp bin/nimrod $bindir/nimrod
chmod 755 $bindir/nimrod chmod 755 $bindir/nimrod
@ -711,8 +711,8 @@ if [ $# -eq 1 ] ; then
chmod 644 $libdir/system/debugger.nim chmod 644 $libdir/system/debugger.nim
cp lib/system/dyncalls.nim $libdir/system/dyncalls.nim cp lib/system/dyncalls.nim $libdir/system/dyncalls.nim
chmod 644 $libdir/system/dyncalls.nim chmod 644 $libdir/system/dyncalls.nim
cp lib/system/ecmasys.nim $libdir/system/ecmasys.nim cp lib/system/jssys.nim $libdir/system/jssys.nim
chmod 644 $libdir/system/ecmasys.nim chmod 644 $libdir/system/jssys.nim
cp lib/system/embedded.nim $libdir/system/embedded.nim cp lib/system/embedded.nim $libdir/system/embedded.nim
chmod 644 $libdir/system/embedded.nim chmod 644 $libdir/system/embedded.nim
cp lib/system/excpt.nim $libdir/system/excpt.nim cp lib/system/excpt.nim $libdir/system/excpt.nim
@ -1101,8 +1101,8 @@ if [ $# -eq 1 ] ; then
chmod 644 $libdir/posix/inotify.nim chmod 644 $libdir/posix/inotify.nim
cp lib/posix/posix.nim $libdir/posix/posix.nim cp lib/posix/posix.nim $libdir/posix/posix.nim
chmod 644 $libdir/posix/posix.nim chmod 644 $libdir/posix/posix.nim
cp lib/ecmas/dom.nim $libdir/ecmas/dom.nim cp lib/js/dom.nim $libdir/js/dom.nim
chmod 644 $libdir/ecmas/dom.nim chmod 644 $libdir/js/dom.nim
echo "installation successful" echo "installation successful"
else else

View file

@ -7,10 +7,10 @@
# distribution, for details about the copyright. # distribution, for details about the copyright.
# #
## Declaration of the Document Object Model for the ECMAScript backend. ## Declaration of the Document Object Model for the JavaScript backend.
when not defined(ecmascript) and not defined(Nimdoc): when not defined(js) and not defined(Nimdoc):
{.error: "This module only works on the ECMAScript platform".} {.error: "This module only works on the JavaScript platform".}
type type
TEventHandlers* {.importc.} = object of TObject TEventHandlers* {.importc.} = object of TObject

View file

@ -35,7 +35,7 @@ proc `!$`*(h: THash): THash {.inline.} =
proc hashData*(Data: Pointer, Size: int): THash = proc hashData*(Data: Pointer, Size: int): THash =
## hashes an array of bytes of size `size` ## hashes an array of bytes of size `size`
var h: THash = 0 var h: THash = 0
when defined(ecmascript): when defined(js):
var p: cstring var p: cstring
asm """`p` = `Data`;""" asm """`p` = `Data`;"""
else: else:
@ -48,12 +48,12 @@ proc hashData*(Data: Pointer, Size: int): THash =
Dec(s) Dec(s)
result = !$h result = !$h
when defined(ecmascript): when defined(js):
var objectID = 0 var objectID = 0
proc hash*(x: Pointer): THash {.inline.} = proc hash*(x: Pointer): THash {.inline.} =
## efficient hashing of pointers ## efficient hashing of pointers
when defined(ecmascript): when defined(js):
asm """ asm """
if (typeof `x` == "object") { if (typeof `x` == "object") {
if ("_NimID" in `x`) if ("_NimID" in `x`)

View file

@ -10,7 +10,7 @@
## Constructive mathematics is naturally typed. -- Simon Thompson ## Constructive mathematics is naturally typed. -- Simon Thompson
## ##
## Basic math routines for Nimrod. ## Basic math routines for Nimrod.
## This module is available for the ECMAScript target. ## This module is available for the JavaScript target.
{.push debugger:off .} # the user does not want to trace a part {.push debugger:off .} # the user does not want to trace a part
# of the standard library! # of the standard library!
@ -50,7 +50,7 @@ proc classify*(x: float): TFloatClass =
## classifies a floating point value. Returns `x`'s class as specified by ## classifies a floating point value. Returns `x`'s class as specified by
## `TFloatClass`. ## `TFloatClass`.
# ECMAScript and most C compilers have no classify: # JavaScript and most C compilers have no classify:
if x == 0.0: if x == 0.0:
if 1.0/x == Inf: if 1.0/x == Inf:
return fcZero return fcZero
@ -138,15 +138,15 @@ when not defined(windows):
proc randomize*() proc randomize*()
## initializes the random number generator with a "random" ## initializes the random number generator with a "random"
## number, i.e. a tickcount. Note: Does nothing for the ECMAScript target, ## number, i.e. a tickcount. Note: Does nothing for the JavaScript target,
## as ECMAScript does not support this. ## as JavaScript does not support this.
proc randomize*(seed: int) proc randomize*(seed: int)
## initializes the random number generator with a specific seed. ## initializes the random number generator with a specific seed.
## Note: Does nothing for the ECMAScript target, ## Note: Does nothing for the JavaScript target,
## as ECMAScript does not support this. ## as JavaScript does not support this.
when not defined(ECMAScript): when not defined(JS):
proc sqrt*(x: float): float {.importc: "sqrt", header: "<math.h>".} proc sqrt*(x: float): float {.importc: "sqrt", header: "<math.h>".}
## computes the square root of `x`. ## computes the square root of `x`.
@ -310,7 +310,7 @@ proc standardDeviation*(s: TRunningStat): float =
{.pop.} {.pop.}
{.pop.} {.pop.}
when isMainModule and not defined(ECMAScript): when isMainModule and not defined(JS):
# Verifies random seed initialization. # Verifies random seed initialization.
let seed = gettime(nil) let seed = gettime(nil)
randomize(seed) randomize(seed)

View file

@ -9,7 +9,7 @@
## This module contains routines and types for dealing with time. ## This module contains routines and types for dealing with time.
## This module is available for the ECMAScript target. ## This module is available for the JavaScript target.
{.push debugger:off.} # the user does not want to trace a part {.push debugger:off.} # the user does not want to trace a part
# of the standard library! # of the standard library!
@ -58,7 +58,7 @@ elif defined(windows):
type type
TTime* = distinct TTimeImpl TTime* = distinct TTimeImpl
elif defined(ECMAScript): elif defined(JS):
type type
TTime* {.final, importc.} = object TTime* {.final, importc.} = object
getDay: proc (): int getDay: proc (): int
@ -115,7 +115,7 @@ type
weekday*: TWeekDay ## The current day of the week. weekday*: TWeekDay ## The current day of the week.
yearday*: range[0..365] ## The number of days since January 1, yearday*: range[0..365] ## The number of days since January 1,
## in the range 0 to 365. ## in the range 0 to 365.
## Always 0 if the target is ECMAScript. ## Always 0 if the target is JS.
isDST*: bool ## Determines whether DST is in effect. Always isDST*: bool ## Determines whether DST is in effect. Always
## ``False`` if time is UTC. ## ``False`` if time is UTC.
tzname*: string ## The timezone this time is in. E.g. GMT tzname*: string ## The timezone this time is in. E.g. GMT
@ -246,7 +246,7 @@ proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
else: else:
result = getLocalTime(TTime(float(t) - secs)) result = getLocalTime(TTime(float(t) - secs))
when not defined(ECMAScript): when not defined(JS):
proc epochTime*(): float {.rtl, extern: "nt$1", tags: [FTime].} proc epochTime*(): float {.rtl, extern: "nt$1", tags: [FTime].}
## gets time after the UNIX epoch (1970) in seconds. It is a float ## gets time after the UNIX epoch (1970) in seconds. It is a float
## because sub-second resolution is likely to be supported (depending ## because sub-second resolution is likely to be supported (depending
@ -265,7 +265,7 @@ when not defined(ECMAScript):
## doWork() ## doWork()
## echo "CPU time [s] ", cpuTime() - t0 ## echo "CPU time [s] ", cpuTime() - t0
when not defined(ECMAScript): when not defined(JS):
# C wrapper: # C wrapper:
type type

View file

@ -184,7 +184,7 @@ proc `..`*[T](b: T): TSlice[T] {.noSideEffect, inline.} =
when not defined(niminheritable): when not defined(niminheritable):
{.pragma: inheritable.} {.pragma: inheritable.}
when not defined(EcmaScript) and not defined(NimrodVM): when not defined(JS) and not defined(NimrodVM):
type type
TGenericSeq* {.compilerproc, pure, inheritable.} = object TGenericSeq* {.compilerproc, pure, inheritable.} = object
len, reserved: int len, reserved: int
@ -900,7 +900,7 @@ template sysAssert(cond: bool, msg: string) =
include "system/inclrtl" include "system/inclrtl"
when not defined(ecmascript) and not defined(nimrodVm) and hostOS != "standalone": when not defined(JS) and not defined(nimrodVm) and hostOS != "standalone":
include "system/cgprocs" include "system/cgprocs"
proc add *[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.} proc add *[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.}
@ -1170,7 +1170,7 @@ proc `$` *(x: int64): string {.magic: "Int64ToStr", noSideEffect.}
## converted to a decimal string. ## converted to a decimal string.
when not defined(NimrodVM): when not defined(NimrodVM):
when not defined(ECMAScript): when not defined(JS):
proc `$` *(x: uint64): string {.noSideEffect.} proc `$` *(x: uint64): string {.noSideEffect.}
## The stingify operator for an unsigned integer argument. Returns `x` ## The stingify operator for an unsigned integer argument. Returns `x`
## converted to a decimal string. ## converted to a decimal string.
@ -1422,7 +1422,7 @@ proc `&` *[T](x: T, y: seq[T]): seq[T] {.noSideEffect.} =
result[y.len] = x result[y.len] = x
when not defined(NimrodVM): when not defined(NimrodVM):
when not defined(ECMAScript): when not defined(JS):
proc seqToPtr[T](x: seq[T]): pointer {.inline, nosideeffect.} = proc seqToPtr[T](x: seq[T]): pointer {.inline, nosideeffect.} =
result = cast[pointer](x) result = cast[pointer](x)
else: else:
@ -1698,7 +1698,7 @@ type
filename: CString filename: CString
len: int # length of slots (when not debugging always zero) len: int # length of slots (when not debugging always zero)
when not defined(ECMAScript): when not defined(JS):
{.push stack_trace:off, profiler:off.} {.push stack_trace:off, profiler:off.}
proc add*(x: var string, y: cstring) {.noStackFrame.} = proc add*(x: var string, y: cstring) {.noStackFrame.} =
var i = 0 var i = 0
@ -1724,7 +1724,7 @@ proc echo*[T](x: varargs[T, `$`]) {.magic: "Echo", tags: [FWriteIO].}
## is converted to a string via ``$``, so it works for user-defined ## is converted to a string via ``$``, so it works for user-defined
## types that have an overloaded ``$`` operator. ## types that have an overloaded ``$`` operator.
## It is roughly equivalent to ``writeln(stdout, x); flush(stdout)``, but ## It is roughly equivalent to ``writeln(stdout, x); flush(stdout)``, but
## available for the ECMAScript target too. ## available for the JavaScript target too.
## Unlike other IO operations this is guaranteed to be thread-safe as ## Unlike other IO operations this is guaranteed to be thread-safe as
## ``echo`` is very often used for debugging convenience. ## ``echo`` is very often used for debugging convenience.
@ -1747,7 +1747,7 @@ proc getTypeInfo*[T](x: T): pointer {.magic: "GetTypeInfo".}
## get type information for `x`. Ordinary code should not use this, but ## get type information for `x`. Ordinary code should not use this, but
## the `typeinfo` module instead. ## the `typeinfo` module instead.
when not defined(EcmaScript): #and not defined(NimrodVM): when not defined(JS): #and not defined(NimrodVM):
{.push stack_trace: off, profiler:off.} {.push stack_trace: off, profiler:off.}
when not defined(NimrodVM): when not defined(NimrodVM):
@ -2166,7 +2166,7 @@ when not defined(EcmaScript): #and not defined(NimrodVM):
`result` = *((NI*) `x`.ClEnv) < 0; `result` = *((NI*) `x`.ClEnv) < 0;
""".} """.}
elif defined(ecmaScript): elif defined(JS):
# Stubs: # Stubs:
proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} = nil proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} = nil
@ -2192,8 +2192,8 @@ elif defined(ecmaScript):
proc deallocShared(p: pointer) = nil proc deallocShared(p: pointer) = nil
proc reallocShared(p: pointer, newsize: int): pointer = nil proc reallocShared(p: pointer, newsize: int): pointer = nil
when defined(ecmaScript): when defined(JS):
include "system/ecmasys" include "system/jssys"
include "system/reprjs" include "system/reprjs"
elif defined(NimrodVM): elif defined(NimrodVM):
proc cmp(x, y: string): int = proc cmp(x, y: string): int =
@ -2437,7 +2437,7 @@ proc shallow*[T](s: var seq[T]) {.noSideEffect, inline.} =
## marks a sequence `s` as `shallow`:idx:. Subsequent assignments will not ## marks a sequence `s` as `shallow`:idx:. Subsequent assignments will not
## perform deep copies of `s`. This is only useful for optimization ## perform deep copies of `s`. This is only useful for optimization
## purposes. ## purposes.
when not defined(EcmaScript) and not defined(NimrodVM): when not defined(JS) and not defined(NimrodVM):
var s = cast[PGenericSeq](s) var s = cast[PGenericSeq](s)
s.reserved = s.reserved or seqShallowFlag s.reserved = s.reserved or seqShallowFlag
@ -2445,7 +2445,7 @@ proc shallow*(s: var string) {.noSideEffect, inline.} =
## marks a string `s` as `shallow`:idx:. Subsequent assignments will not ## marks a string `s` as `shallow`:idx:. Subsequent assignments will not
## perform deep copies of `s`. This is only useful for optimization ## perform deep copies of `s`. This is only useful for optimization
## purposes. ## purposes.
when not defined(EcmaScript) and not defined(NimrodVM): when not defined(JS) and not defined(NimrodVM):
var s = cast[PGenericSeq](s) var s = cast[PGenericSeq](s)
s.reserved = s.reserved or seqShallowFlag s.reserved = s.reserved or seqShallowFlag

View file

@ -151,7 +151,7 @@ proc cstrToNimstr(c: cstring): string {.noStackFrame, compilerproc.} =
return result; return result;
""" """
proc toEcmaStr(s: string): cstring {.noStackFrame, compilerproc.} = proc toJSStr(s: string): cstring {.noStackFrame, compilerproc.} =
asm """ asm """
var len = `s`.length-1; var len = `s`.length-1;
var result = new Array(len); var result = new Array(len);
@ -304,7 +304,7 @@ when defined(kwin):
asm """ asm """
var buf = ""; var buf = "";
for (var i = 0; i < arguments.length; ++i) { for (var i = 0; i < arguments.length; ++i) {
buf += `toEcmaStr`(arguments[i]); buf += `toJSStr`(arguments[i]);
} }
print(buf); print(buf);
""" """
@ -316,7 +316,7 @@ elif defined(nodejs):
asm """ asm """
var buf = ""; var buf = "";
for (var i = 0; i < arguments.length; ++i) { for (var i = 0; i < arguments.length; ++i) {
buf += `toEcmaStr`(arguments[i]); buf += `toJSStr`(arguments[i]);
} }
console.log(buf); console.log(buf);
""" """
@ -338,7 +338,7 @@ else:
if node == nil: raise newException(EIO, "<body> element does not exist yet!") if node == nil: raise newException(EIO, "<body> element does not exist yet!")
asm """ asm """
for (var i = 0; i < arguments.length; ++i) { for (var i = 0; i < arguments.length; ++i) {
var x = `toEcmaStr`(arguments[i]); var x = `toJSStr`(arguments[i]);
`node`.appendChild(document.createTextNode(x)) `node`.appendChild(document.createTextNode(x))
} }
""" """

View file

@ -5,14 +5,14 @@
<!-- This has been written by hand. (c) 2010 Andreas Rumpf --> <!-- This has been written by hand. (c) 2010 Andreas Rumpf -->
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Nimrod ECMAScript Generator Test</title> <title>Nimrod JavaScript Generator Test</title>
<style type="text/css"> <style type="text/css">
span.DecNumber {color: blue} span.DecNumber {color: blue}
</style> </style>
<script src="nimcache/ecmas.js" type="text/javascript"></script> <script src="nimcache/js.js" type="text/javascript"></script>
</head> </head>
<body onload="OnLoad()"> <body onload="OnLoad()">
<form name="form1" action="ecmas.html"> <form name="form1" action="js.html">
<input type="text" name="input1" size="10" /> <input type="text" name="input1" size="10" />
<input type="button" value="Calculate square" onclick="OnButtonClick()" /> <input type="button" value="Calculate square" onclick="OnButtonClick()" />
</form> </form>

View file

@ -2,7 +2,7 @@ discard """
cmd: "nimrod js --hints:on $# $#" cmd: "nimrod js --hints:on $# $#"
""" """
# This file tests the ECMAScript generator # This file tests the JavaScript generator
import import
dom, strutils dom, strutils

View file

@ -3,7 +3,7 @@ discard """
output: "1261129" output: "1261129"
""" """
# This file tests the ECMAScript generator # This file tests the JavaScript generator
import import
dom, strutils dom, strutils

View file

@ -392,7 +392,7 @@ proc main() =
of "compile": of "compile":
compile(r, "tests/compile/t*.nim", p.cmdLineRest.string) compile(r, "tests/compile/t*.nim", p.cmdLineRest.string)
compile(r, "tests/ccg/t*.nim", p.cmdLineRest.string) compile(r, "tests/ccg/t*.nim", p.cmdLineRest.string)
compile(r, "tests/ecmas.nim", p.cmdLineRest.string) compile(r, "tests/js.nim", p.cmdLineRest.string)
compileExample(r, "lib/pure/*.nim", p.cmdLineRest.string) compileExample(r, "lib/pure/*.nim", p.cmdLineRest.string)
compileExample(r, "examples/*.nim", p.cmdLineRest.string) compileExample(r, "examples/*.nim", p.cmdLineRest.string)
compileExample(r, "examples/gtk/*.nim", p.cmdLineRest.string) compileExample(r, "examples/gtk/*.nim", p.cmdLineRest.string)

View file

@ -28,7 +28,7 @@ pdf: "manual;lib;tut1;tut2;nimrodc;c2nim;niminst;gc"
srcdoc2: "system.nim;impure/graphics;wrappers/sdl" srcdoc2: "system.nim;impure/graphics;wrappers/sdl"
srcdoc2: "core/macros;pure/marshal;core/typeinfo;core/unsigned" srcdoc2: "core/macros;pure/marshal;core/typeinfo;core/unsigned"
srcdoc2: "impure/re;pure/sockets" srcdoc2: "impure/re;pure/sockets"
srcdoc: "system/threads.nim;system/channels.nim;ecmas/dom" srcdoc: "system/threads.nim;system/channels.nim;js/dom"
srcdoc2: "pure/os;pure/strutils;pure/math;pure/matchers;pure/algorithm" srcdoc2: "pure/os;pure/strutils;pure/math;pure/matchers;pure/algorithm"
srcdoc2: "pure/complex;pure/times;pure/osproc;pure/pegs;pure/dynlib" srcdoc2: "pure/complex;pure/times;pure/osproc;pure/pegs;pure/dynlib"
srcdoc2: "pure/parseopt;pure/hashes;pure/strtabs;pure/lexbase" srcdoc2: "pure/parseopt;pure/hashes;pure/strtabs;pure/lexbase"