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

Issues
  • 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
  • Compile error when using `$if` with multiple type cases & nested generic fn

    Compile error when using `$if` with multiple type cases & nested generic fn

    V version: V 0.3.0 ab244d2.d6b594c OS: macos, macOS, 12.5, 21G72

    What did you do?

    struct TypeA {}
    struct TypeB {}
    fn next<T>(input T) string {
    	$if T is TypeA || T is TypeB { // this causes error!!
    		return next2(input)
    	} $else {
    		return next2(input)
    	}
    }
    fn next2<T>(input T) string {
    	$if T is TypeA {
    		return T.name
    	} $else $if T is TypeB {
    		return T.name
    	} $else $if T is f64 {
    		return T.name
    	}
    	return 'other type'
    }
    fn main() {
    	ta1 := TypeA{}
    	tb1 := TypeB{}
    	println(next(ta1))
    	println(next(tb1))
    }
    

    What did you expect to see?

    TypeA
    TypeB
    

    What did you see instead? error

    ==================
       ^~~~~~~~~~~~~~~
    /tmp/v_502/comptime_generic_multiple_case.15326913487265528067.tmp.c:12153:42: error: passing 'main__TypeA' (aka 'struct main__TypeA') to parameter of incompatible type 'main__TypeB' (aka 'struct main__TypeB')
                    string _t2 = main__next2_T_main__TypeB(input);
                                                           ^~~~~
    /tmp/v_502/comptime_generic_multiple_case.15326913487265528067.tmp.c:1851:62: note: passing argument to parameter 'input' here
    VV_LOCAL_SYMBOL string main__next2_T_main__TypeB(main__TypeB input);
                                                                 ^
    1 warning 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
    
    [[Command exited with 1]]
    
    Bug 
    opened by ken0x0a 4
  • Use of `multi return` types in Generics leads to C error

    Use of `multi return` types in Generics leads to C error

    V Doctor:

    OS: linux, Ubuntu 20.04.4 LTS (WSL 2)
    Processor: 12 cpus, 64bit, little endian, 11th Gen Intel(R) Core(TM) i5-11400H @ 2.70GHz
    CC version: cc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
    
    getwd: /home/apocryphon/tests/v
    vmodules: /home/apocryphon/.vmodules
    vroot: /home/apocryphon/packages/v
    vexe: /home/apocryphon/packages/v/v
    vexe mtime: 2022-08-06 16:46:27
    is vroot writable: true
    is vmodules writable: true
    V full version: V 0.3.0 d6de533.d6b594c
    
    Git version: git version 2.25.1
    Git vroot status: weekly.2022.31-22-gd6b594c4
    .git/config present: true
    thirdparty/tcc status: thirdparty-linux-amd64 827f7452
    

    What did you do?

    struct Tuple<T> {
        data T
    }
    
    fn main() {
        sample := Tuple<(int, int)>{}
        println(sample)
    }
    

    What did you expect to see?

    There is a related discussion about this in #15300. To make it short, the code above (with some additions) should result in a compilation error or a successful program with behavior resembling tuples (like the ones in Python).

    Related to:

    • #15359
    • #15083
    • #15366
    • #15300

    What did you see instead?

    v -cg:

    /tmp/v_1000/m2.12566730850537185187.tmp.c:1074: error: field 'data' has incomplete type
    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
    

    v -cg -prod:

    /tmp/v_1000/m2.16452454173144520647.tmp.c:1075:23: error: field ‘data’ has incomplete type
     1075 |  multi_return_int_int data;
          |                       ^~~~
    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
    
    Bug 
    opened by Apocryphon-X 0
  • Is there any inconsistency between the assignment when calling a method to pass parameters and assigning to other variables?

    Is there any inconsistency between the assignment when calling a method to pass parameters and assigning to other variables?

    When I assign foo to foo1, it will copy the value of foo to foo1,for example:

    mut foo := Foo{3}
    mut foo1 := foo
    //foo and foo1 do not point to the same memory
    

    But if Foo implements the speak method in the form of mut, then foo1 points to the same memory as foo

    // By the way, does this mut make sense in this interface?
    interface Speaker {
    mut:
    	speak()
    }
    
    fn (mut foo1 Foo) speak() {
    	strconv.v_printf('interface:%p\n', foo1)
    	foo1.a = 9
    }
    
    mut foo := Foo{3}
    foo.speak()
    

    But if the speak method is not implemented in the form of mut, then foo and foo1 do not point to the same memory, which feels very inconsistent

    fn (foo1 Foo) speak() {
    	strconv.v_printf('interface:%p\n', foo1)
    }
    
    mut foo := Foo{3}
    foo.speak()
    
    Bug 
    opened by Silentdoer 0
  • Use of `multi return` types in Generics can confuse struct methods

    Use of `multi return` types in Generics can confuse struct methods

    V Doctor:

    OS: linux, Ubuntu 20.04.4 LTS (WSL 2)
    Processor: 12 cpus, 64bit, little endian, 11th Gen Intel(R) Core(TM) i5-11400H @ 2.70GHz
    CC version: cc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
    
    getwd: /home/apocryphon
    vmodules: /home/apocryphon/.vmodules
    vroot: /home/apocryphon/packages/v
    vexe: /home/apocryphon/packages/v/v
    vexe mtime: 2022-07-26 18:05:29
    is vroot writable: true
    is vmodules writable: true
    V full version: V 0.3.0 d6de533.c976a69
    
    Git version: git version 2.25.1
    Git vroot status: weekly.2022.30-7-gc976a691 (55 commit(s) behind V master)
    .git/config present: true
    thirdparty/tcc status: thirdparty-linux-amd64 827f7452
    

    What did you do?

    import datatypes { Queue }
    
    fn main() {
    	example := Queue<(int, int)>{}
    	// ... 
    	first, second := example.pop()?
    	// ...
    }
    

    What did you expect to see?

    There is a related discussion about this in #15300. To make it short, the code above (with some additions) should result in a compilation error or a successful program with behavior resembling tuples (like the ones in Python).

    Related to:

    • #15359
    • #15083
    • #15369
    • #15300

    What did you see instead?

    /home/apocryphon/packages/v/vlib/datatypes/linked_list.v:27:9: error: expected 2 arguments, but got 1
       25 | // first returns the first element of the linked list
       26 | pub fn (list LinkedList<T>) first() ?T {
       27 |     return if !list.is_empty() { list.head.data } else { error('Linked list is empty') }
          |            ~~
       28 | }
       29 |
    /home/apocryphon/packages/v/vlib/datatypes/linked_list.v:39:15: error: expected 2 arguments, but got 1
       37 |             node = node.next
       38 |         }
       39 |         return node.data
          |                     ~~~~
       40 |     }
       41 | }
    /home/apocryphon/packages/v/vlib/datatypes/linked_list.v:55:16: error: expected 2 arguments, but got 1
       53 |         }
       54 |         if iterations == idx {
       55 |             return node.data
          |                         ~~~~
       56 |         } else {
       57 |             return error('Index out of bounds')
    ...
    
    Bug 
    opened by Apocryphon-X 0
  • `acounter atomic int` is not respected by tcc

    `acounter atomic int` is not respected by tcc

    V doctor:

    OS: linux, Ubuntu 20.04.3 LTS
    Processor: 4 cpus, 64bit, little endian, Intel(R) Core(TM) i3-3225 CPU @ 3.30GHz
    CC version: cc (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
    
    getwd: /v/vnew
    vmodules: /home/delian/.vmodules
    vroot: /v/vnew
    vexe: /v/vnew/v
    vexe mtime: 2022-08-06 11:08:28
    is vroot writable: true
    is vmodules writable: true
    V full version: V 0.3.0 fcde631.6887823
    
    Git version: git version 2.25.1
    Git vroot status: weekly.2022.31-24-g42df4450
    .git/config present: true
    thirdparty/tcc status: stable-thirdparty-linux-amd64 827f7452
    
    

    What did you do? v -g -o vdbg cmd/v && vdbg x.v

    struct App {
    mut:
    	counter  int
    	acounter atomic int
    }
    
    fn (mut a App) run() {
    	for i := 0; i < 1000_000; i++ {
    		a.counter++
    	}
    }
    
    fn (mut a App) run_atomic() {
    	for i := 0; i < 1000_000; i++ {
    		a.acounter++
    	}
    }
    
    fn main() {
    	mut a := &App{}
    	//
    	mut t1 := []thread{cap: 10}
    	for _ in 0 .. 10 {
    		t1 << go a.run()
    	}
    	t1.wait()
    	mut t2 := []thread{cap: 10}
    	for _ in 0 .. 10 {
    		t2 << go a.run_atomic()
    	}
    	t2.wait()
    	dump(a)
    }
    
    

    What did you expect to see?

    [x.v:32] a: &App{
        counter: 4078887
        acounter: 10000000
    }
    

    What did you see instead?

    [x.v:32] a: &App{
        counter: 3132631
        acounter: 3333620
    }
    

    Note: it works fine with gcc and clang. Only tcc does not support atomic ops.

    Bug 
    opened by spytheman 0
  • shared array: array.last() produces C error

    shared array: array.last() produces C error

    OS: linux, Ubuntu 20.04.4 LTS Processor: 4 cpus, 64bit, little endian, Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz CC version: cc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

    getwd: /home/woody vmodules: /home/woody/.vmodules vroot: /home/woody/sources/v/v vexe: /home/woody/sources/v/v/v vexe mtime: 2022-08-06 08:41:02 is vroot writable: true is vmodules writable: true V full version: V 0.3.0 372857c.4588bb4

    Git version: git version 2.25.1 Git vroot status: weekly.2022.31-20-g4588bb44 .git/config present: true thirdparty/tcc status: thirdparty-linux-amd64 827f7452

    module main
    
    fn main() {
    	shared a := []int{}
    	lock  {
    		a << 1
    		a << 2
    	}
    	rlock a {
    		println(a.last())
    	}
    }
    
    

    What did you expect to see? No C error

    What did you see instead?

    [email protected]:~/sources/v/bugs$ v shared_last.v
    ==================
    /tmp/v_1000/shared_last.12850093158604570159.tmp.c:17031: error: cannot convert 'struct array *' to 'struct array'
    ...
    ==================
    (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
    
    Bug 
    opened by WoodyAtHome 1
Releases(weekly.2022.31)
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 2.8k Aug 9, 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.3k Aug 12, 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 2.8k Aug 4, 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.7k Aug 11, 2022
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 868 Aug 10, 2022
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 237 Jul 17, 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.8k Aug 7, 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 Apr 7, 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 931 Aug 3, 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.5k Aug 10, 2022
Mathematical expression parsing and calculation engine library. 数学表达式解析计算引擎库

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

Deng.Liu 228 Jul 29, 2022
A simple interpreter

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

null 18 Mar 16, 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 261 Jul 23, 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 27 Jul 27, 2022
AppsFlyer 487 Jul 16, 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 113 Jul 29, 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 627 Jul 27, 2022
Go concurrent-safe, goroutine-safe, thread-safe queue

goconcurrentqueue - Concurrent safe queues The package goconcurrentqueue offers a public interface Queue with methods for a queue. It comes with multi

Enrique Bris 200 Aug 9, 2022
A strongly typed HTML templating language that compiles to Go code, and has great developer tooling.

A language, command line tool and set of IDE extensions that makes it easier to write HTML user interfaces and websites using Go.

Adrian Hesketh 131 Aug 3, 2022
👩🏼‍💻A simple compiled programming language

The language is written in Go and the target language is C. The built-in library is written in C too

paco 26 Jul 22, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Flamingo 307 Aug 13, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Flamingo 306 Aug 4, 2022
Sand is the next, versatile, high-level compiled or interpreted language that's easy to learn and performant to run.

Sand is the newest, dynamically typed, interpreted programming language. Table of Contents History Project Stats History Sand was created as part of @

Neuron AI 4 Mar 13, 2022
Gpl - University Project on developing a General Purpose Language

General Purpose Language About The Project University Project on developing a Ge

Marcel Vlasenco 1 Jul 9, 2022
💨A well crafted go packages that help you build robust, reliable, maintainable microservices.

Hippo A Microservices Toolkit. Hippo is a collection of well crafted go packages that help you build robust, reliable, maintainable microservices. It

Ahmed 140 Feb 8, 2022