Giter VIP home page Giter VIP logo

fubark / cyber Goto Github PK

View Code? Open in Web Editor NEW
1.1K 19.0 34.0 7.82 MB

Fast and concurrent scripting.

Home Page: https://cyberscript.dev

License: MIT License

Zig 90.01% JavaScript 0.34% Lua 0.60% PHP 0.05% Python 0.31% Ruby 0.03% Wren 0.34% Java 0.38% Raku 0.01% WebAssembly 0.02% C 7.78% Shell 0.05% Vim Script 0.03% C++ 0.03% Rust 0.01% Go 0.01%
apps scripting web wasm embedded gamedev virtual-machine

cyber's People

Contributors

capital-ex avatar ccleavinger avatar dhensen avatar ers35 avatar fubark avatar iacore avatar soomtong avatar sts10 avatar ziord avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cyber's Issues

Error while checking list element in an `if`

In the playground, extending the list example:

-- Construct a new list.
list = [1, 2, 3]

-- The first element of the list starts at index 0.
print list[0]    -- Prints '1'

-- check first element of list
if list[0] == 1:
	print 'Success!'

I'd expect "Success!" to be printed, but the above throws the error:

ParseError: Block requires at least one statement. Use the `pass` statement as a placeholder.
main:8:2:
print 'Success!'
^

Don't think my if statement is wrong, but it could be!

Implement map block syntax.

Running the example from the docs in the playground:

colors = {}:
    red: 0xFF0000
    green: 0x00FF00
    blue: 0x0000FF
    dump func (c):
        print c.red
        print c.green
        print c.blue

    -- Nested map.
    darker {}: 
        red: 0xAA0000
        green: 0x00AA00
        blue: 0x0000AA

gives the following error:

ParseError: Expected end of line or file, got colon
main:1:12:
colors = {}:
^

CStruct with bitfields

Hi, I know it's early days, but I wanted to report this in case there's already a solution. Below is a diff to your examples/{foo.c,ffi.cy} that shows the issue. In short, how to handle C structs that use bit fields?

diff --git a/examples/ffi.cy b/examples/ffi.cy
index 0d8aedf..4f03827 100644
--- a/examples/ffi.cy
+++ b/examples/ffi.cy
@@ -7,7 +7,18 @@
 
 import os 'os'
 
