Simple, fast, safe, compiled language for developing maintainable software

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: ≈110k loc/s with a Clang backend, ≈1 million loc/s with native and tcc backends (Intel i5-7500, SSD, no optimization) (demo video)
  • 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 (demo video)
  • Cross-platform UI library
  • Built-in graphics library
  • Easy cross-compilation
  • REPL
  • Built-in ORM
  • Built-in web framework
  • C and JavaScript backends
  • Great for writing low-level software (Vinix OS)

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 V 1.0. 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 run word_counter/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 .

V net.http, net.websocket, v install

If you plan to use the net.http module, or the net.websocket module, 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

Vinix, an OS/kernel written in V

V is great for writing low-level software like drivers and kernels. Vinix is an OS/kernel that already runs bash, GCC, V, and nano.

https://github.com/vlang/vinix

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
  • vlib/io/writer.v: typo in documentation

    vlib/io/writer.v: typo in documentation

    Describe the bug

    The documentation contains a typo.

    Expected Behavior

    The correct form is:

    can be written to

    Current Behavior

    The documentation says 2 times:

    can be wrote to

    Reproduction Steps

    Open writer.v.

    Possible Solution

    No response

    Additional Information/Context

    No response

    V version

    current

    Environment details (OS name and version, etc.)

    any

    Bug 
    opened by rillig 1
  • or block inside conditional compilation in assignement crash compiler

    or block inside conditional compilation in assignement crash compiler

    Describe the bug

    module main

    import os

    fn main() { config_dir := $if windows { os.home_dir() } $else { os.config_dir() or { os.home_dir() } } println(config_dir) }

    Expected Behavior

    Compilation ok (feature supported) or make compiler fail gracefully AND add documentation

    Current Behavior

    ================== /tmp/v_1000/bug.403690130920050968.tmp.c:17243: error: '{' expected (got "_t2") ...

    (Use v -cg to print the entire error message)

    builder error:

    C error. This should never happen.

    Reproduction Steps

    v bug.v

    Possible Solution

    No response

    Additional Information/Context

    No response

    V version

    V 0.3.2 a6bf20f.5daf39b

    Environment details (OS name and version, etc.)

    Linux Mint 20.3 64 bit

    Bug 
    opened by mp81ss 0
  • sumtype+generics: Failure while trying to push sumtype value to internal Stack

    sumtype+generics: Failure while trying to push sumtype value to internal Stack

    Describe the bug

    Compilation failure when combining datatypes.Stack and a sumtype generic value.

    Expected Behavior

    I expected the sample code to compile and function correctly.

    Current Behavior

    /home/admin/v/vlib/datatypes/stack.v:25:20: error: cannot append `T` to `[]T`
       23 | // push adds an element to the top of the stack
       24 | pub fn (mut stack Stack[T]) push(item T) {
       25 |     stack.elements << item
          |                       ~~~~
       26 | }
       27 |
    Exited with error status 1
    

    Reproduction Steps

    Smallest reproducible example:

    import datatypes
    
    type Content = string | bool
    
    struct DataStack {
    mut:
    	data datatypes.Stack[Content]    
    }
    
    fn (mut dstack DataStack) push(content Content) {
        dstack.data.push(content)
    }
    
    mut dstack := DataStack{}
    dstack.push('hello')
    
    println(dstack)
    

    Possible Solution

    No response

    Additional Information/Context

    No response

    V version

    V 0.3.2 51bb630

    Environment details (OS name and version, etc.)

    vmodules: C:\Users\Subhomoy Haldar\.vmodules
    vroot: C:\Users\Subhomoy Haldar\projects\vlang\v-main
    vexe: C:\Users\Subhomoy Haldar\projects\vlang\v-main\v.exe
    vexe mtime: 2023-01-01 15:13:38
    is vroot writable: true
    is vmodules writable: true
    V full version: V 0.3.2 5acd855.51bb630
    
    Git version: git version 2.39.0.windows.2
    Git vroot status: weekly.2022.50-113-g51bb630e (1 commit(s) behind V master)
    .git/config present: true
    thirdparty/tcc status: thirdparty-windows-amd64 cb89a4fe
    
    Bug Status: Confirmed 
    opened by hungrybluedev 1
  • Compiling issue

    Compiling issue

    Describe the bug

    I received the following error when trying to compile

    ==================
    
    /tmp/v_0/main.3885071449460690037.tmp.c:7387:33: error: parameter 1 ('it') has incomplete type
    
     7387 | static string PGconn_str(PGconn it) { return indent_PGconn_str(it, 0);}
    
          |                          ~~~~~~~^~
    
    /tmp/v_0/main.3885071449460690037.tmp.c: In function 'PGconn_str':
    
    /tmp/v_0/main.3885071449460690037.tmp.c:7387:64: error: type of formal parameter 1 is incomplete
    
     7387 | static string PGconn_str(PGconn it) { return indent_PGconn_str(it, 0);}
    
          |                                                                ^~
    
    /tmp/v_0/main.3885071449460690037.tmp.c: In function 'indent_pg__DB_str':
    
    /tmp/v_0/main.3885071449460690037.tmp.c:7408:118: error: dereferencing pointer to incomplete type 'PGconn' {aka 'struct pg_conn'}
    
     7408 |  string _t14 = isnil(it.conn) ? _SLIT("nil") : (indent_count > 25)? _SLIT("<probably circular>") : indent_PGconn_str(*it.conn, indent_count + 1);
    
          |                                                                                                                      ^~~~~~~~
    
    /tmp/v_0/main.3885071449460690037.tmp.c:7408:118: error: type of formal parameter 1 is incomplete
    
    ...
    
    ==================
    
    (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
    

    Reproduction Steps

    vlang_simple_api.zip

    I am running the code in the zip file in a docker container unzip and run the following. You can see the error in the api container

    make up

    Possible Solution

    No response

    Additional Information/Context

    No response

    V version

    V 0.3.2 c5c7b3a.51bb630

    Environment details (OS name and version, etc.)

    OS: macos, macOS, 12.5.1, 21G83 Processor: 4 cpus, 64bit, little endian, Intel(R) Core(TM) i7-6567U CPU @ 3.30GHz CC version: Apple clang version 14.0.0 (clang-1400.0.29.202)

    Bug 
    opened by mikan-sour 2
  • [ FreeBSD ] examples/http_server.v doesn't actually listen on any ports

    [ FreeBSD ] examples/http_server.v doesn't actually listen on any ports

    Describe the bug

    examples/http_server.v does not listen on any ports.

    Expected Behavior

    Running telnet localhost 8080 should result in a successful connection.

    Current Behavior

    $ telnet localhost 8080
    Trying 127.0.0.1...
    telnet: connect to address 127.0.0.1: Connection refused
    telnet: Unable to connect to remote host
    

    Reproduction Steps

    $ v -cc clang examples/http_server.v $ examples/http_server

    Possible Solution

    No response

    Additional Information/Context

    Very strange. It all works as expected on Linux, so this appears to be FreeBSD specific.

    Originally posted by @JalonSolov in https://github.com/vlang/v/issues/16727#issuecomment-1368257371

    V version

    0.3.2 d19c1ef

    Environment details (OS name and version, etc.)

    FreeBSD 13.1

    Bug 
    opened by yonas 0
Releases(weekly.2022.52)
Owner
The V Programming Language
Simple, fast, safe, compiled language for developing maintainable software
The V Programming Language
A modern dynamically typed programming language that gets compiled to bytecode and is run in a virtual machine called SVM (Strawbry Virtual Machine).

Strawbry A bytecode programming language. Here is what I want Strawbry to look like: var a = 1 var b = 2 var c = a + b print(c) func sqrt(x) { re

PlebusSupremus1234 6 Jan 5, 2022
simple and fast scripting language

The Aument Language The Aument language is a work-in-progress dynamically-typed scripting language with performance first: this scripting language is

The Aument Project 35 Dec 27, 2022
A demonstration of implementing, and using, a "type safe", extensible, and lazy iterator interface in pure C99.

c-iterators A demonstration of implementing, and using, a "type safe", extensible, and lazy iterator interface in pure C99. The iterable is generic on

Chase 69 Jan 2, 2023
a header-only crossplatform type-safe dynamic compiler generator based on C++ 17.

Mu Compiler Generator MuCompilerGenerator(MuCplGen) a Header-Only dynamic compiler generator based on C++ 17. Why MuCplGen? header-only cross-platform

MuGdxy 11 Dec 31, 2021
T# Programming Language. Interpreted language. In development. I will make this compilable later.

The T# Programming Language WARNING! THIS LANGUAGE IS A WORK IN PROGRESS! ANYTHING CAN CHANGE AT ANY MOMENT WITHOUT ANY NOTICE! Install Install $ make

T# 91 Jun 24, 2022
λQ: A Simple Quantum Programming Language based on QWIRE.

λQ λQ: A Simple Language based on QWIRE which can be compiled to QASM. The name λQ means lambda calculus with quantum circuits. This is a term project

Wenhao Tang 5 Jul 11, 2021
A Simple Toy Programming Language

Tovie Lang Small toy programming language. Docs : https://github.com/Jaysmito101/tovie/wiki Examples : 1. Hello World proc_0 "Hello" 32 "World!"

Jaysmito Mukherjee 23 Dec 20, 2022
A simple token-based programming language written in C++.

Fun Assembly Programming Language About It's a simple token-based programming language written in C++ by Soham Malakar and Sanket Tarafder. Know About

Soham Malakar 11 Dec 28, 2022
🐛 Pangea Software's Bugdom for modern systems

Bugdom This is Bugdom running on modern macOS, Windows and Linux! This version, at https://github.com/jorio/Bugdom, is approved by Pangea Software. Ge

Iliyas Jorio 258 Jan 2, 2023
Pangea Software's Mighty Mike (Power Pete) for modern systems

Mighty Mike (a.k.a. Power Pete) This is Pangea Software's Mighty Mike updated to run on modern systems. Set in a toy store, this top-down action game

Iliyas Jorio 120 Dec 26, 2022
3D software rasterizer using C/ C++

REX Rex is a side project I'm working on now for the purpose of learning more about graphics programming and rendering. Currently it's just a 3D softw

Waleed Yaser 11 Apr 8, 2022
Competitive Programming Language MM

MM Language MM Languageは、競技プログラミングのために開発中のプログラミング言語です。 どんなことが可能なのかは、examplesおよびexamples_outputsを参照ください。 まだ開発中の言語であるため、諸々不備があり、コンパイルエラーの行数表示さえまともに出せない状

null 21 Aug 22, 2022
This repository is a summary of the basic knowledge of recruiting job seekers and beginners in the direction of C/C++ technology, including language, program library, data structure, algorithm, system, network, link loading library, interview experience, recruitment, recommendation, etc.

?? C/C++ 技术面试基础知识总结,包括语言、程序库、数据结构、算法、系统、网络、链接装载库等知识及面试经验、招聘、内推等信息。This repository is a summary of the basic knowledge of recruiting job seekers and beginners in the direction of C/C++ technology, including language, program library, data structure, algorithm, system, network, link loading library, interview experience, recruitment, recommendation, etc.

huihut 27k Dec 31, 2022
A cheatsheet of modern C++ language and library features.

C++20/17/14/11 Overview Many of these descriptions and examples come from various resources (see Acknowledgements section), summarized in my own words

Anthony Calandra 15.4k Jan 6, 2023
The DSiLanguagePatcher increases accessibility to foreign region DSi consoles by providing a mean to change the user interface language.

DSi Language Patcher The DSi Language patcher is a small tool, which runs on your DSi (homebrew execution required) and create a copy of your original

null 20 Nov 7, 2022
A library of language lexers for use with Scintilla

README for Lexilla library. The Lexilla library contains a set of lexers and folders that provides support for programming, mark-up, and data languag

Scintilla 93 Jan 1, 2023
An open source, OOP language with editable syntax.

Copper An Open source compiled programming language, In development. Goals Copper is an general-purpose OOP language. Coppers main goal is to allow ea

null 13 Nov 18, 2022
Applied SDLC using C language

SDLC Activity Based Learning Build Code Quality Unity Git Inspector Folder Structure Folder Description 1_Requirements Documents detailing requirement

Arnob Chowdhury 7 Nov 8, 2022
the kyanite programming language

Kyanite Kyanite is a small passion-project programming language intended to be light-weight and simple to use. You can read more on the language itsel

Kyanite 5 Aug 19, 2021