Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. https://vlang.io

Overview

The V Programming Language

vlang.io | Docs | Changelog | Speed | Contributing & compiler design

Sponsor Patreon Discord Twitter

Key Features of V

  • Simplicity: the language can be learned in less than an hour
  • Fast compilation: ≈80k loc/s with a Clang backend, ≈1 million loc/s with x64 and tcc backends (Intel i5-7500, SSD, no optimization)
  • Easy to develop: V compiles itself in less than a second
  • Performance: as fast as C (V's main backend compiles to human readable C)
  • Safety: no null, no globals, no undefined behavior, immutability by default
  • C to V translation
  • Hot code reloading
  • Innovative memory management
  • Cross-platform UI library
  • Built-in graphics library
  • Easy cross compilation
  • REPL
  • Built-in ORM
  • Built-in web framework
  • C and JavaScript backends

Stability guarantee and future changes

Despite being at an early development stage, the V language is relatively stable and has backwards compatibility guarantee, meaning that the code you write today is guaranteed to work a month, a year, or five years from now.

There still may be minor syntax changes before the 1.0 release, but they will be handled automatically via vfmt, as has been done in the past.

The V core APIs (primarily the os module) will still have minor changes until they are stabilized in 2020. Of course the APIs will grow after that, but without breaking existing code.

Unlike many other languages, V is not going to be always changing, with new features being introduced and old features modified. It is always going to be a small and simple language, very similar to the way it is right now.

Installing V from source

Linux, macOS, Windows, *BSD, Solaris, WSL, Android, Raspbian

git clone https://github.com/vlang/v
cd v
make

That's it! Now you have a V executable at [path to V repo]/v. [path to V repo] can be anywhere.

(On Windows make means running make.bat, so make sure you use cmd.exe)

Now you can try ./v run examples/hello_world.v (v.exe on Windows).

V is constantly being updated. To update V, simply run:

v up

C compiler

It's recommended to use Clang, GCC, or Visual Studio. If you are doing development, you most likely already have one of those installed.

Otherwise, follow these instructions:

However, if none is found when running make on Linux or Windows, TCC is downloaded as the default C backend. It's very lightweight (several MB) so this shouldn't take too long.

Symlinking

NB: it is highly recommended, that you put V on your PATH. That saves you the effort to type in the full path to your v executable every time. V provides a convenience v symlink command to do that more easily.

On Unix systems, it creates a /usr/local/bin/v symlink to your executable. To do that, run:

sudo ./v symlink

On Windows, start a new shell with administrative privileges, for example by Windows Key, then type cmd.exe, right click on its menu entry, and choose Run as administrator. In the new administrative shell, cd to the path, where you have compiled v.exe, then type:

.\v.exe symlink

That will make V available everywhere, by adding it to your PATH. Please restart your shell/editor after that, so that it can pick the new PATH variable.

NB: there is no need to run v symlink more than once - v will continue to be available, even after v up, restarts and so on. You only need to run it again, if you decide to move the V repo folder somewhere else.

Docker

Expand Docker instructions
git clone https://github.com/vlang/v
cd v
docker build -t vlang .
docker run --rm -it vlang:latest

Docker with Alpine/musl

git clone https://github.com/vlang/v
cd v
docker build -t vlang --file=Dockerfile.alpine .
docker run --rm -it vlang:latest

Testing and running the examples

Make sure V can compile itself:

v self
$ v
V 0.2.x
Use Ctrl-C or `exit` to exit

>>> println('hello world')
hello world
>>>
cd examples
v hello_world.v && ./hello_world    # or simply
v run hello_world.v                 # this builds the program and runs it right away

v word_counter.v && ./word_counter cinderella.txt
v run news_fetcher.v
v run tetris/tetris.v

NB: In order to build Tetris or 2048 (or anything else using sokol or gg graphics modules) on some Linux systems, you need to install libxi-dev and libxcursor-dev .

If you plan to use the http package, you also need to install OpenSSL on non-Windows systems.

macOS:
brew install openssl

Debian/Ubuntu:
sudo apt install libssl-dev

Arch/Manjaro:
openssl is installed by default

Fedora:
sudo dnf install openssl-devel

V sync

V's sync module and channel implementation uses libatomic. It is most likely already installed on your system, but if not, you can install it, by doing the following:

MacOS: already installed

Debian/Ubuntu:
sudo apt install libatomic1

Fedora/CentOS/RH:
sudo dnf install libatomic-static

V UI

https://github.com/vlang/ui

Android graphical apps

With V's vab tool, building V UI and graphical apps for Android can become as easy as:

./vab /path/to/v/examples/2048

https://github.com/vlang/vab.

Developing web applications

Check out the Building a simple web blog tutorial and Gitly, a light and fast alternative to GitHub/GitLab:

https://github.com/vlang/gitly

Troubleshooting

Please see the Troubleshooting section on our wiki page

Comments
  • Inaccuracies in the README

    Inaccuracies in the README

    The README states that V was to be released on 2019-06-22T18:00Z but it is 2019-06-22T18:06Z and no release exists


    edit: it's 18:24Z and a release exists, ty


    I downloaded the compiler source and IcarusVerilog couldn't process it but there are no other compilers available that can process .v files, please fix

    Type: Discussion 
    opened by myrrlyn 150
  • Just published the first V example to show you some features of the language. Very interested in your input.

    Just published the first V example to show you some features of the language. Very interested in your input.

    Very interested in your input.

    https://github.com/vlang-io/V/blob/master/examples/users.v https://github.com/vlang-io/V/blob/master/examples/hello_world_gui.v https://github.com/vlang-io/V/blob/master/examples/generic_repository.v

    Announcement 
    opened by medvednikov 122
  • V Concurrency Considerations

    V Concurrency Considerations

    Transferred from a document posted here in these documents by @cristian-ilies-vasile:

    V concurrency high level design

    After a carefully consideration of proposed concurrency models and suggestions expressed on discord v-chat channel the high level design is based on GO language model (message passing via channels) which in turn is a variation of communicating sequential processes.

    I did read papers on actor model but seems that coders do not use all the primitives provided by language and resort to threads and queues (see Why Do Scala Developers Mix the Actor Model paper).

    Almost all high level requirements are taken from Proper support for distributed computing, parallelism and concurrency published on github.

    Because there are many words used more or less interchangeably like coroutine, goroutine, fiber, green threads etc I will use the term green thread.

    Key points

    • the language will provide primitives able to deal with green threads – the green threads monitor/scheduler will be part of the language
    • there will be no yield() points in code; the scheduler can suspend / resume / block / cancel any green thread in a preemtive mode
    • based on memory model the green thread will be stackless or stackful
    • one green thread could spawn n others green threads
    • a green thread must be reentrant
    • the scheduler could start a new instance of a green thread in order to accommodate load bursts (elastic computing)
    • Green threads communicate using message passing (channels) instead of shared variables

    Open points

    • mux/demux green threads on real threads how to?
    • structured concurrency
      • Martin Sústrik - http://250bpm.com/blog:71
      • Roman Elizarov - https://medium.com/@elizarov/structured-concurrency-722d765aa952
      • Alan Bateman - https://wiki.openjdk.java.net/display/loom/Structured+Concurrency
    • depending on application scope could have cpu bound or io bound or both type of green threads; do we need 2 different approaches?
    • Debugging
    • how to catch programs bugs (Heisenbugs) before the code is shipped to prod systems?
    • Formal methods / TLA+
    Feature Request 
    opened by ylluminate 90
  • Proper support for distributed computing, parallelism and concurrency

    Proper support for distributed computing, parallelism and concurrency

    There is one thing in V I do care a lot about - parallelism & concurrency for seamless local and distributed programming.

    Note, I didn't want to write this to https://github.com/vlang/v/issues/561 as the scope I'm describing is broader.

    I'm confident every new language must provide first-class support for both parallelism and concurrency. Concurrency to allow one physical CPU thread do cooperative scheduling and parallelism to allow spawning the same go/v routine on several physical threads. This is actually what go lang does (when GOMAXPROCS is set to 2 or more and the underlying operating system supports threads) except for always spawning just one go routine disregarding the number of physical CPU cores (which is where V should improve on - see below).

    Why both concurrency and parallelism and not either of them?

    In the world of big.LITTLE, GPU/FPGA offloading, CPUs with tens/hundreds of physical cores (and hyperthreading on top), mobile devices trying to save as much energy as possible, NUMA supercomputers, mobile & close vicinity networks versus optical fiber networks etc. it's inevitable to dynamically schedule computation directly in runtime of each application (not just operating system wide which is too coarse and thus inefficient and not just cooperatively which would use just one physical CPU core per application which makes sense only for power saving scenarios, but nowhere else).

    We have instruction-level paralellism covered (it's not yet present in V - see e.g. my rant about restrict - but it's a "solved problem" in todays compilers). The rest of the parallelism is just about "how close can we get to pure dataflow programming". Which appears to be kind of difficult.

    Because instruction-level paralelism is solved, the best approach nowadays seems to be to:

    1. write as much serial code which allows being highly optimized by instruction-level parallelism at once in one go/v routine (typically a tight loop or one tree of nested tight loops or a slow I/O or offloading to GPU/FPGA or similar) - the outermost construct of this go routine will be always an endless loop yielding (calling the cooperative/parallel scheduler) every N iterations

    2. then schedule these go/v routines in cooperative manner on one physical CPU core with fixed-size queue (single-producer-single-consumer "SPSC" - for performant implementations see discussion below) in between these go/v routines (this queue is called a channel in go lang); the queue size might be between the size of L1 and 2*L2 cache as suggested in paragraph 3.3 in Analyzing Efficient Stream Processing on Modern Hardware.

    3. and if any go/v routine shall become a bottleneck during computation (i.e. consumer is slower than producer for some time - this can be easily monitored by the cooperative/parallel scheduler as metric "how full are the queues"), a new instance of the slow consumer go/v routine shall be spawned (with respect to reentrancy) in a different operating system thread (i.e. on a different physical CPU core) including all the plumbing work (e.g. spawning an additional go routine acting as multiplexer getting the producers outgoing data and multiplexing it to the original as well as the new instance of the consumer; and spawning a demultiplexer go routine to join the outgoing data from both consumers) - this everything would the cooperative/parallel scheduler do.

    4. and if the queues shall become almost empty for some time, remove the multiplexers and demultiplexers.

    The cooperative/parallel scheduler as referenced above shall be a user-definable routine (if not present, a default built-in scheduler working similarly like described above will be used). This scheduler shall run preemptively (in its own thread?) and get as input arguments at least the following: thread handles, pointers to all go/v routines and corresponding queues between them, pointer to the built-in scheduler (in case the user just wanted to wrap it), and pointer to user-defined metadata (e.g. statistics allowing better scheduling judgement). This would allow for really complex scheduling on embedded systems as well as NUMA systems or any other highly dynamic systems (e.g. a smartphone could leverage being shortly connected to a cluster of other computers or smartphones and offload some slow algorithm there etc.). See e.g. MultiQueues.

    This way one can write application once and deploy it to your grandmas wrist watches as well as to a supercomputer (assuming the user-level scheduler is a "bit more" clever than outlined above - imagine complexity similar to an SQL query optimizer for a distributed DB). It's also a highly failure-tolerant system (imagine Erlang which supports even an online update of the whole application in memory while serving all clients under full load without interruption!). Also as you may have noticed, go lang does not scale first because there is no spawning of redundant go routines (those which will be bottle necks) to other physical CPU cores and second because go doesn't have a dynamic user-influencable scheduler (taking into account advanced statistics, power consumption, etc.).

    There is one catch though. If implemented naively, then such elasticity doesn't guarantee global ordering among channels/queues (ordering works only inside of one channel) and real life scenarios in IT are unfortunately more often than not relying on ordering. This has to be accounted for and will require user intervention (i.e. be syntactically explicit). Either in the form of knowledge where to (a) insert "tagging" of items before they'll be spilled among different channels and (b) where the "tagging" will be removed and used to assemble the original ordering. Or in the form of assigning a strict priority to each channel. Or using other scheme.

    See also lock-free and wait-free datastructures (state of the art as of now) which might be handy for an efficient implementation of parallelism.

    IMHO we could actually postpone the implementation of concurrency and stick with just parallelism (as it's easier to implement than the interleaving between concurrency and parallelism as outlined above), implement the queue and a basic scheduler and first then (maybe even after V 1.0) get back to concurrency. As of now we have parallelism without queues and without the scheduler, so we actually already have a good starting point.

    Table of parallelism possibilities we have nowadays (just for reference):

    parallelism kind | suited for execution duration | latency overhead | suited for how frequent execution startup | internode bandwidth quality has influence | special parallel SW architecture required | requirements for execution & deployment ---| ---| ---| ---| ---| ---| --- CPU non-JIT vectorization on a CPU core | very short to long | ~none | frequent | none (it's just 1 node) | no | binary for the particular CPU CPU JIT vectorization on a CPU core | short to long | low | moderate to frequent | none (it's just 1 node) | no | app source code + VM binary for the particular CPU CPU cores utilization (thread, process, ...) | long | low to moderate | moderate | lower to none (it's just 1 node) | yes (except: pure objects as actors or alike) | binary for the particular CPU accelerators (GPU, FPGA, ...) | long | low to moderate | moderate | lower to none (it's just 1 node) | yes (except: array/matrix/tensor/...-based languages) | binary for the particular CPU and accelerator (GPU, FPGA, ...) supercomputer with NUMA topology | long | moderate | sporadic to moderate | moderate (hypercube/... is really fast) | yes (except: pure objects as actors, etc., array/matrix/tensor/...-based languages) | binary for the particular CPU and accelerator (GPU, FPGA, ...) LAN cluster | long | moderate to high | sporadic to moderate | moderate to high (can be fast, but not always) | yes | binary for at least 2 CPUs and/or at least 2 accelerators (GPU, FPGA, ...) WAN cluster | long | high | sporadic | high (basically can't be that fast) | yes | binary for at least 2 CPUs and/or at least 2 accelerators (GPU, FPGA, ...)

    (in practice these might overlap and/or be used simultaneously)

    P.S. The dynamic scaling over the different kinds of parallelism as outlined in the above table is called "fine grained distributed computing". And if anything from the above proposal sounds crazy to you, then I can assure you, that the world doesn't sleep and there is at least one seamless (fully dynamic) solution offering first class fine grained distributed computing - Unison.


    Other things to consider and/or track:

    1. As of March 2021 the fastest publicly known (and most comprehensive & general) parallelism & concurrency backend/library is Weave
    2. use PRNG (pseudo-random number generator) which copes well with dynamic threading (i.e. doesn't suffer from "same seed leads to same random numbers in all threads") - see e.g. splittable PRNGs such as JAX
    3. maybe infinite loop in rand https://github.com/vlang/v/commit/a7c84834f4ba4948b8102a05b603bf8d51484760#r39632493
    4. g_str_buf with parallel access:
      • https://github.com/vlang/v/commit/778a1cc34ae5674c345d73e2a507bce9f77dea1b#commitcomment-36848204
      • https://github.com/vlang/v/commit/0f92800921c706de0bd872f7eff30047a99c734d
    5. FPU stuff needs special attention from the threading (work stealing) scheduler - see https://github.com/mratsim/weave/issues/163
    6. under the hood, we might utilize some wait-free and lock-free algorithms (see e.g. https://github.com/pramalhe/ConcurrencyFreaks )
    7. reconsider deadlock/livelock/no_thread_running/... detection - see https://github.com/vlang/v/issues/10340
    8. incorporate a "sharded" RwMutex into the standard library and use it also for V's built-in "sharded" data structures (map etc.)
    9. memory models of multicore architectures (x86, ARM, POWER, ...) are still sometimes not fully formally defined but SW memory models are even worse at that :open_mouth: https://research.swtch.com/mm
    Feature Request 
    opened by dumblob 86
  • Eliminate Pointers => use mut instead for ALL cases

    Eliminate Pointers => use mut instead for ALL cases

    Current:

    mut m := sync.WaitGroup{}
    a := m // m is duplicated
    z := someStruct{wg: m} // m is duplicated and requires &, trap for new players
    someFunc(m) // &m is passed
    

    Suggested:

    mut m := sync.WaitGroup{} // m = &sync.WaitGroup
    a := m // a and m share same data
    z := someStruct{wg: m} // z.wg and m share same data
    someFunc(m) // &m is passed
    

    I would suggest that by making all muts act as if they were pointers and values otherwise. This would reduce cognitive load and code. The ptr "&" syntax could be eliminated (mostly). This might help towards #41.

    Thoughts?

    Feature Request Type: Discussion 
    opened by krolaw 86
  • checker: require `params` attribute to use struct as keyword arguments in function

    checker: require `params` attribute to use struct as keyword arguments in function

    Before we had a problem that calling foo() works even it's not wanted.

    fn foo(table &ast.Table) {...}
    

    I choosed kwargs because it's short and well known from Python.

    opened by danieldaeschle 71
  • vweb refactor proposal

    vweb refactor proposal

    Intention

    The vweb module will be refactored to have a structure suitable for parallelization. As a community it would be best to agree on the design collectively.

    The intent of this issue is to settle on a design for the refactored vweb module.

    Proposal

    Use vweb.Context for request specific context, and use the user supplied App struct strictly for state management. Methods defined on App will be declared using shared to enable developers to use lock and rlock as necessary.

    Additionally, vweb.run will take two arguments: an initialized generic type and a vweb.Config struct. This allows developers to initialize anything they may need before server start.

    Example

    import vweb
    
    struct App {
    mut:
    	cnt int
    }
    
    fn main() {
    	conf := vweb.Config{
    		port: 8082
    		static_directory: '.'
    		static_path: '/static'
    	}
    	vweb.run(App{cnt: 100}, conf)
    }
    
    ['/users/:user']
    fn (shared app App) user_endpoint(mut c vweb.Context, user string) vweb.Result {
        rlock {
            return c.json('{"$user": $app.cnt}')
        }
    }
    
    fn (shared app App) index(mut c vweb.Context) vweb.Result {
        lock {
            app.cnt++
        }
    	// These values are available in the index.html template
    	show := true
    	hello := 'Hello world from vweb'
    	numbers := [1, 2, 3]
    	c.enable_chunked_transfer(40)
    	return $vweb.html()
    }
    

    Technical Details

    I haven't looked too deep into it, but I think this is not easily possible. I tried and failed making a POC passing a shared struct to a generic function, or initializing a shared generic type. So here is my question: will it be possible to do these things with V or future versions of V?

    Bug 
    opened by mcastorina 70
  • This language is not as advertised

    This language is not as advertised

    This language is not as advertised

    This language does not do over 90% of what is advertised. Most of what is advertised is not coherent with most of the claims you have stated. With the new release of the playground, most of the examples in the docs fail, even many of the extremely basic ones.

    • You appear to do very basic tokenization/lexing which you use to naïvely convert the code into C or C++ (through testing of the playground)
    • The converter program does virtually no semantic checking other than the most basic type checking
    • Name lookups do not respect nested scopes within functions and caused the playground to crash
    • There is poor checking for certain characters and tokens you disallow
    • Record types and their methods must be declared before use, the type before the methods
    • The playground was crashing frequently
    • The playground is extremely insecure

    You have previously claimed that the V compiler uses no AST. However, most of the features that you claim would require a form of AST to even work, including generics and interfaces. An AST is an abstract syntax tree, which means that it just stores data about the syntax that is in a tree-like format. It's pretty much impossible to not have unless you have a very basic language or doing naïve transformations into another similar language.


    You claim that the language has no runtime but the following require a runtime:

    • All arrays are dynamic
    • println
    • Threads with go
    • Synchronization of threads with runtime.wait()
    • Automatic memory management

    Things that are currently broken:
    - Automatic imports 
    - Interface method calls
    - Interfaces have to be declared with `type Foo interface {` 
    - Foo{a,b} syntax (use Foo{a:a, b:b}) 
    - Closures
    - a[i].field
    - Locks (lock {}). Use sync.Mutex for now. 
    - Enums 
    
    Disabled features:
    - Generics 
    

    Why was the playground lacking a lot of basic functionality? If most of these extremely basic features are broken, how could you have made any software in this language other than basic things? -- e.g. Fibonacci examples.

    Software claimed to be built in V:

    • Volt
    • Filey
    • Vid
    • gitly
    • Hot code reloading

    Claimed C/C++ Translations into V:

    • DOOM
    • DOOM 3
    • LevelDB
    • SQLite

    Claims from your "compare" page:

    - No null
    

    How would you handle pointers?! In your documentation, you demonstrate that pointers exist. This means that no null is false. Pointers also crashed the playground.

    - Much stricter vfmt
    

    And when you mean stricter, what does that mean? It was also failing quite often even on basic code in the playground.

    - Cheaper interfaces without dynamic dispatch
    

    So how do they work? Is it just static dispatch?


    What you have promised does not even come close to what is delivered.

    Type: Discussion 
    opened by gingerBill 62
  • Declarative UI: Swift/Dart vs Qt/QML approach

    Declarative UI: Swift/Dart vs Qt/QML approach

    Hi,

    Update

    V UI has been released, V itself is used for declarations.

    I'm working on declarative UI right now.

    Which approach do you think is the best: Swift/Dart (using the same language for declarations) or Qt/QML (using a smaller cleaner different language)?

    It's nice to have only one language, but the "VML" approach looks cleaner to me.

    Also, I'd need to modify V a lot, for example to allow things like [TextBox{}, Button{}].

    Type: Discussion 
    opened by medvednikov 59
  • Variable Names: Wow - That's 'Opinionated'!

    Variable Names: Wow - That's 'Opinionated'!

    The other day, I was tinkering with a small prog in V which involved enabling / disabling some of OSX's LaunchAgents. For my sins, I named one of my variables launchagentenabledpath [OK. It might not be elegant, or what you'd use, but it's how I roll!].

    Anyway, to my surprise V refused to compile my prog, because it didn't like the way I'd named the variable:

    bad variable name `launchagentenabledpath`
    looks like you have a multi-word name without separating them with `_`
    for example, use `registration_date` instead of `registrationdate`
    

    Now, I know everyone has their own way of naming variables. Ranging from the folks who like to use cryptic one-letter names like x, to the people [like me] who tend to use VariableNamesThatAreABitMoreDescriptive.

    And I know that some programming languages are fussy about what kind of names can begin with uppercase and which with lowercase letters. And then there are languages which require you to distinguish between private and public vars by [for example] beginning the names with an underscore or not. And, at the other end of the spectrum, you have a language like Nim, which is very lax about variable names, being pretty much case agnostic, apart from the initial letter.

    But this is the first time I've had a programming language actually refuse to compile unless I changed a variable name –not because I'd used one that was syntactically "wrong" –but just because it didn't like how I worded it.

    Is it necessary to be quite so "opinionated" as that?

    Interestingly enough, I ran a few long dictionary words through the compiler as variable names [Yes, I do have too much time on my hands!] and found that, rather than any kind of logic for identifying when the miscreant programmer has created a multi-word variable name, it seems the compiler just refuses to accept any variable names longer than 15 letters.

    So, ironically iamamultiword [I am a multi word] is acceptable as a variable name, whilst misunderstanding, extraterrestrial and characterisation are rejected by the compiler as being unseparated-multi-word names.

    In my case, this was a minor irritation –I want to name my variables how I want [within reason]. But I could see it having a bit more of an impact for people programming in languages like German which tend to be a bit more er... 'longwinded' when it comes to naming conventions.

    So, just out of curiosity, why such a relatively short limit on variable names? Did one of the dev team have a traumatic childhood incident involving one of those windowDidNotFinishLoading type names beloved of other platforms and vow never to go there again?

    Type: Discussion 
    opened by madranet 50
  • Discussion on match expression syntax

    Discussion on match expression syntax

    @medvednikov I started implementing https://github.com/vlang/v/issues/1603 by separating the "match statement" from "switch statement" in parser.v (also to fix https://github.com/vlang/v/issues/1602). I encountered the problem of parsing:

    enum Color{
        red, green
    }
    
    match 1 {
        .red => println(1)
        .green => println(2)
        else => println(0)
    }
    

    We need to specify boundaries of each branch either by "new line" or by any other means. For switch V can just look on the next token to see if it's a "case" and stop statements. Your made a hack where V checks if the next token is "=>" to stop parsing statements. Also there is an option to implement error recovery to remove my limitations. I'm ready with "match statement" and "match expression". Here what I've got.


    match 1 {
        else => {println(0)}
    }
    

    This code is unwrapped to

    println(0)
    

    Also you can omit those braces if you are using only one statement there.

    match 1 {
        else => println(0)
    }
    

    Braces allow next case to use enums.

    match 1 {
        .red => {println(1)}
        .green => println(2) // here they could be omitted
        else => println(0)
    }
    

    a := match 1 {
        else => 0
    }
    

    unwraps to

    a := 0
    

    match 1 {
        1 => println(1)
        3 => {
            println(3)
            println(4)
        }
        else => println(0)
    }
    

    This is just like switch works, but you have to use braces for multiple statements for now.


    a := match 1 {
        1 => 2
        3 => {
            3
        }
        else => 5
    }
    

    match_expr requires else for now. match_expr requires the right side of the arrow to be a value. If we allow users to use statements there, then we would have to handle all cases which C doesn't support (i.e. defining variable there). This is the only difference between match_st and match_expr.

    Type: Discussion 
    opened by teggot-teggot 47
  • json2: encode alias struct

    json2: encode alias struct

    Thanks @spytheman @Delta456 !

    struct Aa {
    	sub AliasType
    }
    
    struct Bb {
    	a int
    }
    
    type AliasType = Bb
    
    fn test_encode_alias_field() {
    	s := json.encode(Aa{
    		sub: Bb{
    			a: 1
    		}
    	})
    	assert s == '{"sub":{"a":1}}'
    }
    
    opened by enghitalo 0
  • checker: wrong check

    checker: wrong check

    Describe the bug

    error on $if U is $Alias {

    Expected Behavior

    not error

    Current Behavior

    a.v:8:18: error: only `$tmpl()`, `$env()`, `$embed_file()`, `$pkgconfig()`, `$vweb.html()`, `$compile_error()` and `$compile_warn()` comptime functions are supported right now
        6 | 
        7 | fn encode_struct[U](val U) {
        8 |     $if U is $Alias {
          |                     ^
        9 | 
       10 |     }
    

    Reproduction Steps

    module main
    
    struct Aa {
    	sub int
    }
    
    fn encode_struct[U](val U) {
    	$if U is $Alias {
    
    	}
    }
    
    fn main() {
    	aa := Aa{}
    	encode_struct(aa)
    }
    

    Possible Solution

    No response

    Additional Information/Context

    No response

    V version

    V 0.3.2

    Environment details (OS name and version, etc.)

    Ubuntu

    Bug 
    opened by enghitalo 0
  • os: make os.FileMode public

    os: make os.FileMode public

    This PR makes os.FileMode public. This is necessary for the pathlib module I'm working on (#16782), because Path.inode() returns the result from os.inode(), which is os.FileMode.

    I've ran the tests for tests for the os module, which still work. Let me know if I need to do anything else.

    See discussion under the aforementioned PR: https://github.com/vlang/v/pull/16782#issuecomment-1375560314

    opened by yochem 0
  • fix code generated to matchexpr which returns function

    fix code generated to matchexpr which returns function

    Fix #16473

    Fixes situation which match expr return pointer to function and has more than 5 branch stmst, i.e. it does not get converted to ternary code.

    fn dummy() string {
    	return 'b'
    }
    
    fn err() fn () string {
    	return match Foo.a {
    		.a { dummy }
    		.b { dummy }
    		.c { dummy }
    		.d { dummy }
    		.e { dummy }
    		else { dummy }
    	}
    }
    
    fn test_main() {
    	var := main.err()()
    	assert var == 'b'
    }
    
    opened by felipensp 0
  • C error. This should never happen.

    C error. This should never happen.

    Describe the bug

    I'm currently working on a pathlib library for v: #16782. I wanted to implement a wrapper function around os.open, and raise a custom error if it didn't work, like so:

    pub fn (p Path) open(mode string, options ...int) !os.File {
    	return os.open_file(p.str(), mode, ...options) or {
    		PathError{p, 200, 'cannot open "${p}"', 'open'}
    	}
    }
    

    I started the v repl using a freshly built v from git (of my fork, with the only difference being that it has the pathlib module in vlib/):

    $ ./v
     \   \  /   /  |  Welcome to the V REPL (for help with V itself, type  exit , then run  v help ).
      \   \/   /   |  Note: the REPL is highly experimental. For best V experience, use a text editor,
       \      /    |  save your code in a  main.v  file and execute:  v run main.v
        \    /     |  V 0.3.2 f959fbb . Use  list  to see the accumulated program so far.
         \__/      |  Use Ctrl-C or  exit  to exit, or  help  to see other available commands.
    
    
    >>> import pathlib
    ==================
       ^~~~~~~~~~~~~~~~~~
    /tmp/v_501/.noprefix.01GPB9E584ERTRQ24V00NR3H9E.vrepl_temp.7378359400266354256.tmp.c:23354:25: error: assigning to 'os__File' (aka 'struct os__File') from incompatible type 'pathlib__PathError' (aka 'struct pathlib__PathError')
                    *(os__File*) _t2.data = ((pathlib__PathError){.path = p,.code = 200,.msg =  str_intp(2, _MOV((StrIntpData[]){{_SLIT("cannot open \""), /*115 &pathlib.Path*/0xfe10, {.d_s = pathlib__Path_str(p)}}, {_SLIT("\""), 0, { .d_c = 0 }}})),.func = _SLIT("open"),});
                                          ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /tmp/v_501/.noprefix.01GPB9E584ERTRQ24V00NR3H9E.vrepl_temp.7378359400266354256.tmp.c:23450:4: warning: expression result unused [-Wunused-value]
      (*(os__File*)_t1.data);
       ^~~~~~~~~~~~~~~~~~~~
    9 warnings and 1 error generated.
    ...
    ==================
    (Use `v -cg` to print the entire error message)
    
    builder error:
    ==================
    C error. This should never happen.
    
    This is a compiler bug, please report it using `v bug file.v`.
    
    https://github.com/vlang/v/issues/new/choose
    
    You can also use #help on Discord: https://discord.gg/vlang
    >>>
    

    Here's the C output: https://gist.github.com/yochem/60d58b76372191d143bdf6d4683a6b68.

    Expected Behavior

    Not crashing

    Current Behavior

    Crashing

    Reproduction Steps

    $ git clone https://github.com/yochem/v
    $ git checkout pathlib
    $ make
    $ ./v
    >>> import pathlib
    

    Possible Solution

    No response

    Additional Information/Context

    No response

    V version

    V 0.3.2 f959fbb

    Environment details (OS name and version, etc.)

    OS: macos, macOS, 13.0.1, 22A400 Processor: 4 cpus, 64bit, little endian, Intel(R) Core(TM) i5-8210Y CPU @ 1.60GHz CC version: Apple clang version 14.0.0 (clang-1400.0.29.202)

    getwd: /Users/yochem/Documents/nv vmodules: /Users/yochem/.vmodules vroot: /Users/yochem/Documents/nv vexe: /Users/yochem/Documents/nv/v vexe mtime: 2023-01-09 12:52:32 is vroot writable: true is vmodules writable: false V full version: V 0.3.2 2ec6e2b.f959fbb

    Git version: git version 2.39.0 Git vroot status: weekly.2022.52-14-gf959fbbc (72 commit(s) behind V master) .git/config present: true thirdparty/tcc status: thirdparty-macos-amd64 46662e20

    Bug 
    opened by yochem 4
Releases(weekly.2023.01)
Owner
The V Programming Language
Simple, fast, safe, compiled language for developing maintainable software
The V Programming Language
A fast script language for Go

The Tengo Language Tengo is a small, dynamic, fast, secure script language for Go. Tengo is fast and secure because it's compiled/executed as bytecode

daniel 3k Dec 30, 2022
Fast, portable, non-Turing complete expression evaluation with gradual typing (Go)

Common Expression Language The Common Expression Language (CEL) is a non-Turing complete language designed for simplicity, speed, safety, and portabil

Google 1.4k Dec 24, 2022
Expression evaluation engine for Go: fast, non-Turing complete, dynamic typing, static typing

Expr Expr package provides an engine that can compile and evaluate expressions. An expression is a one-liner that returns a value (mostly, but not lim

Anton Medvedev 3.3k Dec 30, 2022
Starlark in Go: the Starlark configuration language, implemented in Go

Starlark in Go This is the home of the Starlark in Go project. Starlark in Go is an interpreter for Starlark, implemented in Go. Starlark was formerly

Google 1.8k Jan 2, 2023
PHP bindings for the Go programming language (Golang)

PHP bindings for Go This package implements support for executing PHP scripts, exporting Go variables for use in PHP contexts, attaching Go method rec

Alex Palaistras 882 Jan 1, 2023
Compiler for a small language into x86-64 Assembly

Compiler This project is a small compiler, that compiles my own little language into X86-64 Assembly. It then uses yasm and ld to assemble and link in

Maurice Tollmien 242 Dec 13, 2022
Elvish = Expressive Programming Language + Versatile Interactive Shell

Elvish: Expressive Programming Language + Versatile Interactive Shell Elvish is an expressive programming language and a versatile interactive shell,

null 4.9k Dec 25, 2022
A compiler for the ReCT programming language written in Golang

ReCT-Go-Compiler A compiler for the ReCT programming language written in Golang

null 6 Nov 30, 2022
Library for interacting with LLVM IR in pure Go.

llvm Library for interacting with LLVM IR in pure Go. Introduction Introductory blog post "LLVM IR and Go" Our Document Installation go get -u github.

null 995 Dec 24, 2022
A parser library for Go

A dead simple parser package for Go V2 Introduction Tutorial Tag syntax Overview Grammar syntax Capturing Capturing boolean value Streaming Lexing Sta

Alec Thomas 2.8k Dec 30, 2022
Mathematical expression parsing and calculation engine library. 数学表达式解析计算引擎库

Math-Engine 使用 Go 实现的数学表达式解析计算引擎库,它小巧,无任何依赖,具有扩展性(比如可以注册自己的函数到引擎中),比较完整的完成了数学表达式解析执行,包括词法分析、语法分析、构建AST、运行。 go get -u github.com/dengsgo/math-engine 能够

Deng.Liu 255 Jan 3, 2023
A simple interpreter

类型: 基础类型: 整形,浮点,字符串,布尔,空值(nil) 符合类型: 数组,只读数组(元组),字典 支持语句: if, elif, else, for, foreach, break, continue, return 支持类型定义: class, func 语法格式: 赋值语句---> ```

null 19 Aug 10, 2022
A simple RISC-V RV32I assembler

rvasm A simple RISC-V assembler. Supports the RV32i standard plus CSR and other privileged instructions (uret, sret, mret, wfi). Also supports all pse

Zachary Yedidia 3 Nov 17, 2021
dagger is a fast, concurrency safe, mutable, in-memory directed graph library with zero dependencies

dagger is a blazing fast, concurrency safe, mutable, in-memory directed graph implementation with zero dependencies

Coleman Word 266 Dec 19, 2022
Simple, safe and compiled programming language.

The X Programming Language Simple, safe and compiled programming language. Table of Contents Overview OS Support Contributing License Overview The X p

The X Programming Language 51 Dec 28, 2022
AppsFlyer 505 Dec 27, 2022
GoThanks automatically stars Go's official repository and your go.mod github dependencies, providing a simple way to say thanks to the maintainers of the modules you use and the contributors of Go itself.

Give thanks (in the form of a GitHub ★) to your fellow Go modules maintainers. About GoThanks performs the following operations Sends a star to Go's r

psampaz 117 Dec 24, 2022
An experiment in software that has sovereignty over itself.

Sovereign An experiment in software that has sovereignty over itself. Why I Did This If you actually read through all of this, please let me know. You

Joe Henke 1 Feb 11, 2022
Scan and analyze OSS dependencies and licenses from compiled Go binaries

golicense - Go Binary OSS License Scanner golicense is a tool that scans compiled Go binaries and can output all the dependencies, their versions, and

Mitchell Hashimoto 664 Nov 6, 2022