+object bitStruct:
+  flag uint32
+  other uint32
+
+
 lib = os.bindLib('./libfoo.so', [
     os.CFunc{ sym: 'add', args: [#int, #int], ret: #int }
+    os.CFunc{ sym: 'getBitStruct', args: [#uint], ret: bitStruct }
+    os.CStruct{ fields: [#uint, #uint], type: bitStruct}
 ])
-lib.add(123, 321)
+print lib.add(123, 321)
+
+
+print lib.getBitStruct(22).flag
+
diff --git a/examples/foo.c b/examples/foo.c
index 082fc1e..22909ff 100644
--- a/examples/foo.c
+++ b/examples/foo.c
@@ -1,3 +1,16 @@
+#include <stdint.h>
+
+typedef struct bitStruct {
+    uint32_t flag: 1, other: 31;
+} bitStruct;
+
+bitStruct getBitStruct(uint32_t a) {
+   bitStruct b;
+   b.flag = 1;
+   b.other = a;
+   return b;
+}
+
 int add(int a, int b) {
     return a + b;
-}
\ No newline at end of file
+}

Async is not the holy grail

Saw some preliminary mentions of async support in the future Cyber. I just wanted to point out that async is by far not a solution:

What color is your function?
Asynchronous Everything
Why is async "slow" and can not be made fast without making it sync 1
Why is async "slow" and can not be made fast without making it sync 2

Instead I would prefer Cyber exploring the space outlined in Proper support for distributed computing, parallelism and concurrency (yeah, I am obviously biased πŸ˜‰).

Print without inserting a newline at the end?

It might be nice to have the option for print not to insert a newline at the end.

For example, in Python, print takes an optional end-character, allowing user to overwrite the default newline:

print("hello, ", end='')
print("world")

In Go, we get a slightly different method:

fmt.Printf("hello, ")
fmt.Printf("world")

And similarly in Rust, a slightly different macro: print!("hello, ")

Maybe a bit niche for so young a language, but it can be handy when using loops.

OR operator not implemented?

Is an "OR" operator ready to use? I tried | and it seems to work some of the time, but not always:

a = 22
if a < 10 | a > 20:
    print "a is NOT between 10 and 20"
else: 
    print "I don't know what a is"

I'd expect the above code to print "a is NOT between 10 and 20", but playground prints "I don't know what a is".

I'll note that the following works as expected:

a = 22
if a < 10:
    print "a is less than 10"
if a > 20:
    print "a is greater than 20"
else: 
    print "I don't know what a is"

And thus I suspect this is an issue with the OR logic. Apologies if it's just not implemented yet -- it's not mentioned in the Docs at the moment.

Recover

Hi @fubark,

This looks like a really promising scripting language. I was looking to kick the tires and I ran into an issue using recover where the doc example trips an error. In my particular case, I was trying to write a little function that will allow me to step through stdin line by line without triggering a panic and recover seemed designed for this purpose - although if theres an alternative, I would love to know.

--- this recover example which is verbatim form the docs trips  parse error
func kaboom():
    recover err:
        if err == #danger:
            print 'recovered from #danger'
    panic(#danger)

kaboom()  

---
--- results in the following
ParseError: Expected term expr. Parsed recover_k.
recover.cy:2:5:
    recover err:

My example:

-- I would like to wrap readLine so I don't encounter a panic when the stream runs out
hasline = true
for hasline:
    a = readLine()
    print a

-- ./cyber testparse.cy < filetoparse.txt

Windows x64 Build

This shouldn't be too hard to set up since the dependencies are minimal. Just need to run build and see what is needed.

Implement Match block range case.

The matching example from Docs throws an error in the online playground.

val = 1000
match val:
    0..100: print 'at or between 0 and 99'
    100: print 'val is 100'
    200:
        print 'val is 200'
    300, 400:
        print 'combined case'
    else:
        print 'val is {val}'

The error I get is:

ParseError: Expected comma or colon.
main:3:6:
0..100: print 'at or between 0 and 99'
^

date functions

Hi ! for working on some testings I have choose a project that need date functions

and then get values for hours , minutes and seconds
May be, it is not implemented yet ?
regards

Indexing strings uses code points rather than grapheme clusters

Example code:

i = 'πŸ‘¨β€πŸ‘¨β€πŸ‘¦β€πŸ‘¦c'.indexChar('c')
print 'Found char at {i}.' -- Found char at 7.

Indexing strings based on codepoint doesn't really make sense with regards to how unicode is actually rendered and I think it would be a shame to bake these semantics into the language. Yes this is how Python and many other languages have built their string APIs, however some languages such as Swift seem to have taken a somewhat different approach that makes doing the wrong thing in the presence of unicode a lot harder. See this blog post for an overview: https://www.mikeash.com/pyblog/friday-qa-2015-11-06-why-is-swifts-string-api-so-hard.html

I'm not trying to tell you how best to design your language or anything like that, I just want ensure you are aware of the tradeoff here.

Unexpected List Behavior

Seems like the remove operator has an issue....

all_data = [1,2,3,4]

print all_data

for all_data as d:
    print d

print("Remove an item ... ")

all_data.remove(1)

for all_data as d:
    print d


List (4)
1
2
3
4
Remove an item ... 
1
2
2

Logo Proposal

Hi!

I was playing around with a logo design a while back, just for fun, and I thought I'd share it here.
It's basically inspired by angle brackets, and the sharp lines of circuits.

three variations of text logo with cyber written in angular font. variants include version number in different locations.

I'm not proposing this as a final logo, and I know this logo could use some work, plus the project probably doesn't need it at the moment anyway, but if the logo doesn't matter much, I think this would serve much better:
the current one seems incredibly whimsical, from the rotated C to the extended Y and R, and the incredibly high middle dividers on the B and E are also very extreme.

current logo, as described above

I drew the main logo from scratch in Inkscape, and I can share the SVG however you like.
The font used for the version number is Work Sans, though Inter is just as good.

Let me know what you think :)

Implement `catch`.

on macos 12.5 with zig 0.11.0-dev.1899+8da6b393f

func foo():
    return error(#boom)

res = catch foo()
res = catch foo() then 123
res = catch foo() as err then 123

-- A catch block.
res = catch foo() then:
    break 123

with debug build returns a parse error

debug(parser): 0.0: parse error: error.ParseError Expected term expr. Parsed catch_k.
debug(parser): 0.0: catch foo()
res = ca
/Users/broaddus/py-shell/cyber/src/parser.zig:1765:9: 0x104b29677 in reportParseErrorAt (cyber)
        return error.ParseError;
        ^
/Users/broaddus/py-shell/cyber/src/parser.zig:1754:9: 0x104a7690f in reportParseError (cyber)
        return self.reportParseErrorAt(format, args, self.next_pos);
        ^
/Users/broaddus/py-shell/cyber/src/parser.zig:2487:21: 0x104c53f23 in parseTightTermExpr (cyber)
            else => return self.reportParseError("Expected term expr. Parsed {}.", &.{fmt.v(token.tag())}),
                    ^
/Users/broaddus/py-shell/cyber/src/parser.zig:2311:17: 0x104c57867 in parseTermExpr (cyber)
                return self.parseTightTermExpr();
                ^
/Users/broaddus/py-shell/cyber/src/parser.zig:2706:27: 0x104b27c5f in parseExpr (cyber)
                left_id = try self.parseTermExpr();
                          ^
/Users/broaddus/py-shell/cyber/src/parser.zig:2896:38: 0x104b2675f in parseExprOrAssignStatement (cyber)
                            right = (try self.parseExpr(.{})) orelse {
                                     ^
/Users/broaddus/py-shell/cyber/src/parser.zig:1489:25: 0x104a77777 in parseStatement (cyber)
                    if (try self.parseExprOrAssignStatement()) |id| {
                        ^
/Users/broaddus/py-shell/cyber/src/parser.zig:307:29: 0x104a76bc3 in parseBodyStatements (cyber)
                const id = (try self.parseStatement()) orelse break;
                            ^
/Users/broaddus/py-shell/cyber/src/parser.zig:229:28: 0x104a7c823 in parseRoot (cyber)
        const first_stmt = try self.parseBodyStatements(0);
                           ^
info(debug): parse: 256.125ms
ParseError: Expected term expr. Parsed catch_k.

/Users/broaddus/py-shell/cy/test1.cy:4:7:
res = catch foo()

Disallow variable shadowing and remove "let"?

I wonder whether you would consider disallowing variable shadowing altogether (as e.g. V proves to be really valuable and actually not annoying in practice) and thus also remove the need for the let keyword?

Error handling, its (in)visibility and the curse of 3-state logic

Could error handling be made more visible?

Currently try and catch are not required each time a call is being done to a function potentially returning error (actually none - but read below). That leads to poor visibility - when reading the code - into whether errors can be produced by the call or not.

Also, supporting none as non-unusal value is a book example of the billion dollar mistake. Three-state logic is notoriously difficult to handle and our brains are simply not made for that.

Thus none shall be fully checked in compile time by making it visible by requiring the programmer to explicitly handle it at the caller place of a function potentially returning none. This is what e.g. V does and it makes it a much more secure language.

Thoughts? Any changes planned in this regard?

any support for Emacs?

Is there any support for Emacs? (or (N)vim)?
Also, how to install it?
Any *.deb package on debian repos?
Thx a lot

contributing

It would be very nice if you had a contributing.md or something alike

tuples: yes/no? semantics?

con:

  • more stuff to keep track in meta-table
  • slowdown
  • untyped ones can be painful
  • more complex type system

pro

  • much nicer to use for grouping things
  • better than Python (tuples not allowed as function arguments)
  • once proper layouted, they allow function argument reordering for efficiency

C structs compat.

Please support shebang for scripting

cyber doesn't seem to support shebangs (#!):

I can run the fibonacci.cy script manually:

Β» cyber fibonacci.cy
832040

However, when I add #!/usr/bin/env cyber to the top of the script β€” in the hope that I can run it just like any other script β€” all I get is a segfault:

Β» ./fibonacci.cy
'./fibonacci.cy' terminated by signal SIGSEGV (Address boundary error)

And the same thing happens when I run the modified script manually:

Β» cyber fibonacci.cy
'cyber fibonacci.cy' terminated by signal SIGSEGV (Address boundary error)
Β» cyber version
Cyber 0.1 build-203-c483853

Edit: added cyber version

Indentation rules overlap with ":"

I'm very confused why we still need to use ":" to define new blocks of code even though we are using indentation rules. Isn't this already defined by indentation?

It's a waste if it's just to support one-line patterns as well.
if true: print 123

Another comment, can the "func" keyword be replaced with the more concise "fn"?
My preference would be: fn > fnunc > function

Sometimes, when someone is particularly fond of using concise variable names. e.g. st pt li, then when he uses a language with very long keywords, the code becomes particularly stupid.

list of related projects (feel free to edit)

Interpreters

Fast JIT compilers.

Notable mention (syntax etc)

Trouble converting string to int

Having some trouble converting strings that are numbers into integers or numbers.

In the playground:

a_number = int("110")
print 'a number is {a_number}' 

prints a number is 0

I also tried number():

a_number = number("110")
print 'a number is {a_number}'

prints a number is 1

Am I doing something wrong?

Rethink var declaration rules?

Stumbled across the language website from lobste.rs and thought the language was pretty cool! One comment though, considering the test program:

func foo():
    a = 234
    print a

foo()
print(a)

This prints "234" "none", so a is a local variable being declared.

If you change it to:

a = 1
func foo():
    a = 234
    print a

foo()
print(a)

It prints "234" "234", so a is a variable from the enclosing scope, being assigned. There's two very different operations here that look identical, and differ only in context that may be 1000 lines of code away from where it matters.

This seems like a pretty good footgun, since it breaks locality. There's no way to look at func foo() alone and tell whether or not it changes state outside of it. Lua's "every variable is a global unless declared otherwise" has similar effects and is IMO a pretty good example of how much of a PITA this can be, so I humbly beg you to consider whether this is really what you want.

Thanks!

issues with sleep function

hi , testing sleep function

import os 'os'
sleeptime = 4000
while true:
os.sleep(sleeptime)
resp = fetchUrl( url )
print resp

delay is not working , no matter of sleeptime value
May doing something wrong ?
thanks !

update to new for loop syntax (automatically)

~/dev/git/zi/cyber$ zig build cli -Doptimize=ReleaseFast
src/simd.zig:5:20: error: extra capture in for loop
    for (buf) |it, i| {
                   ^
src/simd.zig:5:20: note: run 'zig fmt' to upgrade your code automatically
src/simd.zig:13:24: error: extra capture in for loop
    for (out) |*element, i| {
                       ^
src/simd.zig:13:24: note: run 'zig fmt' to upgrade your code automatically
src/simd.zig:21:24: error: extra capture in for loop
    for (out) |*element, i| {
                       ^
src/simd.zig:21:24: note: run 'zig fmt' to upgrade your code automatically
src/bytecode.zig:123:26: error: extra capture in for loop
        for (args) |arg, i| {
                         ^
src/bytecode.zig:123:26: note: run 'zig fmt' to upgrade your code automatically
src/bytecode.zig:132:26: error: extra capture in for loop
        for (args) |arg, i| {
                         ^
src/bytecode.zig:132:26: note: run 'zig fmt' to upgrade your code automatically
src/builtins/core.zig:337:31: error: extra capture in for loop
            for (elems) |*elem, i| {
                              ^
src/builtins/core.zig:337:31: note: run 'zig fmt' to upgrade your code automatically
src/debug.zig:15:20: error: extra capture in for loop
    for (src) |ch, i| {
                   ^
src/debug.zig:15:20: note: run 'zig fmt' to upgrade your code automatically
src/debug.zig:125:31: error: extra capture in for loop
    for (vm.debugTable) |sym, i| {
                              ^
src/debug.zig:125:31: note: run 'zig fmt' to upgrade your code automatically
src/string.zig:327:20: error: extra capture in for loop
    for (buf) |ch, i| {
                   ^
src/string.zig:327:20: note: run 'zig fmt' to upgrade your code automatically
src/string.zig:528:22: error: extra capture in for loop
    for (str) |code, i| {
                     ^
src/string.zig:528:22: note: run 'zig fmt' to upgrade your code automatically
src/string.zig:757:20: error: extra capture in for loop
    for (buf) |ch, i| {
                   ^
src/string.zig:757:20: note: run 'zig fmt' to upgrade your code automatically
src/api.zig:317:26: error: extra capture in for loop
        for (args) |arg, i| {
                         ^
src/api.zig:317:26: note: run 'zig fmt' to upgrade your code automatically
src/heap.zig:657:25: error: extra capture in for loop
    for (keyIdxs) |idx, i| {
                        ^
src/heap.zig:657:25: note: run 'zig fmt' to upgrade your code automatically
src/heap.zig:741:32: error: extra capture in for loop
    for (capturedVals) |local, i| {
                               ^
src/heap.zig:741:32: note: run 'zig fmt' to upgrade your code automatically
src/heap.zig:765:22: error: extra capture in for loop
    for (vals) |val, i| {
                     ^
src/heap.zig:765:22: note: run 'zig fmt' to upgrade your code automatically
src/vm_compiler.zig:231:40: error: extra capture in for loop
        for (self.chunks.items) |*chunk, i| {
                                       ^
src/vm_compiler.zig:231:40: note: run 'zig fmt' to upgrade your code automatically
src/stdx/testing.zig:93:27: error: extra capture in for loop
    for (act_slice) |act, i| {
                          ^
src/stdx/testing.zig:93:27: note: run 'zig fmt' to upgrade your code automatically
src/stdx/testing.zig:147:32: error: extra capture in for loop
        for (mocks.items) |it, i| {
                               ^
src/stdx/testing.zig:147:32: note: run 'zig fmt' to upgrade your code automatically
src/sema.zig:2930:43: error: extra capture in for loop
        for (sblock.params.items) |varId, i| {
                                          ^
src/sema.zig:2930:43: note: run 'zig fmt' to upgrade your code automatically
error: cyber...
(manually stripped)

Question on libtcc

Hi
I'm interested in cyber, but there a few points in the documention that raises a fundamental question on the 'philosophy' behind the extensibility of cyber.

I had the expectation that with the help of the host beeing written in Zig, the simple extensibility of cyber would be an important feature. But instead there is this whole bit on C compatibility and the introduction of the libtcc dependency.

https://fubark.github.io/cyber/docs/toc/ffi/

Cyber supports binding to an existing C ABI compatible library at runtime.
and
Cyber uses libtcc to JIT compile the bindings so function calls are fast

Why? Sounds pretty complicated, I mean there is Zig ...

On the other hand there is no documentation on Embedding yet.

Could you help me to understand on how this is thought out? It's very good possible I get something wrong here, or at least I miss something here.

Thanks

Fasta parsing experiment

Hi @fubark ,

Thanks again for your awesome language. I played around with cyber a bit today for fasta parsing to see how it might fare against some other languages (inspiration here). My results are here if you are interested in taking a look. Right now python is ahead by ~ 2 orders of magnitude. I know cyber is designed for embedded systems but I thought i might get lucky with some fast I/O as well :).

This is a really promising language thats been fun to use; thank you.
zach cp

time python3 readfq.py < GCA_013297495.1_ASM1329749v1_genomic.fna
real    0m1.065s

time ./cyber readfq.cy <  GCA_013297495.1_ASM1329749v1_genomic.fna
real    2m24.335s

time ./cyber readfq2.cy <  GCA_013297495.1_ASM1329749v1_genomic.fna
real    2m30.641s

Attempting to print the output of return value from execCmd() (value.out) giving 'rawstring'

Hey there. I am attempting to print the output of return value from execCmd() (value.out), but it keeps giving 'rawstring(n)'.
I tried using value.out.utf8() and various other things, but none of them seem to give what I expected as the result. Is the 'out' parameter from the result object of the execCmd call not what I am thinking it should be?

I feel that I must be missing something, or not properly understanding something?

Thanks,
-MH


#!/usr/local/bin/cyber
-- test_script.cy hello

import os 'os'
args = os.args()

runArgs(args[2]) -- hello

func runArgs(arg):
    cmd = [ '/bin/bash', '-c', 'echo "{arg}"' ]
    res = execCmd(cmd)

    if res.exited != 0:
        print res.out
        print res.err
    else:
        print res.out    -- rawstring (5)
        print res.out[0] -- r

        t = res.out.utf8() -- This gives the below error 
        print t            -- Expecting 'hello' printed

        -- panic: `utf8` is either missing in `string` or the call signature: utf8(self, 0 args) is unsupported.
        -- /home/mosthated/_dev/languages/cyber/test_script.cy:17:20 runArgs:
        --         t = res.out.utf8()
        -- I also tried the following:

        print res.out
        print res.out.utf8()
        print string(res.out)
        print string(res.out.utf8())

Question about fetchUrl

hi there !, In Linux and Windows fetchUrl works as an asynchronous function
Is this the expected outcome?
if so , all cyberscript functions are asynchronous ?
I know you mention that asynchronous management is on the road , but what is the native nature of the language ?
thanks!

Some more if/else weirdness

I was refactoring a function and found some weirdness with if/elsebranches in afor` loop.

In the playground, this outputs nothing.

my_arr = [4,5,6,7,8]
what_i_found = find_6_or_7(my_arr)
print 'Found: {what_i_found}' 

func find_6_or_7(an_arr):
    for an_arr each item:
        if item == 6:
            return 6
        else item == 7:
            return 7

But if I change the else to a second if, it runs as expected:

my_arr = [4,5,6,7,8]
what_i_found = find_6_or_7(my_arr)
print 'Found: {what_i_found}' 

func find_6_or_7(an_arr):
    for an_arr each item:
        if item == 6:
            return 6
        if item == 7:
            return 7

Using 2 ifs in this particular example isn't any less efficient than a if and else, but I think there are cases where it would be.

This time, I checked: I use all spaces for indents here.

non-ascii characters not displayed correctly on Windows10

I've tested example/hello.cy in both powershell and cmd.exe, the characters 'δΈ–η•Œ' and other non-ascii characters could not be displayed correctly.

image

I've also tried both using the pre-built binary cyber.exe and the binary built by myself.

Distribution/Compilation Option

Will there be a first-party way or producing a single binary for distributing code? With the focus on embeddibility, I assume it should be easy enough to make a minimal wrapping application, but would love to see this available from the native tooling.

As a Python programmer, distributing code is still needlessly painful with a multitude of partially working options. Would love if Cyber had a solid story here, even if it only worked with pure Cyber code.

Should toString() be added to number?

Kind of the reverse of #31. I tried:

four = 4
four_as_string = four.toString()

in the playground and get following error:

panic: Missing method symbol `toString` from receiver of type `number`.
main:2:18 main:
four_as_string = four.toString()
^

I guess it's a rare case to want to convert a number to a string, but I think it should be possible.

Can't run on emscripten environment.

Hello, I'm trying to run Cyber on the web using emscripten (because of the SDL2 port), however, I getting an runtime error on the process.

Environment

Steps to reproduce

  • Download the zig 0.11-dev compiler and clone cyber repository as described on build documentation.
  • Build the wasm library as described on building documentation.
  • Download and setup emscripten as described on emscripten documentation.
  • Archive the cyber.wasm.o file using the command emar -rcs libcyber.a zig-out/lib/cyber.wasm.o.
  • Create the C file with the code below, it's adapted from examples/c-embedded/main.c.
  • Create the build directory, just for organization.
  • Compile main.c with emcc with the command emcc main.c ./libcyber.a -I./src/ -L. -o build/main.html
  • Run it with cd build/ && emrun main.html.

Expected behaviour

The expected behaviour would be seeing this message on the page's console:

creating Cyber VM
Cyber VM created
2
Success!

Observed behaviour

An exception it's thrown, with a stack trace available on the browser's console, on the page's console only creating Cyber VM it's shown, which means that the problem happens on cyVmCreate function call.

Testing code

main.c:

#include <stdio.h>
#include "cyber.h"

// host functions
void hostFetchUrl(const char *url, size_t urlLen) {}
void hostEvalJS(const char *ptr, size_t len) {}
void hostSleep(uint64_t secs, uint64_t nsecs) {}
void hostLogDebug(const char *ptr, size_t len) {}
void hostLogInfo(const char *ptr, size_t len) {}
void hostLogWarn(const char *ptr, size_t len) {}
void hostLogError(const char *ptr, size_t len) {}
double hostMilliTimestamp() {
    return 0.016;
}
void hostFileWrite(uint32_t fid, const char* str, size_t strLen) {
    printf("%s", str);
}

int main(void) {
    printf("creating Cyber VM\n");
    CyVM* vm = cyVmCreate();
    printf("Cyber VM created\n");
    CStr src = cstr(
        "a = 2\n"
        "print a"
    );
    CyValue val;
    int res = cyVmEval(vm, src, &val);
    if (res == CY_Success) {
        printf("Success!\n");
        cyVmRelease(vm, val);
    } else {
        CStr err = cyVmGetLastErrorReport(vm);
        printf("%s\n", err.charz);
    }
    cyVmDestroy(vm);
    return 0;
}

Extra note

The code above works with wasmtime, when using the wasi-sdk with the same cyber build, with (almost) same building steps.

`nan_f64` compilation errors with latest Zig

Trying to build from the latest I hit an error

Build Summary: 3/6 steps succeeded; 1 failed (disable with --summary none)
cli transitive failure
β”œβ”€ zig build-exe cyber ReleaseFast native 1 errors
└─ install cyber transitive failure
   └─ zig build-exe cyber ReleaseFast native (+3 more reused dependencies)
/home/<username>/Library/zig/ziglang/lib/std/math.zig:93:21: error: Deprecated: use `nan(f64)` instead
pub const nan_f64 = @compileError("Deprecated: use `nan(f64)` instead");
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This fixed it. Happy to create a PR if this is the right approach.

diff --git a/src/builtins/math.zig b/src/builtins/math.zig
index 7b232cc..ddd6c08 100644
--- a/src/builtins/math.zig
+++ b/src/builtins/math.zig
@@ -25,7 +25,7 @@ pub fn initModule(c: *cy.VMcompiler, modId: cy.ModuleId) anyerror!void {
     try b.setVar("ln2", bt.Number, Value.initF64(std.math.ln2));

     // Not a number.
-    try b.setVar("nan", bt.Number, Value.initF64(-std.math.nan_f64));
+    try b.setVar("nan", bt.Number, Value.initF64(-std.math.nan(f64)));

     // Neg infinity.
     try b.setVar("neginf", bt.Number, Value.initF64(-std.math.inf(f64)));
diff --git a/src/vm.zig b/src/vm.zig
index cdba9b7..cb945cb 100644
--- a/src/vm.zig
+++ b/src/vm.zig
@@ -3403,7 +3403,7 @@ fn evalLoop(vm: *VM) linksection(cy.HotSection) error{StackOverflow, OutOfMemory
                 const left = framePtr[pc[1].arg];
                 const right = framePtr[pc[2].arg];
                 if (Value.bothNumbers(left, right)) {
-                    framePtr[pc[3].arg] = Value.initF64(std.math.mod(f64, left.asF64(), right.asF64()) catch std.math.nan_f64);
+                    framePtr[pc[3].arg] = Value.initF64(std.math.mod(f64, left.asF64(), right.asF64()) catch std.math.nan(f64));
                 } else {
                     return @call(.never_inline, panicExpectedNumber, .{vm});
                 }

Performance comparison with daScript

Doing a research on new/modern scripting languages, both Cyber and daScript caught my attention, the later being based on C++.

Would be nice if the maintainers could add Cyber to the benchmarks!

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.