diff --git a/README.md b/README.md index 10eef2e46..fafef11be 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,43 @@ +the idea here was to take https://github.com/hex2f/vlang.io (the original version) and update it to match the actual (live) version of the website the way it was (with all the nunjucks and npm). +i archieved it at the moment and pushed it here https://github.com/vlang/website/pull/242 +but sadly, "because of proprietary backend" (statistics, translations) and the fact that the origin had a lot of "hot fixes" on top of some other version of the original, it had lots of conflicts so it wasnt merged + +i later realised that the npm version is unnecessary and complex as the only JS that has to be used is to give a proper download link depending on user's OS so i tried to move everything to Hugo here https://github.com/t4wE/vlanghugo +for some time i updated that repository to match current state of the website but later gave up (started to feel pointless as it likely would never get mered). + +----------------------------------------------------------------------------------------------------------------------------- # The V Programming Language Website https://vlang.io -*note: You can't run this site locally, because of proprietary backend, but you can preview the html file `preview.html` for styling css.* +![Example](example.png)\ +[The original version](https://github.com/hex2f/vlang.io) was written by [leahlundqvist](https://github.com/hex2f) aka ``hex2f``. + +*note: You can't run the whole site locally, because of proprietary backend, but you can preview the html file `index.html` for styling css.* ## How To Contribute -There are various way you can contribute to this project. Refactoring writings, updating css, Adding Language support etc. We will cover them one by one. +There are various way you can contribute to this project. Refactoring writings, updating css, adding language support etc. We will cover them one by one. ### Styling the website -There is `app.css` file which is the main stylesheet. Use `preview.html` to view the rendered html file. This will help you style the website. +There is `app.css` file in ``build`` folder which is the main stylesheet. It is converted from `app.sass` file from the main repo and then minified. Use `index.html` in ``build`` folder to view the rendered html file. This will help you style the website. ### Adding Language -Use the `english.tr` as a reference to add your translation to this project. +Use the `english.tr` in the ``translations`` folder as a reference to add your translation to this project. + +### Building + +The website is built via Nunjucks templates. By using ``npm run build`` the ``build-pages.js`` script creates pages from njk files (templates), converts sass to css, minifies it, and runs the page on ``localhost:3000`` via **serve**. + +If you only want to build pages and not run them via ``serve`` then delete ``&& serve build/`` from line 23 of ``package.json``. +To build: +``` +git clone https://github.com/vlang/website +cd website +npm install +npm install --global serve +npm run build +``` diff --git a/_layout.html b/_layout.html deleted file mode 100644 index 821b5dc12..000000000 --- a/_layout.html +++ /dev/null @@ -1,63 +0,0 @@ -@define "header" - - - - - - - - - @css "app.css?28" - - The V Programming Language - - -
- -
-
- - - - -
-
-@end - -@define "footer" - - -@end diff --git a/app.css b/app.css old mode 100644 new mode 100755 index 9cdd8f812..be324edf8 --- a/app.css +++ b/app.css @@ -1,945 +1,738 @@ -.select { - position: relative; - display: inline-block; - width: 100% -} - -.select select { - font-size: 14px; - display: inline-block; - width: 100%; - cursor: pointer; - padding: 10px 15px; - outline: 0; - border: none; - border-radius: 8px; - overflow: hidden; - background: #334; - color: #ccc; - appearance: none; - -webkit-appearance: none; - -moz-appearance: none -} - -.select select::-ms-expand { - display: none -} - -.select select:focus, -.select select:hover { - color: #ddd; - background: #445 -} - -.select select:disabled { - opacity: .5; - pointer-events: none -} - -.select_arrow { - position: absolute; - pointer-events: none; - top: 12px; - right: 15px; - width: 0; - height: 0; - border: solid #aaa; - border-width: 0 3px 3px 0; - display: inline-block; - padding: 3px; - transform: rotate(45deg); - -webkit-transform: rotate(45deg) -} - -.select select:focus~.select_arrow, -.select select:hover~.select_arrow { - border-color: #ccc -} - -.select select:disabled~.select_arrow { - border-top-color: #ccc -} - -.svg-inline--fa { - display: inline-block; - font-size: inherit; - height: 1em; - overflow: visible; - vertical-align: -.125em -} - -.svg-inline--fa.fa-w-14 { - width: .875em -} - -body, -html { - height: 100% +@import "./styles/customselect.css"; +@import "./styles/icons.css"; +body, html { + height: 100%; } body { - margin: 0; - font-family: "Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif -} + margin: 0px; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif; +} + +@media (prefers-color-scheme: dark) { + :root { + color-scheme: dark; + --background-primary: #1e1e1e; + --background-secondary: #181818; + --text-primary: #fff; + --text-secondary: #cdcdcd; + --header-text: #cdcdcd; + --header-text-selected: white; + --border-color: #5d5d5d; + --links-color: #78a9e9; + } + .chipnetics { + filter: invert(1); + } + .bigman { + filter: invert(88%); + } .content { - grid-area: content; - height: 100%; - width: 100% + grid-area: content; + height: 100%; + width: 100%; } #app { - display: grid; - grid-template-columns: 1fr; - grid-template-rows: 72px 1fr; - grid-template-areas: "header" "content"; - width: 100% + display: grid; + grid-template-columns: 1fr; + grid-template-rows: 72px 1fr; + grid-template-areas: "header" "content"; + width: 100%; } a { - color: #4078c0; - text-decoration: none + color: #4078C0; + text-decoration: none; } .flex { - flex: 1 + flex: 1; } -button:focus, -input:focus, -textarea:focus { - outline: 0 +input:focus, button:focus, textarea:focus { + outline: none; } .faq { - max-width: 900px; - margin-left: auto; - margin-right: auto; - margin-bottom: 64px + max-width: 900px; + margin-left: auto; + margin-right: auto; + margin-bottom: 64px; } - .faq #faq { - text-align: center; - font-weight: 500 + text-align: center; + font-weight: 500; } - .faq .question { - margin-bottom: 46px + margin-bottom: 46px; } - .faq table { - border-collapse: collapse + border-collapse: collapse; } - .faq td { - border: 1px solid #dfdfdf; - padding: 8px 12px + border: 1px solid #dfdfdf; + padding: 8px 12px; } -@media (max-width:1100px) { - #app { - grid-template-rows: auto 1fr - } +@media (max-width: 1100px) { + #app { + grid-template-rows: auto 1fr; + } } - .codeblock { - background: #334; - padding: 12px 12px 4px 12px; - max-width: calc(100vw - 56px); - border-radius: 6px; - margin: 0; - color: #c9c5c4; - font-size: 15px; - position: relative; - font-family: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace + background: #333344; + padding: 12px 12px 4px 12px; + max-width: calc(100vw - 56px); + border-radius: 8px; + margin: 0px; + color: #c9c5c4; + font-size: 15px; + position: relative; + font-family: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace; } - .codeblock .play-btn-fixed { - position: absolute; - top: 10px; - right: 10px + position: absolute; + top: 10px; + right: 10px; } - .codeblock pre { - overflow-x: auto; - overflow-y: hidden; - line-height: 1.2; - font-family: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace; - white-space: pre-wrap + overflow-x: auto; + overflow-y: hidden; + line-height: 1.2; + font-family: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace; + white-space: pre-wrap; } - .codeblock textarea { - font-size: 15px; - line-height: 1.2; - font-family: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace; - position: absolute; - top: 25px; - left: 10px; - height: calc(100% - 48px); - width: calc(100% - 22px); - caret-color: #fff; - color: transparent; - background: 0 0; - overflow: hidden; - border: none; - resize: none + font-size: 15px; + line-height: 1.2; + font-family: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace; + position: absolute; + top: 49px; + left: 10px; + height: calc(100% - 48px); + width: calc(100% - 22px); + caret-color: #fff; + color: transparent; + background: transparent; + overflow: hidden; + border: none; + resize: none; } - .codeblock textarea.no-header { - top: 25px + top: 25px; } - .codeblock .titlebar { - display: flex; - align-items: center; - margin-bottom: 6px; - position: relative; - top: -2px + display: flex; + align-items: center; + margin-bottom: 6px; + position: relative; + top: -2px; } - .codeblock .play-btn { - background: 0 0; - border: none; - margin: 0; - background: #ffffff33; - color: #ffeeeecf; - border-radius: 4px; - padding: 4px 12px; - font-size: 12px; - z-index: 10; - cursor: pointer + background: transparent; + border: none; + margin: 0px; + background: rgba(255, 255, 255, 0.2); + color: rgba(255, 238, 238, 0.8117647059); + border-radius: 4px; + padding: 4px 12px; + font-size: 12px; + z-index: 10; + cursor: pointer; } - .codeblock .play-btn svg { - height: 1.1em + height: 1.1em; } - .codeblock .play-btn:hover { - background: #ffffff55; - color: #ffeeeedd + background: rgba(255, 255, 255, 0.3333333333); + color: rgba(255, 238, 238, 0.8666666667); } - .codeblock .keyword { - color: #dcd02d + color: #dcd02d; } - .codeblock .return { - color: #ea3b7b + color: #ea3b7b; } - .codeblock .key { - color: #5f84ba + color: #5f84ba; } - .codeblock .string { - color: #ca763c + color: #ca763c; } - .codeblock .number { - color: #b068e7 + color: #b068e7; } - -.codeblock .comment, -.codeblock .separator { - color: #9e9795 +.codeblock .separator, .codeblock .comment { + color: #9e9795; } - -.codeblock .definition, -.codeblock .type { - color: #c5ac41 +.codeblock .definition, .codeblock .type { + color: #c5ac41; } .documentation { - display: flex; - justify-content: center; - max-width: 1200px; - height: calc(100vh - 72px); - padding-right: 6px; - margin-left: auto; - margin-right: auto; - overflow-y: scroll + display: flex; + justify-content: center; + max-width: 1200px; + height: calc(100vh - 72px); + padding-right: 6px; + margin-left: auto; + margin-right: auto; + overflow-y: scroll; } - .documentation .toc { - margin-right: 32px + margin-right: 32px; } - .documentation .toc ul { - padding-inline-start: 24px + padding-inline-start: 24px; } - .documentation .markdown { - margin-left: 32px; - padding-bottom: 64px; - max-width: calc(100vw - 24px) + margin-left: 32px; + padding-bottom: 64px; + max-width: calc(100vw - 24px); } - -.documentation .markdown h1, -.documentation .markdown h2, -.documentation .markdown h3 { - font-weight: 400 +.documentation .markdown h1, .documentation .markdown h2, .documentation .markdown h3 { + font-weight: normal; } - .documentation .markdown h1 { - margin: 12px 0 + margin: 12px 0px; } - .documentation .markdown h2 { - margin: 32px 0 8px 0 + margin: 32px 0px 8px 0px; } - .documentation .markdown h3 { - margin: 8px 0 + margin: 8px 0px; } - .documentation .markdown a { - word-break: break-word + word-break: break-word; } - .documentation .markdown p { - margin: 8px 0 + margin: 8px 0px; } - .documentation .markdown p code { - background: #eee; - padding: 2px 6px; - border-radius: 5px; - font-size: 14px + background: #eee; + padding: 2px 6px; + border-radius: 5px; + font-size: 14px; } - .documentation .markdown .markdownIt-Anchor { - color: #c3cad6 + color: #c3cad6; } - .documentation .markdown .markdownIt-Anchor:hover { - color: #4078c0 + color: #4078c0; } - .documentation .markdown .codeblock { - margin-bottom: 4px + margin-bottom: 4px; +} + +@media (max-width: 1100px) { + .documentation { + height: calc(100vh - 143px); + } +} +@media (max-width: 845px) { + .documentation { + height: calc(100vh - 154px); + } +} +@media (max-width: 800px) { + .documentation { + flex-direction: column; + align-items: center; + height: 100%; + overflow-y: visible; + padding-right: 0px; + } + .documentation .markdown { + margin-left: 8px; + } + .documentation .toc { + margin-right: 0px; + margin-bottom: 32px; + } } - -@media (max-width:1100px) { - .documentation { - height: calc(100vh - 143px) - } -} - -@media (max-width:845px) { - .documentation { - height: calc(100vh - 154px) - } -} - -@media (max-width:800px) { - .documentation { - flex-direction: column; - align-items: center; - height: 100%; - overflow-y: visible; - padding-right: 0 - } - .documentation .markdown { - margin-left: 8px - } - .documentation .toc { - margin-right: 0; - margin-bottom: 32px - } -} - .header { - grid-area: header; - height: 100%; - width: 100%; - position: sticky; - background: #fff; - z-index: 100; - top: 0; - display: flex; - align-items: center + grid-area: header; + height: 100%; + width: 100%; + position: sticky; + background: #fff; + z-index: 100; + top: 0px; + display: flex; + align-items: center; } - .header .logo { - width: 32px; - margin-bottom: -3px; - margin-right: 16px + width: 32px; + margin-bottom: -3px; + margin-right: 16px; } - .header .donate-button { - display: flex; - /*flex-direction: column;*/ - align-items: center; - margin-top: 2px; - margin-left: 12px + display: flex; + flex-direction: column; + align-items: center; + margin-top: 2px; + margin-left: 12px; } - .header .patreon img { - height: 33px + height: 33px; } - .header .nav { - display: flex; - flex-wrap: wrap; - justify-content: center -} - -.header .nav a:hover { - color:#333; + display: flex; + flex-wrap: wrap; + justify-content: center; } - .header .nav .item { - color: #777; - text-decoration: none; - padding-right: 18px; - padding-left: 18px; - font-size: 22px; - font-weight: 300 + color: #777; + text-decoration: none; + padding-right: 18px; + padding-left: 18px; + font-size: 22px; + font-weight: 300; } - .header .nav .item.active { - color: #222b38 + color: #222b38; +} + +@media (max-width: 1100px) { + .header { + position: static; + flex-direction: column; + } + .header .donate-button { + flex-direction: row; + margin-top: 8px; + margin-left: 0px; + margin-bottom: 8px; + } + .header .donate-button .patreon { + margin-right: 12px; + } + .header .donate-button .paypal { + width: 168px; + height: 33px; + background: #3b7bbf; + margin-bottom: 3px; + border-radius: 3px; + color: #fff; + text-align: center; + line-height: 32px; + font-size: 15px; + } + .header .logo { + width: 42px; + margin-top: 8px; + margin-bottom: 12px; + margin-right: 0px; + } } - - .header .donate-button .paypal { - width: 80px; - height: 33px; - background: #3b7bbf; - margin-bottom: 3px; - border-radius: 3px; - color: #fff; - text-align: center; - line-height: 32px; - font-size: 15px; - margin-left: 10px; - } -@media (max-width:1100px) { - .header { - position: static; - flex-direction: column - } - .header .donate-button { - flex-direction: row; - margin-top: 8px; - margin-left: 0; - margin-bottom: 8px - } - .header .donate-button .patreon { - margin-right: 12px - } - /* - .header .donate-button .paypal { - width: 168px; - height: 33px; - background: #3b7bbf; - margin-bottom: 3px; - margin-left: 10px; - border-radius: 3px; - color: #fff; - text-align: center; - line-height: 32px; - font-size: 15px - } - */ - .header .logo { - width: 42px; - margin-top: 8px; - margin-bottom: 12px; - margin-right: 0 - } -} - .landing .hero { - display: flex; - justify-content: space-evenly; - align-items: center; - width: calc(100% - 32px); - max-width: 1200px; - color: #444; - margin: 32px 0; + display: flex; + justify-content: space-evenly; + align-items: center; + width: calc(100% - 32px); + max-width: 1200px; + color: #444; + margin: 64px 0px; } - .landing .hero .info { - max-width: 500px + max-width: 500px; } - .landing .hero .info h1 { - font-weight: 300; - margin: 0 0 0 -2px + font-weight: 300; + margin: 0px 0px 0px -2px; } - .landing .hero .info p { - margin: 4px 0 + margin: 4px 0px; } - .landing .hero .button { - background: #222; - color: #fff; - margin-top: 16px; - margin-right: 8px; - padding: 7px 14px 6px 8px; - border-radius: 6px; - display: inline-flex; - /*align-items: center;*/ - cursor: pointer; - position: relative + background: #222; + color: #fff; + margin-top: 16px; + margin-right: 8px; + padding: 7px 14px 6px 8px; + border-radius: 6px; + display: inline-flex; + align-items: center; + cursor: pointer; + position: relative; } - .landing .hero .button .svg-inline--fa { - width: 32px; - height: 32px; - margin-right: 4px + width: 32px; + height: 32px; + margin-right: 4px; } - .landing .hero .button .options-container .options { - position: absolute; - background: #fff; - color: #333; - border: 1px solid #eee; - right: 0; - top: 54px; - box-sizing: border-box; - border-radius: 6px; - opacity: 0; - pointer-events: none; - transform: translateY(-12px); - transition: all .2s cubic-bezier(.67, .16, .4, 1) + position: absolute; + background: white; + color: #333; + border: 1px solid #eee; + right: 0px; + top: 54px; + box-sizing: border-box; + border-radius: 6px; + opacity: 0; + pointer-events: none; + transform: translateY(-12px); + transition: all 0.2s cubic-bezier(0.67, 0.16, 0.4, 1); } - .landing .hero .button .options-container .options .dl-option { - display: flex; - padding: 8px 8px 8px 6px; - align-items: center; - color: #333 + display: flex; + padding: 8px 8px 8px 6px; + align-items: center; + color: #333; } - .landing .hero .button .options-container .options .dl-option .name { - flex: 1; - margin-right: 32px + flex: 1; + margin-right: 32px; } - .landing .hero .button .options-container .options .dl-option .size { - color: #818e9c; - font-size: 15px + color: #818e9c; + font-size: 15px; } - .landing .hero .button .options-container .options .dl-option svg { - margin-right: 6px; - width: 22px; - height: 22px + margin-right: 6px; + width: 22px; + height: 22px; } - .landing .hero .button .options-container .options .dl-option:hover { - background: #f7f7f7 + background: #f7f7f7; } - .landing .hero .button .options-container:focus { - outline: 0 + outline: none; } - .landing .hero .button .options-container:focus .options { - opacity: 1; - pointer-events: all; - transform: translateY(0) + opacity: 1; + pointer-events: all; + transform: translateY(0px); } - .landing .hero .button .options-container:active .right-icon { - transform: translateY(3px) + transform: translateY(3px); } - .landing .hero .button .options-container .right-icon { - width: 18px; - padding: 12px 2px; - cursor: pointer; - transition: transform .1s + width: 18px; + padding: 12px 2px; + cursor: pointer; + transition: transform 0.1s; } - .landing .hero .button .text { - display: flex; - flex-direction: column; - margin-right: 10px + display: flex; + flex-direction: column; + margin-right: 10px; } - .landing .hero .button .text .link { - margin: 0 4px 0 8px; - font-size: 15px + margin: 0px 4px 0px 8px; + font-size: 15px; } - .landing .hero .button .text .details { - color: #ddd; - padding: 0 4px; - font-size: 13px; - line-height: 18px; - border-radius: 4px; - margin-left: 5px + color: #ddd; + padding: 0px 4px; + font-size: 13px; + line-height: 18px; + border-radius: 4px; + margin-left: 5px; } - .landing .hero .button .text .details svg { - fill: #ddd; - position: relative; - top: 2px; - left: -1px + fill: #ddd; + position: relative; + top: 2px; + left: -1px; +} +.landing .hero .button .fast, .landing .hero .button .changelog { + position: absolute; + bottom: -24px; + left: 0px; + color: #333; + text-decoration: none; } - -.landing .hero .button .changelog, -.landing .hero .button .fast { - position: absolute; - bottom: -24px; - left: 0; - color: #333; - text-decoration: none -} - .landing .hero .button .changelog { - left: auto; - right: 0 + left: auto; + right: 0px; } - .landing .hero .examples { - margin-right: 32px; - display: flex; - flex-direction: column; - align-items: center; - position:relative; - top: -30px; + margin-right: 32px; + display: flex; + flex-direction: column; + align-items: center; } - -.landing .hero .examples .menu { - margin-top: 12px; - display: flex; - justify-content: center; - align-items: center +.landing .hero .examples .codeblock, .landing .hero .examples .menu { + margin-top: 12px; + display: flex; + justify-content: center; + align-items: center; } - -.landing .hero .examples .menu button { - background: 0 0; - border: none; - cursor: pointer +.landing .hero .examples .codeblock button, .landing .hero .examples .menu button { + background: transparent; + border: none; + cursor: pointer; } - -.landing .hero .examples .menu button i { - font-size: 32px!important; - color: #333 +.landing .hero .examples .codeblock button i, .landing .hero .examples .menu button i { + font-size: 32px !important; + color: #333; } - -.landing .hero .examples .menu select { - font-size: 18px +.landing .hero .examples .codeblock select, .landing .hero .examples .menu select { + font-size: 18px; } - -.landing .hero .examples .menu .select { - margin: 0 16px; - width: 200px +.landing .hero .examples .codeblock .select, .landing .hero .examples .menu .select { + margin: 0px 16px; + width: 200px; } - .landing .social { - margin-top: 16px; - padding: 9px 12px; - border-radius: 6px; - margin-right: 38px; - text-align: center + margin-top: 16px; + padding: 9px 12px; + border-radius: 6px; + margin-right: 38px; + text-align: center; } - .landing .social p { - color: #444 + color: #444; } - .landing .social svg { - font-size: 28px; - margin: 0 12px 0 0; - cursor: pointer; - color: #949fad; - pointer: cursor + font-size: 28px; + margin: 0px 12px 0px 0px; + cursor: pointer; + color: #949fad; + pointer: cursor; } - .landing .social svg:hover { - opacity: .8 + opacity: 0.8; } - .landing .social .fa-telegram { - color: #08c + color: #0088cc; } - .landing .social .fa-youtube { - color: red + color: #ff0000; } - .landing .social .fa-discord { - color: #7289da + color: #7289da; } - .landing .social .fa-twitter { - color: #00acee + color: #00acee; } - .landing .links { - margin-top: 12px; - margin-right: 38px; - display: flex; - flex-direction: row; - flex-wrap: wrap; - justify-content: space-between; - font-size: 18px + margin-top: 12px; + margin-right: 38px; + display: flex; + flex-direction: row; + flex-wrap: wrap; + justify-content: space-between; + font-size: 18px; } - .landing .links a:hover { - opacity: .9 + opacity: 0.9; } .landing { - display: flex; - flex-direction: column; - justify-content: flex-start; - align-items: center; - background: linear-gradient(168deg, #fff 800px, #f6f9fc 800px); - padding-bottom: 32px + display: flex; + flex-direction: column; + justify-content: flex-start; + align-items: center; + background: linear-gradient(168deg, white 800px, #f6f9fc 800px); + padding-bottom: 32px; } - .landing .section { - display: flex; - max-width: 1100px; - width: calc(100vw - 32px); - justify-content: space-around; - margin-top: 32px; - background: #fff; - color: #222; - border-radius: 6px; - border: 1px solid #efefef -} - -.landing .section h1, -.landing .section h2 { - font-weight: 300; - margin: 0 + display: flex; + max-width: 1100px; + width: calc(100vw - 32px); + justify-content: space-around; + margin-top: 32px; + background: #fff; + color: #222; + border-radius: 12px; + border: 1px solid #efefef; +} +.landing .section h2, .landing .section h1 { + font-weight: 300; + margin: 0px; } - .landing .section .block { - flex: 1; - padding: 18px 16px; - margin: 12px; - border-radius: 6px; + flex: 1; + padding: 18px 16px; + margin: 12px; + border-radius: 12px; } - .landing .section .block td { - width: 120px; - line-height: 1.5 + width: 120px; + line-height: 1.5; } - .landing .section .block td .sidenote { - font-size: 75%; - position: relative; - top: -5px + font-size: 75%; + position: relative; + top: -5px; } - .landing .section .block pre { - white-space: pre-wrap; - word-break: break-word + white-space: pre-wrap; + word-break: break-word; } - .landing ul { - padding-inline-start: 22px + padding-inline-start: 22px; } - .landing i { - max-width: calc(100vw - 64px); - text-align: center; - font-size: 14px + max-width: calc(100vw - 64px); + text-align: center; + font-size: 14px; +} + +@media (max-width: 1500px) { + .landing .hero .examples .codeblock { + min-width: auto; + } +} +@media (max-width: 1200px) { + .landing .hero { + margin: 32px 0px; + flex-direction: column; + } + .landing .hero .info { + margin-bottom: 32px; + text-align: center; + } + .landing .hero .info .button { + text-align: left; + } + .landing .hero .info .button:last-child { + margin-right: 0px; + } + .landing .hero .info .links, .landing .hero .info .social { + margin-right: 0px; + } + .landing .hero .info .social { + margin-top: 16px; + } + .landing .hero .info .social i { + font-size: 28px; + margin-left: 6px; + margin-right: 6px; + } + .landing .hero .examples { + margin: 0px 8px 0px 8px !important; + } + .landing .editors { + margin-right: 0px; + } +} +@media (max-width: 750px) { + .landing .section { + flex-direction: column; + } } - -@media (max-width:1500px) { - .landing .hero .examples .codeblock { - min-width: auto - } -} - -@media (max-width:1200px) { - .landing .hero { - margin: 32px 0; - flex-direction: column - } - .landing .hero .info { - margin-bottom: 32px; - text-align: center - } - .landing .hero .info .button { - text-align: left - } - .landing .hero .info .button:last-child { - margin-right: 0 - } - .landing .hero .info .links, - .landing .hero .info .social { - margin-right: 0 - } - .landing .hero .info .social { - margin-top: 16px - } - .landing .hero .info .social i { - font-size: 28px; - margin-left: 6px; - margin-right: 6px - } - .landing .hero .examples { - margin: 0 8px 0 8px!important - } - .landing .editors { - margin-right: 0 - } -} - -@media (max-width:750px) { - .landing .section { - flex-direction: column - } -} - .playground { - display: flex; - flex-direction: column + display: flex; + flex-direction: column; } - .playground .editor { - display: flex; - flex: 1 + display: flex; + flex: 1; } - -.playground .editor .codeblock, -.playground .editor .output { - flex: 1; - margin: 6px +.playground .editor .codeblock, .playground .editor .output { + flex: 1; + margin: 6px; } - .playground .select { - margin-left: 8px; - width: 220px + margin-left: 8px; + width: 220px; } -@media (max-width:1100px) { - .playground .editor { - flex-direction: column - } - .playground .editor .codeblock { - max-width: calc(100vw - 36px) - } +@media (max-width: 1100px) { + .playground .editor { + flex-direction: column; + } + .playground .editor .codeblock { + max-width: calc(100vw - 36px); + } } - .editors-info { - max-width: 600px; - text-align: center; - margin-right: auto; - margin-left: auto; - margin-top: 32px + max-width: 600px; + text-align: center; + margin-right: auto; + margin-left: auto; + margin-top: 32px; } - .editors-info h1 { - font-weight: 300; - margin: 0 0 0 -2px + font-weight: 300; + margin: 0 0 0 -2px; } - .editors-info p { - margin: 4px 0 + margin: 4px 0; } .editors { - display: flex; - justify-content: space-evenly; - width: calc(100vw - 32px); - max-width: 600px; - margin-top: 32px; - margin-right: auto; - margin-left: auto; - flex-wrap: wrap + display: flex; + justify-content: space-evenly; + width: calc(100vw - 32px); + max-width: 600px; + margin-top: 32px; + margin-right: auto; + margin-left: auto; + flex-wrap: wrap; } - .editors .editor { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - background: #fff; - color: #000; - height: 100px; - width: 125px; - border: 1px solid #efefef; - border-radius: 6px; - text-decoration: none; - box-shadow: none; - cursor: pointer; - margin-bottom: 16px; - transition: transform .1s, box-shadow .1s + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + background: #fff; + color: #000; + height: 100px; + width: 125px; + border: 1px solid #efefef; + border-radius: 12px; + text-decoration: none; + box-shadow: none; + cursor: pointer; + margin-bottom: 16px; + transition: transform 0.1s, box-shadow 0.1s; } - .editors .editor:hover { - transform: translateY(-3px); - box-shadow: 0 6px 8px 0 rgba(0, 0, 0, .05), 0 16px 32px -2px rgba(0, 0, 0, .05) + transform: translateY(-3px); + box-shadow: 0 6px 8px 0px rgba(0, 0, 0, 0.05), 0 16px 32px -2px rgba(0, 0, 0, 0.05); } - .editors .editor img { - flex: 0; - height: 42px; - margin-bottom: 6px + flex: 0; + height: 42px; + margin-bottom: 6px; } .built-in-v { - display: grid; - grid-template-columns: 1fr 1fr; - grid-auto-flow: row dense; - margin-top: 16px + display: grid; + grid-template-columns: 1fr 1fr; + grid-auto-flow: row dense; + margin-top: 16px; } - -.built-in-v .first, -.built-in-v .second { - padding-bottom: 16px +.built-in-v .first, .built-in-v .second { + padding-bottom: 16px; } - .built-in-v .first { - grid-column-start: 1; - padding-right: 70px + grid-column-start: 1; + padding-right: 70px; } - .built-in-v .second { - grid-column-start: 2 -} - -@media (max-width:750px) { - .built-in-v { - grid-template-columns: 1fr - } - .built-in-v .first, - .built-in-v .second { - grid-column-start: 1 - } + grid-column-start: 2; } -.landing .hero .button .options-container .options:focus, .landing .hero .button .options-container .options:hover { - opacity: 1; - pointer-events: all !important; - transform: translateY(0) +@media (max-width: 750px) { + .built-in-v { + grid-template-columns: 1fr; + } + .built-in-v .first, .built-in-v .second { + grid-column-start: 1; + } } .book { -position:absolute; right:0px; top:50px; text-align:center; display:block; width:155px; font-size:12px; + position: absolute; + right: 0px; + top: 50px; + text-align: center; + display: block; + max-width: 155px; + font-size: 12px; } -@media (max-width:800px) { -.book { - display:none; -} -} -.news { - font-size: 80%; - margin-top: 0 !important; - flex-direction: column; -} -.news .container { - display: flex -} -.news_header{ - text-align:center; - padding-top: 1rem; -} -.news_date { - font-weight: bold; +@media (max-width: 1380px) { + .book { + display: none; + } } -.text-center { - text-align: center; -} \ No newline at end of file +/*# sourceMappingURL=app.css.map */ diff --git a/app.css.map b/app.css.map new file mode 100755 index 000000000..e9f77e071 --- /dev/null +++ b/app.css.map @@ -0,0 +1 @@ +{"version":3,"sourceRoot":"","sources":["app.sass","styles/codeblock.sass","styles/documentation.sass","styles/header.sass","styles/hero.sass","styles/download-button.sass","styles/landing.sass","styles/playground.sass","styles/editors.sass","styles/built-in-v.sass"],"names":[],"mappings":"AAiDQ;AASA;AAxDR;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;EACA;;;AAEF;EACE;EACA;EACA;EACA;EACA;;;AAEF;EACE;EACA;;;AACF;EACE;;;AAEF;EACE;;;AAEF;EACE;EACA;EACA;EACA;;AACA;EACE;EACA;;AACF;EACE;;AACF;EACE;;AACF;EACE;EACA;;;AACJ;EACE;IACE;;;AC9CJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,aAVU;;AAYV;EACE;EACA;EACA;;AAEF;EACE;EACA;EACA;EACA,aArBQ;EAsBR;;AAEF;EACE;EACA;EACA,aA3BQ;EA4BR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AACJ;EACE;EACA;EACA;EACA;EACA;;AACF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AACF;EACE;EACA;;AAEJ;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;;AC7EJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AACA;EACE;;AACJ;EACE;EACA;EACA;;AACA;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACA;EACE;EACA;EACA;EACA;;AACJ;EACE;;AACA;EACE;;AACJ;EACE;;;AAEN;EACE;IACE;;;AAEJ;EACE;IACE;;;AAEJ;EACE;IACE;IACA;IACA;IACA;IACA;;EACA;IACE;;EACF;IACE;IACA;;;AC1DN;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;;AAEF;EACE;EACA;EACA;EACA;EACA;;AAEF;EACE;;AAEF;EACE;EACA;EACA;;AACA;EACE;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;;AAER;EACE;IACE;IACA;;EACA;IACE;IACA;IACA;IACA;;EACA;IACE;;EACF;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EACJ;IACE;IACA;IACA;IACA;;;AClEJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AACA;EACE;EACA;;AACF;EACE;;ACfR;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;EACA;;AAEA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;EACA;EACA;;AACA;EACE;EACA;;AACF;EACE;EACA;;AACF;EACE;EACA;EACA;;AACF;EACE;;AACN;EACE;;AACA;EACE;EACA;EACA;;AAEF;EACE;;AACJ;EACE;EACA;EACA;EACA;;AAEJ;EACE;EACA;EACA;;AACA;EACE;EACA;;AACF;EACE;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;EACA;EACA;;AAEN;EACE;EACA;EACA;EACA;EACA;;AAEF;EACE;EACA;;ADvEA;EACE;EACA;EACA;EACA;;AACA;EACE;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;;AACA;EACE;EACA;;AAEJ;EACE;;AACF;EACE;EACA;;AACR;EACE;EACA;EACA;EACA;EACA;;AACA;EACE;;AACF;EACE;EACA;EACA;EACA;EACA;;AACA;EACE;;AACJ;EACE;;AACF;EACE;;AACF;EACE;;AACF;EACE;;AACJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AAEE;EACE;;;AE7ER;EACE;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;;AACF;EACE;EACA;EACA;EACA;;AACA;EACE;EACA;;AACA;EACE;EACA;EACA;;AACJ;EACE;EACA;;AACN;EACE;;AACF;EACE;EACA;EACA;;;AAGJ;EAIQ;IACE;;;AAEV;EAEI;IACE;IACA;;EACA;IACE;IACA;;EACA;IACE;;EACA;IACE;;EACJ;IACE;;EACF;IACE;;EACA;IACE;IACA;IACA;;EACN;IACE;;EACJ;IACE;;;AAEN;EAEI;IACE;;;AC9EN;EACE;EACA;;AACA;EACE;EACA;;AACA;EACE;EACA;;AACJ;EACE;EACA;;;AACJ;EAEI;IACE;;EACA;IACE;;;ACjBR;EACE;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;;AACF;EACE;;;AACJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;EACA;;AACF;EACE;EACA;EACA;;;AC1CN;EACE;EACA;EACA;EACA;;AACA;EACE;;AACF;EACE;EACA;;AACF;EACE;;;AAEJ;EACE;IACE;;EACA;IACE;;;AT2CN;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGJ;EACI;IACI","file":"app.css"} \ No newline at end of file diff --git a/app.sass b/app.sass new file mode 100755 index 000000000..a1772cd26 --- /dev/null +++ b/app.sass @@ -0,0 +1,65 @@ +$small-screen-width: 1135px + +body, html + height: 100% + +body + margin: 0px + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif + +.content + grid-area: content + height: 100% + width: 100% + +#app + display: grid + grid-template-columns: 1fr + grid-template-rows: 72px 1fr + grid-template-areas: "header" "content" + width: 100% + +a + color: #4078C0 + text-decoration: none + +.flex + flex: 1 + +input:focus, button:focus, textarea:focus + outline: none + +.faq + max-width: 900px + margin-left: auto + margin-right: auto + margin-bottom: 64px + #faq + text-align: center + font-weight: 500 + .question + margin-bottom: 46px + table + border-collapse: collapse + td + border: 1px solid #dfdfdf + padding: 8px 12px +@media (max-width: $small-screen-width) + #app + grid-template-rows: auto 1fr + +#overflowing + word-wrap: break-word + +@import "./styles/customselect.css" +@import "./styles/codeblock.sass" +@import "./styles/documentation.sass" +@import "./styles/header.sass" +@import "./styles/hero.sass" +@import "./styles/landing.sass" +@import "./styles/playground.sass" +@import "./styles/editors.sass" +@import "./styles/built-in-v.sass" +@import "./styles/icons.css" +@import "./styles/news.sass" +@import "./styles/book.sass" \ No newline at end of file diff --git a/build-pages.js b/build-pages.js new file mode 100755 index 000000000..58af1c609 --- /dev/null +++ b/build-pages.js @@ -0,0 +1,94 @@ +const nunjucks = require("nunjucks") +const sass = require('sass') +const NCP = require('ncp') +const CleanCSS = require('clean-css') +const fetch = require('node-fetch') +const mdtoc = require('markdown-toc') +const { promisify } = require('util') +const path = require("path") +const fs = require("fs") +const mkdir = promisify(fs.mkdir) +const rmdir = promisify(fs.rm) +const writeFile = promisify(fs.writeFile) +const renderSass = promisify(sass.render) +const ncp = promisify(NCP.ncp) + +const pages = [ + 'index', + 'compare' + //'docs' + //'play', + //'modules', + //'editors', + // 'faq' + +] + +async function compile() { //this is supposed to build docs but it doesnt work at line 79 + /*console.log('Building docs') + + console.log('Setting up MD parser') + var md = require('markdown-it')({}) + .use(require('markdown-it-toc-and-anchor').default, { slugify: require('uslug') }) + md.renderer.rules.fence = function(tokens, idx) { + let code = tokens[idx].content + .replace(/\n/g, '\\n') + .replace(/"/g, '\\"') + if (code.endsWith('\\n')) code = code.slice(0, -2) + return `{% set code = "${code}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %}\n` + } + + console.log('Fetching MD from github') + let docsMD = await fetch('https://raw.githubusercontent.com/vlang/v/master/doc/docs.md') + + console.log('Building NJK from MD') + docsMD = await docsMD.text() + let docs = md.render(docsMD) + await writeFile('./pages/docs/content.njk', docs) + + console.log('Generating TOC') + let toc = mdtoc(docsMD, { slugify: require('uslug') }).content + console.log('Building NJK from MD TOC') + toc = md.render(toc) + await writeFile('./pages/docs/toc.njk', toc) */ + + console.log('Fetching lastest release') + let release = await fetch('https://api.github.com/repos/vlang/v/releases/latest') + release = await release.json() + let win = release.assets.find(r => r.name === 'v_windows.zip') + let lin = release.assets.find(r => r.name === 'v_linux.zip') + let mac = release.assets.find(r => r.name === 'v_macos.zip') + let versions = `{% set lin_size = "${Math.round((lin.size / 1024 / 1024)*10)/10}MB" %} + {% set mac_size = "${Math.round((mac.size / 1024 / 1024)*10)/10}MB" %} + {% set win_size = "${Math.round((win.size / 1024 / 1024)*10)/10}MB" %} + {% set version = "${release.name}" %}` + await writeFile('./pages/home/download-versions.njk', versions) + console.log('Building pages') + let buildDir = "./build" + await fs.rmSync(buildDir, { recursive: true, force: true }); + console.log('Deleting old build folder if exists') + await fs.promises.mkdir(buildDir, { recursive: true }) + console.log('Creating new build folder') + await Promise.all( + pages.map(page => + writeFile( + path.join(buildDir, page + ".html"), + nunjucks.render(path.join("./pages", page + ".njk")), // this doesnt work for docs.njk + err => err && console.error(err) + ) + ) + ) + console.log('Building sass') + let app_sass = await renderSass({ file: './app.sass' }) + let clean_css = new CleanCSS({}).minify(app_sass.css.toString()) + await writeFile("./build/app.css", clean_css.styles, 'utf8') + console.log('Copying res') + ncp('./res', './build') + console.log('Building successfully finished!') + console.log('Serving page on localhost:3000 via serve cause of "&& serve build/" from line 23 of package.json') +} + +compile() \ No newline at end of file diff --git a/build/app.css b/build/app.css new file mode 100644 index 000000000..fa64f5021 --- /dev/null +++ b/build/app.css @@ -0,0 +1 @@ +.select{position:relative;display:inline-block;width:100%}.select select{font-size:14px;display:inline-block;width:100%;cursor:pointer;padding:10px 15px;outline:0;border:none;border-radius:8px;overflow:hidden;background:#334;color:#ccc;appearance:none;-webkit-appearance:none;-moz-appearance:none}.select select::-ms-expand{display:none}.select select:focus,.select select:hover{color:#ddd;background:#445}.select select:disabled{opacity:.5;pointer-events:none}.select_arrow{position:absolute;pointer-events:none;top:12px;right:15px;width:0;height:0;border:solid #aaa;border-width:0 3px 3px 0;display:inline-block;padding:3px;transform:rotate(45deg);-webkit-transform:rotate(45deg)}.select select:focus~.select_arrow,.select select:hover~.select_arrow{border-color:#ccc}.select select:disabled~.select_arrow{border-top-color:#ccc}.svg-inline--fa{display:inline-block;font-size:inherit;height:1em;overflow:visible;vertical-align:-.125em}.svg-inline--fa.fa-w-14{width:.875em}body,html{height:100%}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Helvetica,Arial,sans-serif}.content{grid-area:content;height:100%;width:100%}#app{display:grid;grid-template-columns:1fr;grid-template-rows:72px 1fr;grid-template-areas:"header" "content";width:100%}a{color:#4078c0;text-decoration:none}.flex{flex:1}button:focus,input:focus,textarea:focus{outline:0}.faq{max-width:900px;margin-left:auto;margin-right:auto;margin-bottom:64px}.faq #faq{text-align:center;font-weight:500}.faq .question{margin-bottom:46px}.faq table{border-collapse:collapse}.faq td{border:1px solid #dfdfdf;padding:8px 12px}@media (max-width:1135px){#app{grid-template-rows:auto 1fr}}#overflowing{word-wrap:break-word}.codeblock{background:#334;padding:12px 12px 4px 12px;max-width:calc(100vw - 56px);border-radius:8px;margin:0;color:#c9c5c4;font-size:15px;position:relative;font-family:"Roboto Mono","Courier New",Menlo,"DejaVu Sans Mono",Monaco,Courier,monospace}.codeblock .play-btn-fixed{position:absolute;top:10px;right:10px}.codeblock pre{overflow-x:auto;overflow-y:hidden;line-height:1.2;font-family:"Roboto Mono","Courier New",Menlo,"DejaVu Sans Mono",Monaco,Courier,monospace;white-space:pre-wrap}.codeblock textarea{font-size:15px;line-height:1.2;font-family:"Roboto Mono","Courier New",Menlo,"DejaVu Sans Mono",Monaco,Courier,monospace;position:absolute;top:49px;left:10px;height:calc(100% - 48px);width:calc(100% - 22px);caret-color:#fff;color:transparent;background:0 0;overflow:hidden;border:none;resize:none}.codeblock textarea.no-header{top:25px}.codeblock .titlebar{display:flex;align-items:center;margin-bottom:6px;position:relative;top:-2px}.codeblock .play-btn{background:0 0;border:none;margin:0;background:rgba(255,255,255,.2);color:rgba(255,238,238,.8117647059);border-radius:4px;padding:4px 12px;font-size:12px;z-index:10;cursor:pointer}.codeblock .play-btn svg{height:1.1em}.codeblock .play-btn:hover{background:rgba(255,255,255,.3333333333);color:rgba(255,238,238,.8666666667)}.codeblock .keyword{color:#dcd02d}.codeblock .return{color:#ea3b7b}.codeblock .key{color:#5f84ba}.codeblock .string{color:#ca763c}.codeblock .number{color:#b068e7}.codeblock .comment,.codeblock .separator{color:#9e9795}.codeblock .definition,.codeblock .type{color:#c5ac41}.documentation{display:flex;justify-content:center;max-width:1200px;height:calc(100vh - 72px);padding-right:6px;margin-left:auto;margin-right:auto;overflow-y:scroll}.documentation .toc{margin-right:32px}.documentation .toc ul{padding-inline-start:24px}.documentation .markdown{margin-left:32px;padding-bottom:64px;max-width:calc(100vw - 24px)}.documentation .markdown h1,.documentation .markdown h2,.documentation .markdown h3{font-weight:400}.documentation .markdown h1{margin:12px 0}.documentation .markdown h2{margin:32px 0 8px 0}.documentation .markdown h3{margin:8px 0}.documentation .markdown a{word-break:break-word}.documentation .markdown p{margin:8px 0}.documentation .markdown p code{background:#eee;padding:2px 6px;border-radius:5px;font-size:14px}.documentation .markdown .markdownIt-Anchor{color:#c3cad6}.documentation .markdown .markdownIt-Anchor:hover{color:#4078c0}.documentation .markdown .codeblock{margin-bottom:4px}@media (max-width:1100px){.documentation{height:calc(100vh - 143px)}}@media (max-width:845px){.documentation{height:calc(100vh - 154px)}}@media (max-width:800px){.documentation{flex-direction:column;align-items:center;height:100%;overflow-y:visible;padding-right:0}.documentation .markdown{margin-left:8px}.documentation .toc{margin-right:0;margin-bottom:32px}}.header{grid-area:header;height:100%;width:100%;position:sticky;background:#fff;z-index:100;top:0;display:flex;align-items:center}.header .logo{width:32px;margin-bottom:-3px;margin-right:16px;margin-left:16px}.header .nav{display:flex;flex-wrap:wrap;justify-content:center}.header .nav .item{color:#777;text-decoration:none;padding-right:18px;padding-left:18px;font-size:22px;font-weight:300}.header .nav .item.active{color:#222b38}.header .donate-button{display:flex;align-items:center;margin-top:2px;margin-left:12px}.header .donate-button .patreon img{width:168px;height:33px;margin-left:10px}.header .donate-button .paypal{width:80px;height:33px;background:#3b7bbf;margin-bottom:3px;border-radius:3px;color:#fff;text-align:center;line-height:32px;font-size:15px;margin-left:10px}.header .donate-button .github{width:80px;height:33px;background:#3b7bbf;margin-bottom:3px;border-radius:3px;color:#fff;text-align:center;line-height:32px;font-size:15px;margin-left:10px}@media (max-width:1100px){.header{position:static;flex-direction:column}.header .donate-button{flex-direction:row;margin-top:8px;margin-left:0;margin-bottom:8px}.header .donate-button .patreon{margin-right:12px}.header .donate-button .paypal{width:168px;height:33px;background:#3b7bbf;margin-bottom:3px;border-radius:3px;color:#fff;text-align:center;line-height:32px;font-size:15px}.header .donate-button .github{width:168px;height:33px;background:#3b7bbf;margin-bottom:3px;border-radius:3px;color:#fff;text-align:center;line-height:32px;font-size:15px}.header .logo{width:42px;margin-top:8px;margin-bottom:12px;margin-right:0}}.landing .hero{display:flex;justify-content:space-evenly;align-items:center;width:calc(100% - 32px);max-width:1200px;color:#444;margin:34px 0}.landing .hero .info{max-width:500px}.landing .hero .info h1{font-weight:300;margin:0 0 0 -2px}.landing .hero .info p{margin:4px 0}.landing .hero .info .button{align-items:normal}.landing .hero .button{background:#222;color:#fff;margin-top:16px;margin-right:8px;padding:7px 14px 6px 8px;border-radius:6px;display:inline-flex;align-items:center;cursor:pointer;position:relative}.landing .hero .button .svg-inline--fa{width:32px;height:32px;margin-right:4px}.landing .hero .button .options-container .options{position:absolute;background:#fff;color:#333;border:1px solid #eee;right:0;top:54px;box-sizing:border-box;border-radius:6px;opacity:0;transform:translateY(-12px);transition:all .2s cubic-bezier(.67,.16,.4,1)}.landing .hero .button .options-container .options .dl-option{display:flex;padding:8px 8px 8px 6px;align-items:center;color:#333}.landing .hero .button .options-container .options .dl-option .name{flex:1;margin-right:32px}.landing .hero .button .options-container .options .dl-option .size{color:#818e9c;font-size:15px}.landing .hero .button .options-container .options .dl-option svg{margin-right:6px;width:22px;height:22px}.landing .hero .button .options-container .options .dl-option:hover{background:#f7f7f7}.landing .hero .button .options-container:focus{outline:0}.landing .hero .button .options-container:focus .options{opacity:1;pointer-events:all;transform:translateY(0)}.landing .hero .button .options-container:active .right-icon{transform:translateY(3px)}.landing .hero .button .options-container .right-icon{width:18px;padding:12px 2px;cursor:pointer;transition:transform .1s}.landing .hero .button .text{display:flex;flex-direction:column;margin-right:10px}.landing .hero .button .text .link{margin:0 4px 0 8px;font-size:15px}.landing .hero .button .text .details{color:#ddd;padding:0 4px;font-size:13px;line-height:18px;border-radius:4px;margin-left:5px}.landing .hero .button .text .details svg{fill:#ddd;position:relative;top:2px;left:-1px}.landing .hero .button .changelog,.landing .hero .button .fast{position:absolute;bottom:-24px;left:0;color:#333;text-decoration:none}.landing .hero .button .changelog{left:auto;right:0}.landing .hero .examples{margin-right:32px;display:flex;flex-direction:column;align-items:center}.landing .hero .examples .codeblock,.landing .hero .examples .menu{margin-top:12px;display:flex;justify-content:center;align-items:center}.landing .hero .examples .codeblock button,.landing .hero .examples .menu button{background:0 0;border:none;cursor:pointer}.landing .hero .examples .codeblock button i,.landing .hero .examples .menu button i{font-size:32px!important;color:#333}.landing .hero .examples .codeblock select,.landing .hero .examples .menu select{font-size:18px}.landing .hero .examples .codeblock .select,.landing .hero .examples .menu .select{margin:0 16px;width:200px}.landing .social{margin-top:16px;padding:9px 12px;border-radius:6px;margin-right:38px;text-align:center}.landing .social p{color:#444}.landing .social svg{font-size:28px;margin:0 12px 0 0;cursor:pointer;color:#949fad;pointer:cursor}.landing .social svg:hover{opacity:.8}.landing .social .fa-telegram{color:#08c}.landing .social .fa-youtube{color:red}.landing .social .fa-discord{color:#7289da}.landing .social .fa-twitter{color:#00acee}.landing .links{margin-top:12px;margin-right:38px;margin-left:10px;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:space-between;font-size:18px}.landing .links a:hover{opacity:.9}.landing{display:flex;flex-direction:column;justify-content:flex-start;align-items:center;background:linear-gradient(168deg,#fff 800px,#f6f9fc 800px);padding-bottom:32px}.landing .section{display:flex;max-width:1100px;width:calc(100vw - 32px);justify-content:space-around;margin-top:32px;background:#fff;color:#222;border-radius:12px;border:1px solid #efefef}.landing .section h1,.landing .section h2{font-weight:300;margin:0}.landing .section .block{flex:1;padding:18px 16px;margin:12px;border-radius:12px}.landing .section .block td{width:120px;line-height:1.5}.landing .section .block td .sidenote{font-size:75%;position:relative;top:-5px}.landing .section .block pre{white-space:pre-wrap;word-break:break-word}.landing .section img{max-width:100%}.landing .section code{overflow-wrap:break-word}.landing .section a{overflow-wrap:break-word}.landing ul{padding-inline-start:22px}.landing i{max-width:calc(100vw - 64px);text-align:center;font-size:14px}@media (max-width:1500px){.landing .hero .examples .codeblock{min-width:auto}}@media (max-width:1380px){.landing .hero{margin:32px 0;flex-direction:column}.landing .hero .info{margin-bottom:32px;text-align:center}.landing .hero .info .button{text-align:left}.landing .hero .info .button:last-child{margin-right:0}.landing .hero .info .links,.landing .hero .info .social{margin-right:12px}.landing .hero .info .social{margin-top:16px}.landing .hero .info .social i{font-size:28px;margin-left:6px;margin-right:6px}.landing .hero .examples{margin:0 8px 0 8px!important}.landing .editors{margin-right:0}}@media (max-width:750px){.landing .section{flex-direction:column}}.playground{display:flex;flex-direction:column}.playground .editor{display:flex;flex:1}.playground .editor .codeblock,.playground .editor .output{flex:1;margin:6px}.playground .select{margin-left:8px;width:220px}@media (max-width:1100px){.playground .editor{flex-direction:column}.playground .editor .codeblock{max-width:calc(100vw - 36px)}}.editors-info{max-width:600px;text-align:center;margin-right:auto;margin-left:auto;margin-top:32px}.editors-info h1{font-weight:300;margin:0 0 0 -2px}.editors-info p{margin:4px 0}.editors{display:flex;justify-content:space-evenly;width:calc(100vw - 32px);max-width:600px;margin-top:32px;margin-right:auto;margin-left:auto;flex-wrap:wrap}.editors .editor{display:flex;flex-direction:column;align-items:center;justify-content:center;background:#fff;color:#000;height:100px;width:125px;border:1px solid #efefef;border-radius:12px;text-decoration:none;box-shadow:none;cursor:pointer;margin-bottom:16px;transition:transform .1s,box-shadow .1s}.editors .editor:hover{transform:translateY(-3px);box-shadow:0 6px 8px 0 rgba(0,0,0,.05),0 16px 32px -2px rgba(0,0,0,.05)}.editors .editor img{flex:0;height:42px;margin-bottom:6px}.built-in-v{display:grid;grid-template-columns:1fr 1fr;grid-auto-flow:row dense;margin-top:16px}.built-in-v .first,.built-in-v .second{padding-bottom:16px}.built-in-v .first{grid-column-start:1;padding-right:70px}.built-in-v .second{grid-column-start:2}@media (max-width:750px){.built-in-v{grid-template-columns:1fr}.built-in-v .first,.built-in-v .second{grid-column-start:1}}.left:hover{cursor:pointer}.right:hover{cursor:pointer}.news{font-size:80%;margin-top:0!important;flex-direction:column}.news .container{display:flex;overflow-x:auto;scroll-behavior:smooth;-webkit-overflow-scrolling:touch}.news .block{min-width:89.5px}.news_header{text-align:center;padding-top:1rem}.news_date{font-weight:700}.text-center{text-align:center}@media (max-width:920px){.news .container{flex-direction:column}.left{display:none}.right{display:none}}.left{position:absolute;left:5px;top:50%;transform:translateY(-50%);height:180px;width:35px}.right{position:absolute;right:5px;top:50%;transform:translateY(-50%);height:180px;width:35px}.actual_news{padding:0 40px;position:relative}.book{position:absolute;right:0;text-align:center;display:block;max-width:155px;font-size:12px}@media (max-width:825px){.book{display:none}} \ No newline at end of file diff --git a/build/compare.html b/build/compare.html new file mode 100644 index 000000000..4a620b2bf --- /dev/null +++ b/build/compare.html @@ -0,0 +1,457 @@ + + + + + + + + + + + + + The V Comparison + + +
+ + +
+
+

Comparison of V and other languages

+

+V was created because none of the existing languages had all of the following +features: +

+ +
Fast compilation D, Go, Delphi +
Simplicity & maintainabilityGo +
Great performance on par with C and
zero cost C interop
C, C++, D, Delphi, Rust +
Safety (immutability, no null, option types, free from data races) Rust +
Easy concurrency Go +
Easy cross compilationGo +
Compile time code generationD +
Small compiler with zero dependencies- +
No global state- +
Hot code reloadingC# (.NET 6+), Dart +
+

+Initially I was going to compare V to all major languages, but it got repetitive pretty quickly. +

+

+The table above and the list of the features on the home page should give you a pretty good picture. +

+

+For example, it's pretty obvious that compared to C++, V is much simpler. It offers significantly faster compilation speed, +safety, lack of undefined behavior, easy concurrency, compile time code generation, etc. +

+

+Compared to Python, it's much faster, simpler, safer, more maintainable, etc. +

+

+You can use this formula for any language. +

+

+Syntax comparison: +

+

+V for Go developers +

+

+V for C++ developers +

+

+Since V is very similar to Go, and its domain is similar to Rust's, I left a comparison with these two languages. +

+

Go

+

+V is very similar to Go, and these are the things it improves upon: +

+

+— No err != nil checks (replaced by result types) +

+

+— No undefined values +

+

+— No variable shadowing +

+

+— Immutability by default +

+

+— Enums +

+

+— Sum types (type Expr = IfExpr | StringLiteral | IntLiteral | ...) +

+

+— String interpolation: println('$foo: $bar.baz') +

+

+— If and match expressions (including sum type matches) +

+

+— No global state (globals can be enabled for low level applications like kernels via a command line flag)
+

+

+— A simple way to check whether an array contains an element: if elem in arr {. +

+— Only one declaration style: a := 0 +

+

+— Warnings for unused imports and vars for quicker development without annoying +interruptions. But only in development/debugging mode. +
+Making a production build still requires fixing all of them, thus enforcing +clean code. +

+— Much smaller runtime +

+

+— Much smaller binaries (a simple web server written in V is 65 KB vs 7 MB in Go) +

+

+— Zero cost C interop +

+

+— GC is optional +

+

+— Much faster serialization using codegen and no runtime reflection +

+

+— Precompiled text and HTML templates unlike Go's html/templates that have to be parsed on every request +

+

+— Fearless concurrency (no data race guarantee at compilation) wip +

+

+— No null (null is only allowed in unsafe code) +

+

+— Stricter vfmt to ensure one coding style +

+

+— Centralized package manager: vpm.vlang.io (v install ...) +

+

+— Much simpler and less verbose testing, assert. +

+

+— Primitive types can have methods resulting in less verbose code: strings.Replace(strings.Replace(s, "a", "A", -1), "b", "B", -1) => +
s.replace('a', 'A').replace('b', 'B') +

+

+
+

Rust

+Rust has a very different philosophy. +

+It is a complex language with a growing set of features and a steep learning curve. No doubt, once you learn and understand the language, +it becomes a very powerful tool for developing safe, fast, and stable software. But the complexity is +still there. +

+

+V's goal is to allow building maintainable and predictable software. That's why the language +is so simple and maybe even boring for some. The good thing is, you can jump into any part of the project +and understand what's going on, feel like it was you who wrote it, because the language is simple and +there's only one way of doing things. +

+

+Rust's compilation speed is slow, on par with C++. V compiles 1.2 million lines of code per cpu per second. +

+
+

V vs Rust vs Go: Example

+

+Since V's domain is close to both Go and Rust, I decided to use a simple example to compare the three. +

+

+It's a simple program that fetches top Hacker News stories concurrently. +

+

+Rust +

+
use serde::Deserialize;
+use std::sync::{Arc, Mutex};
+
+const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
+const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
+
+#[derive(Deserialize)]
+struct Story {
+    title: String,
+}
+
+fn main() {
+    let story_ids: Arc<Vec<u64>> = Arc::new(reqwest::get(STORIES_URL).unwrap().json().unwrap());
+    let cursor = Arc::new(Mutex::new(0));
+    let mut handles = Vec::new();
+    for _ in 0..8 {
+        let cursor = cursor.clone();
+        let story_ids = story_ids.clone();
+        handles.push(std::thread::spawn(move || loop {
+            let index = {
+                let mut cursor_guard = cursor.lock().unwrap();
+                let index = *cursor_guard;
+                if index >= story_ids.len() {
+                    return;
+                }
+                *cursor_guard += 1;
+                index
+            };
+            let story_url = format!("{}/{}.json", ITEM_URL_BASE, story_ids[index]);
+            let story: Story = reqwest::get(&story_url).unwrap().json().unwrap();
+            println!("{}", story.title);
+        }));
+    }
+    for handle in handles {
+        handle.join().unwrap();
+    }
+}
+
+Go +
package main
+
+import (
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"sync"
+)
+
+const STORIES_URL = "https://hacker-news.firebaseio.com/v0/topstories.json"
+const ITEM_URL_BASE = "https://hacker-news.firebaseio.com/v0/item"
+
+type Story struct {
+	Title string
+}
+
+func main() {
+	rsp, err := http.Get(STORIES_URL)
+	if err != nil {
+		panic(err)
+	}
+	defer rsp.Body.Close()
+	data, err := ioutil.ReadAll(rsp.Body)
+	if err != nil {
+		panic(err)
+	}
+	var ids []int
+	if err := json.Unmarshal(data, &ids); err != nil {
+		panic(err)
+	}
+	var cursor int
+	var mutex sync.Mutex
+	next := func() int {
+		mutex.Lock()
+		defer mutex.Unlock()
+		temp := cursor
+		cursor++
+		return temp
+	}
+	wg := sync.WaitGroup{}
+	for i := 0; i < 8; i++ {
+		wg.Add(1)
+		go func() {
+			for cursor := next(); cursor < len(ids); cursor = next() {
+				url := fmt.Sprintf(
+					"%s/%d.json",
+					ITEM_URL_BASE,
+					ids[cursor],
+				)
+				rsp, err := http.Get(url)
+				if err != nil {
+					panic(err)
+				}
+				defer rsp.Body.Close()
+
+				data, err := ioutil.ReadAll(rsp.Body)
+				if err != nil {
+					panic(err)
+				}
+				var story Story
+				if err := json.Unmarshal(data, &story); err != nil {
+					panic(err)
+				}
+				fmt.Println(story.Title)
+			}
+			wg.Done()
+		}()
+	}
+	wg.Wait()
+}
+
+V +
import net.http
+import json
+
+const (
+	stories_url   = 'https://hacker-news.firebaseio.com/v0/topstories.json'
+	item_base_url = 'https://hacker-news.firebaseio.com/v0/item'
+)
+
+struct Story {
+	title string
+}
+
+struct Cursor {
+mut:
+	pos int
+}
+
+fn main() {
+	resp := http.get(stories_url) ?
+	ids := json.decode([]int, resp.text) ?
+	shared cursor := Cursor{}
+	mut threads := []thread{}
+
+	for _ in 0 .. 8 {
+		threads << go fn (ids []int, shared cursor Cursor) {
+			for {
+				id := lock cursor {
+					if cursor.pos >= ids.len {
+						break
+					}
+					cursor.pos++
+					ids[cursor.pos - 1]
+				}
+				resp := http.get('$item_base_url/${id}.json') or { panic(err) }
+				story := json.decode(Story, resp.text) or { panic(err) }
+				println(story.title)
+			}
+		}(ids, shared cursor)
+	}
+	threads.wait()
+}
+
+Nim +

+V and Nim are very different. One of V's main philosophies is "there must be only one way of doing things". +This results in predictable, simple, and maintainable code. +

+

+Nim gives a lot of options and freedom to developers. For example, in V you would write +foo.bar_baz(), +but in Nim all of these are valid: foo.barBaz(), foo.bar_baz(), +bar_baz(foo), barBaz(foo), +barbaz(foo) etc. +

+

+In V there's only one way to return a value from a function: return value. In Nim you can do +return value, result = value, value (final expression), or modify +a ref argument. +

+

Features like macros and OOP offer multiple ways to solve problems and increase complexity.

+

Nim's strings are mutable, in my opinion this is a huge drawback. I'll post a detailed article +about the power of immutable strings.

+

Unlike V, Nim generates unreadable C code with lots of extra bloat. For example:

+
var users = [
+    User(name: "Carl", last_name: "Black", age: 22),
+    User(name: "Sam", last_name: "Johnson", age: 23)
+]
+
+If we build this with nim c -d:release test.nim, we get +
STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_5, "Carl", 4);
+STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_6, "Black", 5);
+STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_7, "Sam", 3);
+STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_8, "Johnson", 7);
+NIM_CONST tyArray_m9aGbgPB3gZgFcKcDkjg9a8g TM_R8RUzYq41iOx0I9bZH5Nyrw_4 = { { ((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_5), ((NimStringDesc*) &TM_R8RUzY
+q41iOx0I9bZH5Nyrw_6), ((NI) 22)},
+
+{((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_7), ((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_8), ((NI) 23)}}
+;
+
+N_LIB_PRIVATE N_NIMCALL(void, NimMainModule)(void) {
+{
+        TFrame FR_; FR_.len = 0;
+}
+nimRegisterGlobalMarker(TM_R8RUzYq41iOx0I9bZH5Nyrw_3);
+        genericAssign((void*)users_oOczRkVOc3qtKT8rsAJzaw, (void*)TM_R8RUzYq41iOx0I9bZH5Nyrw_4, (&NTI_m9aGbgPB3gZgFcKcDkjg9a8g_));
+}
+
+N_LIB_PRIVATE N_NIMCALL(void, aDatInit000)(void) {
+static TNimNode* TM_R8RUzYq41iOx0I9bZH5Nyrw_2[3];
+static TNimNode TM_R8RUzYq41iOx0I9bZH5Nyrw_0[4];
+NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.size = sizeof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ);
+NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.kind = 18;
+NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.base = 0;
+NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.flags = 2;
+TM_R8RUzYq41iOx0I9bZH5Nyrw_2[0] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1];
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].kind = 1;
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].offset = offsetof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ, name);
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].typ = (&NTI_77mFvmsOLKik79ci2hXkHEg_);
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].name = "name";
+TM_R8RUzYq41iOx0I9bZH5Nyrw_2[1] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2];
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].kind = 1;
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].offset = offsetof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ, last_name);
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].typ = (&NTI_77mFvmsOLKik79ci2hXkHEg_);
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].name = "last_name";
+TM_R8RUzYq41iOx0I9bZH5Nyrw_2[2] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3];
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].kind = 1;
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].offset = offsetof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ, age);
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].typ = (&NTI_rR5Bzr1D5krxoo1NcNyeMA_);
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].name = "age";
+TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].len = 3; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].kind = 2; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].sons = &TM_R8RUzYq41iOx0I9bZH5Nyrw_2[0]
+;
+NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.node = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0];
+NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.size = sizeof(tyArray_m9aGbgPB3gZgFcKcDkjg9a8g);
+NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.kind = 16;
+NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.base = (&NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_);
+NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.flags = 2;
+}
+
+

+V can emit native code directly, Nim can only emit C and JavaScript. It's also possible to embed C code +in Nim, which reduces safety and portability. +

+

Nim allows importing functions into global namespace. This becomes a huge problem when working on large +code bases. Explicit imports that V, Go, Oberon have are much more practical: pkg.function() vs +function(). +

+

V's syntax is cleaner with fewer rules. Lack of significant whitespace improves +readability and maintainability of large code bases and makes generating code much easier. +From my experience of working with a huge Python code base, moving large blocks of code in whitespace sensitive +languages is scary. +

+

The list can go on and on. Nim is a language with a lot of features, still developing and changing. +V is not going to change much, if at all. +

+

Again, I'm not saying it's a worse language. It's a very different language that offers a lot of +options and features. Many developers prefer this approach. And that's ok. +

+
+ +
+ Web design by Leah. + + + logo by Sonovice and Don. + +
+
+ +
+ + +
\ No newline at end of file diff --git a/build/css b/build/css new file mode 100755 index 000000000..76300141f --- /dev/null +++ b/build/css @@ -0,0 +1,520 @@ +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxFIzIFKw.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxMIzIFKw.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxEIzIFKw.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxLIzIFKw.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxHIzIFKw.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxGIzIFKw.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxIIzI.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fCRc4EsA.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fABc4EsA.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fCBc4EsA.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fBxc4EsA.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fCxc4EsA.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fChc4EsA.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu72xKOzY.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu5mxKOzY.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7mxKOzY.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4WxKOzY.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7WxKOzY.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7GxKOzY.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fCRc4EsA.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fABc4EsA.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fCBc4EsA.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fBxc4EsA.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fCxc4EsA.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fChc4EsA.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCRc4EsA.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfABc4EsA.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCBc4EsA.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBxc4EsA.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCxc4EsA.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfChc4EsA.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/build/examples/consts.v b/build/examples/consts.v new file mode 100755 index 000000000..ca1c2f002 --- /dev/null +++ b/build/examples/consts.v @@ -0,0 +1,28 @@ +import strings + +struct Color { + r int + g int + b int +} + +pub fn (c Color) str() string { + return '{$c.r, $c.g, $c.b}' +} + +fn rgb(r, g, b int) Color { + return Color{r: r, g: g, b: b} +} + +const ( + NUMBERS = [1, 2, 3] + + RED = Color{r: 255, g: 0, b: 0} + BLUE = rgb(0, 0, 255) +) + +fn main() { + println(NUMBERS) + println(RED) + println(BLUE) +} diff --git a/build/examples/copy_struct.v b/build/examples/copy_struct.v new file mode 100755 index 000000000..0cfe2f5eb --- /dev/null +++ b/build/examples/copy_struct.v @@ -0,0 +1,13 @@ +struct User { + name string + age int +} + +fn main() { + user1 := User{'Bob', 20} + user2 := { user1 | name: 'Peter' } + println(user1.name) + println(user1.age) + println(user2.name) + println(user2.age) +} diff --git a/build/examples/fib.v b/build/examples/fib.v new file mode 100755 index 000000000..06e9f563e --- /dev/null +++ b/build/examples/fib.v @@ -0,0 +1,12 @@ +fn fib(n int) int { + if n <= 1 { + return n + } + return fib(n - 1) + fib(n - 2) +} + +fn main() { + for i := 0; i < 10; i++ { + println(fib(i)) + } +} \ No newline at end of file diff --git a/build/examples/fibmem.v b/build/examples/fibmem.v new file mode 100755 index 000000000..124bd41fe --- /dev/null +++ b/build/examples/fibmem.v @@ -0,0 +1,27 @@ +const ( + MAX = 15 +) + +struct Fib { + nums []int +} + +fn (fib mut Fib) calc(n int) int { + if n <= 1 { + return n + } + if fib.nums[n] != 0 { + return fib.nums[n] + } + fib.nums[n] = fib.calc(n - 1) + fib.calc(n - 2) + return fib.nums[n] +} + +fn main() { + mut fib := Fib { + nums: [0].repeat(MAX) + } + for i := 0; i < MAX; i++ { + println(fib.calc(i)) + } +} diff --git a/build/examples/hello.v b/build/examples/hello.v new file mode 100755 index 000000000..a5ac8d7d4 --- /dev/null +++ b/build/examples/hello.v @@ -0,0 +1,6 @@ +fn main() { + areas := ['game', 'web', 'tools', 'science', 'systems', 'GUI', 'mobile'] + for area in areas { + println('Hello, $area developers!') + } +} \ No newline at end of file diff --git a/build/examples/json.v b/build/examples/json.v new file mode 100755 index 000000000..26d1bd51e --- /dev/null +++ b/build/examples/json.v @@ -0,0 +1,39 @@ +import json + +struct User { + name string + age int +mut: + is_registered bool +} + +fn main() { + s := '[{ "name":"Frodo", "age":25}, {"name":"Bobby", "age":10}]' + mut users := json.decode( []User, s) or { + eprintln('Failed to parse json') + return + } + for user in users { + println('$user.name: $user.age') + } + println('') + for i, user in users { + println('$i) $user.name') + if !user.can_register() { + println('Cannot register $user.name, they are too young') + continue + } + users[i].register() // `user` is immutable, we have to modify the array + } + // Let's encode users again just for fun + println('') + println(json.encode(users)) +} + +fn (u User) can_register() bool { + return u.age >= 16 +} + +fn (u mut User) register() { + u.is_registered = true +} diff --git a/build/examples/op_overload.v b/build/examples/op_overload.v new file mode 100755 index 000000000..f8d3f45bc --- /dev/null +++ b/build/examples/op_overload.v @@ -0,0 +1,29 @@ +struct Vec { + x int + y int +} + +pub fn (a Vec) str() string { + return '{$a.x, $a.y}' +} + +fn (a Vec) + (b Vec) Vec { + return Vec { + a.x + b.x, + a.y + b.y + } +} + +fn (a Vec) - (b Vec) Vec { + return Vec { + a.x - b.x, + a.y - b.y + } +} + +fn main() { + a := Vec{2, 3} + b := Vec{4, 5} + println(a + b) + println(a - b) +} diff --git a/build/examples/users.v b/build/examples/users.v new file mode 100755 index 000000000..a538a3c20 --- /dev/null +++ b/build/examples/users.v @@ -0,0 +1,36 @@ +struct User { + id int + name string +} + +struct Repo { + users []User +} + +fn new_repo() Repo { + return Repo { + users: [User{1, 'Andrew'}, User {2, 'Bob'}, User {10, 'Charles'}] + } +} + +fn (r Repo) find_user_by_id(id int) ?User { + for user in r.users { + if user.id == id { + // V automatically wraps this into an option type + return user + } + } + return error('User $id not found') +} + +fn main() { + repo := new_repo() + // Option types must be handled by `or` blocks + user := repo.find_user_by_id(10) or { + // `or` block must end with `return`, `break`, or `continue` + println('not found') + return + } + println(user.id) // ==> '10' + println(user.name) // ==> 'Charles' +} diff --git a/build/index.html b/build/index.html new file mode 100644 index 000000000..f7bea6c58 --- /dev/null +++ b/build/index.html @@ -0,0 +1,1009 @@ + + + + + + + + + + + + + The V Programming Language + + +
+
+
+ + + + +
+
+
+ + +
+ The first printed book on V! +
+
+
+

+ The V Programming Language 0.3 + + beta + +

+

+ Simple, fast, safe, compiled. For developing maintainable software. +

+ + + + + + + +
+github.com/vlang/v +33k +
+
+ + + + + + + +
+ +
+
+ + + +
+
+
+
+
+
fn main() {
+    areas := ['game', 'web', 'tools', 'science', 'systems',
+              'embedded', 'drivers', 'GUI', 'mobile']
+    for area in areas {
+        println('Hello, ${area} developers!')
+    }
+}
+ + + +
+ + +
+
+ +
+
+

Latest news

+
+
+ +
+
+
+ January 30, 2023 +
+ +
+
+
+ January 2, 2023 +
+ +
+
+
+ October 31, 2022 +
+ +
+
+
+ August 31, 2022 +
+ +
+
+
+ June 30, 2022 +
+ +
+
+
+ June 22, 2022 +
+ +
+
+
+ June 10, 2022 +
+ +
+
+
+ June 9, 2022 +
+
+ As of today, programs built with the V compiler no longer leak memory by default. +
+
+
+
+ May 29, 2022 +
+
+ 7000 pull requests have been merged! +
+
+ +
+
+
+ +
+
+
+

+ Simple language for building maintainable programs

+

+ You can learn the entire language by going through the + documentation over a weekend, and in most cases there's only one way to do something. +

+

+ This results in simple, readable, and maintainable code. +

+

+ Despite being simple, V gives a lot of power to the developer and can be used in pretty much every field, including systems programming, webdev, gamedev, GUI, mobile, science, embedded, tooling, etc. +

+

+ V is very similar to Go. If you know Go, you already know ≈80% of V. + Things V improves on Go: vlang.io/compare#go. +

+
+
+

Safety

+ +
+
+ +
+
+

Performance

+
    +
  • C interop without any costs
  • +
  • Minimal amount of allocations
  • +
  • Built-in serialization without runtime reflection
  • +
  • Compiles to native binaries without any dependencies: a simple web server is only about 250 KB
  • +
  • As fast as C (V's main backend compiles to human readable C), + with equivalent code. +
    V does introduce some overhead for safety (such as array bounds checking, GC free), but these features can be disabled/bypassed when performance is more important. +
  • +
+
+
+

Fast compilation

+

+ V compiles ≈110k (Clang backend) and ≈500k (x64 and tcc backends) lines of code per second.
(Intel i5-7500, SM0256L SSD, no optimization)

+ V is written in V and compiles itself in under a second. +

+

+ Most of the compiler is still single threaded, so it's going to be 2-3x faster in the future! +

+
+
+
+
+

Small and easy to build compiler

+

+ V can be bootstrapped in under a second by compiling its code translated to C with a simple

+
cc v.c
No libraries or dependencies needed. +

+ For comparison, space and time required to build each compiler: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Space  Build time
Go525 MB1m 33s
Rust30 GB45m
GCC8 GB50m
Clang90 GB + [0] + 60m
Swift70 GB + [1] + 90m
V< 10 MB + [2] + <1s
+
+
+

Building V in 0.3 seconds and then using the resulting binary to build itself again:

+ + + +

+ Try it yourself: +

+ + wget https://github.com/vlang/v/releases/latest/download/v_linux.zip
+ unzip v_linux && cd v
+ time ./v self +
+
+
+
+
+

Innovative and flexible memory management

+

+ V avoids doing unnecessary allocations in the first place + by using value types, string buffers, promoting a simple abstraction-free code style. +

+

+ There are 4 ways to manage memory in V. +

+

+ The default is a minimal and a well performing tracing GC. + +

+

+ The second way is autofree, it can be enabled with -autofree. It takes care of most objects (~90-100%): + the compiler inserts necessary free calls automatically during compilation. + Remaining small percentage of objects is freed via GC. + The developer doesn't need to change anything in their code. "It just works", + like in Python, Go, or Java, except there's no heavy GC tracing everything + or expensive RC for each object. +

+

+ For developers willing to have more low level control, memory can be managed manually + with -gc none. +

+

+ Arena allocation is available via v -prealloc. +

+
+
+

+ V's autofree demo. All objects are freed during compilation. Running the Ved editor on an 8 MB file with 0 leaks: +

+ + + +
+
+
+
+

C translation

+

V can translate your entire C project and offer you the safety, simplicity, and compilation speed-up (via modules).

+
+
v translate file.c
+
+std::vector s;
+s.push_back("V is ");
+s.push_back("awesome");
+std::cout << s.size();
+
mut s := []
+s << 'V is '
+s << 'awesome'
+println(s.len)
+
+

+ A blog post about translating DOOM will be published.

+ C++ to V translation is at an early stage. +

+
+
+

+ Translating DOOM from C to V and building it in under a second: +

+ +

+ You can read translated code here: + github.com/vlang/doom +

+
+
+
+
+

Hot code reloading

+

+ Get your changes instantly without recompiling. +

+ Since you also don't have to get to the state you are working on after every compilation, this can save a lot of precious minutes of your development time. +

+ github.com/.../examples/hot_reload +
+
+ +
+
+
+
+

A powerful graphics library

+

+ Cross-platform drawing library, using OpenGL/Metal/DirectX 11 for rendering 2D/3D applications. +

+

+ The following features are planned: +

+
    +
  • Loading complex 3D objects with textures
  • +
  • Camera (moving, looking around)
  • +
  • Skeletal animation
  • +
+

A simple example of the graphics library in action is tetris.v.

+

For 3D examples, check out this.

+
+
+ +
+
+
+
+

Light and fast cross-platform GUI library

+

+ Build native UI apps with V UI. You no longer need to embed a browser to develop cross-platform apps quickly.

+ V has a UI module that uses custom drawing, similar to Qt and Flutter, but with as much similarity to the native GUI toolkit as possible. +

+

+ It has a declarative API similar to SwiftUI and React Native and runs on Windows, Linux, macOS, and Android. +

+

+ Coming soon: +

+
    +
  • a Delphi-like visual editor for building native GUI apps
  • +
  • iOS support
  • +
+

github.com/vlang/ui

+
+
+

+ Volt, a 300 KB Slack client built with V and V ui: + +

+ https://volt-app.com + + + + +
+
+
+
+

Easy cross compilation

+

+ To cross compile your software simply run v -os windows or v -os linux. No extra steps required, even for GUI and graphical apps!

+ (Compiling macOS software only works on macOS for now.) +

+
+
+

+ Building V for Windows using V for macOS, and then testing resulting v.exe on a Windows VM: +

+
+
+
+
+

Painless deployments and dependency management

+

+ To build your project, no matter how big, all you need to do is run +

v .
+

+ No build environments, makefiles, headers, virtual environments, etc.
+ You get a single statically linked binary that is guaranteed to work on all operating systems (provided you cross compile) without any dependencies.

+ Installing new libraries via vpm, a centralized package manager written in V, is as simple as +
v install ui
+    
+

+
+
+

Run everywhere

+

+ V can emit (human readable) C, so you get the great platform support and optimization of GCC and Clang. (Use v -prod . to make optimized builds.)

+ Emitting C will always be an option, even after direct machine code generation matures.

+ V can call C code, and calling V code is possible in any language that has C interop. +

+
+
+
+
+

REPL

+
v
+>>> import net.http
+>>> data := http.get('https://vlang.io/utc_now')?
+>>> data.text
+1565977541
+
+
+

Cross-platform shell scripts in V

+

+ V can be used as an alternative to Bash to write deployment scripts, build scripts, etc. + The advantage of using V for this is the simplicity and predictability of the language, and cross-platform support. "V scripts" run on Unix-like systems as well as on Windows. +

+
for file in ls('build/') {
+  rm(file)
+}
+mv('v.exe', 'build/')
+
+v run deploy.vsh
+

Read more about V script

+
+
+
+
+

Code formatting with vfmt for consistent style

+

+ No more arguments about coding styles. There's one official coding style + enforced by the vfmt formatter. +

+

+ All V code bases are guaranteed to use + the same style, making it easier to read and change code written by + other developers. +

+
v fmt -w hello.v
+
+
+

A built-in code profiler

+

+ Build and run your program with +

v -profile profile.txt x.v && ./x
and + you'll get a detailed list for all function calls: number of calls, average time per + call, total time per call. +

+
+
+
+
+

JavaScript and WASM backends

+

+ V programs can be translated to JavaScript: +

+
v -o hello.js hello.v
+

+ They can also be compiled to WASM (for now with Emscripten). + V compiler compiled to WASM and running V programs by translating them to JavaScript: +

+

+ v-wasm.vercel.app +

+

A game written using V's graphical backend and compiled to WASM:

+ v2048 +
+
+

Automatic documentation

+

+ Use vdoc to get instant documentation generated directly from + the module's source code. No need to keep and update separate documentation. +

+
v doc os
+
+
+
+
+

Built-in testing framework

+

+ Writing tests is very easy: just start your test function with test_ +

fn get_string() string { return 'hello' }
+
+fn test_get_string() {
+  assert get_string() == 'hello'
+}
+      

+

+ +
+

Friendly error messages

+

+ Helpful error messages make learning the language and fixing errors simpler: + +

+
user.v:8:14: error: `update_user` parameter `user` is mutable, you need to provide `mut`: `update_user(mut user)`
+
+    7 |     mut user := User{}
+    8 |     update_user(user)
+      |                 ~~~~
+    9 | }
+  
+
+
+
+
+

Powerful built-in web framework

+

github.com/vlang/v/tree/master/vlib/vweb

+
+
+
+
+
['/post/:id']
+fn (b Blog) show_post(id int) vweb.Result {
+  post := b.posts_repo.retrieve(id) or {
+    return vweb.not_found()
+  }
+  return vweb.view(post)
+}
+
+

Gitly, a light and fast alternative to GitHub/GitLab is built in V and vweb.

+
+
+

Built-in ORM

+

+

+
+
+
+ +
+
import sqlite
+
+struct Customer {
+  id int
+  name string
+  nr_orders int
+  country string
+}
+
+fn main() {
+  db := sqlite.connect('example.sqlite') or {
+    panic('could not create/find example.sqlite')
+  }
+
+  nr_customers := sql db {
+    select count from Customer
+  }
+  println('number of all customers: ${nr_customers}')
+
+  // V syntax can be used to build queries
+  uk_customers := sql db {
+    select from Customer where country == 'uk' && nr_orders > 0
+  }
+
+  for customer in uk_customers {
+    println('${customer.id} - ${customer.name}')
+  }
+
+  // by adding `limit 1` we tell V that there will be
+  // only one object
+  customer := sql db {
+    select from Customer where id == 1 limit 1
+  }
+  println(customer.name)
+
+  // insert a new customer
+  new_customer := Customer{name: 'Bob', nr_orders: 10}
+  sql db {
+    insert new_customer into Customer
+  }
+}
+
+
+
+
+
+
+
+

Built in V

+
+
+

V

+

V itself is written in V.

+
+
+

Volt

+

Native desktop client for Slack, Skype, Matrix, Telegram, Twitch and many more services.

+
+ +
+ +

Vinix

+

A minimalistic open-source OS that can already run Bash, GCC, and V.

+
+
+

Ved

+

Open-source 1 MB editor with the performance of Sublime Text.

+
+ +
+

vsql

+

A single-file SQL database written in pure V with no dependencies.

+
+
+

coreutils in V

+

Programs equivalent to GNU coreutils, written 100% in V.

+ +
+ +
+

C to V translator

+

This tool can already translate entire original DOOM. C++ support is planned as well. It does full automatic conversion to human readable code.

+
+
+

V UI

+

Cross-platform widget toolkit.

+
+ +
+

Gitly

+

Open-source light and fast alternative to GitHub/GitLab.

+
+
+

Vorum

+

Right now it's very basic forum/blogging software, but in the future it will be a full featured light alternative to Discourse.
The V forum runs on Vorum.

+
+ +
+

vgram

+

A bot library for Telegram Bot API.

+
+
+

Awesome V

+

A curated list of awesome V frameworks, libraries and software

+
+ +
+

The V Tensor Library

+

An n-dimensional Tensor data structure, sophisticated reduction, elementwise, and accumulation operations, data Structures that can easily be passed to C libraries, powerful linear algebra routines backed by VSL. +

+
+
+

The V Scientific Library +

+

A Scientific Library with a great variety of different modules.

+
+ + +
+
+

Are you using V to build your product or library? Have it added to this list.

+
+
+
+
+ Web design by Leah. + + + logo by Sonovice and Don. + +
+
+ +
+ + diff --git a/build/media/arrow-left.png b/build/media/arrow-left.png new file mode 100644 index 000000000..78b22920a Binary files /dev/null and b/build/media/arrow-left.png differ diff --git a/build/media/arrow-right.png b/build/media/arrow-right.png new file mode 100644 index 000000000..d5a7e008f Binary files /dev/null and b/build/media/arrow-right.png differ diff --git a/img/book.jpg b/build/media/book.jpg old mode 100644 new mode 100755 similarity index 100% rename from img/book.jpg rename to build/media/book.jpg diff --git a/build/media/buildv.mp4 b/build/media/buildv.mp4 new file mode 100755 index 000000000..98dc5c008 Binary files /dev/null and b/build/media/buildv.mp4 differ diff --git a/build/media/dk b/build/media/dk new file mode 100755 index 000000000..41b56ec6a --- /dev/null +++ b/build/media/dk @@ -0,0 +1 @@ +Discord: 818 onlineDiscord818 online \ No newline at end of file diff --git a/build/media/dk.svg b/build/media/dk.svg new file mode 100755 index 000000000..85a13c971 --- /dev/null +++ b/build/media/dk.svg @@ -0,0 +1 @@ +Discord: 542 onlineDiscord542 online \ No newline at end of file diff --git a/build/media/doom.png b/build/media/doom.png new file mode 100755 index 000000000..86d06f899 Binary files /dev/null and b/build/media/doom.png differ diff --git a/img/down.png b/build/media/down.png old mode 100644 new mode 100755 similarity index 100% rename from img/down.png rename to build/media/down.png diff --git a/img/emacs.png b/build/media/emacs.png old mode 100644 new mode 100755 similarity index 100% rename from img/emacs.png rename to build/media/emacs.png diff --git a/build/media/gg.png b/build/media/gg.png new file mode 100755 index 000000000..5d8b18ee8 Binary files /dev/null and b/build/media/gg.png differ diff --git a/build/media/hot.mp4 b/build/media/hot.mp4 new file mode 100644 index 000000000..c7b548cc8 Binary files /dev/null and b/build/media/hot.mp4 differ diff --git a/build/media/intellij.png b/build/media/intellij.png new file mode 100755 index 000000000..2dfea2108 Binary files /dev/null and b/build/media/intellij.png differ diff --git a/build/media/patreon.png b/build/media/patreon.png new file mode 100755 index 000000000..06adabf7d Binary files /dev/null and b/build/media/patreon.png differ diff --git a/build/media/screen3.png b/build/media/screen3.png new file mode 100644 index 000000000..f98c40f5a Binary files /dev/null and b/build/media/screen3.png differ diff --git a/img/sponsor_chipnetics.svg b/build/media/sponsor_chipnetics.svg old mode 100644 new mode 100755 similarity index 100% rename from img/sponsor_chipnetics.svg rename to build/media/sponsor_chipnetics.svg diff --git a/build/media/sponsor_mx.png b/build/media/sponsor_mx.png new file mode 100755 index 000000000..5aa5b73e0 Binary files /dev/null and b/build/media/sponsor_mx.png differ diff --git a/img/sponsor_syndica.jpg b/build/media/sponsor_syndica.jpg old mode 100644 new mode 100755 similarity index 100% rename from img/sponsor_syndica.jpg rename to build/media/sponsor_syndica.jpg diff --git a/img/sponsor_threefold.svg b/build/media/sponsor_threefold.svg old mode 100644 new mode 100755 similarity index 98% rename from img/sponsor_threefold.svg rename to build/media/sponsor_threefold.svg index 6e52d4070..567d83fed --- a/img/sponsor_threefold.svg +++ b/build/media/sponsor_threefold.svg @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/media/sublime.png b/build/media/sublime.png new file mode 100644 index 000000000..8be1c1f54 Binary files /dev/null and b/build/media/sublime.png differ diff --git a/build/media/tw b/build/media/tw new file mode 100755 index 000000000..1da1ed957 --- /dev/null +++ b/build/media/tw @@ -0,0 +1 @@ +Follow7.5k \ No newline at end of file diff --git a/build/media/tw.svg b/build/media/tw.svg new file mode 100755 index 000000000..17e720e0e --- /dev/null +++ b/build/media/tw.svg @@ -0,0 +1 @@ +Follow7.6k \ No newline at end of file diff --git a/build/media/v-logo.png b/build/media/v-logo.png new file mode 100755 index 000000000..c55a04d70 Binary files /dev/null and b/build/media/v-logo.png differ diff --git a/img/veasel.png b/build/media/veasel.png old mode 100644 new mode 100755 similarity index 100% rename from img/veasel.png rename to build/media/veasel.png diff --git a/build/media/vid.png b/build/media/vid.png new file mode 100755 index 000000000..8a5141afa Binary files /dev/null and b/build/media/vid.png differ diff --git a/build/media/vim.png b/build/media/vim.png new file mode 100755 index 000000000..9d1f781c8 Binary files /dev/null and b/build/media/vim.png differ diff --git a/build/media/volt.png b/build/media/volt.png new file mode 100755 index 000000000..4ba1b8def Binary files /dev/null and b/build/media/volt.png differ diff --git a/build/media/vscode.png b/build/media/vscode.png new file mode 100755 index 000000000..8be88a81a Binary files /dev/null and b/build/media/vscode.png differ diff --git a/build/media/vwin.mp4 b/build/media/vwin.mp4 new file mode 100755 index 000000000..a4384df8d Binary files /dev/null and b/build/media/vwin.mp4 differ diff --git a/img/youtube_comp_speed.png b/build/media/youtube_comp_speed.png old mode 100644 new mode 100755 similarity index 100% rename from img/youtube_comp_speed.png rename to build/media/youtube_comp_speed.png diff --git a/img/youtube_compile_speed.png b/build/media/youtube_compile_speed.png old mode 100644 new mode 100755 similarity index 100% rename from img/youtube_compile_speed.png rename to build/media/youtube_compile_speed.png diff --git a/build/tokenizer.js b/build/tokenizer.js new file mode 100755 index 000000000..e82ad20d9 --- /dev/null +++ b/build/tokenizer.js @@ -0,0 +1,130 @@ +// WARNING!!! // +// Very bad parser, i'm not a big brain low level girl :( // +// - Leah // + +const keywords = [ + "break", + "const", + "continue", + "defer", + "else", + "enum", + "fn", + "for", + "go", + "goto", + "if", + "import", + "in", + "interface", + "match", + "module", + "mut", + "none", + "or", + "pub", + "struct", + "type" +] +const ops = ["+","-","*","/","%","&","|","^","<<",">>"] +const assignments = ["+=","-=", "*=","/=","%=","&=","|=","^=",">>=","<<=",":=","="] +const breakers = ["(",")", "{","}"] +const types = ["bool","string","i8","i16","int","i64","i128","byte","u16","u32","u64","u128","rune","f32","f64","byteptr","voidptr"] + +function peek (tokens, steps = 1) { + const token = tokens[tokens.length - steps] + if (typeof token === 'object') { + token.setType = (value) => { tokens[tokens.length - steps].type = value; return token } + token.setValue = (value) => { tokens[tokens.length - steps].value = value; return token } + token.pushValue = (value) => { tokens[tokens.length - steps].value += value; return token } + } + return { type: '', value: '', ...token } +} + +function finishType (tokens, type) { + peek(tokens).setType(type) + tokens.push({ type: 'unknown', value: '' }) +} + +function Tokenizer (code) { + return new Promise((resolve, reject) => { + let i = 0 + let readingString = false + let commentLayer = 0 + let stringStarter = "" + let readingComment = false + let readingMultiLineComment = false + const tokens = [{ type: 'unknown', value: '' }] + + function IsKeyword (next, str) { return keywords.indexOf(str) > -1 && !readingString && !readingComment && (next === ' ' || next === '\n' || !next) } + function IsType (next, str) { return types.indexOf(str) > -1 && !readingString && !readingComment && (next === ' ' || next === '\n' || !next || IsBreak(next)) } + function IsAssignment (str) { return assignments.indexOf(str) > -1 && !readingString && !readingComment } + function IsOp (str) { return ops.indexOf(str) > -1 && !readingString && !readingComment } + function IsBreak (str) { return breakers.indexOf(str) > -1 && !readingString && !readingComment} + function IsNumber (str) { return str.match(/^[0-9]+$/) && !readingString && !readingComment} + + while (i <= code.length) { + if (code[i] === '/' && (code[i+1] === '/' || code[i+1] === '*') && code[i-1] !== '\\') { + commentLayer++ + readingComment = true + if (code[i+1] === '*') readingMultiLineComment = true + } else + if (code[i] === '*' && code[i+1] === '/' && code[i-1] !== '\\') { + commentLayer-- + if(commentLayer === 0) { + readingComment = false + readingMultiLineComment = false + finishType(tokens, 'comment') + } + } else + if (IsKeyword(code[i], peek(tokens).value)) { finishType(tokens, 'keyword') } else + if (IsType(code[i], peek(tokens).value)) { finishType(tokens, 'type') } else + if (IsAssignment(peek(tokens).value)) { finishType(tokens, 'definition') } else + if (IsOp(peek(tokens).value)) { finishType(tokens, 'operator') } else + if (IsBreak(peek(tokens).value)) { finishType(tokens, 'separator') } else + if (IsNumber(peek(tokens).value)) { finishType(tokens, 'number') } else + if (peek(tokens).value === 'return' && !readingString && !readingComment && (code[i] === ' ' || code[i] === '\n' || !code[i])) { finishType(tokens, 'return') } + + if (peek(tokens).value === ' ' || peek(tokens).value === '\n') { finishType(tokens, 'whitespace') } else + if (IsBreak(code[i])) { + if (peek(tokens, 3).type === 'keyword') { finishType(tokens, 'key') } else { finishType(tokens, 'unknown') } + } else if ((code[i] === ' ' && !readingString) || (code[i] === '\n' && !readingString && code[i-1] !== '\\')) { + if(code[i] === '\n' && readingComment && !readingMultiLineComment) { + commentLayer-- + if(commentLayer === 0) { + finishType(tokens, 'comment') + readingComment = false + } + } else if (!readingComment) { + finishType(tokens, 'unknown') + } + } + + if ((code[i] === '\'' || code[i] === '\"') && code[i - 1] !== "\\" && !readingComment) { + if (code[i] === stringStarter && readingString) { + peek(tokens).pushValue(code[i]) + if (readingString) { finishType(tokens, 'string') } + readingString = false + } else if(!readingString) { + finishType(tokens, 'unknown') + peek(tokens).pushValue(code[i]) + stringStarter = code[i] + readingString = true + } else { + peek(tokens).pushValue(code[i]) + } + } else { + if(i < code.length) { peek(tokens).pushValue(code[i]) } else { + if(peek(tokens).value.endsWith('\n')) { tokens.push({ type: 'whitespace', value: ' ' }) } + else if (peek(tokens).value === '' && peek(tokens).type === 'unknown' && peek(tokens, 2).value.endsWith('\n')) { + peek(tokens).setType('whitespace') + peek(tokens).setValue(' ') + } + } + } + i++ + } + if(peek(tokens).value.endsWith('\n')) tokens.push({ type: 'whitespace', value: ' ' }) + resolve(tokens.length === 1 && tokens[0].value === '' ? [{ type: 'whitespace', value: ' ' }] : tokens) + }) +} \ No newline at end of file diff --git a/example.png b/example.png new file mode 100644 index 000000000..d01dc3b18 Binary files /dev/null and b/example.png differ diff --git a/img/doom.png b/img/doom.png deleted file mode 100644 index 89dcbdf1b..000000000 Binary files a/img/doom.png and /dev/null differ diff --git a/img/gg.png b/img/gg.png deleted file mode 100644 index bf7ea6b48..000000000 Binary files a/img/gg.png and /dev/null differ diff --git a/img/patreon.png b/img/patreon.png deleted file mode 100644 index c158d7b3d..000000000 Binary files a/img/patreon.png and /dev/null differ diff --git a/img/sponsor_mx.png b/img/sponsor_mx.png deleted file mode 100644 index e3ddd1649..000000000 Binary files a/img/sponsor_mx.png and /dev/null differ diff --git a/img/sublime.png b/img/sublime.png deleted file mode 100644 index 6594baae3..000000000 Binary files a/img/sublime.png and /dev/null differ diff --git a/img/v-logo.png b/img/v-logo.png deleted file mode 100644 index b91c72f2c..000000000 Binary files a/img/v-logo.png and /dev/null differ diff --git a/img/vim.png b/img/vim.png deleted file mode 100644 index 5b609fe5f..000000000 Binary files a/img/vim.png and /dev/null differ diff --git a/img/vscode.png b/img/vscode.png deleted file mode 100644 index 71eaa9d5d..000000000 Binary files a/img/vscode.png and /dev/null differ diff --git a/index.html b/index.html deleted file mode 100644 index b0dd80768..000000000 --- a/index.html +++ /dev/null @@ -1,1106 +0,0 @@ -@t header - - - -
-
-
-

The V Programming Language 0.3 beta

-

Simple, fast, safe, compiled. For developing maintainable software.

- - -
- github.com/vlang/v - 32k -
-
- - - - - - -
- - - - - - - - - -
-
- - - -
- The first printed book on V! -
- -
-
- -
-
-
-
-
-
fn main() {
-    areas := ['game', 'web', 'tools', 'science', 'systems',
-              'embedded', 'drivers', 'GUI', 'mobile']
-    for area in areas {
-        println('Hello, ${area} developers!')
-    }
-}
- - - -
- - - - -
-
-
- -
- -
-

Latest news

-
- -
- -
-
- January 30, 2023 -
- -
- -
-
- October 31, 2022 -
- -
- -
-
- August 31, 2022 -
- -
- -
-
- June 30, 2022 -
- -
- -
-
- June 22, 2022 -
- -
-
-
- June 10, 2022 -
- -
- -
-
- June 9, 2022 -
-
- As of today, programs built with the V compiler no longer leak memory by default. -
-
- - - -
- -
- -
-
-

%simple_language_for_maintainable_programs

-

- You can learn the entire language by going through the - documentation over a weekend, and in most cases there's only one way to do something. -

- This results in simple, readable, and maintainable code. -

- Despite being simple, V gives a lot of power to the developer and can be used in pretty much every field, including systems programming, webdev, gamedev, GUI, mobile, science, embedded, tooling, etc. -

-

- V is very similar to Go. If you know Go, you already know ≈80% of V. - Things V improves on Go: vlang.io/compare#go. -

-
-
-

Safety

- -
-
- - - - -
-
-

Performance

-
    -
  • C interop without any costs
  • -
  • Minimal amount of allocations
  • -
  • Built-in serialization without runtime reflection
  • -
  • Compiles to native binaries without any dependencies: a simple web server is only about 250 KB
  • -
  • As fast as C (V's main backend compiles to human readable C), - with equivalent code. -
    V does introduce some overhead for safety (such as array bounds checking, GC free), but these features can be disabled/bypassed when performance is more important. -
  • -
-
-
-

Fast compilation

-

- V compiles ≈110k (Clang backend) and ≈500k (x64 and tcc backends) lines of code per second.
(Intel i5-7500, SM0256L SSD, no optimization)

- V is written in V and compiles itself in under a second. -

-

- Most of the compiler is still single threaded, so it's going to be 2-3x faster in the future! -

-
-
- - - - - - - - -
-
-

Small and easy to build compiler

-

- V can be bootstrapped in under a second by compiling its code translated to C with a simple

cc v.c
No libraries or dependencies needed. -

- For comparison, space and time required to build each compiler: -

- - - - - - - - -
Space  Build time
Go525 MB1m 33s
Rust30 GB45m
GCC8 GB50m
Clang90 GB - [0] - 60m
Swift70 GB - [1] - 90m
V< 10 MB - [2] - <1s
-
-
-

Building V in 0.3 seconds and then using the resulting binary to build itself again:

- - - - - - -

- Try it yourself: -

- - wget https://github.com/vlang/v/releases/latest/download/v_linux.zip
- unzip v_linux && cd v
- time ./v self -
-
-
- - - -
-
-

Flexible memory management

-

- V avoids doing unnecessary allocations in the first place - by using value types, string buffers, promoting a simple abstraction-free code style. -

-

- There are 4 ways to manage memory in V. -

-

- The default is a minimal and a well performing tracing GC. - -

- The second way is autofree, it can be enabled with -autofree. It takes care of most objects (~90-100%): - the compiler inserts necessary free calls automatically during compilation. - Remaining small percentage of objects is freed via GC. - The developer doesn't need to change anything in their code. "It just works", - like in Python, Go, or Java, except there's no heavy GC tracing everything - or expensive RC for each object. -

-

- For developers willing to have more low level control, memory can be managed manually - - with -gc none. -

- -

- Arena allocation is available via v -prealloc. -

- - - -
-
-

- V's autofree demo. All objects are freed during compilation. Running the Ved editor on an 8 MB file with 0 leaks: -

- - - - - -
-
- -
-
-

C translation

-

V can translate your entire C project and offer you the safety, simplicity, and compilation speed-up (via modules).

-
-
v translate file.c
-
-std::vector s;
-s.push_back("V is ");
-s.push_back("awesome");
-std::cout << s.size();
- -
mut s := []
-s << 'V is '
-s << 'awesome'
-println(s.len)
-
-

- A blog post about translating DOOM will be published.

- C++ to V translation is at an early stage. -

-
-
-

- Translating DOOM from C to V and building it in under a second: -

- - -

-You can read translated code here: -github.com/vlang/doom -

-
-
- -
-
-

Hot code reloading

-

- Get your changes instantly without recompiling. -

- Since you also don't have to get to the state you are working on after every compilation, this can save a lot of precious minutes of your development time. -

- github.com/.../examples/hot_reload -
-
- -
-
- -
-
-

Powerful graphics libraries

-

- Cross-platform drawing library built on top of GDI+/Cocoa Drawing, and an OpenGL based graphics library for more complex 2D/3D applications, that will also have the following features: -

-
    -
  • Loading complex 3D objects with textures
  • -
  • Camera (moving, looking around)
  • -
  • Skeletal animation
  • -
-

DirectX, Vulkan, and Metal support is planned.

-

A simple example of the graphics library in action is tetris.v.

-
-
- -
-
- -
-
-

Light and fast cross-platform GUI library

-

- Build native UI apps with V UI. You no longer need to embed a browser to develop cross-platform apps quickly.

- V has a UI module that uses custom drawing, similar to Qt and Flutter, but with as much similarity to the native GUI toolkit as possible. -

-

- It has a declarative API similar to SwiftUI and React Native and runs on Windows, Linux, macOS, and Android. -

-

- Coming soon: -

-
    -
  • a Delphi-like visual editor for building native GUI apps
  • -
  • iOS support
  • -
-

github.com/vlang/ui

-
-
-

- Volt, a 300 KB Slack client built with V and V UI: -

- -
-
- -
-
-

Easy cross compilation

-

- To cross compile your software simply run v -os windows or v -os linux. No extra steps required, even for GUI and graphical apps!

- (Compiling macOS software only works on macOS for now.) -

-
-
-

- Building V for Windows using V for macOS, and then testing resulting v.exe on a Windows VM: -

-
-
- -
-
-

Painless deployments and dependency management

-

- To build your project, no matter how big, all you need to do is run -

-v .
-

- No build environments, makefiles, headers, virtual environments, etc.
- You get a single statically linked binary that is guaranteed to work on all operating systems (provided you cross compile) without any dependencies.

- Installing new libraries via vpm, a centralized package manager written in V, is as simple as -
-v install ui
-		
-

-
-
-

Run everywhere

-

- V can emit (human readable) C, so you get the great platform support and optimization of GCC and Clang. (Use v -prod . to make optimized builds.)

- Emitting C will always be an option, even after direct machine code generation matures.

- V can call C code, and calling V code is possible in any language that has C interop. -

-
-
- -
-
-

REPL

-
v
->>> import net.http
->>> data := http.get('https://vlang.io/utc_now')?
->>> data.text
-1565977541
-
-
-

Cross-platform shell scripts in V

-

- V can be used as an alternative to Bash to write deployment scripts, build scripts, etc. - -The advantage of using V for this is the simplicity and predictability of the language, and cross-platform support. "V scripts" run on Unix-like systems as well as on Windows. -

-
for file in ls('build/') {
-  rm(file)
-}
-mv('v.exe', 'build/')
-
-v run deploy.vsh
-

Read more about V script

-
-
- -
-
-

Code formatting with vfmt for consistent style

-

- No more arguments about coding styles. There's one official coding style - enforced by the vfmt formatter. -

-

- All V code bases are guaranteed to use - the same style, making it easier to read and change code written by - other developers. -

-
v fmt -w hello.v
-
-
-

A built-in code profiler

-

- Build and run your program with

v -profile profile.txt x.v && ./x
and - you'll get a detailed list for all function calls: number of calls, average time per - call, total time per call. -

-
-
- -
-
-

JavaScript and WASM backends

-

- V programs can be translated to JavaScript: -

-
v -o hello.js hello.v
-

- They can also be compiled to WASM (for now with Emscripten). - V compiler compiled to WASM and running V programs by translating them to JavaScript: -

-

- v-wasm.vercel.app -

-

A game written using V's graphical backend and compiled to WASM:

- v2048 - -
-
-

Automatic documentation

-

- Use vdoc to get instant documentation generated directly from - the module's source code. No need to keep and update separate documentation. -

-
v doc os
-
-
- -
-
-

Built-in testing framework

-

- Writing tests is very easy: just start your test function with test_ -

-fn get_string() string { return 'hello' }
-
-fn test_get_string() {
-  assert get_string() == 'hello'
-}
-      

-

- -
-

Friendly error messages

-

- Helpful error messages make learning the language and fixing errors simpler: - -

-
-user.v:8:14: error: `update_user` parameter `user` is mutable, you need to provide `mut`: `update_user(mut user)`
-
-    7 |     mut user := User{}
-    8 |     update_user(user)
-      |                 ~~~~
-    9 | }
-	
-
-
- -
-
-

Powerful built-in web framework

-

github.com/vlang/v/tree/master/vlib/vweb

- -
-
-
- Run -
- -
['/post/:id'] -fn (b Blog) show_post(id int) vweb.Result { - post := b.posts_repo.retrieve(id) or { - return vweb.not_found() - } - return vweb.view(post) -}
-
- - -

Gitly, a light and fast alternative to GitHub/GitLab is built in V and vweb.

-
- -
-

Built-in ORM

-

- -

- -
-
- Run -
- -
import sqlite - -struct Customer { - id int - name string - nr_orders int - country string -} - -fn main() { - db := sqlite.connect('example.sqlite') or { - panic('could not create/find example.sqlite') - } - - nr_customers := sql db { - select count from Customer - } - println('number of all customers: ${nr_customers}') - - // V syntax can be used to build queries - uk_customers := sql db { - select from Customer where country == 'uk' && nr_orders > 0 - } - - for customer in uk_customers { - println('${customer.id} - ${customer.name}') - } - - // by adding `limit 1` we tell V that there will be - // only one object - customer := sql db { - select from Customer where id == 1 limit 1 - } - println(customer.name) - - // insert a new customer - new_customer := Customer{name: 'Bob', nr_orders: 10} - sql db { - insert new_customer into Customer - } -} -
-
- - -

-
-
-
-
-
-

Built in V

-
-
-

V

-

V itself is written in V.

-
-
-

Volt

-

Native desktop client for Slack, Skype, Matrix, Telegram, Twitch and many more services.

-
- -
- -

Vinix

-

A minimalistic open-source OS that can already run Bash, GCC, and V.

-
-
-

Ved

-

Open-source 1 MB editor with the performance of Sublime Text.

-
- -
-

vsql

-

A single-file SQL database written in pure V with no dependencies.

-
-
-

coreutils in V

-

Programs equivalent to GNU coreutils, written 100% in V.

- -
- -
-

C to V translator

-

This tool can already translate entire original DOOM. C++ support is planned as well. It does full automatic conversion to human readable code.

-
-
-

V UI

-

Cross-platform widget toolkit.

-
- -
-

Gitly

-

Open-source light and fast alternative to GitHub/GitLab.

-
-
-

Vorum

-

Right now it's very basic forum/blogging software, but in the future it will be a full featured light alternative to Discourse.
The V forum runs on Vorum.

-
- -
-

vgram

-

A bot library for Telegram Bot API.

-
-
-

Awesome V

-

A curated list of awesome V frameworks, libraries and software

-
- -
-

The V Tensor Library

-

An n-dimensional Tensor data structure, sophisticated reduction, elementwise, and accumulation operations, data Structures that can easily be passed to C libraries, powerful linear algebra routines backed by VSL. -

-
-
-

The V Scientific Library -

-

A Scientific Library with a great variety of different modules.

-
- - -
-
-

Are you using V to build your product or library? Have it added to this list.

-
-
-
- - Web design by Leah. - - - logo by Sonovice and Don. - -
- -@t footer diff --git a/package.json b/package.json new file mode 100755 index 000000000..e7a5cfd01 --- /dev/null +++ b/package.json @@ -0,0 +1,27 @@ +{ + "name": "vlangio", + "version": "1.0.0", + "description": "", + "main": "build-pages.js", + "dependencies": { + "markdown-it": "^13.0.1", + "markdown-it-toc-and-anchor": "^4.2.0", + "markdown-toc": "^1.2.0", + "ncp": "^2.0.0", + "node-fetch": "^2.6.0", + "nunjucks": "^3.2.4", + "serve-static": "^1.15.0", + "serve": "^14.2.0", + "uslug": "^1.0.4" + }, + "devDependencies": { + "clean-css": "^4.2.3", + "node-sass": "^8.0.0", + "sass": "^1.57.1" + }, + "scripts": { + "build": "node build-pages.js && serve build/" + }, + "author": "", + "license": "ISC" +} diff --git a/compare.html b/pages/compare.njk old mode 100644 new mode 100755 similarity index 75% rename from compare.html rename to pages/compare.njk index be4d6869e..806d3ccaa --- a/compare.html +++ b/pages/compare.njk @@ -1,58 +1,27 @@ -@t header - +{% set active_page = 'compare' %} +{% set page_title = 'The V Comparison' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %}
- -
-
+

Comparison of V and other languages

-

V was created because none of the existing languages had all of the following features:

-
Fast compilation D, Go, Delphi -
Simplicity & maintainabilityGo -
Great performance on par with C and
zero cost C interop
C, C++, D, Delphi, Rust -
Safety (immutability, no null, option types, free from data races) Rust -
Easy concurrency Go -
Easy cross compilationGo -
Compile time code generationD -
Small compiler with zero dependencies- -
No global state- -
Hot code reloadingC# (.NET 6+), Dart -
- +Fast compilation D, Go, Delphi +Simplicity & maintainabilityGo +Great performance on par with C and
zero cost C interop C, C++, D, Delphi, Rust +Safety (immutability, no null, option types, free from data races) Rust +Easy concurrency Go +Easy cross compilationGo +Compile time code generationD +Small compiler with zero dependencies- +No global state- +Hot code reloadingC# (.NET 6+), Dart +

Initially I was going to compare V to all major languages, but it got repetitive pretty quickly.

@@ -73,17 +42,15 @@

Comparison of V and other languages

Syntax comparison:

-V for Go developers +V for Go developers

-V for C++ developers +V for C++ developers

Since V is very similar to Go, and its domain is similar to Rust's, I left a comparison with these two languages.

- -

Go

- +

Go

V is very similar to Go, and these are the things it improves upon:

@@ -116,7 +83,7 @@

Go

— A simple way to check whether an array contains an element: if elem in arr {. -

+

— Only one declaration style: a := 0

@@ -125,7 +92,7 @@

Go


Making a production build still requires fixing all of them, thus enforcing clean code. -

+

— Much smaller runtime

@@ -144,7 +111,7 @@

Go

— Precompiled text and HTML templates unlike Go's html/templates that have to be parsed on every request

-— Fearless concurrency (no data race guarantee at compilation) wip +— Fearless concurrency (no data race guarantee at compilation) wip

— No null (null is only allowed in unsafe code) @@ -159,28 +126,26 @@

Go

— Much simpler and less verbose testing, assert.

-— Primitive types can have methods resulting in less verbose code: strings.Replace(strings.Replace(s, "a", "A", -1), "b", "B", -1) => +— Primitive types can have methods resulting in less verbose code: strings.Replace(strings.Replace(s, "a", "A", -1), "b", "B", -1) =>
s.replace('a', 'A').replace('b', 'B')


-

Rust

- -Rust has a very different philosophy. - +

Rust

+Rust has a very different philosophy.

It is a complex language with a growing set of features and a steep learning curve. No doubt, once you learn and understand the language, it becomes a very powerful tool for developing safe, fast, and stable software. But the complexity is still there.

-V's goal is to allow building maintainable and predictable software. That's why the language +V's goal is to allow building maintainable and predictable software. That's why the language is so simple and maybe even boring for some. The good thing is, you can jump into any part of the project and understand what's going on, feel like it was you who wrote it, because the language is simple and - there's only one way of doing things. +there's only one way of doing things.

-Rust's compilation speed is slow, on par with C++. V compiles 1.2 million lines of code per cpu per second. +Rust's compilation speed is slow, on par with C++. V compiles 1.2 million lines of code per cpu per second.


V vs Rust vs Go: Example

@@ -196,8 +161,8 @@

V vs Rust vs Go: Example

use serde::Deserialize;
 use std::sync::{Arc, Mutex};
 
-const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
-const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
+const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
+const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
 
 #[derive(Deserialize)]
 struct Story {
@@ -205,7 +170,7 @@ 

V vs Rust vs Go: Example

} fn main() { - let story_ids: Arc<Vec<u64>> = Arc::new(reqwest::get(STORIES_URL).unwrap().json().unwrap()); + let story_ids: Arc<Vec<u64>> = Arc::new(reqwest::get(STORIES_URL).unwrap().json().unwrap()); let cursor = Arc::new(Mutex::new(0)); let mut handles = Vec::new(); for _ in 0..8 { @@ -215,14 +180,14 @@

V vs Rust vs Go: Example

let index = { let mut cursor_guard = cursor.lock().unwrap(); let index = *cursor_guard; - if index >= story_ids.len() { + if index >= story_ids.len() { return; } *cursor_guard += 1; index }; let story_url = format!("{}/{}.json", ITEM_URL_BASE, story_ids[index]); - let story: Story = reqwest::get(&story_url).unwrap().json().unwrap(); + let story: Story = reqwest::get(&story_url).unwrap().json().unwrap(); println!("{}", story.title); })); } @@ -231,11 +196,8 @@

V vs Rust vs Go: Example

} }
- Go - -
-package main
+
package main
 
 import (
 	"encoding/json"
@@ -263,7 +225,7 @@ 

V vs Rust vs Go: Example

panic(err) } var ids []int - if err := json.Unmarshal(data, &ids); err != nil { + if err := json.Unmarshal(data, &ids); err != nil { panic(err) } var cursor int @@ -276,12 +238,12 @@

V vs Rust vs Go: Example

return temp } wg := sync.WaitGroup{} - for i := 0; i < 8; i++ { + for i := 0; i < 8; i++ { wg.Add(1) go func() { - for cursor := next(); cursor < len(ids); cursor = next() { + for cursor := next(); cursor < len(ids); cursor = next() { url := fmt.Sprintf( - "%s/%d.json", + "%s/%d.json", ITEM_URL_BASE, ids[cursor], ) @@ -296,7 +258,7 @@

V vs Rust vs Go: Example

panic(err) } var story Story - if err := json.Unmarshal(data, &story); err != nil { + if err := json.Unmarshal(data, &story); err != nil { panic(err) } fmt.Println(story.Title) @@ -307,11 +269,8 @@

V vs Rust vs Go: Example

wg.Wait() }
- V - -
-import net.http
+
import net.http
 import json
 
 const (
@@ -335,10 +294,10 @@ 

V vs Rust vs Go: Example

mut threads := []thread{} for _ in 0 .. 8 { - threads << go fn (ids []int, shared cursor Cursor) { + threads << go fn (ids []int, shared cursor Cursor) { for { id := lock cursor { - if cursor.pos >= ids.len { + if cursor.pos >= ids.len { break } cursor.pos++ @@ -353,14 +312,11 @@

V vs Rust vs Go: Example

threads.wait() }
- Nim -

V and Nim are very different. One of V's main philosophies is "there must be only one way of doing things". This results in predictable, simple, and maintainable code.

-

Nim gives a lot of options and freedom to developers. For example, in V you would write foo.bar_baz(), @@ -373,31 +329,24 @@

V vs Rust vs Go: Example

return value, result = value, value (final expression), or modify a ref argument.

-

Features like macros and OOP offer multiple ways to solve problems and increase complexity.

-

Nim's strings are mutable, in my opinion this is a huge drawback. I'll post a detailed article about the power of immutable strings.

-

Unlike V, Nim generates unreadable C code with lots of extra bloat. For example:

-
-var users = [
+
var users = [
     User(name: "Carl", last_name: "Black", age: 22),
     User(name: "Sam", last_name: "Johnson", age: 23)
 ]
 
- If we build this with nim c -d:release test.nim, we get - -
-STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_5, "Carl", 4);
+
STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_5, "Carl", 4);
 STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_6, "Black", 5);
 STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_7, "Sam", 3);
 STRING_LITERAL(TM_R8RUzYq41iOx0I9bZH5Nyrw_8, "Johnson", 7);
-NIM_CONST tyArray_m9aGbgPB3gZgFcKcDkjg9a8g TM_R8RUzYq41iOx0I9bZH5Nyrw_4 = { { ((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_5), ((NimStringDesc*) &TM_R8RUzY
+NIM_CONST tyArray_m9aGbgPB3gZgFcKcDkjg9a8g TM_R8RUzYq41iOx0I9bZH5Nyrw_4 = { { ((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_5), ((NimStringDesc*) &TM_R8RUzY
 q41iOx0I9bZH5Nyrw_6), ((NI) 22)},
 
-{((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_7), ((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_8), ((NI) 23)}}
+{((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_7), ((NimStringDesc*) &TM_R8RUzYq41iOx0I9bZH5Nyrw_8), ((NI) 23)}}
 ;
 
 N_LIB_PRIVATE N_NIMCALL(void, NimMainModule)(void) {
@@ -405,7 +354,7 @@ 

V vs Rust vs Go: Example

TFrame FR_; FR_.len = 0; } nimRegisterGlobalMarker(TM_R8RUzYq41iOx0I9bZH5Nyrw_3); - genericAssign((void*)users_oOczRkVOc3qtKT8rsAJzaw, (void*)TM_R8RUzYq41iOx0I9bZH5Nyrw_4, (&NTI_m9aGbgPB3gZgFcKcDkjg9a8g_)); + genericAssign((void*)users_oOczRkVOc3qtKT8rsAJzaw, (void*)TM_R8RUzYq41iOx0I9bZH5Nyrw_4, (&NTI_m9aGbgPB3gZgFcKcDkjg9a8g_)); } N_LIB_PRIVATE N_NIMCALL(void, aDatInit000)(void) { @@ -415,31 +364,30 @@

V vs Rust vs Go: Example

NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.kind = 18; NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.base = 0; NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.flags = 2; -TM_R8RUzYq41iOx0I9bZH5Nyrw_2[0] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1]; +TM_R8RUzYq41iOx0I9bZH5Nyrw_2[0] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1]; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].kind = 1; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].offset = offsetof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ, name); -TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].typ = (&NTI_77mFvmsOLKik79ci2hXkHEg_); +TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].typ = (&NTI_77mFvmsOLKik79ci2hXkHEg_); TM_R8RUzYq41iOx0I9bZH5Nyrw_0[1].name = "name"; -TM_R8RUzYq41iOx0I9bZH5Nyrw_2[1] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2]; +TM_R8RUzYq41iOx0I9bZH5Nyrw_2[1] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2]; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].kind = 1; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].offset = offsetof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ, last_name); -TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].typ = (&NTI_77mFvmsOLKik79ci2hXkHEg_); +TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].typ = (&NTI_77mFvmsOLKik79ci2hXkHEg_); TM_R8RUzYq41iOx0I9bZH5Nyrw_0[2].name = "last_name"; -TM_R8RUzYq41iOx0I9bZH5Nyrw_2[2] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3]; +TM_R8RUzYq41iOx0I9bZH5Nyrw_2[2] = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3]; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].kind = 1; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].offset = offsetof(tyObject_User_Qp0mfNOzxWdmSSWLHA9cnZQ, age); -TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].typ = (&NTI_rR5Bzr1D5krxoo1NcNyeMA_); +TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].typ = (&NTI_rR5Bzr1D5krxoo1NcNyeMA_); TM_R8RUzYq41iOx0I9bZH5Nyrw_0[3].name = "age"; -TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].len = 3; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].kind = 2; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].sons = &TM_R8RUzYq41iOx0I9bZH5Nyrw_2[0] +TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].len = 3; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].kind = 2; TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0].sons = &TM_R8RUzYq41iOx0I9bZH5Nyrw_2[0] ; -NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.node = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0]; +NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_.node = &TM_R8RUzYq41iOx0I9bZH5Nyrw_0[0]; NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.size = sizeof(tyArray_m9aGbgPB3gZgFcKcDkjg9a8g); NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.kind = 16; -NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.base = (&NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_); +NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.base = (&NTI_Qp0mfNOzxWdmSSWLHA9cnZQ_); NTI_m9aGbgPB3gZgFcKcDkjg9a8g_.flags = 2; }
-

V can emit native code directly, Nim can only emit C and JavaScript. It's also possible to embed C code in Nim, which reduces safety and portability. @@ -459,7 +407,10 @@

V vs Rust vs Go: Example

Again, I'm not saying it's a worse language. It's a very different language that offers a lot of options and features. Many developers prefer this approach. And that's ok.

-
+ +{% include "./home/footer.njk" %}
-@t footer + +{% include "./components/foot.njk" %} +
\ No newline at end of file diff --git a/pages/components/codeblock.njk b/pages/components/codeblock.njk new file mode 100755 index 000000000..b48493272 --- /dev/null +++ b/pages/components/codeblock.njk @@ -0,0 +1,65 @@ +{%- macro random_int(len) -%} +{%- for _ in range(len) -%} +{{ range(10) | random }} +{%- endfor -%} +{%- endmacro -%} + +{% set cbid = "codeblock_" + random_int(8) %} +{% set hlid = "codeblock_hl_" + random_int(8) %} +{% set taid = "codeblock_ta_" + random_int(8) %} +{% set rbid = "codeblock_rb_" + random_int(8) %} + +
+ {% if noheader %} + + {% else %} +
+ {{filename}} +
+ {% include "../icons/play.html" %} Run +
+ {% endif %} +
{{code}}
+
+ + \ No newline at end of file diff --git a/pages/components/foot.njk b/pages/components/foot.njk new file mode 100644 index 000000000..17c7245b6 --- /dev/null +++ b/pages/components/foot.njk @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/pages/components/head.njk b/pages/components/head.njk new file mode 100755 index 000000000..8d5cc667c --- /dev/null +++ b/pages/components/head.njk @@ -0,0 +1,14 @@ + + + + + + + + + + + {{page_title}} + + +
\ No newline at end of file diff --git a/pages/components/nav.njk b/pages/components/nav.njk new file mode 100755 index 000000000..4feb67b37 --- /dev/null +++ b/pages/components/nav.njk @@ -0,0 +1,21 @@ +
+
+ + + + +
+
\ No newline at end of file diff --git a/pages/docs.njk b/pages/docs.njk new file mode 100755 index 000000000..e2e7bc609 --- /dev/null +++ b/pages/docs.njk @@ -0,0 +1,12 @@ +{% set active_page = 'docs' %} +{% set page_title = 'The V Documentation' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %} + + +{% include "./docs/documentation.njk" %} + + +{% include "./components/foot.njk" %} + + diff --git a/pages/docs/content.njk b/pages/docs/content.njk new file mode 100644 index 000000000..f0f08c564 --- /dev/null +++ b/pages/docs/content.njk @@ -0,0 +1,3361 @@ +

# V Documentation

+

(See https://modules.vlang.io/ for documentation of V's standard library)

+

# Introduction

+

V is a statically typed compiled programming language designed for building maintainable software.

+

It's similar to Go and its design has also been influenced by Oberon, Rust, Swift, +Kotlin, and Python.

+

V is a very simple language. Going through this documentation will take you about an hour, +and by the end of it you will have pretty much learned the entire language.

+

The language promotes writing simple and clear code with minimal abstraction.

+

Despite being simple, V gives the developer a lot of power. +Anything you can do in other languages, you can do in V.

+

# Installing V from source

+

The best way to get the latest and greatest V, is to install it from source. +It is easy, and it takes only a few seconds:

+{% set code = "git clone https://github.com/vlang/v\ncd v\nmake\n# HINT: Using Windows?: run make.bat in the cmd.exe shell" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

For more details, see the +Installing V +section in the README.md.

+

# Upgrading V to latest version

+

If V is already installed on a machine, it can be upgraded to its latest version +by using the V's built-in self-updater. +To do so, run the command v up.

+

# Getting started

+

You can let V automatically set up the bare-bones structure of a project for you +by using any of the following commands in a terminal:

+ +

# Table of Contents

+

<table> +<tr><td width=33% valign=top>

+ +

</td><td width=33% valign=top>

+ +

</td><td valign=top>

+ +

</td></tr> +<tr><td width=33% valign=top>

+ +

</td><td width=33% valign=top>

+ +

</td><td valign=top>

+ +

</td></tr> +</table>

+

<!-- +Note: There are several special keywords, which you can put after the code fences for v: +compile, cgen, live, ignore, failcompile, okfmt, oksyntax, badsyntax, wip, nofmt +For more details, do: v check-md +-->

+

# Hello World

+{% set code = "fn main() {\n println('hello world')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Save this snippet into a file named hello.v. Now do: v run hello.v.

+
+

That is assuming you have symlinked your V with v symlink, as described +here. +If you haven't yet, you have to type the path to V manually.

+
+

Congratulations - you just wrote and executed your first V program!

+

You can compile a program without execution with v hello.v. +See v help for all supported commands.

+

From the example above, you can see that functions are declared with the fn keyword. +The return type is specified after the function name. +In this case main doesn't return anything, so there is no return type.

+

As in many other languages (such as C, Go, and Rust), main is the entry point of your program.

+

println is one of the few built-in functions. +It prints the value passed to it to standard output.

+

fn main() declaration can be skipped in one file programs. +This is useful when writing small programs, "scripts", or just learning the language. +For brevity, fn main() will be skipped in this tutorial.

+

This means that a "hello world" program in V is as simple as

+{% set code = "println('hello world')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +If you do not use explicitly fn main() {}, you need to make sure, that all your +declarations, come before any variable assignment statements, or top level function calls, +since V will consider everything after the first assignment/function call as part of your +implicit main function.

+
+

# Running a project folder with several files

+

Suppose you have a folder with several .v files in it, where one of them +contains your main() function, and the other files have other helper +functions. They may be organized by topic, but still not yet structured +enough to be their own separate reusable modules, and you want to compile +them all into one program.

+

In other languages, you would have to use includes or a build system +to enumerate all files, compile them separately to object files, +then link them into one final executable.

+

In V however, you can compile and run the whole folder of .v files together, +using just v run .. Passing parameters also works, so you can +do: v run . --yourparam some_other_stuff

+

The above will first compile your files into a single program (named +after your folder/project), and then it will execute the program with +--yourparam some_other_stuff passed to it as CLI parameters.

+

Your program can then use the CLI parameters like this:

+{% set code = "import os\n\nprintln(os.args)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +After a successful run, V will delete the generated executable. +If you want to keep it, use v -keepc run . instead, or just compile +manually with v . .

+
+
+

Note +Any V compiler flags should be passed before the run command. +Everything after the source file/folder, will be passed to the program +as is - it will not be processed by V.

+
+

# Comments

+{% set code = "// This is a single line comment.\n/*\nThis is a multiline comment.\n /* It can be nested. */\n*/" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Functions

+{% set code = "fn main() {\n println(add(77, 33))\n println(sub(100, 50))\n}\n\nfn add(x int, y int) int {\n return x + y\n}\n\nfn sub(x int, y int) int {\n return x - y\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Again, the type comes after the argument's name.

+

Just like in Go and C, functions cannot be overloaded. +This simplifies the code and improves maintainability and readability.

+

# Hoistings

+

Functions can be used before their declaration: +add and sub are declared after main, but can still be called from main. +This is true for all declarations in V and eliminates the need for header files +or thinking about the order of files and declarations.

+

# Returning multiple values

+{% set code = "fn foo() (int, int) {\n return 2, 3\n}\n\na, b := foo()\nprintln(a) // 2\nprintln(b) // 3\nc, _ := foo() // ignore values using `_`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Symbol visibility

+{% set code = "pub fn public_function() {\n}\n\nfn private_function() {\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Functions are private (not exported) by default. +To allow other modules to use them, prepend pub. The same applies +to structs, constants and types.

+
+

Note +pub can only be used from a named module. +For information about creating a module, see Modules.

+
+

# Variables

+{% set code = "name := 'Bob'\nage := 20\nlarge_number := i64(9999999999)\nprintln(name)\nprintln(age)\nprintln(large_number)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Variables are declared and initialized with :=. This is the only +way to declare variables in V. This means that variables always have an initial +value.

+

The variable's type is inferred from the value on the right hand side. +To choose a different type, use type conversion: +the expression T(v) converts the value v to the +type T.

+

Unlike most other languages, V only allows defining variables in functions. +By default V does not allow global variables. See more details.

+

For consistency across different code bases, all variable and function names +must use the snake_case style, as opposed to type names, which must use PascalCase.

+

# Mutable variables

+{% set code = "mut age := 20\nprintln(age)\nage = 21\nprintln(age)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

To change the value of the variable use =. In V, variables are +immutable by default. +To be able to change the value of the variable, you have to declare it with mut.

+

Try compiling the program above after removing mut from the first line.

+

# Initialization vs assignment

+

Note the (important) difference between := and =. +:= is used for declaring and initializing, = is used for assigning.

+{% set code = "fn main() {\n age = 21\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This code will not compile, because the variable age is not declared. +All variables need to be declared in V.

+{% set code = "fn main() {\n age := 21\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The values of multiple variables can be changed in one line. +In this way, their values can be swapped without an intermediary variable.

+{% set code = "mut a := 0\nmut b := 1\nprintln('${a}, ${b}') // 0, 1\na, b = b, a\nprintln('${a}, ${b}') // 1, 0" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Declaration errors

+

In development mode the compiler will warn you that you haven't used the variable +(you'll get an "unused variable" warning). +In production mode (enabled by passing the -prod flag to v – v -prod foo.v) +it will not compile at all (like in Go).

+{% set code = "fn main() {\n a := 10\n if true {\n a := 20 // error: redefinition of `a`\n }\n // warning: unused variable `a`\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Unlike most languages, variable shadowing is not allowed. Declaring a variable with a name +that is already used in a parent scope will cause a compilation error.

+

# V Types

+

# Primitive types

+{% set code = "bool\n\nstring\n\ni8 i16 int i64 i128 (soon)\nu8 u16 u32 u64 u128 (soon)\n\nrune // represents a Unicode code point\n\nf32 f64\n\nisize, usize // platform-dependent, the size is how many bytes it takes to reference any location in memory\n\nvoidptr // this one is mostly used for [C interoperability](#v-and-c)\n\nany // similar to C's void* and Go's interface{}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +Unlike C and Go, int is always a 32 bit integer.

+
+

There is an exception to the rule that all operators +in V must have values of the same type on both sides. A small primitive type +on one side can be automatically promoted if it fits +completely into the data range of the type on the other side. +These are the allowed possibilities:

+{% set code = " i8 → i16 → int → i64\n ↘ ↘\n f32 → f64\n ↗ ↗\n u8 → u16 → u32 → u64 ⬎\n ↘ ↘ ↘ ptr\n i8 → i16 → int → i64 ⬏" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

An int value for example can be automatically promoted to f64 +or i64 but not to u32. (u32 would mean loss of the sign for +negative values). +Promotion from int to f32, however, is currently done automatically +(but can lead to precision loss for large values).

+

Literals like 123 or 4.56 are treated in a special way. They do +not lead to type promotions, however they default to int and f64 +respectively, when their type has to be decided:

+{% set code = "u := u16(12)\nv := 13 + u // v is of type `u16` - no promotion\nx := f32(45.6)\ny := x + 3.14 // x is of type `f32` - no promotion\na := 75 // a is of type `int` - default for int literal\nb := 14.7 // b is of type `f64` - default for float literal\nc := u + a // c is of type `int` - automatic promotion of `u`'s value\nd := b + x // d is of type `f64` - automatic promotion of `x`'s value" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Strings

+{% set code = "name := 'Bob'\nassert name.len == 3 // will print 3\nassert name[0] == u8(66) // indexing gives a byte, u8(66) == `B`\nassert name[1..3] == 'ob' // slicing gives a string 'ob'\n\n// escape codes\nwindows_newline := '\r\n' // escape special characters like in C\nassert windows_newline.len == 2\n\n// arbitrary bytes can be directly specified using `\x##` notation where `#` is\n// a hex digit aardvark_str := '\x61ardvark' assert aardvark_str == 'aardvark'\nassert '\xc0'[0] == u8(0xc0)\n\n// or using octal escape `\###` notation where `#` is an octal digit\naardvark_str2 := '\141ardvark'\nassert aardvark_str2 == 'aardvark'\n\n// Unicode can be specified directly as `\u####` where # is a hex digit\n// and will be converted internally to its UTF-8 representation\nstar_str := '\u2605' // ★\nassert star_str == '★'\nassert star_str == '\xe2\x98\x85' // UTF-8 can be specified this way too." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

In V, a string is a read-only array of bytes. All Unicode characters are encoded using UTF-8:

+{% set code = "s := 'hello 🌎' // emoji takes 4 bytes\nassert s.len == 10\n\narr := s.bytes() // convert `string` to `[]u8`\nassert arr.len == 10\n\ns2 := arr.bytestr() // convert `[]byte` to `string`\nassert s2 == s" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

String values are immutable. You cannot mutate elements:

+{% set code = "mut s := 'hello 🌎'\ns[0] = `H` // not allowed" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

error: cannot assign to s[i] since V strings are immutable

+
+

Note that indexing a string will produce a byte, not a rune nor another string. Indexes +correspond to bytes in the string, not Unicode code points. If you want to convert the byte to a +string, use the .ascii_str() method on the byte:

+{% set code = "country := 'Netherlands'\nprintln(country[0]) // Output: 78\nprintln(country[0].ascii_str()) // Output: N" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Both single and double quotes can be used to denote strings. For consistency, vfmt converts double +quotes to single quotes unless the string contains a single quote character.

+

For raw strings, prepend r. Escape handling is not done for raw strings:

+{% set code = "s := r'hello\nworld' // the `\n` will be preserved as two characters\nprintln(s) // \"hello\nworld\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Strings can be easily converted to integers:

+{% set code = "s := '42'\nn := s.int() // 42\n\n// all int literals are supported\nassert '0xc3'.int() == 195\nassert '0o10'.int() == 8\nassert '0b1111_0000_1010'.int() == 3850\nassert '-0b1111_0000_1010'.int() == -3850" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

For more advanced string processing and conversions, refer to the +vlib/strconv module.

+

# String interpolation

+

Basic interpolation syntax is pretty simple - use ${ before a variable name and } after. The +variable will be converted to a string and embedded into the literal:

+{% set code = "name := 'Bob'\nprintln('Hello, ${name}!') // Hello, Bob!" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

It also works with fields: 'age = ${user.age}'. You may also use more complex expressions: +'can register = ${user.age > 13}'.

+

Format specifiers similar to those in C's printf() are also supported. f, g, x, o, b, +etc. are optional and specify the output format. The compiler takes care of the storage size, so +there is no hd or llu.

+

To use a format specifier, follow this pattern:

+

${varname:[flags][width][.precision][type]}

+ +

See +Format Placeholder Specification +for more information.

+{% set code = "x := 123.4567\nprintln('[${x:.2}]') // round to two decimal places => [123.46]\nprintln('[${x:10}]') // right-align with spaces on the left => [ 123.457]\nprintln('[${int(x):-10}]') // left-align with spaces on the right => [123 ]\nprintln('[${int(x):010}]') // pad with zeros on the left => [0000000123]\nprintln('[${int(x):b}]') // output as binary => [1111011]\nprintln('[${int(x):o}]') // output as octal => [173]\nprintln('[${int(x):X}]') // output as uppercase hex => [7B]\n\nprintln('[${10.0000:.2}]') // remove insignificant 0s at the end => [10]\nprintln('[${10.0000:.2f}]') // do show the 0s at the end, even though they do not change the number => [10.00]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# String operators

+{% set code = "name := 'Bob'\nbobby := name + 'by' // + is used to concatenate strings\nprintln(bobby) // \"Bobby\"\nmut s := 'hello '\ns += 'world' // `+=` is used to append to a string\nprintln(s) // \"hello world\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

All operators in V must have values of the same type on both sides. You cannot concatenate an +integer to a string:

+{% set code = "age := 10\nprintln('age = ' + age) // not allowed" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

error: infix expr: cannot use int (right expression) as string

+
+

We have to either convert age to a string:

+{% set code = "age := 11\nprintln('age = ' + age.str())" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

or use string interpolation (preferred):

+{% set code = "age := 12\nprintln('age = ${age}')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

See all methods of string +and related modules strings, +strconv.

+

# Runes

+

A rune represents a single Unicode character and is an alias for u32. +To denote them, use <code>`</code> (backticks) :

+{% set code = "rocket := `🚀`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A rune can be converted to a UTF-8 string by using the .str() method.

+{% set code = "rocket := `🚀`\nassert rocket.str() == '🚀'" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A rune can be converted to UTF-8 bytes by using the .bytes() method.

+{% set code = "rocket := `🚀`\nassert rocket.bytes() == [u8(0xf0), 0x9f, 0x9a, 0x80]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Hex, Unicode, and Octal escape sequences also work in a rune literal:

+{% set code = "assert `\x61` == `a`\nassert `\141` == `a`\nassert `\u0061` == `a`\n\n// multibyte literals work too\nassert `\u2605` == `★`\nassert `\u2605`.bytes() == [u8(0xe2), 0x98, 0x85]\nassert `\xe2\x98\x85`.bytes() == [u8(0xe2), 0x98, 0x85]\nassert `\342\230\205`.bytes() == [u8(0xe2), 0x98, 0x85]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Note that rune literals use the same escape syntax as strings, but they can only hold one unicode +character. Therefore, if your code does not specify a single Unicode character, you will receive an +error at compile time.

+

Also remember that strings are indexed as bytes, not runes, so beware:

+{% set code = "rocket_string := '🚀'\nassert rocket_string[0] != `🚀`\nassert 'aloha!'[0] == `a`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A string can be converted to runes by the .runes() method.

+{% set code = "hello := 'Hello World 👋'\nhello_runes := hello.runes() // [`H`, `e`, `l`, `l`, `o`, ` `, `W`, `o`, `r`, `l`, `d`, ` `, `👋`]\nassert hello_runes.string() == hello" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Numbers

+{% set code = "a := 123" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This will assign the value of 123 to a. By default a will have the +type int.

+

You can also use hexadecimal, binary or octal notation for integer literals:

+{% set code = "a := 0x7B\nb := 0b01111011\nc := 0o173" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

All of these will be assigned the same value, 123. They will all have type +int, no matter what notation you used.

+

V also supports writing numbers with _ as separator:

+{% set code = "num := 1_000_000 // same as 1000000\nthree := 0b0_11 // same as 0b11\nfloat_num := 3_122.55 // same as 3122.55\nhexa := 0xF_F // same as 255\noct := 0o17_3 // same as 0o173" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If you want a different type of integer, you can use casting:

+{% set code = "a := i64(123)\nb := u8(42)\nc := i16(12345)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Assigning floating point numbers works the same way:

+{% set code = "f := 1.0\nf1 := f64(3.14)\nf2 := f32(3.14)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If you do not specify the type explicitly, by default float literals +will have the type of f64.

+

Float literals can also be declared as a power of ten:

+{% set code = "f0 := 42e1 // 420\nf1 := 123e-2 // 1.23\nf2 := 456e+2 // 45600" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Arrays

+

An array is a collection of data elements of the same type. An array literal is a +list of expressions surrounded by square brackets. An individual element can be +accessed using an index expression. Indexes start from 0:

+{% set code = "mut nums := [1, 2, 3]\nprintln(nums) // `[1, 2, 3]`\nprintln(nums[0]) // `1`\nprintln(nums[1]) // `2`\n\nnums[1] = 5\nprintln(nums) // `[1, 5, 3]`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

<a id='array-operations'></a>

+

An element can be appended to the end of an array using the push operator <<. +It can also append an entire array.

+{% set code = "mut nums := [1, 2, 3]\nnums << 4\nprintln(nums) // \"[1, 2, 3, 4]\"\n\n// append array\nnums << [5, 6, 7]\nprintln(nums) // \"[1, 2, 3, 4, 5, 6, 7]\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "mut names := ['John']\nnames << 'Peter'\nnames << 'Sam'\n// names << 10 <-- This will not compile. `names` is an array of strings." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

val in array returns true if the array contains val. See in operator.

+{% set code = "names := ['John', 'Peter', 'Sam']\nprintln('Alex' in names) // \"false\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Array Fields

+

There are two fields that control the "size" of an array:

+ +{% set code = "mut nums := [1, 2, 3]\nprintln(nums.len) // \"3\"\nprintln(nums.cap) // \"3\" or greater\nnums = [] // The array is now empty\nprintln(nums.len) // \"0\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

data is a field (of type voidptr) with the address of the first +element. This is for low-level unsafe code.

+
+

Note +Fields are read-only and can't be modified by the user.

+
+

# Array Initialization

+

The type of an array is determined by the first element:

+ +

The user can explicitly specify the type for the first element: [u8(16), 32, 64, 128]. +V arrays are homogeneous (all elements must have the same type). +This means that code like [1, 'a'] will not compile.

+

The above syntax is fine for a small number of known elements but for very large or empty +arrays there is a second initialization syntax:

+{% set code = "mut a := []int{len: 10000, cap: 30000, init: 3}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This creates an array of 10000 int elements that are all initialized with 3. Memory +space is reserved for 30000 elements. The parameters len, cap and init are optional; +len defaults to 0 and init to the default initialization of the element type (0 +for numerical type, '' for string, etc). The run time system makes sure that the +capacity is not smaller than len (even if a smaller value is specified explicitly):

+{% set code = "arr := []int{len: 5, init: -1}\n// `arr == [-1, -1, -1, -1, -1]`, arr.cap == 5\n\n// Declare an empty array:\nusers := []int{}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Setting the capacity improves performance of pushing elements to the array +as reallocations can be avoided:

+{% set code = "mut numbers := []int{cap: 1000}\nprintln(numbers.len) // 0\n// Now appending elements won't reallocate\nfor i in 0 .. 1000 {\n numbers << i\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +The above code uses a range for statement.

+
+

You can initialize the array by accessing the it variable which gives +the index as shown here:

+{% set code = "count := []int{len: 4, init: it}\nassert count == [0, 1, 2, 3]\n\nmut square := []int{len: 6, init: it * it}\n// square == [0, 1, 4, 9, 16, 25]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Array Types

+

An array can be of these types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypesExample Definition
Number[]int,[]i64
String[]string
Rune[]rune
Boolean[]bool
Array[][]int
Struct[]MyStructName
Channel[]chan f64
Function[]MyFunctionType []fn (int) bool
Interface[]MyInterfaceName
Sum Type[]MySumTypeName
Generic Type[]T
Map[]map[string]f64
Enum[]MyEnumType
Alias[]MyAliasTypeName
Thread[]thread int
Reference[]&f64
Shared[]shared MyStructType
+

Example Code:

+

This example uses Structs and Sum Types to create an array +which can handle different types (e.g. Points, Lines) of data elements.

+{% set code = "struct Point {\n x int\n y int\n}\n\nstruct Line {\n p1 Point\n p2 Point\n}\n\ntype ObjectSumType = Line | Point\n\nmut object_list := []ObjectSumType{}\nobject_list << Point{1, 1}\nobject_list << Line{\n p1: Point{3, 3}\n p2: Point{4, 4}\n}\ndump(object_list)\n/*\nobject_list: [ObjectSumType(Point{\n x: 1\n y: 1\n}), ObjectSumType(Line{\n p1: Point{\n x: 3\n y: 3\n }\n p2: Point{\n x: 4\n y: 4\n }\n})]\n*/" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Multidimensional Arrays

+

Arrays can have more than one dimension.

+

2d array example:

+{% set code = "mut a := [][]int{len: 2, init: []int{len: 3}}\na[0][1] = 2\nprintln(a) // [[0, 2, 0], [0, 0, 0]]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

3d array example:

+{% set code = "mut a := [][][]int{len: 2, init: [][]int{len: 3, init: []int{len: 2}}}\na[0][1][1] = 2\nprintln(a) // [[[0, 0], [0, 2], [0, 0]], [[0, 0], [0, 0], [0, 0]]]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Array methods

+

All arrays can be easily printed with println(arr) and converted to a string +with s := arr.str().

+

Copying the data from the array is done with .clone():

+{% set code = "nums := [1, 2, 3]\nnums_copy := nums.clone()" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Arrays can be efficiently filtered and mapped with the .filter() and +.map() methods:

+{% set code = "nums := [1, 2, 3, 4, 5, 6]\neven := nums.filter(it % 2 == 0)\nprintln(even) // [2, 4, 6]\n// filter can accept anonymous functions\neven_fn := nums.filter(fn (x int) bool {\n return x % 2 == 0\n})\nprintln(even_fn)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "words := ['hello', 'world']\nupper := words.map(it.to_upper())\nprintln(upper) // ['HELLO', 'WORLD']\n// map can also accept anonymous functions\nupper_fn := words.map(fn (w string) string {\n return w.to_upper()\n})\nprintln(upper_fn) // ['HELLO', 'WORLD']" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

it is a builtin variable which refers to the element currently being +processed in filter/map methods.

+

Additionally, .any() and .all() can be used to conveniently test +for elements that satisfy a condition.

+{% set code = "nums := [1, 2, 3]\nprintln(nums.any(it == 2)) // true\nprintln(nums.all(it >= 2)) // false" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

There are further built-in methods for arrays:

+ +

See all methods of array

+

See also vlib/arrays.

+
# Sorting Arrays
+

Sorting arrays of all kinds is very simple and intuitive. Special variables a and b +are used when providing a custom sorting condition.

+{% set code = "mut numbers := [1, 3, 2]\nnumbers.sort() // 1, 2, 3\nnumbers.sort(a > b) // 3, 2, 1" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "struct User {\n age int\n name string\n}\n\nmut users := [User{21, 'Bob'}, User{20, 'Zarkon'}, User{25, 'Alice'}]\nusers.sort(a.age < b.age) // sort by User.age int field\nusers.sort(a.name > b.name) // reverse sort by User.name string field" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V also supports custom sorting, through the sort_with_compare array method. +Which expects a comparing function which will define the sort order. +Useful for sorting on multiple fields at the same time by custom sorting rules. +The code below sorts the array ascending on name and descending age.

+{% set code = "struct User {\n age int\n name string\n}\n\nmut users := [User{21, 'Bob'}, User{65, 'Bob'}, User{25, 'Alice'}]\n\ncustom_sort_fn := fn (a &User, b &User) int {\n // return -1 when a comes before b\n // return 0, when both are in same order\n // return 1 when b comes before a\n if a.name == b.name {\n if a.age < b.age {\n return 1\n }\n if a.age > b.age {\n return -1\n }\n return 0\n }\n if a.name < b.name {\n return -1\n } else if a.name > b.name {\n return 1\n }\n return 0\n}\nusers.sort_with_compare(custom_sort_fn)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Array Slices

+

A slice is a part of a parent array. Initially it refers to the elements +between two indices separated by a .. operator. The right-side index must +be greater than or equal to the left side index.

+

If a right-side index is absent, it is assumed to be the array length. If a +left-side index is absent, it is assumed to be 0.

+{% set code = "nums := [0, 10, 20, 30, 40]\nprintln(nums[1..4]) // [10, 20, 30]\nprintln(nums[..4]) // [0, 10, 20, 30]\nprintln(nums[1..]) // [10, 20, 30, 40]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

In V slices are arrays themselves (they are not distinct types). As a result +all array operations may be performed on them. E.g. they can be pushed onto an +array of the same type:

+{% set code = "array_1 := [3, 5, 4, 7, 6]\nmut array_2 := [0, 1]\narray_2 << array_1[..3]\nprintln(array_2) // `[0, 1, 3, 5, 4]`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A slice is always created with the smallest possible capacity cap == len (see +cap above) no matter what the capacity or length +of the parent array is. As a result it is immediately reallocated and copied to another +memory location when the size increases thus becoming independent from the +parent array (copy on grow). In particular pushing elements to a slice +does not alter the parent:

+{% set code = "mut a := [0, 1, 2, 3, 4, 5]\nmut b := a[2..4]\nb[0] = 7 // `b[0]` is referring to `a[2]`\nprintln(a) // `[0, 1, 7, 3, 4, 5]`\nb << 9\n// `b` has been reallocated and is now independent from `a`\nprintln(a) // `[0, 1, 7, 3, 4, 5]` - no change\nprintln(b) // `[7, 3, 9]`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Appending to the parent array may or may not make it independent from its child slices. +The behaviour depends on the parent's capacity and is predictable:

+{% set code = "mut a := []int{len: 5, cap: 6, init: 2}\nmut b := a[1..4]\na << 3\n// no reallocation - fits in `cap`\nb[2] = 13 // `a[3]` is modified\na << 4\n// a has been reallocated and is now independent from `b` (`cap` was exceeded)\nb[1] = 3 // no change in `a`\nprintln(a) // `[2, 2, 2, 13, 2, 3, 4]`\nprintln(b) // `[2, 3, 13]`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can call .clone() on the slice, if you do want to have an independent copy right away:

+{% set code = "mut a := [0, 1, 2, 3, 4, 5]\nmut b := a[2..4].clone()\nb[0] = 7 // Note: `b[0]` is NOT referring to `a[2]`, as it would have been, without the .clone()\nprintln(a) // [0, 1, 2, 3, 4, 5]\nprintln(b) // [7, 3]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
# Slices with negative indexes
+

V supports array and string slices with negative indexes. +Negative indexing starts from the end of the array towards the start, +for example -3 is equal to array.len - 3. +Negative slices have a different syntax from normal slices, i.e. you need +to add a gate between the array name and the square bracket: a#[..-3]. +The gate specifies that this is a different type of slice and remember that +the result is "locked" inside the array. +The returned slice is always a valid array, though it may be empty:

+{% set code = "a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprintln(a#[-3..]) // [7, 8, 9]\nprintln(a#[-20..]) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprintln(a#[-20..-8]) // [0, 1]\nprintln(a#[..-3]) // [0, 1, 2, 3, 4, 5, 6]\n\n// empty arrays\nprintln(a#[-20..-10]) // []\nprintln(a#[20..10]) // []\nprintln(a#[20..30]) // []" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Array method chaining

+

You can chain the calls of array methods like .filter() and .map() and use +the it built-in variable to achieve a classic map/filter functional paradigm:

+{% set code = "// using filter, map and negatives array slices\nfiles := ['pippo.jpg', '01.bmp', '_v.txt', 'img_02.jpg', 'img_01.JPG']\nfiltered := files.filter(it#[-4..].to_lower() == '.jpg').map(it.to_upper())\n// ['PIPPO.JPG', 'IMG_02.JPG', 'IMG_01.JPG']" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Fixed size arrays

+

V also supports arrays with fixed size. Unlike ordinary arrays, their +length is constant. You cannot append elements to them, nor shrink them. +You can only modify their elements in place.

+

However, access to the elements of fixed size arrays is more efficient, +they need less memory than ordinary arrays, and unlike ordinary arrays, +their data is on the stack, so you may want to use them as buffers if you +do not want additional heap allocations.

+

Most methods are defined to work on ordinary arrays, not on fixed size arrays. +You can convert a fixed size array to an ordinary array with slicing:

+{% set code = "mut fnums := [3]int{} // fnums is a fixed size array with 3 elements.\nfnums[0] = 1\nfnums[1] = 10\nfnums[2] = 100\nprintln(fnums) // => [1, 10, 100]\nprintln(typeof(fnums).name) // => [3]int\n\nfnums2 := [1, 10, 100]! // short init syntax that does the same (the syntax will probably change)\n\nanums := fnums[..] // same as `anums := fnums[0..fnums.len]`\nprintln(anums) // => [1, 10, 100]\nprintln(typeof(anums).name) // => []int" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Note that slicing will cause the data of the fixed size array to be copied to +the newly created ordinary array.

+

# Maps

+{% set code = "mut m := map[string]int{} // a map with `string` keys and `int` values\nm['one'] = 1\nm['two'] = 2\nprintln(m['one']) // \"1\"\nprintln(m['bad_key']) // \"0\"\nprintln('bad_key' in m) // Use `in` to detect whether such key exists\nprintln(m.keys()) // ['one', 'two']\nm.delete('two')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Maps can have keys of type string, rune, integer, float or voidptr.

+

The whole map can be initialized using this short syntax:

+{% set code = "numbers := {\n 'one': 1\n 'two': 2\n}\nprintln(numbers)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If a key is not found, a zero value is returned by default:

+{% set code = "sm := {\n 'abc': 'xyz'\n}\nval := sm['bad_key']\nprintln(val) // ''" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "intm := {\n 1: 1234\n 2: 5678\n}\ns := intm[3]\nprintln(s) // 0" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

It's also possible to use an or {} block to handle missing keys:

+{% set code = "mm := map[string]int{}\nval := mm['bad_key'] or { panic('key not found') }" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can also check, if a key is present, and get its value, if it was present, in one go:

+{% set code = "m := {\n 'abc': 'def'\n}\nif v := m['abc'] {\n println('the map value for that key is: ${v}')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The same option check applies to arrays:

+{% set code = "arr := [1, 2, 3]\nlarge_index := 999\nval := arr[large_index] or { panic('out of bounds') }\nprintln(val)\n// you can also do this, if you want to *propagate* the access error:\nval2 := arr[333]!\nprintln(val2)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V also supports nested maps:

+{% set code = "mut m := map[string]map[string]int{}\nm['greet'] = {\n 'Hello': 1\n}\nm['place'] = {\n 'world': 2\n}\nm['code']['orange'] = 123\nprint(m)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Maps are ordered by insertion, like dictionaries in Python. The order is a +guaranteed language feature. This may change in the future.

+

See all methods of +map +and +maps.

+

# Module imports

+

For information about creating a module, see Modules.

+

Modules can be imported using the import keyword:

+{% set code = "import os\n\nfn main() {\n // read text from stdin\n name := os.input('Enter your name: ')\n println('Hello, ${name}!')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This program can use any public definitions from the os module, such +as the input function. See the standard library +documentation for a list of common modules and their public symbols.

+

By default, you have to specify the module prefix every time you call an external function. +This may seem verbose at first, but it makes code much more readable +and easier to understand - it's always clear which function from +which module is being called. This is especially useful in large code bases.

+

Cyclic module imports are not allowed, like in Go.

+

# Selective imports

+

You can also import specific functions and types from modules directly:

+{% set code = "import os { input }\n\nfn main() {\n // read text from stdin\n name := input('Enter your name: ')\n println('Hello, ${name}!')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +This will import the module as well. Also, this is not allowed for +constants - they must always be prefixed.

+
+

You can import several specific symbols at once:

+{% set code = "import os { input, user_os }\n\nname := input('Enter your name: ')\nprintln('Name: ${name}')\ncurrent_os := user_os()\nprintln('Your OS is ${current_os}.')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Module import aliasing

+

Any imported module name can be aliased using the as keyword:

+
+

Note +This example will not compile unless you have created mymod/sha256.v

+
+{% set code = "import crypto.sha256\nimport mymod.sha256 as mysha256\n\nfn main() {\n v_hash := sha256.sum('hi'.bytes()).hex()\n my_hash := mysha256.sum('hi'.bytes()).hex()\n assert my_hash == v_hash\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You cannot alias an imported function or type. +However, you can redeclare a type.

+{% set code = "import time\nimport math\n\ntype MyTime = time.Time\n\nfn (mut t MyTime) century() int {\n return int(1.0 + math.trunc(f64(t.year) * 0.009999794661191))\n}\n\nfn main() {\n mut my_time := MyTime{\n year: 2020\n month: 12\n day: 25\n }\n println(time.new_time(my_time).utc_string())\n println('Century: ${my_time.century()}')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Statements & expressions

+

# If

+{% set code = "a := 10\nb := 20\nif a < b {\n println('${a} < ${b}')\n} else if a > b {\n println('${a} > ${b}')\n} else {\n println('${a} == ${b}')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

if statements are pretty straightforward and similar to most other languages. +Unlike other C-like languages, +there are no parentheses surrounding the condition and the braces are always required.

+

if can be used as an expression:

+{% set code = "num := 777\ns := if num % 2 == 0 { 'even' } else { 'odd' }\nprintln(s)\n// \"odd\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Type checks and casts

+

You can check the current type of a sum type using is and its negated form !is.

+

You can do it either in an if:

+{% set code = "struct Abc {\n val string\n}\n\nstruct Xyz {\n foo string\n}\n\ntype Alphabet = Abc | Xyz\n\nx := Alphabet(Abc{'test'}) // sum type\nif x is Abc {\n // x is automatically casted to Abc and can be used here\n println(x)\n}\nif x !is Abc {\n println('Not Abc')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

or using match:

+{% set code = "match x {\n Abc {\n // x is automatically casted to Abc and can be used here\n println(x)\n }\n Xyz {\n // x is automatically casted to Xyz and can be used here\n println(x)\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This works also with struct fields:

+{% set code = "struct MyStruct {\n x int\n}\n\nstruct MyStruct2 {\n y string\n}\n\ntype MySumType = MyStruct | MyStruct2\n\nstruct Abc {\n bar MySumType\n}\n\nx := Abc{\n bar: MyStruct{123} // MyStruct will be converted to MySumType type automatically\n}\nif x.bar is MyStruct {\n // x.bar is automatically casted\n println(x.bar)\n} else if x.bar is MyStruct2 {\n new_var := x.bar as MyStruct2\n // ... or you can use `as` to create a type cast an alias manually:\n println(new_var)\n}\nmatch x.bar {\n MyStruct {\n // x.bar is automatically casted\n println(x.bar)\n }\n else {}\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Mutable variables can change, and doing a cast would be unsafe. +However, sometimes it's useful to type cast despite mutability. +In such cases the developer must mark the expression with the mut keyword +to tell the compiler that they know what they're doing.

+

It works like this:

+{% set code = "mut x := MySumType(MyStruct{123})\nif mut x is MyStruct {\n // x is casted to MyStruct even if it's mutable\n // without the mut keyword that wouldn't work\n println(x)\n}\n// same with match\nmatch mut x {\n MyStruct {\n // x is casted to MyStruct even if it's mutable\n // without the mut keyword that wouldn't work\n println(x)\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Match

+{% set code = "os := 'windows'\nprint('V is running on ')\nmatch os {\n 'darwin' { println('macOS.') }\n 'linux' { println('Linux.') }\n else { println(os) }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A match statement is a shorter way to write a sequence of if - else statements. +When a matching branch is found, the following statement block will be run. +The else branch will be run when no other branches match.

+{% set code = "number := 2\ns := match number {\n 1 { 'one' }\n 2 { 'two' }\n else { 'many' }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A match statement can also to be used as an if - else if - else alternative:

+{% set code = "match true {\n 2 > 4 { println('if') }\n 3 == 4 { println('else if') }\n 2 == 2 { println('else if2') }\n else { println('else') }\n}\n// 'else if2' should be printed" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

or as an unless alternative: unless Ruby

+{% set code = "match false {\n 2 > 4 { println('if') }\n 3 == 4 { println('else if') }\n 2 == 2 { println('else if2') }\n else { println('else') }\n}\n// 'if' should be printed" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A match expression returns the value of the final expression from the matching branch.

+{% set code = "enum Color {\n red\n blue\n green\n}\n\nfn is_red_or_blue(c Color) bool {\n return match c {\n .red, .blue { true } // comma can be used to test multiple values\n .green { false }\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A match statement can also be used to branch on the variants of an enum +by using the shorthand .variant_here syntax. An else branch is not allowed +when all the branches are exhaustive.

+{% set code = "c := `v`\ntyp := match c {\n `0`...`9` { 'digit' }\n `A`...`Z` { 'uppercase' }\n `a`...`z` { 'lowercase' }\n else { 'other' }\n}\nprintln(typ)\n// 'lowercase'" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can also use ranges as match patterns. If the value falls within the range +of a branch, that branch will be executed.

+

Note that the ranges use ... (three dots) rather than .. (two dots). This is +because the range is inclusive of the last element, rather than exclusive +(as .. ranges are). Using .. in a match branch will throw an error.

+{% set code = "const start = 1\n\nconst end = 10\n\nc := 2\nnum := match c {\n start...end {\n 1000\n }\n else {\n 0\n }\n}\nprintln(num)\n// 1000" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Constants can also be used in the range branch expressions.

+
+

Note +match as an expression is not usable in for loop and if statements.

+
+

# In operator

+

in allows to check whether an array or a map contains an element. +To do the opposite, use !in.

+{% set code = "nums := [1, 2, 3]\nprintln(1 in nums) // true\nprintln(4 !in nums) // true\nm := {\n 'one': 1\n 'two': 2\n}\nprintln('one' in m) // true\nprintln('three' !in m) // true" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

It's also useful for writing boolean expressions that are clearer and more compact:

+{% set code = "enum Token {\n plus\n minus\n div\n mult\n}\n\nstruct Parser {\n token Token\n}\n\nparser := Parser{}\nif parser.token == .plus || parser.token == .minus || parser.token == .div || parser.token == .mult {\n // ...\n}\nif parser.token in [.plus, .minus, .div, .mult] {\n // ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V optimizes such expressions, +so both if statements above produce the same machine code and no arrays are created.

+

# For loop

+

V has only one looping keyword: for, with several forms.

+

# for/in

+

This is the most common form. You can use it with an array, map or +numeric range.

+
# Array for
+{% set code = "numbers := [1, 2, 3, 4, 5]\nfor num in numbers {\n println(num)\n}\nnames := ['Sam', 'Peter']\nfor i, name in names {\n println('${i}) ${name}')\n // Output: 0) Sam\n // 1) Peter\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The for value in arr form is used for going through elements of an array. +If an index is required, an alternative form for index, value in arr can be used.

+

Note, that the value is read-only. +If you need to modify the array while looping, you need to declare the element as mutable:

+{% set code = "mut numbers := [0, 1, 2]\nfor mut num in numbers {\n num++\n}\nprintln(numbers) // [1, 2, 3]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

When an identifier is just a single underscore, it is ignored.

+
# Custom iterators
+

Types that implement a next method returning an Option can be iterated +with a for loop.

+{% set code = "struct SquareIterator {\n arr []int\nmut:\n idx int\n}\n\nfn (mut iter SquareIterator) next() ?int {\n if iter.idx >= iter.arr.len {\n return none\n }\n defer {\n iter.idx++\n }\n return iter.arr[iter.idx] * iter.arr[iter.idx]\n}\n\nnums := [1, 2, 3, 4, 5]\niter := SquareIterator{\n arr: nums\n}\nfor squared in iter {\n println(squared)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The code above prints:

+{% set code = "1\n4\n9\n16\n25" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
# Map for
+{% set code = "m := {\n 'one': 1\n 'two': 2\n}\nfor key, value in m {\n println('${key} -> ${value}')\n // Output: one -> 1\n // two -> 2\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Either key or value can be ignored by using a single underscore as the identifier.

+{% set code = "m := {\n 'one': 1\n 'two': 2\n}\n// iterate over keys\nfor key, _ in m {\n println(key)\n // Output: one\n // two\n}\n// iterate over values\nfor _, value in m {\n println(value)\n // Output: 1\n // 2\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
# Range for
+{% set code = "// Prints '01234'\nfor i in 0 .. 5 {\n print(i)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

low..high means an exclusive range, which represents all values +from low up to but not including high.

+

# Condition for

+{% set code = "mut sum := 0\nmut i := 0\nfor i <= 100 {\n sum += i\n i++\n}\nprintln(sum) // \"5050\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This form of the loop is similar to while loops in other languages. +The loop will stop iterating once the boolean condition evaluates to false. +Again, there are no parentheses surrounding the condition, and the braces are always required.

+

# Bare for

+{% set code = "mut num := 0\nfor {\n num += 2\n if num >= 10 {\n break\n }\n}\nprintln(num) // \"10\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The condition can be omitted, resulting in an infinite loop.

+

# C for

+{% set code = "for i := 0; i < 10; i += 2 {\n // Don't print 6\n if i == 6 {\n continue\n }\n println(i)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Finally, there's the traditional C style for loop. It's safer than the while form +because with the latter it's easy to forget to update the counter and get +stuck in an infinite loop.

+

Here i doesn't need to be declared with mut since it's always going to be mutable by definition.

+

# Labelled break & continue

+

break and continue control the innermost for loop by default. +You can also use break and continue followed by a label name to refer to an outer for +loop:

+{% set code = "outer: for i := 4; true; i++ {\n println(i)\n for {\n if i < 7 {\n continue outer\n } else {\n break outer\n }\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The label must immediately precede the outer loop. +The above code prints:

+{% set code = "4\n5\n6\n7" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Defer

+

A defer statement defers the execution of a block of statements +until the surrounding function returns.

+{% set code = "import os\n\nfn read_log() {\n mut ok := false\n mut f := os.open('log.txt') or { panic(err) }\n defer {\n f.close()\n }\n // ...\n if !ok {\n // defer statement will be called here, the file will be closed\n return\n }\n // ...\n // defer statement will be called here, the file will be closed\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If the function returns a value the defer block is executed after the return +expression is evaluated:

+{% set code = "import os\n\nenum State {\n normal\n write_log\n return_error\n}\n\n// write log file and return number of bytes written\n\nfn write_log(s State) !int {\n mut f := os.create('log.txt')!\n defer {\n f.close()\n }\n if s == .write_log {\n // `f.close()` will be called after `f.write()` has been\n // executed, but before `write_log()` finally returns the\n // number of bytes written to `main()`\n return f.writeln('This is a log file')\n } else if s == .return_error {\n // the file will be closed after the `error()` function\n // has returned - so the error message will still report\n // it as open\n return error('nothing written; file open: ${f.is_opened}')\n }\n // the file will be closed here, too\n return 0\n}\n\nfn main() {\n n := write_log(.return_error) or {\n println('Error: ${err}')\n 0\n }\n println('${n} bytes written')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Goto

+

V allows unconditionally jumping to a label with goto. The label name must be contained +within the same function as the goto statement. A program may goto a label outside +or deeper than the current scope. goto allows jumping past variable initialization or +jumping back to code that accesses memory that has already been freed, so it requires +unsafe.

+{% set code = "if x {\n // ...\n if y {\n unsafe {\n goto my_label\n }\n }\n // ...\n}\nmy_label:" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

goto should be avoided, particularly when for can be used instead. +Labelled break/continue can be used to break out of +a nested loop, and those do not risk violating memory-safety.

+

# Structs

+{% set code = "struct Point {\n x int\n y int\n}\n\nmut p := Point{\n x: 10\n y: 20\n}\nprintln(p.x) // Struct fields are accessed using a dot\n// Alternative literal syntax for structs with 3 fields or fewer\np = Point{10, 20}\nassert p.x == 10" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Heap structs

+

Structs are allocated on the stack. To allocate a struct on the heap +and get a reference to it, use the & prefix:

+{% set code = "struct Point {\n x int\n y int\n}\n\np := &Point{10, 10}\n// References have the same syntax for accessing fields\nprintln(p.x)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The type of p is &Point. It's a reference to Point. +References are similar to Go pointers and C++ references.

+{% set code = "struct Foo {\nmut:\n x int\n}\n\nfa := Foo{1}\nmut a := fa\na.x = 2\nassert fa.x == 1\nassert a.x == 2\n\n// fb := Foo{ 1 }\n// mut b := &fb // error: `fb` is immutable, cannot have a mutable reference to it\n// b.x = 2\n\nmut fc := Foo{1}\nmut c := &fc\nc.x = 2\nassert fc.x == 2\nassert c.x == 2\nprintln(fc) // Foo{ x: 2 }\nprintln(c) // &Foo{ x: 2 } // Note `&` prefixed." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

see also Stack and Heap

+

# Default field values

+{% set code = "struct Foo {\n n int // n is 0 by default\n s string // s is '' by default\n a []int // a is `[]int{}` by default\n pos int = -1 // custom default value\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

All struct fields are zeroed by default during the creation of the struct. +Array and map fields are allocated. +In case of reference value, see.

+

It's also possible to define custom default values.

+

# Required fields

+{% set code = "struct Foo {\n n int [required]\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can mark a struct field with the [required] attribute, to tell V that +that field must be initialized when creating an instance of that struct.

+

This example will not compile, since the field n isn't explicitly initialized:

+{% set code = "_ = Foo{}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

<a id='short-struct-initialization-syntax'></a>

+

# Short struct literal syntax

+{% set code = "struct Point {\n x int\n y int\n}\n\nmut p := Point{\n x: 10\n y: 20\n}\np = Point{\n x: 30\n y: 4\n}\nassert p.y == 4\n//\n// array: first element defines type of array\npoints := [Point{10, 20}, Point{20, 30}, Point{40, 50}]\nprintln(points) // [Point{x: 10, y: 20}, Point{x: 20, y: 30}, Point{x: 40,y: 50}]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Omitting the struct name also works for returning a struct literal or passing one +as a function argument.

+

# Struct update syntax

+

V makes it easy to return a modified version of an object:

+{% set code = "struct User {\n name string\n age int\n is_registered bool\n}\n\nfn register(u User) User {\n return User{\n ...u\n is_registered: true\n }\n}\n\nmut user := User{\n name: 'abc'\n age: 23\n}\nuser = register(user)\nprintln(user)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Trailing struct literal arguments

+

V doesn't have default function arguments or named arguments, for that trailing struct +literal syntax can be used instead:

+{% set code = "[params]\nstruct ButtonConfig {\n text string\n is_disabled bool\n width int = 70\n height int = 20\n}\n\nstruct Button {\n text string\n width int\n height int\n}\n\nfn new_button(c ButtonConfig) &Button {\n return &Button{\n width: c.width\n height: c.height\n text: c.text\n }\n}\n\nbutton := new_button(text: 'Click me', width: 100)\n// the height is unset, so it's the default value\nassert button.height == 20" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

As you can see, both the struct name and braces can be omitted, instead of:

+{% set code = "new_button(ButtonConfig{text:'Click me', width:100})" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This only works for functions that take a struct for the last argument.

+
+

Note the [params] tag is used to tell V, that the trailing struct parameter +can be omitted entirely, so that you can write button := new_button(). +Without it, you have to specify at least one of the field names, even if it +has its default value, otherwise the compiler will produce this error message, +when you call the function with no parameters: +error: expected 1 arguments, but got 0.

+
+

# Access modifiers

+

Struct fields are private and immutable by default (making structs immutable as well). +Their access modifiers can be changed with +pub and mut. In total, there are 5 possible options:

+{% set code = "struct Foo {\n a int // private immutable (default)\nmut:\n b int // private mutable\n c int // (you can list multiple fields with the same access modifier)\npub:\n d int // public immutable (readonly)\npub mut:\n e int // public, but mutable only in parent module\n__global:\n // (not recommended to use, that's why the 'global' keyword starts with __)\n f int // public and mutable both inside and outside parent module\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Private fields are available only inside the same module, any attempt +to directly access them from another module will cause an error during compilation. +Public immutable fields are readonly everywhere.

+

# Anonymous structs

+

V supports anonymous structs: structs that don't have to be declared separately +with a struct name.

+{% set code = "struct Book {\n author struct {\n name string\n age int\n }\n\n title string\n}\n\nbook := Book{\n author: struct {\n name: 'Samantha Black'\n age: 24\n }\n}\nassert book.author.name == 'Samantha Black'\nassert book.author.age == 24" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# [noinit] structs

+

V supports [noinit] structs, which are structs that cannot be initialised outside the module +they are defined in. They are either meant to be used internally or they can be used externally +through factory functions.

+

For an example, consider the following source in a directory sample:

+{% set code = "module sample\n\n[noinit]\npub struct Information {\npub:\n data string\n}\n\npub fn new_information(data string) !Information {\n if data.len == 0 || data.len > 100 {\n return error('data must be between 1 and 100 characters')\n }\n return Information{\n data: data\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Note that new_information is a factory function. Now when we want to use this struct +outside the module:

+{% set code = "import sample\n\nfn main() {\n // This doesn't work when the [noinit] attribute is present:\n // info := sample.Information{\n // data: 'Sample information.'\n // }\n\n // Use this instead:\n info := sample.new_information('Sample information.')!\n\n println(info)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Methods

+{% set code = "struct User {\n age int\n}\n\nfn (u User) can_register() bool {\n return u.age > 16\n}\n\nuser := User{\n age: 10\n}\nprintln(user.can_register()) // \"false\"\nuser2 := User{\n age: 20\n}\nprintln(user2.can_register()) // \"true\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V doesn't have classes, but you can define methods on types. +A method is a function with a special receiver argument. +The receiver appears in its own argument list between the fn keyword and the method name. +Methods must be in the same module as the receiver type.

+

In this example, the can_register method has a receiver of type User named u. +The convention is not to use receiver names like self or this, +but a short, preferably one letter long, name.

+

# Embedded structs

+

V support embedded structs .

+{% set code = "struct Size {\nmut:\n width int\n height int\n}\n\nfn (s &Size) area() int {\n return s.width * s.height\n}\n\nstruct Button {\n Size\n title string\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

With embedding, the struct Button will automatically have get all the fields and methods from +the struct Size, which allows you to do:

+{% set code = "mut button := Button{\n title: 'Click me'\n height: 2\n}\n\nbutton.width = 3\nassert button.area() == 6\nassert button.Size.area() == 6\nprint(button)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

output :

+{% set code = "Button{\n Size: Size{\n width: 3\n height: 2\n }\n title: 'Click me'\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Unlike inheritance, you cannot type cast between structs and embedded structs +(the embedding struct can also has its own fields, and it can also embed multiple structs).

+

If you need to access embedded structs directly, use an explicit reference like button.Size.

+

Conceptually, embedded structs are similar to mixins +in OOP, NOT base classes.

+

You can also initialize an embedded struct:

+{% set code = "mut button := Button{\n Size: Size{\n width: 3\n height: 2\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

or assign values:

+{% set code = "button.Size = Size{\n width: 4\n height: 5\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If multiple embedded structs have methods or fields with the same name, or if methods or fields +with the same name are defined in the struct, you can call methods or assign to variables in +the embedded struct like button.Size.area(). +When you do not specify the embedded struct name, the method of the outermost struct will be +targeted.

+

# Unions

+

Just like structs, unions support embedding.

+{% set code = "struct Rgba32_Component {\n r byte\n g byte\n b byte\n a byte\n}\n\nunion Rgba32 {\n Rgba32_Component\n value u32\n}\n\nclr1 := Rgba32{\n value: 0x008811FF\n}\n\nclr2 := Rgba32{\n Rgba32_Component: Rgba32_Component{\n a: 128\n }\n}\n\nsz := sizeof(Rgba32)\nunsafe {\n println('Size: ${sz}B,clr1.b: ${clr1.b},clr2.b: ${clr2.b}')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Output: Size: 4B, clr1.b: 136, clr2.b: 0

+

Union member access must be performed in an unsafe block.

+
+

Note +Embedded struct arguments are not necessarily stored in the order listed.

+
+

# Functions 2

+

# Immutable function args by default

+

In V function arguments are immutable by default, and mutable args have to be +marked on call.

+

Since there are also no globals, that means that the return values of the functions, +are a function of their arguments only, and their evaluation has no side effects +(unless the function uses I/O).

+

Function arguments are immutable by default, even when references are passed.

+
+

Note +V is not a purely functional language however.

+
+

There is a compiler flag to enable global variables (-enable-globals), but this is +intended for low-level applications like kernels and drivers.

+

# Mutable arguments

+

It is possible to modify function arguments by declaring them with the keyword mut:

+{% set code = "struct User {\n name string\nmut:\n is_registered bool\n}\n\nfn (mut u User) register() {\n u.is_registered = true\n}\n\nmut user := User{}\nprintln(user.is_registered) // \"false\"\nuser.register()\nprintln(user.is_registered) // \"true\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

In this example, the receiver (which is just the first argument) is explicitly marked as mutable, +so register() can change the user object. The same works with non-receiver arguments:

+{% set code = "fn multiply_by_2(mut arr []int) {\n for i in 0 .. arr.len {\n arr[i] *= 2\n }\n}\n\nmut nums := [1, 2, 3]\nmultiply_by_2(mut nums)\nprintln(nums)\n// \"[2, 4, 6]\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Note, that you have to add mut before nums when calling this function. This makes +it clear that the function being called will modify the value.

+

It is preferable to return values instead of modifying arguments, +e.g. user = register(user) (or user.register()) instead of register(mut user). +Modifying arguments should only be done in performance-critical parts of your application +to reduce allocations and copying.

+

For this reason V doesn't allow the modification of arguments with primitive types (e.g. integers). +Only more complex types such as arrays and maps may be modified.

+

# Variable number of arguments

+{% set code = "fn sum(a ...int) int {\n mut total := 0\n for x in a {\n total += x\n }\n return total\n}\n\nprintln(sum()) // 0\nprintln(sum(1)) // 1\nprintln(sum(2, 3)) // 5\n// using array decomposition\na := [2, 3, 4]\nprintln(sum(...a)) // <-- using prefix ... here. output: 9\nb := [5, 6, 7]\nprintln(sum(...b)) // output: 18" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Anonymous & higher order functions

+{% set code = "fn sqr(n int) int {\n return n * n\n}\n\nfn cube(n int) int {\n return n * n * n\n}\n\nfn run(value int, op fn (int) int) int {\n return op(value)\n}\n\nfn main() {\n // Functions can be passed to other functions\n println(run(5, sqr)) // \"25\"\n // Anonymous functions can be declared inside other functions:\n double_fn := fn (n int) int {\n return n + n\n }\n println(run(5, double_fn)) // \"10\"\n // Functions can be passed around without assigning them to variables:\n res := run(5, fn (n int) int {\n return n + n\n })\n println(res) // \"10\"\n // You can even have an array/map of functions:\n fns := [sqr, cube]\n println(fns[0](10)) // \"100\"\n fns_map := {\n 'sqr': sqr\n 'cube': cube\n }\n println(fns_map['cube'](2)) // \"8\"\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Closures

+

V supports closures too. +This means that anonymous functions can inherit variables from the scope they were created in. +They must do so explicitly by listing all variables that are inherited.

+{% set code = "my_int := 1\nmy_closure := fn [my_int] () {\n println(my_int)\n}\nmy_closure() // prints 1" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Inherited variables are copied when the anonymous function is created. +This means that if the original variable is modified after the creation of the function, +the modification won't be reflected in the function.

+{% set code = "mut i := 1\nfunc := fn [i] () int {\n return i\n}\nprintln(func() == 1) // true\ni = 123\nprintln(func() == 1) // still true" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

However, the variable can be modified inside the anonymous function. +The change won't be reflected outside, but will be in the later function calls.

+{% set code = "fn new_counter() fn () int {\n mut i := 0\n return fn [mut i] () int {\n i++\n return i\n }\n}\n\nc := new_counter()\nprintln(c()) // 1\nprintln(c()) // 2\nprintln(c()) // 3" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If you need the value to be modified outside the function, use a reference. +Warning: you need to make sure the reference is always valid, +otherwise this can result in undefined behavior.

+{% set code = "mut i := 0\nmut ref := &i\nprint_counter := fn [ref] () {\n println(*ref)\n}\n\nprint_counter() // 0\ni = 10\nprint_counter() // 10" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Parameter evaluation order

+

The evaluation order of the parameters of function calls is NOT guaranteed. +Take for example the following program:

+{% set code = "fn f(a1 int, a2 int, a3 int) {\n dump(a1 + a2 + a3)\n}\n\nfn main() {\n f(dump(100), dump(200), dump(300))\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V currently does not guarantee, that it will print 100, 200, 300 in that order. +The only guarantee is that 600 (from the body of f), will be printed after all of them. +That may change in V 1.0 .

+

# References

+{% set code = "struct Foo {}\n\nfn (foo Foo) bar_method() {\n // ...\n}\n\nfn bar_function(foo Foo) {\n // ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If a function argument is immutable (like foo in the examples above) +V can pass it either by value or by reference. The compiler will decide, +and the developer doesn't need to think about it.

+

You no longer need to remember whether you should pass the struct by value +or by reference.

+

You can ensure that the struct is always passed by reference by +adding &:

+{% set code = "struct Foo {\n abc int\n}\n\nfn (foo &Foo) bar() {\n println(foo.abc)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

foo is still immutable and can't be changed. For that, +(mut foo Foo) must be used.

+

In general, V's references are similar to Go pointers and C++ references. +For example, a generic tree structure definition would look like this:

+{% set code = "struct Node[T] {\n val T\n left &Node[T]\n right &Node[T]\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

To dereference a reference, use the * operator, just like in C.

+

# Constants

+{% set code = "const (\n pi = 3.14\n world = '世界'\n)\n\nprintln(pi)\nprintln(world)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Constants are declared with const. They can only be defined +at the module level (outside of functions). +Constant values can never be changed. You can also declare a single +constant separately:

+{% set code = "const e = 2.71828" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V constants are more flexible than in most languages. You can assign more complex values:

+{% set code = "struct Color {\n r int\n g int\n b int\n}\n\nfn rgb(r int, g int, b int) Color {\n return Color{\n r: r\n g: g\n b: b\n }\n}\n\nconst (\n numbers = [1, 2, 3]\n red = Color{\n r: 255\n g: 0\n b: 0\n }\n // evaluate function call at compile-time*\n blue = rgb(0, 0, 255)\n)\n\nprintln(numbers)\nprintln(red)\nprintln(blue)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

* WIP - for now function calls are evaluated at program start-up

+

Global variables are not normally allowed, so this can be really useful.

+

Modules

+

Constants can be made public with pub const:

+{% set code = "module mymodule\n\npub const golden_ratio = 1.61803\n\nfn calc() {\n println(mymodule.golden_ratio)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The pub keyword is only allowed before the const keyword and cannot be used inside +a const ( ) block.

+

Outside from module main all constants need to be prefixed with the module name.

+

# Required module prefix

+

When naming constants, snake_case must be used. In order to distinguish consts +from local variables, the full path to consts must be specified. For example, +to access the PI const, full math.pi name must be used both outside the math +module, and inside it. That restriction is relaxed only for the main module +(the one containing your fn main()), where you can use the unqualified name of +constants defined there, i.e. numbers, rather than main.numbers.

+

vfmt takes care of this rule, so you can type println(pi) inside the math module, +and vfmt will automatically update it to println(math.pi).

+

<!-- +Many people prefer all caps consts: TOP_CITIES. This wouldn't work +well in V, because consts are a lot more powerful than in other languages. +They can represent complex structures, and this is used quite often since there +are no globals:

+{% set code = "println('Top cities: ${top_cities.filter(.usa)}')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

-->

+

# Builtin functions

+

Some functions are builtin like println. Here is the complete list:

+{% set code = "fn print(s string) // prints anything on stdout\nfn println(s string) // prints anything and a newline on stdout\n\nfn eprint(s string) // same as print(), but uses stderr\nfn eprintln(s string) // same as println(), but uses stderr\n\nfn exit(code int) // terminates the program with a custom error code\nfn panic(s string) // prints a message and backtraces on stderr, and terminates the program with error code 1\nfn print_backtrace() // prints backtraces on stderr" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +Although the print functions take a string, V accepts other printable types too. +See below for details.

+
+

There is also a special built-in function called dump.

+

# println

+

println is a simple yet powerful builtin function, that can print anything: +strings, numbers, arrays, maps, structs.

+{% set code = "struct User {\n name string\n age int\n}\n\nprintln(1) // \"1\"\nprintln('hi') // \"hi\"\nprintln([1, 2, 3]) // \"[1, 2, 3]\"\nprintln(User{ name: 'Bob', age: 20 }) // \"User{name:'Bob', age:20}\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

See also Array methods.

+

<a id='custom-print-of-types'></a>

+

# Printing custom types

+

If you want to define a custom print value for your type, simply define a +str() string method:

+{% set code = "struct Color {\n r int\n g int\n b int\n}\n\npub fn (c Color) str() string {\n return '{${c.r}, ${c.g}, ${c.b}}'\n}\n\nred := Color{\n r: 255\n g: 0\n b: 0\n}\nprintln(red)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Dumping expressions at runtime

+

You can dump/trace the value of any V expression using dump(expr). +For example, save this code sample as factorial.v, then run it with +v run factorial.v:

+{% set code = "fn factorial(n u32) u32 {\n if dump(n <= 1) {\n return dump(1)\n }\n return dump(n * factorial(n - 1))\n}\n\nfn main() {\n println(factorial(5))\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You will get:

+{% set code = "[factorial.v:2] n <= 1: false\n[factorial.v:2] n <= 1: false\n[factorial.v:2] n <= 1: false\n[factorial.v:2] n <= 1: false\n[factorial.v:2] n <= 1: true\n[factorial.v:3] 1: 1\n[factorial.v:5] n * factorial(n - 1): 2\n[factorial.v:5] n * factorial(n - 1): 6\n[factorial.v:5] n * factorial(n - 1): 24\n[factorial.v:5] n * factorial(n - 1): 120\n120" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Note that dump(expr) will trace both the source location, +the expression itself, and the expression value.

+

# Modules

+

Every file in the root of a folder is part of the same module. +Simple programs don't need to specify module name, in which case it defaults to 'main'.

+

See symbol visibility, Access modifiers.

+

# Create modules

+

V is a very modular language. Creating reusable modules is encouraged and is +quite easy to do. +To create a new module, create a directory with your module's name containing +.v files with code:

+{% set code = "cd ~/code/modules\nmkdir mymodule\nvim mymodule/myfile.v" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "// myfile.v\nmodule mymodule\n\n// To export a function we have to use `pub`\npub fn say_hi() {\n println('hello from mymodule!')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can now use mymodule in your code:

+{% set code = "import mymodule\n\nfn main() {\n mymodule.say_hi()\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} + +

# init functions

+

If you want a module to automatically call some setup/initialization code when it is imported, +you can use a module init function:

+{% set code = "fn init() {\n // your setup code here ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The init function cannot be public - it will be called automatically. This feature is +particularly useful for initializing a C library.

+

# Type Declarations

+

# Type aliases

+

To define a new type NewType as an alias for ExistingType, +do type NewType = ExistingType.<br/> +This is a special case of a sum type declaration.

+

# Enums

+{% set code = "enum Color as u8 {\n red\n green\n blue\n}\n\nmut color := Color.red\n// V knows that `color` is a `Color`. No need to use `color = Color.green` here.\ncolor = .green\nprintln(color) // \"green\"\nmatch color {\n .red { println('the color was red') }\n .green { println('the color was green') }\n .blue { println('the color was blue') }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The enum type can be any integer type, but can be omitted, if it is int: enum Color {.

+

Enum match must be exhaustive or have an else branch. +This ensures that if a new enum field is added, it's handled everywhere in the code.

+

Enum fields cannot re-use reserved keywords. However, reserved keywords may be escaped +with an @.

+{% set code = "enum Color {\n @none\n red\n green\n blue\n}\n\ncolor := Color.@none\nprintln(color)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Integers may be assigned to enum fields.

+{% set code = "enum Grocery {\n apple\n orange = 5\n pear\n}\n\ng1 := int(Grocery.apple)\ng2 := int(Grocery.orange)\ng3 := int(Grocery.pear)\nprintln('Grocery IDs: ${g1}, ${g2}, ${g3}')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Output: Grocery IDs: 0, 5, 6.

+

Operations are not allowed on enum variables; they must be explicitly cast to int.

+

Enums can have methods, just like structs.

+{% set code = "enum Cycle {\n one\n two\n three\n}\n\nfn (c Cycle) next() Cycle {\n match c {\n .one {\n return .two\n }\n .two {\n return .three\n }\n .three {\n return .one\n }\n }\n}\n\nmut c := Cycle.one\nfor _ in 0 .. 10 {\n println(c)\n c = c.next()\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Output:

+{% set code = "one\ntwo\nthree\none\ntwo\nthree\none\ntwo\nthree\none" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Function Types

+

You can use type aliases for naming specific function signatures - for +example:

+{% set code = "type Filter = fn (string) string" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This works like any other type - for example, a function can accept an +argument of a function type:

+{% set code = "type Filter = fn (string) string\n\nfn filter(s string, f Filter) string {\n return f(s)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V has duck-typing, so functions don't need to declare compatibility with +a function type - they just have to be compatible:

+{% set code = "fn uppercase(s string) string {\n return s.to_upper()\n}\n\n// now `uppercase` can be used everywhere where Filter is expected" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Compatible functions can also be explicitly cast to a function type:

+{% set code = "my_filter := Filter(uppercase)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The cast here is purely informational - again, duck-typing means that the +resulting type is the same without an explicit cast:

+{% set code = "my_filter := uppercase" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can pass the assigned function as an argument:

+{% set code = "println(filter('Hello world', my_filter)) // prints `HELLO WORLD`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

And you could of course have passed it directly as well, without using a +local variable:

+{% set code = "println(filter('Hello world', uppercase))" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

And this works with anonymous functions as well:

+{% set code = "println(filter('Hello world', fn (s string) string {\n return s.to_upper()\n}))" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can see the complete +example here.

+

# Interfaces

+{% set code = "// interface-example.1\nstruct Dog {\n breed string\n}\n\nfn (d Dog) speak() string {\n return 'woof'\n}\n\nstruct Cat {\n breed string\n}\n\nfn (c Cat) speak() string {\n return 'meow'\n}\n\n// unlike Go and like TypeScript, V's interfaces can define fields, not just methods.\ninterface Speaker {\n breed string\n speak() string\n}\n\nfn main() {\n dog := Dog{'Leonberger'}\n cat := Cat{'Siamese'}\n\n mut arr := []Speaker{}\n arr << dog\n arr << cat\n for item in arr {\n println('a ${item.breed} says: ${item.speak()}')\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Implement an interface

+

A type implements an interface by implementing its methods and fields. +There is no explicit declaration of intent, no "implements" keyword.

+

An interface can have a mut: section. Implementing types will need +to have a mut receiver, for methods declared in the mut: section +of an interface.

+{% set code = "// interface-example.2\nmodule main\n\ninterface Foo {\n write(string) string\n}\n\n// => the method signature of a type, implementing interface Foo should be:\n// `fn (s Type) write(a string) string`\n\ninterface Bar {\nmut:\n write(string) string\n}\n\n// => the method signature of a type, implementing interface Bar should be:\n// `fn (mut s Type) write(a string) string`\n\nstruct MyStruct {}\n\n// MyStruct implements the interface Foo, but *not* interface Bar\nfn (s MyStruct) write(a string) string {\n return a\n}\n\nfn main() {\n s1 := MyStruct{}\n fn1(s1)\n // fn2(s1) -> compile error, since MyStruct does not implement Bar\n}\n\nfn fn1(s Foo) {\n println(s.write('Foo'))\n}\n\n// fn fn2(s Bar) { // does not match\n// println(s.write('Foo'))\n// }" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Casting an interface

+

We can test the underlying type of an interface using dynamic cast operators:

+{% set code = "// interface-exmaple.3 (continued from interface-exampe.1)\ninterface Something {}\n\nfn announce(s Something) {\n if s is Dog {\n println('a ${s.breed} dog') // `s` is automatically cast to `Dog` (smart cast)\n } else if s is Cat {\n println('a cat speaks ${s.speak()}')\n } else {\n println('something else')\n }\n}\n\nfn main() {\n dog := Dog{'Leonberger'}\n cat := Cat{'Siamese'}\n announce(dog)\n announce(cat)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "// interface-example.4\ninterface IFoo {\n foo()\n}\n\ninterface IBar {\n bar()\n}\n\n// implements only IFoo\nstruct SFoo {}\n\nfn (sf SFoo) foo() {}\n\n// implements both IFoo and IBar\nstruct SFooBar {}\n\nfn (sfb SFooBar) foo() {}\n\nfn (sfb SFooBar) bar() {\n dump('This implements IBar')\n}\n\nfn main() {\n mut arr := []IFoo{}\n arr << SFoo{}\n arr << SFooBar{}\n\n for a in arr {\n dump(a)\n // In order to execute instances that implements IBar.\n if a is IBar {\n // a.bar() // Error.\n b := a as IBar\n dump(b)\n b.bar()\n }\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

For more information, see Dynamic casts.

+

# Interface method definitions

+

Also unlike Go, an interface can have it's own methods, similar to how +structs can have their methods. These 'interface methods' do not have +to be implemented, by structs which implement that interface. +They are just a convenient way to write i.some_function() instead of +some_function(i), similar to how struct methods can be looked at, as +a convenience for writing s.xyz() instead of xyz(s).

+
+

Note +This feature is NOT a "default implementation" like in C#.

+
+

For example, if a struct cat is wrapped in an interface a, that has +implemented a method with the same name speak, as a method implemented by +the struct, and you do a.speak(), only the interface method is called:

+{% set code = "interface Adoptable {}\n\nfn (a Adoptable) speak() string {\n return 'adopt me!'\n}\n\nstruct Cat {}\n\nfn (c Cat) speak() string {\n return 'meow!'\n}\n\nstruct Dog {}\n\nfn main() {\n cat := Cat{}\n assert dump(cat.speak()) == 'meow!'\n //\n a := Adoptable(cat)\n assert dump(a.speak()) == 'adopt me!' // call Adoptable's `speak`\n if a is Cat {\n // Inside this `if` however, V knows that `a` is not just any\n // kind of Adoptable, but actually a Cat, so it will use the\n // Cat `speak`, NOT the Adoptable `speak`:\n dump(a.speak()) // meow!\n }\n //\n b := Adoptable(Dog{})\n assert dump(b.speak()) == 'adopt me!' // call Adoptable's `speak`\n // if b is Dog {\n // dump(b.speak()) // error: unknown method or field: Dog.speak\n // }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Embedded interface

+

Interfaces support embedding, just like structs:

+{% set code = "pub interface Reader {\nmut:\n read(mut buf []byte) ?int\n}\n\npub interface Writer {\nmut:\n write(buf []byte) ?int\n}\n\n// ReaderWriter embeds both Reader and Writer.\n// The effect is the same as copy/pasting all of the\n// Reader and all of the Writer methods/fields into\n// ReaderWriter.\npub interface ReaderWriter {\n Reader\n Writer\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Sum types

+

A sum type instance can hold a value of several different types. Use the type +keyword to declare a sum type:

+{% set code = "struct Moon {}\n\nstruct Mars {}\n\nstruct Venus {}\n\ntype World = Mars | Moon | Venus\n\nsum := World(Moon{})\nassert sum.type_name() == 'Moon'\nprintln(sum)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The built-in method type_name returns the name of the currently held +type.

+

With sum types you could build recursive structures and write concise but powerful code on them.

+{% set code = "// V's binary tree\nstruct Empty {}\n\nstruct Node {\n value f64\n left Tree\n right Tree\n}\n\ntype Tree = Empty | Node\n\n// sum up all node values\n\nfn sum(tree Tree) f64 {\n return match tree {\n Empty { 0 }\n Node { tree.value + sum(tree.left) + sum(tree.right) }\n }\n}\n\nfn main() {\n left := Node{0.2, Empty{}, Empty{}}\n right := Node{0.3, Empty{}, Node{0.4, Empty{}, Empty{}}}\n tree := Node{0.5, left, right}\n println(sum(tree)) // 0.2 + 0.3 + 0.4 + 0.5 = 1.4\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Dynamic casts

+

To check whether a sum type instance holds a certain type, use sum is Type. +To cast a sum type to one of its variants you can use sum as Type:

+{% set code = "struct Moon {}\n\nstruct Mars {}\n\nstruct Venus {}\n\ntype World = Mars | Moon | Venus\n\nfn (m Mars) dust_storm() bool {\n return true\n}\n\nfn main() {\n mut w := World(Moon{})\n assert w is Moon\n w = Mars{}\n // use `as` to access the Mars instance\n mars := w as Mars\n if mars.dust_storm() {\n println('bad weather!')\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

as will panic if w doesn't hold a Mars instance. +A safer way is to use a smart cast.

+

# Smart casting

+{% set code = "if w is Mars {\n assert typeof(w).name == 'Mars'\n if w.dust_storm() {\n println('bad weather!')\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

w has type Mars inside the body of the if statement. This is +known as flow-sensitive typing. +If w is a mutable identifier, it would be unsafe if the compiler smart casts it without a warning. +That's why you have to declare a mut before the is expression:

+{% set code = "if mut w is Mars {\n assert typeof(w).name == 'Mars'\n if w.dust_storm() {\n println('bad weather!')\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Otherwise w would keep its original type.

+
+

This works for both, simple variables and complex expressions like user.name

+
+

# Matching sum types

+

You can also use match to determine the variant:

+{% set code = "struct Moon {}\n\nstruct Mars {}\n\nstruct Venus {}\n\ntype World = Mars | Moon | Venus\n\nfn open_parachutes(n int) {\n println(n)\n}\n\nfn land(w World) {\n match w {\n Moon {} // no atmosphere\n Mars {\n // light atmosphere\n open_parachutes(3)\n }\n Venus {\n // heavy atmosphere\n open_parachutes(1)\n }\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

match must have a pattern for each variant or have an else branch.

+{% set code = "struct Moon {}\nstruct Mars {}\nstruct Venus {}\n\ntype World = Moon | Mars | Venus\n\nfn (m Moon) moon_walk() {}\nfn (m Mars) shiver() {}\nfn (v Venus) sweat() {}\n\nfn pass_time(w World) {\n match w {\n // using the shadowed match variable, in this case `w` (smart cast)\n Moon { w.moon_walk() }\n Mars { w.shiver() }\n else {}\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Option/Result types and error handling

+

Option types are for types which may represent none. Result types may +represent an error returned from a function.

+

Option types are declared by prepending ? to the type name: ?Type. +Result types use !: !Type.

+{% set code = "struct User {\n id int\n name string\n}\n\nstruct Repo {\n users []User\n}\n\nfn (r Repo) find_user_by_id(id int) !User {\n for user in r.users {\n if user.id == id {\n // V automatically wraps this into a result or option type\n return user\n }\n }\n return error('User ${id} not found')\n}\n\n// A version of the function using an option\nfn (r Repo) find_user_by_id2(id int) ?User {\n for user in r.users {\n if user.id == id {\n return user\n }\n }\n return none\n}\n\nfn main() {\n repo := Repo{\n users: [User{1, 'Andrew'}, User{2, 'Bob'}, User{10, 'Charles'}]\n }\n user := repo.find_user_by_id(10) or { // Option/Result types must be handled by `or` blocks\n println(err)\n return\n }\n println(user.id) // \"10\"\n println(user.name) // \"Charles\"\n\n user2 := repo.find_user_by_id2(10) or { return }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V used to combine Option and Result into one type, now they are separate.

+

The amount of work required to "upgrade" a function to an option/result function is minimal; +you have to add a ? or ! to the return type and return an error when something goes wrong.

+

This is the primary mechanism for error handling in V. They are still values, like in Go, +but the advantage is that errors can't be unhandled, and handling them is a lot less verbose. +Unlike other languages, V does not handle exceptions with throw/try/catch blocks.

+

err is defined inside an or block and is set to the string message passed +to the error() function.

+{% set code = "user := repo.find_user_by_id(7) or {\n println(err) // \"User 7 not found\"\n return\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Handling options/results

+

There are four ways of handling an option/result. The first method is to +propagate the error:

+{% set code = "import net.http\n\nfn f(url string) !string {\n resp := http.get(url)!\n return resp.body\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

http.get returns !http.Response. Because ! follows the call, the +error will be propagated to the caller of f. When using ? after a +function call producing an option, the enclosing function must return +an option as well. If error propagation is used in the main() +function it will panic instead, since the error cannot be propagated +any further.

+

The body of f is essentially a condensed version of:

+{% set code = " resp := http.get(url) or { return err }\n return resp.body" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

The second method is to break from execution early:

+{% set code = "user := repo.find_user_by_id(7) or { return }" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Here, you can either call panic() or exit(), which will stop the execution of the +entire program, or use a control flow statement (return, break, continue, etc) +to break from the current block.

+
+

Note +break and continue can only be used inside a for loop.

+
+

V does not have a way to forcibly "unwrap" an option (as other languages do, +for instance Rust's unwrap() or Swift's !). To do this, use or { panic(err) } instead.

+
+

The third method is to provide a default value at the end of the or block. +In case of an error, that value would be assigned instead, +so it must have the same type as the content of the Option being handled.

+{% set code = "fn do_something(s string) !string {\n if s == 'foo' {\n return 'foo'\n }\n return error('invalid string')\n}\n\na := do_something('foo') or { 'default' } // a will be 'foo'\nb := do_something('bar') or { 'default' } // b will be 'default'\nprintln(a)\nprintln(b)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

The fourth method is to use if unwrapping:

+{% set code = "import net.http\n\nif resp := http.get('https://google.com') {\n println(resp.body) // resp is a http.Response, not an option\n} else {\n println(err)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Above, http.get returns a !http.Response. resp is only in scope for the first +if branch. err is only in scope for the else branch.

+

# Custom error types

+

V gives you the ability to define custom error types through the IError interface. +The interface requires two methods: msg() string and code() int. Every type that +implements these methods can be used as an error.

+

When defining a custom error type it is recommended to embed the builtin Error default +implementation. This provides an empty default implementation for both required methods, +so you only have to implement what you really need, and may provide additional utility +functions in the future.

+{% set code = "struct PathError {\n Error\n path string\n}\n\nfn (err PathError) msg() string {\n return 'Failed to open path: ${err.path}'\n}\n\nfn try_open(path string) ? {\n return IError(PathError{\n path: path\n })\n}\n\nfn main() {\n try_open('/tmp') or { panic(err) }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Generics

+{% set code = "\nstruct Repo[T] {\n db DB\n}\n\nstruct User {\n id int\n name string\n}\n\nstruct Post {\n id int\n user_id int\n title string\n body string\n}\n\nfn new_repo[T](db DB) Repo[T] {\n return Repo[T]{db: db}\n}\n\n// This is a generic function. V will generate it for every type it's used with.\nfn (r Repo[T]) find_by_id(id int) ?T {\n table_name := T.name // in this example getting the name of the type gives us the table name\n return r.db.query_one[T]('select * from ${table_name} where id = ?', id)\n}\n\ndb := new_db()\nusers_repo := new_repo[User](db) // returns Repo[User]\nposts_repo := new_repo[Post](db) // returns Repo[Post]\nuser := users_repo.find_by_id(1)? // find_by_id[User]\npost := posts_repo.find_by_id(1)? // find_by_id[Post]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Currently generic function definitions must declare their type parameters, but in +future V will infer generic type parameters from single-letter type names in +runtime parameter types. This is why find_by_id can omit [T], because the +receiver argument r uses a generic type T.

+

Another example:

+{% set code = "fn compare[T](a T, b T) int {\n if a < b {\n return -1\n }\n if a > b {\n return 1\n }\n return 0\n}\n\n// compare[int]\nprintln(compare(1, 0)) // Outputs: 1\nprintln(compare(1, 1)) // 0\nprintln(compare(1, 2)) // -1\n// compare[string]\nprintln(compare('1', '0')) // Outputs: 1\nprintln(compare('1', '1')) // 0\nprintln(compare('1', '2')) // -1\n// compare[f64]\nprintln(compare(1.1, 1.0)) // Outputs: 1\nprintln(compare(1.1, 1.1)) // 0\nprintln(compare(1.1, 1.2)) // -1" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Concurrency

+

# Spawning Concurrent Tasks

+

V's model of concurrency is going to be very similar to Go's. +For now, spawn foo() runs foo() concurrently in a different thread:

+{% set code = "import math\n\nfn p(a f64, b f64) { // ordinary function without return value\n c := math.sqrt(a * a + b * b)\n println(c)\n}\n\nfn main() {\n spawn p(3, 4)\n // p will be run in parallel thread\n // It can also be written as follows\n // spawn fn (a f64, b f64) {\n // c := math.sqrt(a * a + b * b)\n // println(c)\n // }(3, 4)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

There's also a go keyword. Right now go foo() will be automatically renamed via vfmt +to spawn foo(), and there will be a way to launch a coroutine with go (a lightweight +thread managed by the runtime).

+

Sometimes it is necessary to wait until a parallel thread has finished. This can +be done by assigning a handle to the started thread and calling the wait() method +to this handle later:

+{% set code = "import math\n\nfn p(a f64, b f64) { // ordinary function without return value\n c := math.sqrt(a * a + b * b)\n println(c) // prints `5`\n}\n\nfn main() {\n h := spawn p(3, 4)\n // p() runs in parallel thread\n h.wait()\n // p() has definitely finished\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This approach can also be used to get a return value from a function that is run in a +parallel thread. There is no need to modify the function itself to be able to call it +concurrently.

+{% set code = "import math { sqrt }\n\nfn get_hypot(a f64, b f64) f64 { // ordinary function returning a value\n c := sqrt(a * a + b * b)\n return c\n}\n\nfn main() {\n g := spawn get_hypot(54.06, 2.08) // spawn thread and get handle to it\n h1 := get_hypot(2.32, 16.74) // do some other calculation here\n h2 := g.wait() // get result from spawned thread\n println('Results: ${h1}, ${h2}') // prints `Results: 16.9, 54.1`\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If there is a large number of tasks, it might be easier to manage them +using an array of threads.

+{% set code = "import time\n\nfn task(id int, duration int) {\n println('task ${id} begin')\n time.sleep(duration * time.millisecond)\n println('task ${id} end')\n}\n\nfn main() {\n mut threads := []thread{}\n threads << spawn task(1, 500)\n threads << spawn task(2, 900)\n threads << spawn task(3, 100)\n threads.wait()\n println('done')\n}\n\n// Output:\n// task 1 begin\n// task 2 begin\n// task 3 begin\n// task 3 end\n// task 1 end\n// task 2 end\n// done" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Additionally for threads that return the same type, calling wait() +on the thread array will return all computed values.

+{% set code = "fn expensive_computing(i int) int {\n return i * i\n}\n\nfn main() {\n mut threads := []thread int{}\n for i in 1 .. 10 {\n threads << spawn expensive_computing(i)\n }\n // Join all tasks\n r := threads.wait()\n println('All jobs finished: ${r}')\n}\n\n// Output: All jobs finished: [1, 4, 9, 16, 25, 36, 49, 64, 81]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Channels

+

Channels are the preferred way to communicate between threads. V's channels work basically like +those in Go. You can push objects into a channel on one end and pop objects from the other end. +Channels can be buffered or unbuffered and it is possible to select from multiple channels.

+

# Syntax and Usage

+

Channels have the type chan objtype. An optional buffer length can specified as the cap field +in the declaration:

+{% set code = "ch := chan int{} // unbuffered - \"synchronous\"\nch2 := chan f64{cap: 100} // buffer length 100" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Channels do not have to be declared as mut. The buffer length is not part of the type but +a field of the individual channel object. Channels can be passed to threads like normal +variables:

+{% set code = "fn f(ch chan int) {\n // ...\n}\n\nfn main() {\n ch := chan int{}\n spawn f(ch)\n // ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Objects can be pushed to channels using the arrow operator. The same operator can be used to +pop objects from the other end:

+{% set code = "// make buffered channels so pushing does not block (if there is room in the buffer)\nch := chan int{cap: 1}\nch2 := chan f64{cap: 1}\nn := 5\n// push\nch <- n\nch2 <- 7.3\nmut y := f64(0.0)\nm := <-ch // pop creating new variable\ny = <-ch2 // pop into existing variable" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

A channel can be closed to indicate that no further objects can be pushed. Any attempt +to do so will then result in a runtime panic (with the exception of select and +try_push() - see below). Attempts to pop will return immediately if the +associated channel has been closed and the buffer is empty. This situation can be +handled using an or {} block (see Handling options/results).

+{% set code = "ch := chan int{}\nch2 := chan f64{}\n// ...\nch.close()\n// ...\nm := <-ch or {\n println('channel has been closed')\n}\n\n// propagate error\ny := <-ch2 ?" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Channel Select

+

The select command allows monitoring several channels at the same time +without noticeable CPU load. It consists of a list of possible transfers and associated branches +of statements - similar to the match command:

+{% set code = "import time\n\nfn main() {\n ch := chan f64{}\n ch2 := chan f64{}\n ch3 := chan f64{}\n mut b := 0.0\n c := 1.0\n // ... setup spawn threads that will send on ch/ch2\n spawn fn (the_channel chan f64) {\n time.sleep(5 * time.millisecond)\n the_channel <- 1.0\n }(ch)\n spawn fn (the_channel chan f64) {\n time.sleep(1 * time.millisecond)\n the_channel <- 1.0\n }(ch2)\n spawn fn (the_channel chan f64) {\n _ := <-the_channel\n }(ch3)\n\n select {\n a := <-ch {\n // do something with `a`\n eprintln('> a: ${a}')\n }\n b = <-ch2 {\n // do something with predeclared variable `b`\n eprintln('> b: ${b}')\n }\n ch3 <- c {\n // do something if `c` was sent\n time.sleep(5 * time.millisecond)\n eprintln('> c: ${c} was send on channel ch3')\n }\n 500 * time.millisecond {\n // do something if no channel has become ready within 0.5s\n eprintln('> more than 0.5s passed without a channel being ready')\n }\n }\n eprintln('> done')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The timeout branch is optional. If it is absent select waits for an unlimited amount of time. +It is also possible to proceed immediately if no channel is ready in the moment select is called +by adding an else { ... } branch. else and <timeout> are mutually exclusive.

+

The select command can be used as an expression of type bool +that becomes false if all channels are closed:

+{% set code = "if select {\n ch <- a {\n // ...\n }\n} {\n // channel was open\n} else {\n // channel is closed\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Special Channel Features

+

For special purposes there are some builtin fields and methods:

+{% set code = "struct Abc {\n x int\n}\n\na := 2.13\nch := chan f64{}\nres := ch.try_push(a) // try to perform `ch <- a`\nprintln(res)\nl := ch.len // number of elements in queue\nc := ch.cap // maximum queue length\nis_closed := ch.closed // bool flag - has `ch` been closed\nprintln(l)\nprintln(c)\nmut b := Abc{}\nch2 := chan Abc{}\nres2 := ch2.try_pop(mut b) // try to perform `b = <-ch2`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The try_push/pop() methods will return immediately with one of the results +.success, .not_ready or .closed - dependent on whether the object has been transferred or +the reason why not. +Usage of these methods and fields in production is not recommended - +algorithms based on them are often subject to race conditions. Especially .len and +.closed should not be used to make decisions. +Use or branches, error propagation or select instead (see Syntax and Usage +and Channel Select above).

+

# Shared Objects

+

Data can be exchanged between a thread and the calling thread via a shared variable. +Such variables should be created as shared and passed to the thread as such, too. +The underlying struct contains a hidden mutex that allows locking concurrent access +using rlock for read-only and lock for read/write access.

+{% set code = "struct St {\nmut:\n x int // data to be shared\n}\n\nfn (shared b St) g() {\n lock b {\n // read/modify/write b.x\n }\n}\n\nfn main() {\n shared a := St{\n x: 10\n }\n spawn a.g()\n // ...\n rlock a {\n // read a.x\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Shared variables must be structs, arrays or maps.

+

# JSON

+

Because of the ubiquitous nature of JSON, support for it is built directly into V.

+

V generates code for JSON encoding and decoding. +No runtime reflection is used. This results in much better performance.

+

# Decoding JSON

+{% set code = "import json\n\nstruct Foo {\n x int\n}\n\nstruct User {\n // Adding a [required] attribute will make decoding fail, if that\n // field is not present in the input.\n // If a field is not [required], but is missing, it will be assumed\n // to have its default value, like 0 for numbers, or '' for strings,\n // and decoding will not fail.\n name string [required]\n age int\n // Use the `skip` attribute to skip certain fields\n foo Foo [skip]\n // If the field name is different in JSON, it can be specified\n last_name string [json: lastName]\n}\n\ndata := '{ \"name\": \"Frodo\", \"lastName\": \"Baggins\", \"age\": 25 }'\nuser := json.decode(User, data) or {\n eprintln('Failed to decode json, error: ${err}')\n return\n}\nprintln(user.name)\nprintln(user.last_name)\nprintln(user.age)\n// You can also decode JSON arrays:\nsfoos := '[{\"x\":123},{\"x\":456}]'\nfoos := json.decode([]Foo, sfoos)!\nprintln(foos[0].x)\nprintln(foos[1].x)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The json.decode function takes two arguments: +the first is the type into which the JSON value should be decoded and +the second is a string containing the JSON data.

+

# Encoding JSON

+{% set code = "import json\n\nstruct User {\n name string\n score i64\n}\n\nmut data := map[string]int{}\nuser := &User{\n name: 'Pierre'\n score: 1024\n}\n\ndata['x'] = 42\ndata['y'] = 360\n\nprintln(json.encode(data)) // {\"x\":42,\"y\":360}\nprintln(json.encode(user)) // {\"name\":\"Pierre\",\"score\":1024}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Testing

+

# Asserts

+{% set code = "fn foo(mut v []int) {\n v[0] = 1\n}\n\nmut v := [20]\nfoo(mut v)\nassert v[0] < 4" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

An assert statement checks that its expression evaluates to true. If an assert fails, +the program will usually abort. Asserts should only be used to detect programming errors. When an +assert fails it is reported to stderr, and the values on each side of a comparison operator +(such as <, ==) will be printed when possible. This is useful to easily find an +unexpected value. Assert statements can be used in any function, not just test ones, +which is handy when developing new functionality, to keep your invariants in check.

+
+

Note +All assert statements are removed, when you compile your program with the -prod flag.

+
+

# Asserts with an extra message

+

This form of the assert statement, will print the extra message when it fails. Note, that +you can use any string expression there - string literals, functions returning a string, +strings that interpolate variables, etc.

+{% set code = "fn test_assertion_with_extra_message_failure() {\n for i in 0 .. 100 {\n assert i * 2 - 45 < 75 + 10, 'assertion failed for i: ${i}'\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Asserts that do not abort your program

+

When initially prototyping functionality and tests, it is sometimes desirable to +have asserts, that do not stop the program, but just print their failures. That can +be achieved by tagging your assert containing functions with an [assert_continues] +tag, for example running this program:

+{% set code = "[assert_continues]\nfn abc(ii int) {\n assert ii == 2\n}\n\nfor i in 0 .. 4 {\n abc(i)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

... will produce this output:

+{% set code = "assert_continues_example.v:3: FAIL: fn main.abc: assert ii == 2\n left value: ii = 0\n right value: 2\nassert_continues_example.v:3: FAIL: fn main.abc: assert ii == 2\n left value: ii = 1\n right value: 2\nassert_continues_example.v:3: FAIL: fn main.abc: assert ii == 2\n left value: ii = 3\n right value: 2" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +V also supports a command line flag -assert continues, which will change the +behaviour of all asserts globally, as if you had tagged every function with [assert_continues].

+
+

# Test files

+{% set code = "// hello.v\nmodule main\n\nfn hello() string {\n return 'Hello world'\n}\n\nfn main() {\n println(hello())\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "// hello_test.v\nmodule main\n\nfn test_hello() {\n assert hello() == 'Hello world'\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

To run the test file above, use v hello_test.v. This will check that the function hello is +producing the correct output. V executes all test functions in the file.

+
+

Note +All _test.v files (both external and internal ones), are compiled as separate programs. +In other words, you may have as many _test.v files, and tests in them as you like, they will +not affect the compilation of your other code in .v files normally at all, but only when you +do explicitly v file_test.v or v test ..

+
+ +

In the example above, test_hello is an internal test, that can call +the private function hello() because hello_test.v has module main, +just like hello.v, i.e. both are part of the same module. Note also that +since module main is a regular module like the others, internal tests can +be used to test private functions in your main program .v files too.

+

You can also define these special test functions in a test file:

+ +

If a test function has an error return type, any propagated errors will fail the test:

+{% set code = "import strconv\n\nfn test_atoi() ? {\n assert strconv.atoi('1')? == 1\n assert strconv.atoi('one')? == 1 // test will fail\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Running tests

+

To run test functions in an individual test file, use v foo_test.v.

+

To test an entire module, use v test mymodule. You can also use v test . to test +everything inside your current folder (and subfolders). You can pass the -stats +option to see more details about the individual tests run.

+

You can put additional test data, including .v source files in a folder, named +testdata, right next to your _test.v files. V's test framework will ignore +such folders, while scanning for tests to run. This is useful, if you want to +put .v files with invalid V source code, or other tests, including known +failing ones, that should be run in a specific way/options by a parent _test.v +file.

+
+

Note +The path to the V compiler, is available through @VEXE, so a _test.v +file, can easily run other test files like this:

+
+{% set code = "import os\n\nfn test_subtest() {\n res := os.execute('${os.quoted_path(@VEXE)} other_test.v')\n assert res.exit_code == 1\n assert res.output.contains('other_test.v does not exist')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Memory management

+

V avoids doing unnecessary allocations in the first place by using value types, +string buffers, promoting a simple abstraction-free code style.

+

Most objects (~90-100%) are freed by V's autofree engine: the compiler inserts +necessary free calls automatically during compilation. Remaining small percentage +of objects is freed via reference counting.

+

The developer doesn't need to change anything in their code. "It just works", like in +Python, Go, or Java, except there's no heavy GC tracing everything or expensive RC for +each object.

+

# Control

+

You can take advantage of V's autofree engine and define a free() method on custom +data types:

+{% set code = "struct MyType {}\n\n[unsafe]\nfn (data &MyType) free() {\n // ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Just as the compiler frees C data types with C's free(), it will statically insert +free() calls for your data type at the end of each variable's lifetime.

+

Autofree can be enabled with an -autofree flag.

+

For developers willing to have more low level control, autofree can be disabled with +-manualfree, or by adding a [manualfree] on each function that wants manage its +memory manually. (See attributes).

+
+

Note +Autofree is still WIP. Until it stabilises and becomes the default, please +avoid using it. Right now allocations are handled by a minimal and well performing GC +until V's autofree engine is production ready.

+
+

Examples

+{% set code = "import strings\n\nfn draw_text(s string, x int, y int) {\n // ...\n}\n\nfn draw_scene() {\n // ...\n name1 := 'abc'\n name2 := 'def ghi'\n draw_text('hello ${name1}', 10, 10)\n draw_text('hello ${name2}', 100, 10)\n draw_text(strings.repeat(`X`, 10000), 10, 50)\n // ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The strings don't escape draw_text, so they are cleaned up when +the function exits.

+

In fact, with the -prealloc flag, the first two calls won't result in any allocations at all. +These two strings are small, so V will use a preallocated buffer for them.

+{% set code = "struct User {\n name string\n}\n\nfn test() []int {\n number := 7 // stack variable\n user := User{} // struct allocated on stack\n numbers := [1, 2, 3] // array allocated on heap, will be freed as the function exits\n println(number)\n println(user)\n println(numbers)\n numbers2 := [4, 5, 6] // array that's being returned, won't be freed here\n return numbers2\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Stack and Heap

+

# Stack and Heap Basics

+

Like with most other programming languages there are two locations where data can +be stored:

+ +

# V's default approach

+

Due to performance considerations V tries to put objects on the stack if possible +but allocates them on the heap when obviously necessary. Example:

+{% set code = "struct MyStruct {\n n int\n}\n\nstruct RefStruct {\n r &MyStruct\n}\n\nfn main() {\n q, w := f()\n println('q: ${q.r.n}, w: ${w.n}')\n}\n\nfn f() (RefStruct, &MyStruct) {\n a := MyStruct{\n n: 1\n }\n b := MyStruct{\n n: 2\n }\n c := MyStruct{\n n: 3\n }\n e := RefStruct{\n r: &b\n }\n x := a.n + c.n\n println('x: ${x}')\n return e, &c\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Here a is stored on the stack since it's address never leaves the function f(). +However a reference to b is part of e which is returned. Also a reference to +c is returned. For this reason b and c will be heap allocated.

+

Things become less obvious when a reference to an object is passed as function argument:

+{% set code = "struct MyStruct {\nmut:\n n int\n}\n\nfn main() {\n mut q := MyStruct{\n n: 7\n }\n w := MyStruct{\n n: 13\n }\n x := q.f(&w) // references of `q` and `w` are passed\n println('q: ${q}\nx: ${x}')\n}\n\nfn (mut a MyStruct) f(b &MyStruct) int {\n a.n += b.n\n x := a.n * b.n\n return x\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Here the call q.f(&w) passes references to q and w because a is +mut and b is of type &MyStruct in f()'s declaration, so technically +these references are leaving main(). However the lifetime of these +references lies inside the scope of main() so q and w are allocated +on the stack.

+

# Manual Control for Stack and Heap

+

In the last example the V compiler could put q and w on the stack +because it assumed that in the call q.f(&w) these references were only +used for reading and modifying the referred values – and not to pass the +references themselves somewhere else. This can be seen in a way that the +references to q and w are only borrowed to f().

+

Things become different if f() is doing something with a reference itself:

+{% set code = "struct RefStruct {\nmut:\n r &MyStruct\n}\n\n// see discussion below\n[heap]\nstruct MyStruct {\n n int\n}\n\nfn main() {\n m := MyStruct{}\n mut r := RefStruct{\n r: &m\n }\n r.g()\n println('r: ${r}')\n}\n\nfn (mut r RefStruct) g() {\n s := MyStruct{\n n: 7\n }\n r.f(&s) // reference to `s` inside `r` is passed back to `main() `\n}\n\nfn (mut r RefStruct) f(s &MyStruct) {\n r.r = s // would trigger error without `[heap]`\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Here f() looks quite innocent but is doing nasty things – it inserts a +reference to s into r. The problem with this is that s lives only as long +as g() is running but r is used in main() after that. For this reason +the compiler would complain about the assignment in f() because s "might +refer to an object stored on stack". The assumption made in g() that the call +r.f(&s) would only borrow the reference to s is wrong.

+

A solution to this dilemma is the [heap] attribute at the declaration of +struct MyStruct. It instructs the compiler to always allocate MyStruct-objects +on the heap. This way the reference to s remains valid even after g() returns. +The compiler takes into consideration that MyStruct objects are always heap +allocated when checking f() and allows assigning the reference to s to the +r.r field.

+

There is a pattern often seen in other programming languages:

+{% set code = "fn (mut a MyStruct) f() &MyStruct {\n // do something with a\n return &a // would return address of borrowed object\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Here f() is passed a reference a as receiver that is passed back to the caller and returned +as result at the same time. The intention behind such a declaration is method chaining like +y = x.f().g(). However, the problem with this approach is that a second reference +to a is created – so it is not only borrowed and MyStruct has to be +declared as [heap].

+

In V the better approach is:

+{% set code = "struct MyStruct {\nmut:\n n int\n}\n\nfn (mut a MyStruct) f() {\n // do something with `a`\n}\n\nfn (mut a MyStruct) g() {\n // do something else with `a`\n}\n\nfn main() {\n x := MyStruct{} // stack allocated\n mut y := x\n y.f()\n y.g()\n // instead of `mut y := x.f().g()\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This way the [heap] attribute can be avoided – resulting in better performance.

+

However, stack space is very limited as mentioned above. For this reason the [heap] +attribute might be suitable for very large structures even if not required by use cases +like those mentioned above.

+

There is an alternative way to manually control allocation on a case to case basis. This +approach is not recommended but shown here for the sake of completeness:

+{% set code = "struct MyStruct {\n n int\n}\n\nstruct RefStruct {\nmut:\n r &MyStruct\n}\n\n// simple function - just to overwrite stack segment previously used by `g()`\n\nfn use_stack() {\n x := 7.5\n y := 3.25\n z := x + y\n println('${x} ${y} ${z}')\n}\n\nfn main() {\n m := MyStruct{}\n mut r := RefStruct{\n r: &m\n }\n r.g()\n use_stack() // to erase invalid stack contents\n println('r: ${r}')\n}\n\nfn (mut r RefStruct) g() {\n s := &MyStruct{ // `s` explicitly refers to a heap object\n n: 7\n }\n // change `&MyStruct` -> `MyStruct` above and `r.f(s)` -> `r.f(&s)` below\n // to see data in stack segment being overwritten\n r.f(s)\n}\n\nfn (mut r RefStruct) f(s &MyStruct) {\n r.r = unsafe { s } // override compiler check\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Here the compiler check is suppressed by the unsafe block. To make s be heap +allocated even without [heap] attribute the struct literal is prefixed with +an ampersand: &MyStruct{...}.

+

This last step would not be required by the compiler but without it the reference +inside r becomes invalid (the memory area pointed to will be overwritten by +use_stack()) and the program might crash (or at least produce an unpredictable +final output). That's why this approach is unsafe and should be avoided!

+

# ORM

+

(This is still in an alpha state)

+

V has a built-in ORM (object-relational mapping) which supports SQLite, MySQL and Postgres, +but soon it will support MS SQL and Oracle.

+

V's ORM provides a number of benefits:

+ +{% set code = "import db.sqlite\n\n// sets a custom table name. Default is struct name (case-sensitive)\n[table: 'customers']\nstruct Customer {\n id int [primary; sql: serial] // a field named `id` of integer type must be the first field\n name string [nonull]\n nr_orders int\n country string [nonull]\n}\n\ndb := sqlite.connect('customers.db')?\n\n// you can create tables:\n// CREATE TABLE IF NOT EXISTS `Customer` (\n// `id` INTEGER PRIMARY KEY,\n// `name` TEXT NOT NULL,\n// `nr_orders` INTEGER,\n// `country` TEXT NOT NULL\n// )\nsql db {\n create table Customer\n}\n\n// select count(*) from customers\nnr_customers := sql db {\n select count from Customer\n}\nprintln('number of all customers: ${nr_customers}')\n// V syntax can be used to build queries\nuk_customers := sql db {\n select from Customer where country == 'uk' && nr_orders > 0\n}\nprintln(uk_customers.len)\nfor customer in uk_customers {\n println('${customer.id} - ${customer.name}')\n}\n// by adding `limit 1` we tell V that there will be only one object\ncustomer := sql db {\n select from Customer where id == 1 limit 1\n}\nprintln('${customer.id} - ${customer.name}')\n// insert a new customer\nnew_customer := Customer{\n name: 'Bob'\n nr_orders: 10\n}\nsql db {\n insert new_customer into Customer\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

For more examples and the docs, see vlib/orm.

+

# Writing Documentation

+

The way it works is very similar to Go. It's very simple: there's no need to +write documentation separately for your code, +vdoc will generate it from docstrings in the source code.

+

Documentation for each function/type/const must be placed right before the declaration:

+{% set code = "// clearall clears all bits in the array\n\nfn clearall() {\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The comment must start with the name of the definition.

+

Sometimes one line isn't enough to explain what a function does, in that case comments should +span to the documented function using single line comments:

+{% set code = "// copy_all recursively copies all elements of the array by their value,\n// if `dupes` is false all duplicate values are eliminated in the process.\n\nfn copy_all(dupes bool) {\n // ...\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

By convention it is preferred that comments are written in present tense.

+

An overview of the module must be placed in the first comment right after the module's name.

+

To generate documentation use vdoc, for example v doc net.http.

+

# Newlines in Documentation Comments

+

Comments spanning multiple lines are merged together using spaces, unless

+ +

# Tools

+

# v fmt

+

You don't need to worry about formatting your code or setting style guidelines. +v fmt takes care of that:

+{% set code = "v fmt file.v" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

It's recommended to set up your editor, so that v fmt -w runs on every save. +A vfmt run is usually pretty cheap (takes <30ms).

+

Always run v fmt -w file.v before pushing your code.

+

# Disabling the formatting locally

+

To disable formatting for a block of code, wrap it with // vfmt off and +// vfmt on comments.

+{% set code = "// Not affected by fmt\n// vfmt off\n\n... your code here ...\n\n// vfmt on\n\n// Affected by fmt\n... your code here ..." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# v shader

+

You can use GPU shaders with V graphical apps. You write your shaders in an +annotated GLSL dialect +and use v shader to compile them for all supported target platforms.

+{% set code = "v shader /path/to/project/dir/or/file.v" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Currently you need to +include a header and declare a glue function +before using the shader in your code.

+

# Profiling

+

V has good support for profiling your programs: v -profile profile.txt run file.v +That will produce a profile.txt file, which you can then analyze.

+

The generated profile.txt file will have lines with 4 columns: +a) how many times a function was called +b) how much time in total a function took (in ms) +c) how much time on average, a call to a function took (in ns) +d) the name of the v function

+

You can sort on column 3 (average time per function) using: +sort -n -k3 profile.txt|tail

+

You can also use stopwatches to measure just portions of your code explicitly:

+{% set code = "import time\n\nfn main() {\n sw := time.new_stopwatch()\n println('Hello world')\n println('Greeting the world took: ${sw.elapsed().nanoseconds()}ns')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Package management

+

A V module is a single folder with .v files inside. A V package can +contain one or more V modules. A V package should have a v.mod file +at its top folder, describing the contents of the package.

+

V packages are installed normally in your ~/.vmodules folder. That +location can be overridden by setting the env variable VMODULES.

+

# Package commands

+

You can use the V frontend to do package operations, just like you can +use it for compiling code, formatting code, vetting code etc.

+{% set code = "v [package_command] [param]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

where a package command can be one of:

+{% set code = " install Install a package from VPM.\n remove Remove a package that was installed from VPM.\n search Search for a package from VPM.\n update Update an installed package from VPM.\n upgrade Upgrade all the outdated packages.\n list List all installed packages.\n outdated Show installed packages that need updates." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

You can install packages already created by someone else with VPM:

+{% set code = "v install [package]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Example:

+{% set code = "v install ui" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Packages can be installed directly from git or mercurial repositories.

+{% set code = "v install [--once] [--git|--hg] [url]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Example:

+{% set code = "v install --git https://github.com/vlang/markdown" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Sometimes you may want to install the dependencies ONLY if those are not installed:

+{% set code = "v install --once [package]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Removing a package with v:

+{% set code = "v remove [package]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Example:

+{% set code = "v remove ui" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Updating an installed package from VPM:

+{% set code = "v update [package]" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Example:

+{% set code = "v update ui" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Or you can update all your packages:

+{% set code = "v update" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

To see all the packages you have installed, you can use:

+{% set code = "v list" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Example:

+{% set code = "> v list\nInstalled packages:\n markdown\n ui" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

To see all the packages that need updates:

+{% set code = "v outdated" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Example:

+{% set code = "> v outdated\nPackage are up to date." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Publish package

+
    +
  1. +

    Put a v.mod file inside the toplevel folder of your package (if you +created your package with the command v new mypackage or v init +you already have a v.mod file).

    +{% set code = "v new mypackage\nInput your project description: My nice package.\nInput your project version: (0.0.0) 0.0.1\nInput your project license: (MIT)\nInitialising ...\nComplete!" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

    Example v.mod:

    +{% set code = "Module {\n name: 'mypackage'\n description: 'My nice package.'\n version: '0.0.1'\n license: 'MIT'\n dependencies: []\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

    Minimal file structure:

    +{% set code = "v.mod\nmypackage.v" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

    The name of your package should be used with the module directive +at the top of all files in your package. For mypackage.v:

    +{% set code = "module mypackage\n\npub fn hello_world() {\n println('Hello World!')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
  2. +
  3. +

    Create a git repository in the folder with the v.mod file +(this is not required if you used v new or v init):

    +{% set code = "git init\ngit add .\ngit commit -m \"INIT\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
  4. +
  5. +

    Create a public repository on github.com.

    +
  6. +
  7. +

    Connect your local repository to the remote repository and push the changes.

    +
  8. +
  9. +

    Add your package to the public V package registry VPM: +https://vpm.vlang.io/new

    +

    You will have to login with your Github account to register the package. +Warning: Currently it is not possible to edit your entry after submitting. +Check your package name and github url twice as this cannot be changed by you later.

    +
  10. +
  11. +

    The final package name is a combination of your github account and +the package name you provided e.g. mygithubname.mypackage.

    +
  12. +
+

Optional: tag your V package with vlang and vlang-package on github.com +to allow for a better search experience.

+

# Advanced Topics

+

# Attributes

+

V has several attributes that modify the behavior of functions and structs.

+

An attribute is a compiler instruction specified inside [] right before a +function/struct/enum declaration and applies only to the following declaration.

+{% set code = "// [flag] enables Enum types to be used as bitfields\n\n[flag]\nenum BitField {\n read\n write\n other\n}\n\nfn main() {\n assert 1 == int(BitField.read)\n assert 2 == int(BitField.write)\n mut bf := BitField.read\n assert bf.has(.read | .other) // test if *at least one* of the flags is set\n assert !bf.all(.read | .other) // test if *all* of the flags is set\n bf.set(.write | .other)\n assert bf.has(.read | .write | .other)\n assert bf.all(.read | .write | .other)\n bf.toggle(.other)\n assert bf == BitField.read | .write\n assert bf.all(.read | .write)\n assert !bf.has(.other)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Struct field deprecations:

+{% set code = "module abc\n\n// Note that only *direct* accesses to Xyz.d in *other modules*, will produce deprecation notices/warnings:\npub struct Xyz {\npub mut:\n a int\n d int [deprecated: 'use Xyz.a instead'; deprecated_after: '2999-03-01']\n // the tags above, will produce a notice, since the deprecation date is in the far future\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Function/method deprecations:

+{% set code = "// Calling this function will result in a deprecation warning\n\n[deprecated]\nfn old_function() {\n}\n\n// It can also display a custom deprecation message\n\n[deprecated: 'use new_function() instead']\nfn legacy_function() {}\n\n// You can also specify a date, after which the function will be\n// considered deprecated. Before that date, calls to the function\n// will be compiler notices - you will see them, but the compilation\n// is not affected. After that date, calls will become warnings,\n// so ordinary compiling will still work, but compiling with -prod\n// will not (all warnings are treated like errors with -prod).\n// 6 months after the deprecation date, calls will be hard\n// compiler errors.\n\n[deprecated: 'use new_function2() instead']\n[deprecated_after: '2021-05-27']\nfn legacy_function2() {}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +{% set code = "// This function's calls will be inlined.\n[inline]\nfn inlined_function() {\n}\n\n// This function's calls will NOT be inlined.\n[noinline]\nfn function() {\n}\n\n// This function will NOT return to its callers.\n// Such functions can be used at the end of or blocks,\n// just like exit/1 or panic/1. Such functions can not\n// have return types, and should end either in for{}, or\n// by calling other `[noreturn]` functions.\n[noreturn]\nfn forever() {\n for {}\n}\n\n// The following struct must be allocated on the heap. Therefore, it can only be used as a\n// reference (`&Window`) or inside another reference (`&OuterStruct{ Window{...} }`).\n// See section \"Stack and Heap\"\n[heap]\nstruct Window {\n}\n\n// V will not generate this function and all its calls if the provided flag is false.\n// To use a flag, use `v -d flag`\n[if debug]\nfn foo() {\n}\n\nfn bar() {\n foo() // will not be called if `-d debug` is not passed\n}\n\n// The memory pointed to by the pointer arguments of this function will not be\n// freed by the garbage collector (if in use) before the function returns\n[keep_args_alive]\nfn C.my_external_function(voidptr, int, voidptr) int\n\n// Calls to following function must be in unsafe{} blocks.\n// Note that the code in the body of `risky_business()` will still be\n// checked, unless you also wrap it in `unsafe {}` blocks.\n// This is useful, when you want to have an `[unsafe]` function that\n// has checks before/after a certain unsafe operation, that will still\n// benefit from V's safety features.\n[unsafe]\nfn risky_business() {\n // code that will be checked, perhaps checking pre conditions\n unsafe {\n // code that *will not be* checked, like pointer arithmetic,\n // accessing union fields, calling other `[unsafe]` fns, etc...\n // Usually, it is a good idea to try minimizing code wrapped\n // in unsafe{} as much as possible.\n // See also [Memory-unsafe code](#memory-unsafe-code)\n }\n // code that will be checked, perhaps checking post conditions and/or\n // keeping invariants\n}\n\n// V's autofree engine will not take care of memory management in this function.\n// You will have the responsibility to free memory manually yourself in it.\n[manualfree]\nfn custom_allocations() {\n}\n\n// For C interop only, tells V that the following struct is defined with `typedef struct` in C\n[typedef]\nstruct C.Foo {\n}\n\n// Used to add a custom calling convention to a function, available calling convention: stdcall, fastcall and cdecl.\n// This list also applies for type aliases (see below).\n[callconv: \"stdcall\"]\nfn C.DefWindowProc(hwnd int, msg int, lparam int, wparam int)\n\n// Used to add a custom calling convention to a function type aliases.\n[callconv: \"fastcall\"]\ntype FastFn = fn (int) bool\n\n// Windows only:\n// Without this attribute all graphical apps will have the following behavior on Windows:\n// If run from a console or terminal; keep the terminal open so all (e)println statements can be viewed.\n// If run from e.g. Explorer, by double-click; app is opened, but no terminal is opened, and no (e)println output can be seen.\n// Use it to force-open a terminal to view output in, even if the app is started from Explorer.\n// Valid before main() only.\n[console]\nfn main() {\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Conditional compilation

+

# Compile time pseudo variables

+

V also gives your code access to a set of pseudo string variables, +that are substituted at compile time:

+ +

That allows you to do the following example, useful while debugging/logging/tracing your code:

+{% set code = "eprintln('file: ' + @FILE + ' | line: ' + @LINE + ' | fn: ' + @MOD + '.' + @FN)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Another example, is if you want to embed the version/name from v.mod inside your executable:

+{% set code = "import v.vmod\nvm := vmod.decode( @VMOD_FILE ) or { panic(err) }\neprintln('${vm.name} ${vm.version}\n ${vm.description}')" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Compile-time reflection

+

Having built-in JSON support is nice, but V also allows you to create efficient +serializers for any data format. V has compile-time if and for constructs:

+{% set code = "struct User {\n name string\n age int\n}\n\nfn main() {\n $for field in User.fields {\n $if field.typ is string {\n println('${field.name} is of type string')\n }\n }\n}\n\n// Output:\n// name is of type string" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

See examples/compiletime/reflection.v +for a more complete example.

+

# Compile time code

+

$ is used as a prefix for compile-time operations.

+

# $if condition

+{% set code = "fn main() {\n // Support for multiple conditions in one branch\n $if ios || android {\n println('Running on a mobile device!')\n }\n $if linux && x64 {\n println('64-bit Linux.')\n }\n // Usage as expression\n os := $if windows { 'Windows' } $else { 'UNIX' }\n println('Using ${os}')\n // $else-$if branches\n $if tinyc {\n println('tinyc')\n } $else $if clang {\n println('clang')\n } $else $if gcc {\n println('gcc')\n } $else {\n println('different compiler')\n }\n $if test {\n println('testing')\n }\n // v -cg ...\n $if debug {\n println('debugging')\n }\n // v -prod ...\n $if prod {\n println('production build')\n }\n // v -d option ...\n $if option ? {\n println('custom option')\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

If you want an if to be evaluated at compile time it must be prefixed with a $ sign. +Right now it can be used to detect an OS, compiler, platform or compilation options. +$if debug is a special option like $if windows or $if x32, it's enabled if the program +is compiled with v -g or v -cg. +If you're using a custom ifdef, then you do need $if option ? {} and compile withv -d option. +Full list of builtin options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OSCompilersPlatformsOther
windows, linux, macosgcc, tinycamd64, arm64debug, prod, test
mac, darwin, ios,clang, mingwx64, x32js, glibc, prealloc
android, mach, dragonflymsvclittle_endianno_bounds_checking, freestanding
gnu, hpux, haiku, qnxcplusplusbig_endianno_segfault_handler, no_backtrace, no_main
solaris, termux
+

# $embed_file

+{% set code = "import os\nfn main() {\n embedded_file := $embed_file('v.png')\n os.write_file('exported.png', embedded_file.to_string())!\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V can embed arbitrary files into the executable with the $embed_file(<path>) +compile time call. Paths can be absolute or relative to the source file.

+

When you do not use -prod, the file will not be embedded. Instead, it will +be loaded the first time your program calls embedded_file.data() at runtime, making +it easier to change in external editor programs, without needing to recompile +your executable.

+

When you compile with -prod, the file will be embedded inside your +executable, increasing your binary size, but making it more self contained +and thus easier to distribute. In this case, embedded_file.data() will cause no IO, +and it will always return the same data.

+

$embed_file supports compression of the embedded file when compiling with -prod. +Currently only one compression type is supported: zlib

+{% set code = "import os\nfn main() {\n embedded_file := $embed_file('v.png', .zlib) // compressed using zlib\n os.write_file('exported.png', embedded_file.to_string())!\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

$embed_file returns +EmbedFileData +which could be used to obtain the file contents as string or []u8.

+

# $tmpl for embedding and parsing V template files

+

V has a simple template language for text and html templates, and they can easily +be embedded via $tmpl('path/to/template.txt'):

+{% set code = "fn build() string {\n name := 'Peter'\n age := 25\n numbers := [1, 2, 3]\n return $tmpl('1.txt')\n}\n\nfn main() {\n println(build())\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

1.txt:

+{% set code = "name: @name\n\nage: @age\n\nnumbers: @numbers\n\n@for number in numbers\n @number\n@end" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

output:

+{% set code = "name: Peter\n\nage: 25\n\nnumbers: [1, 2, 3]\n\n1\n2\n3" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

See more details

+

# $env

+{% set code = "module main\n\nfn main() {\n compile_time_env := $env('ENV_VAR')\n println(compile_time_env)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

V can bring in values at compile time from environment variables. +$env('ENV_VAR') can also be used in top-level #flag and #include statements: +#flag linux -I $env('JAVA_HOME')/include.

+

# $compile_error and $compile_warn

+

These two comptime functions are very useful for displaying custom errors/warnings during +compile time.

+

Both receive as their only argument a string literal that contains the message to display:

+{% set code = "// x.v\nmodule main\n\n$if linux {\n $compile_error('Linux is not supported')\n}\n\nfn main() {\n}\n\n$ v run x.v\nx.v:4:5: error: Linux is not supported\n 2 |\n 3 | $if linux {\n 4 | $compile_error('Linux is not supported')\n | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n 5 | }\n 6 |" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Environment specific files

+

If a file has an environment-specific suffix, it will only be compiled for that environment.

+ +

Here is a more complete example: +main.v:

+{% set code = "module main\nfn main() { println(message) }" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

main_default.c.v:

+{% set code = "module main\nconst ( message = 'Hello world' )" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

main_linux.c.v:

+{% set code = "module main\nconst ( message = 'Hello linux' )" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

main_windows.c.v:

+{% set code = "module main\nconst ( message = 'Hello windows' )" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

With the example above:

+ +
+

A combinatorial _d_customflag_linux.c.v postfix will not work. +If you do need a custom flag file, that has platform dependent code, use the +postfix _d_customflag.v, and then use platform dependent compile time +conditional blocks inside it, i.e. $if linux {} etc.

+
+ +

See also Cross Compilation.

+

# Memory-unsafe code

+

Sometimes for efficiency you may want to write low-level code that can potentially +corrupt memory or be vulnerable to security exploits. V supports writing such code, +but not by default.

+

V requires that any potentially memory-unsafe operations are marked intentionally. +Marking them also indicates to anyone reading the code that there could be +memory-safety violations if there was a mistake.

+

Examples of potentially memory-unsafe operations are:

+ +

To mark potentially memory-unsafe operations, enclose them in an unsafe block:

+{% set code = "// allocate 2 uninitialized bytes & return a reference to them\nmut p := unsafe { malloc(2) }\np[0] = `h` // Error: pointer indexing is only allowed in `unsafe` blocks\nunsafe {\n p[0] = `h` // OK\n p[1] = `i`\n}\np++ // Error: pointer arithmetic is only allowed in `unsafe` blocks\nunsafe {\n p++ // OK\n}\nassert *p == `i`" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Best practice is to avoid putting memory-safe expressions inside an unsafe block, +so that the reason for using unsafe is as clear as possible. Generally any code +you think is memory-safe should not be inside an unsafe block, so the compiler +can verify it.

+

If you suspect your program does violate memory-safety, you have a head start on +finding the cause: look at the unsafe blocks (and how they interact with +surrounding code).

+
+

Note +This is work in progress.

+
+

# Structs with reference fields

+

Structs with references require explicitly setting the initial value to a +reference value unless the struct already defines its own initial value.

+

Zero-value references, or nil pointers, will NOT be supported in the future, +for now data structures such as Linked Lists or Binary Trees that rely on reference +fields that can use the value 0, understanding that it is unsafe, and that it can +cause a panic.

+{% set code = "struct Node {\n a &Node\n b &Node = unsafe { nil } // Auto-initialized to nil, use with caution!\n}\n\n// Reference fields must be initialized unless an initial value is declared.\n// Zero (0) is OK but use with caution, it's a nil pointer.\nfoo := Node{\n a: 0\n}\nbar := Node{\n a: &foo\n}\nbaz := Node{\n a: 0\n b: 0\n}\nqux := Node{\n a: &foo\n b: &bar\n}\nprintln(baz)\nprintln(qux)" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# sizeof and __offsetof

+ +{% set code = "struct Foo {\n a int\n b int\n}\n\nassert sizeof(Foo) == 8\nassert __offsetof(Foo, a) == 0\nassert __offsetof(Foo, b) == 4" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Limited operator overloading

+

Operator overloading defines the behavior of certain binary operators for certain types.

+{% set code = "struct Vec {\n x int\n y int\n}\n\nfn (a Vec) str() string {\n return '{${a.x}, ${a.y}}'\n}\n\nfn (a Vec) + (b Vec) Vec {\n return Vec{a.x + b.x, a.y + b.y}\n}\n\nfn (a Vec) - (b Vec) Vec {\n return Vec{a.x - b.x, a.y - b.y}\n}\n\nfn main() {\n a := Vec{2, 3}\n b := Vec{4, 5}\n mut c := Vec{1, 2}\n\n println(a + b) // \"{6, 8}\"\n println(a - b) // \"{-2, -2}\"\n c += a\n //^^ autogenerated from + overload\n println(c) // \"{3, 5}\"\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Operator overloading goes against V's philosophy of simplicity and predictability. +But since scientific and graphical applications are among V's domains, +operator overloading is an important feature to have in order to improve readability:

+

a.add(b).add(c.mul(d)) is a lot less readable than a + b + c * d.

+
+

Operator overloading is possible for the following binary operators: +, -, *, /, %, <, ==.

+

# Implicitly generated overloads

+ +

# Restriction

+

To improve safety and maintainability, operator overloading is limited.

+

# Type restrictions

+ +

# Other restrictions

+ +

# Performance tuning

+

The generated C code is usually fast enough, when you compile your code +with -prod. There are some situations though, where you may want to give +additional hints to the compiler, so that it can further optimize some +blocks of code.

+
+

Note +These are rarely needed, and should not be used, unless you +profile your code, and then see that there are significant benefits for them. +To cite gcc's documentation: "programmers are notoriously bad at predicting +how their programs actually perform".

+
+

[inline] - you can tag functions with [inline], so the C compiler will +try to inline them, which in some cases, may be beneficial for performance, +but may impact the size of your executable.

+

[direct_array_access] - in functions tagged with [direct_array_access] +the compiler will translate array operations directly into C array operations - +omitting bounds checking. This may save a lot of time in a function that iterates +over an array but at the cost of making the function unsafe - unless +the boundaries will be checked by the user.

+

if _likely_(bool expression) { this hints the C compiler, that the passed +boolean expression is very likely to be true, so it can generate assembly +code, with less chance of branch misprediction. In the JS backend, +that does nothing.

+

if _unlikely_(bool expression) { similar to _likely_(x), but it hints that +the boolean expression is highly improbable. In the JS backend, that does nothing.

+

<a id='Reflection via codegen'>

+

# Atomics

+

V has no special support for atomics, yet, nevertheless it's possible to treat variables as atomics +by calling C functions from V. The standard C11 atomic functions like atomic_store() +are usually defined with the help of macros and C compiler magic to provide a kind of +overloaded C functions. +Since V does not support overloading functions by intention there are wrapper functions defined in +C headers named atomic.h that are part of the V compiler infrastructure.

+

There are dedicated wrappers for all unsigned integer types and for pointers. +(byte is not fully supported on Windows) – the function names include the type name +as suffix. e.g. C.atomic_load_ptr() or C.atomic_fetch_add_u64().

+

To use these functions the C header for the used OS has to be included and the functions +that are intended to be used have to be declared. Example:

+{% set code = "$if windows {\n #include \"@VEXEROOT/thirdparty/stdatomic/win/atomic.h\"\n} $else {\n #include \"@VEXEROOT/thirdparty/stdatomic/nix/atomic.h\"\n}\n\n// declare functions we want to use - V does not parse the C header\nfn C.atomic_store_u32(&u32, u32)\nfn C.atomic_load_u32(&u32) u32\nfn C.atomic_compare_exchange_weak_u32(&u32, &u32, u32) bool\nfn C.atomic_compare_exchange_strong_u32(&u32, &u32, u32) bool\n\nconst num_iterations = 10000000\n\n// see section \"Global Variables\" below\n__global (\n atom u32 // ordinary variable but used as atomic\n)\n\nfn change() int {\n mut races_won_by_change := 0\n for {\n mut cmp := u32(17) // addressable value to compare with and to store the found value\n // atomic version of `if atom == 17 { atom = 23 races_won_by_change++ } else { cmp = atom }`\n if C.atomic_compare_exchange_strong_u32(&atom, &cmp, 23) {\n races_won_by_change++\n } else {\n if cmp == 31 {\n break\n }\n cmp = 17 // re-assign because overwritten with value of atom\n }\n }\n return races_won_by_change\n}\n\nfn main() {\n C.atomic_store_u32(&atom, 17)\n t := spawn change()\n mut races_won_by_main := 0\n mut cmp17 := u32(17)\n mut cmp23 := u32(23)\n for i in 0 .. num_iterations {\n // atomic version of `if atom == 17 { atom = 23 races_won_by_main++ }`\n if C.atomic_compare_exchange_strong_u32(&atom, &cmp17, 23) {\n races_won_by_main++\n } else {\n cmp17 = 17\n }\n desir := if i == num_iterations - 1 { u32(31) } else { u32(17) }\n // atomic version of `for atom != 23 {} atom = desir`\n for !C.atomic_compare_exchange_weak_u32(&atom, &cmp23, desir) {\n cmp23 = 23\n }\n }\n races_won_by_change := t.wait()\n atom_new := C.atomic_load_u32(&atom)\n println('atom: ${atom_new}, #exchanges: ${races_won_by_main + races_won_by_change}')\n // prints `atom: 31, #exchanges: 10000000`)\n println('races won by\n- `main()`: ${races_won_by_main}\n- `change()`: ${races_won_by_change}')\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

In this example both main() and the spawned thread change() try to replace a value of 17 +in the global atom with a value of 23. The replacement in the opposite direction is +done exactly 10000000 times. The last replacement will be with 31 which makes the spawned +thread finish.

+

It is not predictable how many replacements occur in which thread, but the sum will always +be 10000000. (With the non-atomic commands from the comments the value will be higher or the program +will hang – dependent on the compiler optimization used.)

+

# Global Variables

+

By default V does not allow global variables. However, in low level applications they have their +place so their usage can be enabled with the compiler flag -enable-globals. +Declarations of global variables must be surrounded with a __global ( ... ) +specification – as in the example above.

+

An initializer for global variables must be explicitly converted to the +desired target type. If no initializer is given a default initialization is done. +Some objects like semaphores and mutexes require an explicit initialization in place, i.e. +not with a value returned from a function call but with a method call by reference. +A separate init() function can be used for this purpose – it will be called before main():

+{% set code = "import sync\n\n__global (\n sem sync.Semaphore // needs initialization in `init()`\n mtx sync.RwMutex // needs initialization in `init()`\n f1 = f64(34.0625) // explicily initialized\n shmap shared map[string]f64 // initialized as empty `shared` map\n f2 f64 // initialized to `0.0`\n)\n\nfn init() {\n sem.init(0)\n mtx.init()\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Be aware that in multi threaded applications the access to global variables is subject +to race conditions. There are several approaches to deal with these:

+ +

# Cross compilation

+

To cross compile your project simply run

+{% set code = "v -os windows ." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

or

+{% set code = "v -os linux ." %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +Cross-compiling a windows binary on a linux machine requires the GNU C compiler for +MinGW-w64 (targeting Win64) to first be installed.

+
+

For Ubuntu/Debian based distributions:

+{% set code = "sudo apt-get install gcc-mingw-w64-x86-64" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

For Arch based distributions:

+{% set code = "sudo pacman -S mingw-w64-gcc" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

(Cross compiling for macOS is temporarily not possible.)

+

If you don't have any C dependencies, that's all you need to do. This works even +when compiling GUI apps using the ui module or graphical apps using gg.

+

You will need to install Clang, LLD linker, and download a zip file with +libraries and include files for Windows and Linux. V will provide you with a link.

+

# Debugging

+

# C Backend binaries (Default)

+

To debug issues in the generated binary (flag: -b c), you can pass these flags:

+ +

For best debugging experience if you are writing a low level wrapper for an existing +C library, you can pass several of these flags at the same time: +v -keepc -cg -showcc yourprogram.v, then just run your debugger (gdb/lldb) or IDE +on the produced executable yourprogram.

+

If you just want to inspect the generated C code, +without further compilation, you can also use the -o flag (e.g. -o file.c). +This will make V produce the file.c then stop.

+

If you want to see the generated C source code for just a single C function, +for example main, you can use: -printfn main -o file.c.

+

To debug the V executable itself you need to compile from src with ./v -g -o v cmd/v.

+

You can debug tests with for example v -g -keepc prog_test.v. The -keepc flag is needed, +so that the executable is not deleted, after it was created and ran.

+

To see a detailed list of all flags that V supports, +use v help, v help build and v help build-c.

+

Commandline Debugging

+
    +
  1. compile your binary with debugging info v -g hello.v
  2. +
  3. debug with lldb or GDB +e.g. lldb hello
  4. +
+

Troubleshooting (debugging) executables created with V in GDB

+

Visual debugging Setup:

+ +

# Native Backend binaries

+

Currently there is no debugging support for binaries, created by the +native backend (flag: -b native).

+

# Javascript Backend

+

To debug the generated Javascript output you can activate source maps: +v -b js -sourcemap hello.v -o hello.js

+

For all supported options check the latest help: +v help build-js

+

# V and C

+

# Calling C from V

+

Example

+{% set code = "#flag -lsqlite3\n#include \"sqlite3.h\"\n// See also the example from https://www.sqlite.org/quickstart.html\nstruct C.sqlite3 {\n}\n\nstruct C.sqlite3_stmt {\n}\n\ntype FnSqlite3Callback = fn (voidptr, int, &&char, &&char) int\n\nfn C.sqlite3_open(&char, &&C.sqlite3) int\n\nfn C.sqlite3_close(&C.sqlite3) int\n\nfn C.sqlite3_column_int(stmt &C.sqlite3_stmt, n int) int\n\n// ... you can also just define the type of parameter and leave out the C. prefix\n\nfn C.sqlite3_prepare_v2(&C.sqlite3, &char, int, &&C.sqlite3_stmt, &&char) int\n\nfn C.sqlite3_step(&C.sqlite3_stmt)\n\nfn C.sqlite3_finalize(&C.sqlite3_stmt)\n\nfn C.sqlite3_exec(db &C.sqlite3, sql &char, cb FnSqlite3Callback, cb_arg voidptr, emsg &&char) int\n\nfn C.sqlite3_free(voidptr)\n\nfn my_callback(arg voidptr, howmany int, cvalues &&char, cnames &&char) int {\n unsafe {\n for i in 0 .. howmany {\n print('| ${cstring_to_vstring(cnames[i])}: ${cstring_to_vstring(cvalues[i]):20} ')\n }\n }\n println('|')\n return 0\n}\n\nfn main() {\n db := &C.sqlite3(0) // this means `sqlite3* db = 0`\n // passing a string literal to a C function call results in a C string, not a V string\n C.sqlite3_open(c'users.db', &db)\n // C.sqlite3_open(db_path.str, &db)\n query := 'select count(*) from users'\n stmt := &C.sqlite3_stmt(0)\n // Note: You can also use the `.str` field of a V string,\n // to get its C style zero terminated representation\n C.sqlite3_prepare_v2(db, &char(query.str), -1, &stmt, 0)\n C.sqlite3_step(stmt)\n nr_users := C.sqlite3_column_int(stmt, 0)\n C.sqlite3_finalize(stmt)\n println('There are ${nr_users} users in the database.')\n //\n error_msg := &char(0)\n query_all_users := 'select * from users'\n rc := C.sqlite3_exec(db, &char(query_all_users.str), my_callback, voidptr(7), &error_msg)\n if rc != C.SQLITE_OK {\n eprintln(unsafe { cstring_to_vstring(error_msg) })\n C.sqlite3_free(error_msg)\n }\n C.sqlite3_close(db)\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Calling V from C

+

Since V can compile to C, calling V code from C is very easy, once you know how.

+

Use v -o file.c your_file.v to generate a C file, corresponding to the V code.

+

More details in call_v_from_c example.

+

# Passing C compilation flags

+

Add #flag directives to the top of your V files to provide C compilation flags like:

+ +

You can (optionally) use different flags for different targets. +Currently the linux, darwin , freebsd, and windows flags are supported.

+
+

Note +Each flag must go on its own line (for now)

+
+{% set code = "#flag linux -lsdl2\n#flag linux -Ivig\n#flag linux -DCIMGUI_DEFINE_ENUMS_AND_STRUCTS=1\n#flag linux -DIMGUI_DISABLE_OBSOLETE_FUNCTIONS=1\n#flag linux -DIMGUI_IMPL_API=" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

In the console build command, you can use:

+ +

You can define a VFLAGS environment variable in your terminal to store your -cc +and -cflags settings, rather than including them in the build command each time.

+

# #pkgconfig

+

Add #pkgconfig directive is used to tell the compiler which modules should be used for compiling +and linking using the pkg-config files provided by the respective dependencies.

+

As long as backticks can't be used in #flag and spawning processes is not desirable for security +and portability reasons, V uses its own pkgconfig library that is compatible with the standard +freedesktop one.

+

If no flags are passed it will add --cflags and --libs, both lines below do the same:

+{% set code = "#pkgconfig r_core\n#pkgconfig --cflags --libs r_core" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The .pc files are looked up into a hardcoded list of default pkg-config paths, the user can add +extra paths by using the PKG_CONFIG_PATH environment variable. Multiple modules can be passed.

+

To check the existence of a pkg-config use $pkgconfig('pkg') as a compile time "if" condition to +check if a pkg-config exists. If it exists the branch will be created. Use $else or $else $if +to handle other cases.

+{% set code = "$if $pkgconfig('mysqlclient') {\n #pkgconfig mysqlclient\n} $else $if $pkgconfig('mariadb') {\n #pkgconfig mariadb\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Including C code

+

You can also include C code directly in your V module. +For example, let's say that your C code is located in a folder named 'c' inside your module folder. +Then:

+ +{% set code = "Module {\n name: 'mymodule',\n description: 'My nice module wraps a simple C library.',\n version: '0.0.1'\n dependencies: []\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} + +{% set code = "#flag -I @VMODROOT/c\n#flag @VMODROOT/c/implementation.o\n#include \"header.h\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +
+

Note +@VMODROOT will be replaced by V with the nearest parent folder, +where there is a v.mod file. +Any .v file beside or below the folder where the v.mod file is, +can use #flag @VMODROOT/abc to refer to this folder. +The @VMODROOT folder is also prepended to the module lookup path, +so you can import other modules under your @VMODROOT, by just naming them.

+
+

The instructions above will make V look for an compiled .o file in +your module folder/c/implementation.o. +If V finds it, the .o file will get linked to the main executable, that used the module. +If it does not find it, V assumes that there is a @VMODROOT/c/implementation.c file, +and tries to compile it to a .o file, then will use that.

+

This allows you to have C code, that is contained in a V module, so that its distribution is easier. +You can see a complete minimal example for using C code in a V wrapper module here: +project_with_c_code. +Another example, demonstrating passing structs from C to V and back again: +interoperate between C to V to C.

+

# C types

+

Ordinary zero terminated C strings can be converted to V strings with +unsafe { &char(cstring).vstring() } or if you know their length already with +unsafe { &char(cstring).vstring_with_len(len) }.

+
+

Note +The .vstring() and .vstring_with_len() methods do NOT create a copy of the cstring, +so you should NOT free it after calling the method .vstring(). +If you need to make a copy of the C string (some libc APIs like getenv pretty much require that, +since they return pointers to internal libc memory), you can use cstring_to_vstring(cstring).

+
+

On Windows, C APIs often return so called wide strings (utf16 encoding). +These can be converted to V strings with string_from_wide(&u16(cwidestring)) .

+

V has these types for easier interoperability with C:

+ +

To cast a voidptr to a V reference, use user := &User(user_void_ptr).

+

voidptr can also be dereferenced into a V struct through casting: user := User(user_void_ptr).

+

an example of a module that calls C code from V

+

# C Declarations

+

C identifiers are accessed with the C prefix similarly to how module-specific +identifiers are accessed. Functions must be redeclared in V before they can be used. +Any C types may be used behind the C prefix, but types must be redeclared in V in +order to access type members.

+

To redeclare complex types, such as in the following C code:

+{% set code = "struct SomeCStruct {\n uint8_t implTraits;\n uint16_t memPoolData;\n union {\n struct {\n void* data;\n size_t size;\n };\n\n DataView view;\n };\n};" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

members of sub-data-structures may be directly declared in the containing struct as below:

+{% set code = "struct C.SomeCStruct {\n implTraits byte\n memPoolData u16\n // These members are part of sub data structures that can't currently be represented in V.\n // Declaring them directly like this is sufficient for access.\n // union {\n // struct {\n data voidptr\n size usize\n // }\n view C.DataView\n // }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

The existence of the data members is made known to V, and they may be used without +re-creating the original structure exactly.

+

Alternatively, you may embed the sub-data-structures to maintain +a parallel code structure.

+

# Export to shared library

+

By default all V functions have the following naming scheme in C: [module name]__[fn_name].

+

For example, fn foo() {} in module bar will result in bar__foo().

+

To use a custom export name, use the [export] attribute:

+{% set code = "[export: 'my_custom_c_name']\nfn foo() {\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

# Translating C to V

+

V can translate your C code to human readable V code, and generating V wrappers +on top of C libraries.

+

C2V currently uses Clang's AST to generate V, so to translate a C file to V +you need to have Clang installed on your machine.

+

Let's create a simple program test.c first:

+{% set code = "#include \"stdio.h\"\n\nint main() {\n for (int i = 0; i < 10; i++) {\n printf(\"hello world\n\");\n }\n return 0;\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Run v translate test.c, and V will generate test.v:

+{% set code = "fn main() {\n for i := 0; i < 10; i++ {\n println('hello world')\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

To generate a wrapper on top of a C library use this command:

+{% set code = "v translate wrapper c_code/libsodium/src/libsodium" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

This will generate a directory libsodium with a V module.

+

Example of a C2V generated libsodium wrapper:

+

https://github.com/vlang/libsodium

+

<br>

+

When should you translate C code and when should you simply call C code from V?

+

If you have well-written, well-tested C code, +then of course you can always simply call this C code from V.

+

Translating it to V gives you several advantages:

+ +

# Working around C issues

+

In some cases, C interop can be extremely difficult. +One of these such cases is when headers conflict with each other. +For example, V needs to include the Windows header libraries in order for your V binaries to work +seamlessly across all platforms.

+

However, since the Windows header libraries use extremely generic names such as Rectangle, +this will cause a conflict if you wish to use C code that also has a name defined as Rectangle.

+

For very specific cases like this, we have #preinclude.

+

This will allow things to be configured before V adds in its built in libraries.

+

Example usage:

+{% set code = "// This will include before built in libraries are used.\n#preinclude \"pre_include.h\"\n// This will include after built in libraries are used.\n#include \"include.h\"" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

An example of what might be included in pre_include.h +can be found here

+

This is an advanced feature, and will not be necessary +outside of very specific cases with C interop, +meaning it could cause more issues than it solves.

+

Consider it last resort!

+

# Other V Features

+

# Inline assembly

+

<!-- ignore because it doesn't pass fmt test (why?) -->

+{% set code = "a := 100\nb := 20\nmut c := 0\nasm amd64 {\n mov eax, a\n add eax, b\n mov c, eax\n ; =r (c) as c // output\n ; r (a) as a // input\n r (b) as b\n}\nprintln('a: ${a}') // 100\nprintln('b: ${b}') // 20\nprintln('c: ${c}') // 120" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

For more examples, see +github.com/vlang/v/tree/master/vlib/v/tests/assembly/asm_test.amd64.v

+

# Hot code reloading

+{% set code = "module main\n\nimport time\n\n[live]\nfn print_message() {\n println('Hello! Modify this message while the program is running.')\n}\n\nfn main() {\n for {\n print_message()\n time.sleep(500 * time.millisecond)\n }\n}" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Build this example with v -live message.v.

+

You can also run this example with v -live run message.v. +Make sure that in command you use a path to a V's file, +not a path to a folder (like v -live run .) - +in that case you need to modify content of a folder (add new file, for example), +because changes in message.v will have no effect.

+

Functions that you want to be reloaded must have [live] attribute +before their definition.

+

Right now it's not possible to modify types while the program is running.

+

More examples, including a graphical application: +github.com/vlang/v/tree/master/examples/hot_reload.

+

# Cross-platform shell scripts in V

+

V can be used as an alternative to Bash to write deployment scripts, build scripts, etc.

+

The advantage of using V for this, is the simplicity and predictability of the language, and +cross-platform support. "V scripts" run on Unix-like systems, as well as on Windows.

+

To use V's script mode, save your source file with the .vsh file extension. +It will make all functions in the os module global (so that you can use mkdir() instead +of os.mkdir(), for example).

+

V also knows to compile & run .vsh files immediately, so you do not need a separate +step to compile them. V will also recompile an executable, produced by a .vsh file, +only when it is older than the .vsh source file, i.e. runs after the first one, will +be faster, since there is no need for a re-compilation of a script, that has not been changed.

+

An example deploy.vsh:

+{% set code = "#!/usr/bin/env -S v\n\n// Note: The shebang line above, associates the .vsh file to V on Unix-like systems,\n// so it can be run just by specifying the path to the .vsh file, once it's made\n// executable, using `chmod +x deploy.vsh`, i.e. after that chmod command, you can\n// run the .vsh script, by just typing its name/path like this: `./deploy.vsh`\n\n// print command then execute it\nfn sh(cmd string) {\n println('❯ ${cmd}')\n print(execute_or_exit(cmd).output)\n}\n\n// Remove if build/ exits, ignore any errors if it doesn't\nrmdir_all('build') or {}\n\n// Create build/, never fails as build/ does not exist\nmkdir('build')?\n\n// Move *.v files to build/\nresult := execute('mv *.v build/')\nif result.exit_code != 0 {\n println(result.output)\n}\n\nsh('ls')\n\n// Similar to:\n// files := ls('.')?\n// mut count := 0\n// if files.len > 0 {\n// for file in files {\n// if file.ends_with('.v') {\n// mv(file, 'build/') or {\n// println('err: ${err}')\n// return\n// }\n// }\n// count++\n// }\n// }\n// if count == 0 {\n// println('No files')\n// }" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

Now you can either compile this like a normal V program and get an executable you can deploy and run +anywhere: +v deploy.vsh && ./deploy

+

Or just run it more like a traditional Bash script: +v run deploy.vsh

+

On Unix-like platforms, the file can be run directly after making it executable using chmod +x: +./deploy.vsh

+

# Vsh scripts with no extension

+

Whilst V does normally not allow vsh scripts without the designated file extension, there is a way +to circumvent this rule and have a file with a fully custom name and shebang. Whilst this feature +exists it is only recommended for specific usecases like scripts that will be put in the path and +should not be used for things like build or deploy scripts. To access this feature start the +file with #!/usr/bin/env -S v -raw-vsh-tmp-prefix tmp where tmp is the prefix for +the built executable. This will run in crun mode so it will only rebuild if changes to the script +were made and keep the binary as tmp.<scriptfilename>. Caution: if this filename already +exists the file will be overridden. If you want to rebuild each time and not keep this binary +instead use #!/usr/bin/env -S v -raw-vsh-tmp-prefix tmp run.

+

# Appendices

+

# Appendix I: Keywords

+

V has 44 reserved keywords (3 are literals):

+{% set code = "as\nasm\nassert\natomic\nbreak\nconst\ncontinue\ndefer\nelse\nenum\nfalse\nfn\nfor\ngo\ngoto\nif\nimport\nin\ninterface\nis\nisreftype\nlock\nmatch\nmodule\nmut\nnone\nor\npub\nreturn\nrlock\nselect\nshared\nsizeof\nspawn\nstatic\nstruct\ntrue\ntype\ntypeof\nunion\nunsafe\nvolatile\n__global\n__offsetof" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} +

See also V Types.

+

# Appendix II: Operators

+

This lists operators for primitive types only.

+{% set code = "+ sum integers, floats, strings\n- difference integers, floats\n* product integers, floats\n/ quotient integers, floats\n% remainder integers\n\n~ bitwise NOT integers\n& bitwise AND integers\n| bitwise OR integers\n^ bitwise XOR integers\n\n! logical NOT bools\n&& logical AND bools\n|| logical OR bools\n!= logical XOR bools\n\n<< left shift integer << unsigned integer\n>> right shift integer >> unsigned integer\n>>> unsigned right shift integer >> unsigned integer\n\n\nPrecedence Operator\n 5 * / % << >> >>> &\n 4 + - | ^\n 3 == != < <= > >=\n 2 &&\n 1 ||\n\n\nAssignment Operators\n+= -= *= /= %=\n&= |= ^=\n>>= <<= >>>=" %} + {% set noheader = true %} + {% include '../components/codeblock.njk' %} + {% set noheader = false %} diff --git a/pages/docs/documentation.njk b/pages/docs/documentation.njk new file mode 100755 index 000000000..611a4e7a2 --- /dev/null +++ b/pages/docs/documentation.njk @@ -0,0 +1,8 @@ +
+
+ {% include "./toc.njk" %} +
+
+ {% include "./content.njk" %} +
+
\ No newline at end of file diff --git a/pages/docs/toc.njk b/pages/docs/toc.njk new file mode 100755 index 000000000..ed4189f80 --- /dev/null +++ b/pages/docs/toc.njk @@ -0,0 +1,308 @@ + diff --git a/pages/editors.njk b/pages/editors.njk new file mode 100755 index 000000000..d44fbe5bd --- /dev/null +++ b/pages/editors.njk @@ -0,0 +1,26 @@ +{% set active_page = 'editors' %} +{% set page_title = 'The V Editors' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %} + +
+

The V Editors

+

V has extensive editor integration, provided by our amazing community ❤️

+
+ +
+ + + V for VS Code + + + + V for Vim + + + + Vid Editor + +
+ +{% include "./components/foot.njk" %} diff --git a/pages/faq.njk b/pages/faq.njk new file mode 100755 index 000000000..6f60de42d --- /dev/null +++ b/pages/faq.njk @@ -0,0 +1,165 @@ +{% set active_page = 'faq' %} +{% set page_title = 'The V FAQ' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %} + +
+

FAQ

+
+Why create V when there are already so many languages? Why not use Go, Rust, C++, Python etc? +

+Detailed comparison of V and other languages. +

+
+
+What language is V written in? +

+V. The compiler can compile itself. The original version was written in Go. +

+
+
+Does V use LLVM? +

+No. V uses C as its backend and will compile directly to machine code by the time of the 1.0 release. +

+On the benefits of using C as a language backend. +

+
+
+ What about optimization? +

+For now V emits C and uses GCC/Clang for optimized production builds. +This way you get access to sophisticated optimization. +

+Such builds are compiled ≈150 times slower than V development builds (but are still +an order of magnitude +faster than C++ production builds). +

+This can be a problem for industries where optimization is required during development (for example AAA +games). In this case, hot code reloading can be used. +

+

+In the future V will have its own optimizer. +

+
+
+ Is there garbage collection? +

+No. V manages memory at compilation, like Rust: +vlang.io/docs#memory-management +

+
+
+ Is there a package manager? +

+Yes! V is a very modular language and encourages creation of modules that are easy to reuse. +

+vpm.vlang.io. +

+Submitting your V module takes a couple of seconds. +

+Installing modules is as easy as +

v install sqlite
+
+
+ What about concurrency? +

+It's going to be the same as in Go. To run foo() concurrently, just call it with +go foo(). Right now it launches the function in a new system thread. Soon coroutines and +the scheduler will be implemented. +

+
+
+Does V run on bare metal? +

+Yes! Simply run with -freestanding to exclude libc and vlib. See an example here. +

+
+
+Will I be able to use a custom allocator? +

+Yes. This hasn't been implemented yet. +

+
+
+Is V going to change a lot? When is v1.0 happening? +

+Right now V is under heavy development, lots of things change. +

+A stable 0.2 version will be released in early December 2019. +

+1.0 is going to have forward compatibility, meaning that +V 1.0 programs will continue to compile and run without change. +

+It's very important to give developers certainty and stability, and not to be in beta for years. +This means that we need to be careful with the 1.0 release. It's going to happen +in early 2020. +

+
+ What operating systems are supported? +

+Windows, macOS, Linux, FreeBSD, OpenBSD, NetBSD, DragonflyBSD, Solaris, Android (Termux). +

+Android and iOS later this year. +

+
+
+Who's behind V? +

+Me and +150+ open source contributors. +

+
+
+How can it translate C++? It's impossible for one person to write a C++ parser. +

+Clang parser is used for translating C/C++ to V. +

+
+
+What about editor support? +

+There are basic plugins for VS Code and +Vim. Also check out the Vid editor, which is written in V. +It has V support built in. +

+Plugins for Emacs, and other popular editors will be available soon. +

+V is a small and simple language, it doesn't need a powerful IDE. +

+
+ Why "V"? +

+Initially the language had the same name as the product it was created for: Volt. The extension was ".v", +I didn't want to mess up git history, so I decided to name it V :) +

+It's a simple name that reflects the simplicity of the language, and it's easy to pronounce for everyone in the +world. +

+Please note that the name of the language is "V", not "Vlang" or "V-Lang" etc. +

The name is not very searchable (like Go), so use +#vlang on Twitter, +vlang on Google etc. +

+
+Any plans to implement macros? +

+No, sorry. Macros can be really useful, but they complicate the code significantly. +Every company, team, developer can extend the language, and it's no longer +possible to jump into a new codebase and immediately understand what's going on. +

+V will have sophisticated code generation. +

+

+
+Under which license is V published? +

+MIT. +

+

+
+Have an unanswered question? +Contact me. +
+
+{% include "./components/foot.njk" %} diff --git a/pages/home/book.njk b/pages/home/book.njk new file mode 100755 index 000000000..1f5bd07c2 --- /dev/null +++ b/pages/home/book.njk @@ -0,0 +1,5 @@ + + +
+ The first printed book on V! +
\ No newline at end of file diff --git a/pages/home/built-in-v.njk b/pages/home/built-in-v.njk new file mode 100755 index 000000000..a91ecc74f --- /dev/null +++ b/pages/home/built-in-v.njk @@ -0,0 +1,78 @@ +
+
+

Built in V

+
+
+

V

+

V itself is written in V.

+
+
+

Volt

+

Native desktop client for Slack, Skype, Matrix, Telegram, Twitch and many more services.

+
+ +
+ +

Vinix

+

A minimalistic open-source OS that can already run Bash, GCC, and V.

+
+
+

Ved

+

Open-source 1 MB editor with the performance of Sublime Text.

+
+ +
+

vsql

+

A single-file SQL database written in pure V with no dependencies.

+
+
+

coreutils in V

+

Programs equivalent to GNU coreutils, written 100% in V.

+ +
+ +
+

C to V translator

+

This tool can already translate entire original DOOM. C++ support is planned as well. It does full automatic conversion to human readable code.

+
+
+

V UI

+

Cross-platform widget toolkit.

+
+ +
+

Gitly

+

Open-source light and fast alternative to GitHub/GitLab.

+
+
+

Vorum

+

Right now it's very basic forum/blogging software, but in the future it will be a full featured light alternative to Discourse.
The V forum runs on Vorum.

+
+ +
+

vgram

+

A bot library for Telegram Bot API.

+
+
+

Awesome V

+

A curated list of awesome V frameworks, libraries and software

+
+ +
+

The V Tensor Library

+

An n-dimensional Tensor data structure, sophisticated reduction, elementwise, and accumulation operations, data Structures that can easily be passed to C libraries, powerful linear algebra routines backed by VSL. +

+
+
+

The V Scientific Library +

+

A Scientific Library with a great variety of different modules.

+
+ + +
+
+

Are you using V to build your product or library? Have it added to this list.

+
+
+
\ No newline at end of file diff --git a/pages/home/download-button.njk b/pages/home/download-button.njk new file mode 100755 index 000000000..0a3b23f7a --- /dev/null +++ b/pages/home/download-button.njk @@ -0,0 +1,65 @@ +{% from "./download-versions.njk" import lin_size, mac_size, win_size, version %} +
+ + {% include "../icons/windows.html" %} +
+ Download for Windows + v0.3.x - 14.3MB +
+
+ +
+ + \ No newline at end of file diff --git a/pages/home/download-button1.njk b/pages/home/download-button1.njk new file mode 100644 index 000000000..4eb0f6d3a --- /dev/null +++ b/pages/home/download-button1.njk @@ -0,0 +1,41 @@ +
+ + +
+ Download for Linux + v0.3.x - 6.6MB +
+
+ +
\ No newline at end of file diff --git a/pages/home/download-versions.njk b/pages/home/download-versions.njk new file mode 100755 index 000000000..971dd3794 --- /dev/null +++ b/pages/home/download-versions.njk @@ -0,0 +1,4 @@ +{% set lin_size = "14.4MB" %} + {% set mac_size = "12MB" %} + {% set win_size = "14.6MB" %} + {% set version = "weekly.2023.15" %} \ No newline at end of file diff --git a/pages/home/examples.njk b/pages/home/examples.njk new file mode 100755 index 000000000..bd92732cf --- /dev/null +++ b/pages/home/examples.njk @@ -0,0 +1,142 @@ +
+{% include "./veasel.njk" %} +
+
+
+
+
fn main() {
+    areas := ['game', 'web', 'tools', 'science', 'systems',
+              'embedded', 'drivers', 'GUI', 'mobile']
+    for area in areas {
+        println('Hello, ${area} developers!')
+    }
+}
+ + + +
+ + +
\ No newline at end of file diff --git a/pages/home/follow.njk b/pages/home/follow.njk new file mode 100755 index 000000000..7e6f5c4e1 --- /dev/null +++ b/pages/home/follow.njk @@ -0,0 +1,8 @@ +
+ + + + + + +
\ No newline at end of file diff --git a/pages/home/footer.njk b/pages/home/footer.njk new file mode 100644 index 000000000..df13fac3a --- /dev/null +++ b/pages/home/footer.njk @@ -0,0 +1,7 @@ +
+ Web design by Leah. + + + logo by Sonovice and Don. + +
\ No newline at end of file diff --git a/pages/home/headline.njk b/pages/home/headline.njk new file mode 100644 index 000000000..a189d8b13 --- /dev/null +++ b/pages/home/headline.njk @@ -0,0 +1,9 @@ +

+ The V Programming Language 0.3 + + beta + +

+

+ Simple, fast, safe, compiled. For developing maintainable software. +

\ No newline at end of file diff --git a/pages/home/landing.njk b/pages/home/landing.njk new file mode 100755 index 000000000..d37006d79 --- /dev/null +++ b/pages/home/landing.njk @@ -0,0 +1,21 @@ +
+ {% include "./book.njk" %} +
+
+ {% include "./headline.njk" %} + {% include "../icons/github.html" %} + {% include "./download-button.njk" %} + {% include "./links.njk" %} + {% include "./social.njk" %} + {% include "./follow.njk" %} +
+ + {% include "./examples.njk" %} +
+ + {% include "./news.njk" %} + {% include "./sections.njk" %} + {% include "./built-in-v.njk" %} + {% include "./footer.njk" %} +
+ \ No newline at end of file diff --git a/pages/home/links.njk b/pages/home/links.njk new file mode 100755 index 000000000..c14bf80de --- /dev/null +++ b/pages/home/links.njk @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/pages/home/news.njk b/pages/home/news.njk new file mode 100755 index 000000000..aad0d5f64 --- /dev/null +++ b/pages/home/news.njk @@ -0,0 +1,97 @@ +
+
+

Latest news

+
+
+ +
+
+
+ January 30, 2023 +
+ +
+
+
+ January 2, 2023 +
+ +
+
+
+ October 31, 2022 +
+ +
+
+
+ August 31, 2022 +
+ +
+
+
+ June 30, 2022 +
+ +
+
+
+ June 22, 2022 +
+ +
+
+
+ June 10, 2022 +
+ +
+
+
+ June 9, 2022 +
+
+ As of today, programs built with the V compiler no longer leak memory by default. +
+
+
+
+ May 29, 2022 +
+
+ 7000 pull requests have been merged! +
+
+ +
+
+
+ \ No newline at end of file diff --git a/pages/home/sections.njk b/pages/home/sections.njk new file mode 100755 index 000000000..85af50c14 --- /dev/null +++ b/pages/home/sections.njk @@ -0,0 +1,486 @@ +
+
+
+

+ Simple language for building maintainable programs

+

+ You can learn the entire language by going through the + documentation over a weekend, and in most cases there's only one way to do something. +

+

+ This results in simple, readable, and maintainable code. +

+

+ Despite being simple, V gives a lot of power to the developer and can be used in pretty much every field, including systems programming, webdev, gamedev, GUI, mobile, science, embedded, tooling, etc. +

+

+ V is very similar to Go. If you know Go, you already know ≈80% of V. + Things V improves on Go: vlang.io/compare#go. +

+
+
+

Safety

+ +
+
+ {% include "./sponsors.njk" %} +
+
+

Performance

+
    +
  • C interop without any costs
  • +
  • Minimal amount of allocations
  • +
  • Built-in serialization without runtime reflection
  • +
  • Compiles to native binaries without any dependencies: a simple web server is only about 250 KB
  • +
  • As fast as C (V's main backend compiles to human readable C), + with equivalent code. +
    V does introduce some overhead for safety (such as array bounds checking, GC free), but these features can be disabled/bypassed when performance is more important. +
  • +
+
+
+

Fast compilation

+

+ V compiles ≈110k (Clang backend) and ≈500k (x64 and tcc backends) lines of code per second.
(Intel i5-7500, SM0256L SSD, no optimization)

+ V is written in V and compiles itself in under a second. +

+

+ Most of the compiler is still single threaded, so it's going to be 2-3x faster in the future! +

+
+
+
+
+

Small and easy to build compiler

+

+ V can be bootstrapped in under a second by compiling its code translated to C with a simple

+
cc v.c
No libraries or dependencies needed. +

+ For comparison, space and time required to build each compiler: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Space  Build time
Go525 MB1m 33s
Rust30 GB45m
GCC8 GB50m
Clang90 GB + [0] + 60m
Swift70 GB + [1] + 90m
V< 10 MB + [2] + <1s
+
+
+

Building V in 0.3 seconds and then using the resulting binary to build itself again:

+ + + +

+ Try it yourself: +

+ + wget https://github.com/vlang/v/releases/latest/download/v_linux.zip
+ unzip v_linux && cd v
+ time ./v self +
+
+
+
+
+

Innovative and flexible memory management

+

+ V avoids doing unnecessary allocations in the first place + by using value types, string buffers, promoting a simple abstraction-free code style. +

+

+ There are 4 ways to manage memory in V. +

+

+ The default is a minimal and a well performing tracing GC. + +

+

+ The second way is autofree, it can be enabled with -autofree. It takes care of most objects (~90-100%): + the compiler inserts necessary free calls automatically during compilation. + Remaining small percentage of objects is freed via GC. + The developer doesn't need to change anything in their code. "It just works", + like in Python, Go, or Java, except there's no heavy GC tracing everything + or expensive RC for each object. +

+

+ For developers willing to have more low level control, memory can be managed manually + with -gc none. +

+

+ Arena allocation is available via v -prealloc. +

+
+
+

+ V's autofree demo. All objects are freed during compilation. Running the Ved editor on an 8 MB file with 0 leaks: +

+ + + +
+
+
+
+

C translation

+

V can translate your entire C project and offer you the safety, simplicity, and compilation speed-up (via modules).

+
+
v translate file.c
+
+std::vector s;
+s.push_back("V is ");
+s.push_back("awesome");
+std::cout << s.size();
+
mut s := []
+s << 'V is '
+s << 'awesome'
+println(s.len)
+
+

+ A blog post about translating DOOM will be published.

+ C++ to V translation is at an early stage. +

+
+
+

+ Translating DOOM from C to V and building it in under a second: +

+ +

+ You can read translated code here: + github.com/vlang/doom +

+
+
+
+
+

Hot code reloading

+

+ Get your changes instantly without recompiling. +

+ Since you also don't have to get to the state you are working on after every compilation, this can save a lot of precious minutes of your development time. +

+ github.com/.../examples/hot_reload +
+
+ +
+
+
+
+

A powerful graphics library

+

+ Cross-platform drawing library, using OpenGL/Metal/DirectX 11 for rendering 2D/3D applications. +

+

+ The following features are planned: +

+
    +
  • Loading complex 3D objects with textures
  • +
  • Camera (moving, looking around)
  • +
  • Skeletal animation
  • +
+

A simple example of the graphics library in action is tetris.v.

+

For 3D examples, check out this.

+
+
+ +
+
+
+
+

Light and fast cross-platform GUI library

+

+ Build native UI apps with V UI. You no longer need to embed a browser to develop cross-platform apps quickly.

+ V has a UI module that uses custom drawing, similar to Qt and Flutter, but with as much similarity to the native GUI toolkit as possible. +

+

+ It has a declarative API similar to SwiftUI and React Native and runs on Windows, Linux, macOS, and Android. +

+

+ Coming soon: +

+
    +
  • a Delphi-like visual editor for building native GUI apps
  • +
  • iOS support
  • +
+

github.com/vlang/ui

+
+
+

+ Volt, a 300 KB Slack client built with V and V ui: + +

+ https://volt-app.com + + + + +
+
+
+
+

Easy cross compilation

+

+ To cross compile your software simply run v -os windows or v -os linux. No extra steps required, even for GUI and graphical apps!

+ (Compiling macOS software only works on macOS for now.) +

+
+
+

+ Building V for Windows using V for macOS, and then testing resulting v.exe on a Windows VM: +

+
+
+
+
+

Painless deployments and dependency management

+

+ To build your project, no matter how big, all you need to do is run +

v .
+

+ No build environments, makefiles, headers, virtual environments, etc.
+ You get a single statically linked binary that is guaranteed to work on all operating systems (provided you cross compile) without any dependencies.

+ Installing new libraries via vpm, a centralized package manager written in V, is as simple as +
v install ui
+    
+

+
+
+

Run everywhere

+

+ V can emit (human readable) C, so you get the great platform support and optimization of GCC and Clang. (Use v -prod . to make optimized builds.)

+ Emitting C will always be an option, even after direct machine code generation matures.

+ V can call C code, and calling V code is possible in any language that has C interop. +

+
+
+
+
+

REPL

+
v
+>>> import net.http
+>>> data := http.get('https://vlang.io/utc_now')?
+>>> data.text
+1565977541
+
+
+

Cross-platform shell scripts in V

+

+ V can be used as an alternative to Bash to write deployment scripts, build scripts, etc. + The advantage of using V for this is the simplicity and predictability of the language, and cross-platform support. "V scripts" run on Unix-like systems as well as on Windows. +

+
for file in ls('build/') {
+  rm(file)
+}
+mv('v.exe', 'build/')
+
+v run deploy.vsh
+

Read more about V script

+
+
+
+
+

Code formatting with vfmt for consistent style

+

+ No more arguments about coding styles. There's one official coding style + enforced by the vfmt formatter. +

+

+ All V code bases are guaranteed to use + the same style, making it easier to read and change code written by + other developers. +

+
v fmt -w hello.v
+
+
+

A built-in code profiler

+

+ Build and run your program with +

v -profile profile.txt x.v && ./x
and + you'll get a detailed list for all function calls: number of calls, average time per + call, total time per call. +

+
+
+
+
+

JavaScript and WASM backends

+

+ V programs can be translated to JavaScript: +

+
v -o hello.js hello.v
+

+ They can also be compiled to WASM (for now with Emscripten). + V compiler compiled to WASM and running V programs by translating them to JavaScript: +

+

+ v-wasm.vercel.app +

+

A game written using V's graphical backend and compiled to WASM:

+ v2048 +
+
+

Automatic documentation

+

+ Use vdoc to get instant documentation generated directly from + the module's source code. No need to keep and update separate documentation. +

+
v doc os
+
+
+
+
+

Built-in testing framework

+

+ Writing tests is very easy: just start your test function with test_ +

fn get_string() string { return 'hello' }
+
+fn test_get_string() {
+  assert get_string() == 'hello'
+}
+      

+

+ +
+

Friendly error messages

+

+ Helpful error messages make learning the language and fixing errors simpler: + +

+
user.v:8:14: error: `update_user` parameter `user` is mutable, you need to provide `mut`: `update_user(mut user)`
+
+    7 |     mut user := User{}
+    8 |     update_user(user)
+      |                 ~~~~
+    9 | }
+  
+
+
+
+
+

Powerful built-in web framework

+

github.com/vlang/v/tree/master/vlib/vweb

+
+
+
+
+
['/post/:id']
+fn (b Blog) show_post(id int) vweb.Result {
+  post := b.posts_repo.retrieve(id) or {
+    return vweb.not_found()
+  }
+  return vweb.view(post)
+}
+
+

Gitly, a light and fast alternative to GitHub/GitLab is built in V and vweb.

+
+
+

Built-in ORM

+

+

+
+
+
+ +
+
import sqlite
+
+struct Customer {
+  id int
+  name string
+  nr_orders int
+  country string
+}
+
+fn main() {
+  db := sqlite.connect('example.sqlite') or {
+    panic('could not create/find example.sqlite')
+  }
+
+  nr_customers := sql db {
+    select count from Customer
+  }
+  println('number of all customers: ${nr_customers}')
+
+  // V syntax can be used to build queries
+  uk_customers := sql db {
+    select from Customer where country == 'uk' && nr_orders > 0
+  }
+
+  for customer in uk_customers {
+    println('${customer.id} - ${customer.name}')
+  }
+
+  // by adding `limit 1` we tell V that there will be
+  // only one object
+  customer := sql db {
+    select from Customer where id == 1 limit 1
+  }
+  println(customer.name)
+
+  // insert a new customer
+  new_customer := Customer{name: 'Bob', nr_orders: 10}
+  sql db {
+    insert new_customer into Customer
+  }
+}
+
+
+
+
+
\ No newline at end of file diff --git a/pages/home/social.njk b/pages/home/social.njk new file mode 100755 index 000000000..80c1c6603 --- /dev/null +++ b/pages/home/social.njk @@ -0,0 +1,19 @@ +
+ + + + + +       + + + + + +
\ No newline at end of file diff --git a/pages/home/sponsors.njk b/pages/home/sponsors.njk new file mode 100755 index 000000000..2b64baf47 --- /dev/null +++ b/pages/home/sponsors.njk @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/pages/home/veasel.njk b/pages/home/veasel.njk new file mode 100755 index 000000000..cbd955fb5 --- /dev/null +++ b/pages/home/veasel.njk @@ -0,0 +1,5 @@ +
+ + + +
\ No newline at end of file diff --git a/pages/icons/apple.html b/pages/icons/apple.html new file mode 100755 index 000000000..796affc55 --- /dev/null +++ b/pages/icons/apple.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/chat-bubble.html b/pages/icons/chat-bubble.html new file mode 100755 index 000000000..f5b3a0620 --- /dev/null +++ b/pages/icons/chat-bubble.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/discord.html b/pages/icons/discord.html new file mode 100755 index 000000000..5b24b3552 --- /dev/null +++ b/pages/icons/discord.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/github.html b/pages/icons/github.html new file mode 100755 index 000000000..0ab64d676 --- /dev/null +++ b/pages/icons/github.html @@ -0,0 +1,12 @@ + + + + + + + +
+github.com/vlang/v +33k +
+
\ No newline at end of file diff --git a/pages/icons/linux.html b/pages/icons/linux.html new file mode 100755 index 000000000..d692b95a4 --- /dev/null +++ b/pages/icons/linux.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/play.html b/pages/icons/play.html new file mode 100755 index 000000000..ec0831696 --- /dev/null +++ b/pages/icons/play.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/telegram.html b/pages/icons/telegram.html new file mode 100755 index 000000000..d7e8653e0 --- /dev/null +++ b/pages/icons/telegram.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/twitter.html b/pages/icons/twitter.html new file mode 100755 index 000000000..bb380c641 --- /dev/null +++ b/pages/icons/twitter.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/windows.html b/pages/icons/windows.html new file mode 100755 index 000000000..367013d23 --- /dev/null +++ b/pages/icons/windows.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/icons/youtube.html b/pages/icons/youtube.html new file mode 100755 index 000000000..bd86b52cc --- /dev/null +++ b/pages/icons/youtube.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pages/index.njk b/pages/index.njk new file mode 100755 index 000000000..03995da2d --- /dev/null +++ b/pages/index.njk @@ -0,0 +1,6 @@ +{% set active_page = 'home' %} +{% set page_title = 'The V Programming Language' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %} +{% include "./home/landing.njk" %} +{% include "./components/foot.njk" %} diff --git a/pages/modules.njk b/pages/modules.njk new file mode 100755 index 000000000..fbb5c6a3b --- /dev/null +++ b/pages/modules.njk @@ -0,0 +1,10 @@ +{% set active_page = 'modules' %} +{% set page_title = 'The V Modules' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %} + +

+This page hasn't been implemented yet. It will be added once v doc works again. +

+ +{% include "./components/foot.njk" %} diff --git a/pages/play.njk b/pages/play.njk new file mode 100755 index 000000000..b39ce20eb --- /dev/null +++ b/pages/play.njk @@ -0,0 +1,8 @@ +{% set active_page = 'play' %} +{% set page_title = 'The V Playground' %} +{% include "./components/head.njk" %} +{% include "./components/nav.njk" %} + +{% include "./playground/playground.njk" %} + +{% include "./components/foot.njk" %} diff --git a/pages/playground/playground.njk b/pages/playground/playground.njk new file mode 100755 index 000000000..e9ad18263 --- /dev/null +++ b/pages/playground/playground.njk @@ -0,0 +1,57 @@ +{%- macro random_int(len) -%} + {%- for _ in range(len) -%} + {{ range(10) | random }} + {%- endfor -%} +{%- endmacro -%} + +{% set pgid = "playground_" + random_int(8) %} +{% set slid = "playground_select_" + random_int(8) %} +{% set opid = "playground_output_" + random_int(8) %} +
+ +
+ +
+
+
+ {% set filename = "V Playground - v0.1.24" %} + {% set output_to = opid %} + {% set setter = pgid %} + {% include '../components/codeblock.njk' %} + + {% set setter = "" %} + {% set output_to = "" %} +
+
+ Program Output +
+
+
+
+
+ \ No newline at end of file diff --git a/preview.html b/preview.html deleted file mode 100644 index 1984fe076..000000000 --- a/preview.html +++ /dev/null @@ -1,1093 +0,0 @@ - - - - - - - - - - - The V Programming Language - - -
- -
-
- - - - -
-
- - - -
-
-
-

The V Programming Language 0.3

-

Simple, fast, safe, compiled. For developing maintainable software.

- - -
- github.com/vlang/v - 30k -
-
- - - - - - -
- - - - - - - - - -
-
- - - -
- The first printed book on V! -
- -
-
- -
-
-
-
-
-
fn main() {
-    areas := ['game', 'web', 'tools', 'science', 'systems',
-              'embedded', 'drivers', 'GUI', 'mobile']
-    for area in areas {
-        println('Hello, $area developers!')
-    }
-}
- - - -
- - - - -
-
-
- -
-
- Latest news
-
- -
-
- June 30, 2022 -
- -
- -
-
- June 22, 2022 -
- -
-
-
- June 10, 2022 -
- -
- -
-
- June 9, 2022 -
-
- As of today, programs built with the V compiler no longer leak memory by default. -
-
- - -
-
- May 29, 2022 -
-
- 7000 pull requests have been merged! -
-
- - -
- -
-
-

%simple_language_for_maintainable_programs

-

- You can learn the entire language by going through the - documentation over a weekend, and in most cases there's only one way to do something. -

- This results in simple, readable, and maintainable code. -

- Despite being simple, V gives a lot of power to the developer and can be used in pretty much every field, including systems programming, webdev, gamedev, GUI, mobile, science, embedded, tooling, etc. -

-

- V is very similar to Go. If you know Go, you already know ≈80% of V. - Things V improves on Go: vlang.io/compare#go. -

-
-
-

Safety

- -
-
- - - - -
-
-

Performance

-
    -
  • As fast as C (V's main backend compiles to human readable C)
  • -
  • C interop without any costs
  • -
  • Minimal amount of allocations
  • -
  • Built-in serialization without runtime reflection
  • -
  • Compiles to native binaries without any dependencies: a simple web server is only 65 KB
  • -
-
-
-

Fast compilation

-

- V compiles ≈110k (Clang backend) and ≈500k (x64 and tcc backends) lines of code per second.
(Intel i5-7500, SM0256L SSD, no optimization)

- V is written in V and compiles itself in under a second. -

-

- Most of the compiler is still single threaded, so it's going to be 2-3x faster in the future! -

-
-
- - - - - - - - -
-
-

Small and easy to build compiler

-

- V can be bootstrapped in under a second by compiling its code translated to C with a simple

cc v.c
No libraries or dependencies needed. -

- For comparison, space and time required to build each compiler: -

- - - - - - - - -
Space  Build time
Go525 MB1m 33s
Rust30 GB45m
GCC8 GB50m
Clang90 GB - [0] - 60m
Swift70 GB - [1] - 90m
V< 10 MB - [2] - <1s
-
-
-

Building V in 0.3 seconds and then using the resulting binary to build itself again:

- - - - - - -
-
- - - -
-
-

Innovative and flexible memory management

-

- V avoids doing unnecessary allocations in the first place - by using value types, string buffers, promoting a simple abstraction-free code style. -

-

- Right now allocations are handled by a minimal and well performing GC until V's autofree engine is production ready. -

- Autofree can be enabled with -autofree. It takes care of most objects (~90-100%): - the compiler inserts necessary free calls automatically during compilation. - Remaining small percentage of objects is freed via GC. - The developer doesn't need to change anything in their code. "It just works", - like in Python, Go, or Java, except there's no heavy GC tracing everything - or expensive RC for each object. -

-

- For developers willing to have more low level control, memory can be managed manually - - with -gc none. -

- -

- Arena allocation is available via v -prealloc. -

- - - -
-
-

- V's autofree demo. All objects are freed during compilation. Running the Ved editor on an 8 MB file with 0 leaks: -

- - - - - -
-
- -
-
-

C translation

-

V can translate your entire C project and offer you the safety, simplicity, and compilation speed-up (via modules).

-
-
v translate file.c
-
-std::vector s;
-s.push_back("V is ");
-s.push_back("awesome");
-std::cout << s.size();
- -
mut s := []
-s << 'V is '
-s << 'awesome'
-println(s.len)
-
-

- A blog post about translating DOOM will be published.

- C++ to V translation is at an early stage. -

-
-
-

- Translating DOOM from C to V and building it in under a second: -

- - -

-You can read translated code here: -github.com/vlang/doom -

-
-
- -
-
-

Hot code reloading

-

- Get your changes instantly without recompiling. -

- Since you also don't have to get to the state you are working on after every compilation, this can save a lot of precious minutes of your development time. -

- github.com/.../examples/hot_reload -
-
- -
-
- -
-
-

Powerful graphics libraries

-

- Cross-platform drawing library built on top of GDI+/Cocoa Drawing, and an OpenGL based graphics library for more complex 2D/3D applications, that will also have the following features: -

-
    -
  • Loading complex 3D objects with textures
  • -
  • Camera (moving, looking around)
  • -
  • Skeletal animation
  • -
-

DirectX, Vulkan, and Metal support is planned.

-

A simple example of the graphics library in action is tetris.v.

-
-
- -
-
- -
-
-

Native cross-platform GUI library

-

- Build native apps with native controls. You no longer need to embed a browser to develop cross-platform apps quickly.

- V has a ui module that uses native GUI toolkits: WinAPI/GDI+ on Windows, Cocoa on macOS. On Linux custom drawing is used.

- Coming soon: -

-
    -
  • a Delphi-like visual editor for building native GUI apps
  • -
  • iOS/Android support with native controls
  • -
  • a declarative API similar to SwiftUI and React Native
  • -
-

github.com/vlang/ui

-
-
-

- Volt, a 300 KB Slack client built with V and V ui: -

- -
-
- -
-
-

Easy cross compilation

-

- To cross compile your software simply run v -os windows. or v -os linux. No extra steps required, even for GUI and graphical apps!

- (Compiling macOS software only works on macOS for now.) -

-
-
-

- Building V for Windows using V for macOS, and then testing resulting v.exe on a Windows VM: -

-
-
- -
-
-

Painless deployments and dependency management

-

- To build your project, no matter how big, all you need to do is run -

-v .
-

- No build environments, makefiles, headers, virtual environments, etc.
- You get a single statically linked binary that is guaranteed to work on all operating systems (provided you cross compile) without any dependencies.

- Installing new libraries via vpm, a centralized package manager written in V, is as simple as -
-v install ui
-		
-

-
-
-

Run everywhere

-

- V can emit (human readable) C, so you get the great platform support and optimization of GCC and Clang. (Use v -prod . to make optimized builds.)

- Emitting C will always be an option, even after direct machine code generation matures.

- V can call C code, and calling V code is possible in any language that has C interop. -

-
-
- -
-
-

REPL

-
v
->>> import net.http
->>> data := http.get('https://vlang.io/utc_now')?
->>> data.text
-1565977541
-
-
-

Cross-platform shell scripts in V

-

- V can be used as an alternative to Bash to write deployment scripts, build scripts, etc. - -The advantage of using V for this is the simplicity and predictability of the language, and cross-platform support. "V scripts" run on Unix-like systems as well as on Windows. -

-
for file in ls('build/') {
-  rm(file)
-}
-mv('v.exe', 'build/')
-
-v run deploy.vsh
-

Read more about V script

-
-
- -
-
-

Code formatting with vfmt for consistent style

-

- No more arguments about coding styles. There's one official coding style - enforced by the vfmt formatter. -

-

- All V code bases are guaranteed to use - the same style, making it easier to read and change code written by - other developers. -

-
v fmt -w hello.v
-
-
-

A built-in code profiler

-

- Build and run your program with

v -profile profile.txt x.v && ./x
and - you'll get a detailed list for all function calls: number of calls, average time per - call, total time per call. -

-
-
- -
-
-

JavaScript and WASM backends

-

- V programs can be translated to JavaScript: -

-
v -o hello.js hello.v
-

- They can also be compiled to WASM (for now with Emscripten). - V compiler compiled to WASM and running V programs by translating them to JavaScript: -

-

- v-wasm.vercel.app -

-

A game written using V's graphical backend and compiled to WASM:

- v2048 - -
-
-

Automatic documentation

-

- Use vdoc to get instant documentation generated directly from - the module's source code. No need to keep and update separate documentation. -

-
v doc os
-
-
- -
-
-

Built-in testing framework

-

- Writing tests is very easy: just start your test function with test_ -

-fn get_string() string { return 'hello' }
-
-fn test_get_string() {
-  assert get_string() == 'hello'
-}
-      

-

- -
-

Friendly error messages

-

- Helpful error messages make learning the language and fixing errors simpler: - -

-
-user.v:8:14: error: `update_user` parameter `user` is mutable, you need to provide `mut`: `update_user(mut user)`
-
-    7 |     mut user := User{}
-    8 |     update_user(user)
-      |                 ~~~~
-    9 | }
-	
-
-
- -
-
-

Powerful built-in web framework

-

github.com/vlang/v/tree/master/vlib/vweb

- -
-
-
- Run -
- -
['/post/:id'] -fn (b Blog) show_post(id int) vweb.Result { - post := b.posts_repo.retrieve(id) or { - return vweb.not_found() - } - return vweb.view(post) -}
-
- - -

Gitly, a light and fast alternative to GitHub/GitLab is built in V and vweb.

-
- -
-

Built-in ORM

-

- -

- -
-
- Run -
- -
import sqlite - -struct Customer { - id int - name string - nr_orders int - country string -} - -fn main() { - db := sqlite.connect('example.sqlite') or { - panic('could not create/find example.sqlite') - } - - nr_customers := sql db { - select count from Customer - } - println('number of all customers: $nr_customers') - - // V syntax can be used to build queries - uk_customers := sql db { - select from Customer where country == 'uk' && nr_orders > 0 - } - - for customer in uk_customers { - println('$customer.id - $customer.name') - } - - // by adding `limit 1` we tell V that there will be - // only one object - customer := sql db { - select from Customer where id == 1 limit 1 - } - println(customer.name) - - // insert a new customer - new_customer := Customer{name: 'Bob', nr_orders: 10} - sql db { - insert new_customer into Customer - } -} -
-
- - -

-
-
-
-
-
-

Built in V

-
-
-

V

-

V itself is written in V.

-
-
-

Volt

-

Native desktop client for Slack, Skype, Matrix, Telegram, Twitch and many more services.

-
- -
- -

Vinix

-

A minimalistic open-source OS that can already run Bash, GCC, and V.

-
-
-

Ved

-

Open-source 1 MB editor with the performance of Sublime Text.

-
- -
-

vsql

-

A single-file SQL database written in pure V with no dependencies.

-
-
-

coreutils in V

-

Programs equivalent to GNU coreutils, written 100% in V.

- -
- -
-

C to V translator

-

This tool can already translate entire original DOOM. C++ support is planned as well. It does full automatic conversion to human readable code.

-
-
-

V UI

-

Cross-platform widget toolkit using native APIs.

-
- -
-

Gitly

-

Open-source light and fast alternative to GitHub/GitLab.

-
-
-

Vorum

-

Right now it's very basic forum/blogging software, but in the future it will be a full featured light alternative to Discourse.
The V forum runs on Vorum.

-
- -
-

vgram

-

A bot library for Telegram Bot API.

-
-
-

Awesome V

-

A curated list of awesome V frameworks, libraries and software

-
- -
-
-

Are you using V to build your product or library? Have it added to this list.

-
-
-
- - Web design by Leah. - - - logo by Sonovice and Don. - -
- - - diff --git a/res/css b/res/css new file mode 100755 index 000000000..76300141f --- /dev/null +++ b/res/css @@ -0,0 +1,520 @@ +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxFIzIFKw.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxMIzIFKw.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxEIzIFKw.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxLIzIFKw.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxHIzIFKw.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxGIzIFKw.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxIIzI.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fCRc4EsA.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fABc4EsA.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fCBc4EsA.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fBxc4EsA.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fCxc4EsA.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fChc4EsA.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu72xKOzY.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu5mxKOzY.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7mxKOzY.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4WxKOzY.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7WxKOzY.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7GxKOzY.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fCRc4EsA.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fABc4EsA.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fCBc4EsA.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fBxc4EsA.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fCxc4EsA.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fChc4EsA.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCRc4EsA.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfABc4EsA.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCBc4EsA.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBxc4EsA.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCxc4EsA.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfChc4EsA.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 100; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 200; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 300; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* cyrillic-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhGq3-OXg.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhPq3-OXg.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhIq3-OXg.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhEq3-OXg.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhFq3-OXg.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 500; + src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/res/examples/consts.v b/res/examples/consts.v new file mode 100755 index 000000000..ca1c2f002 --- /dev/null +++ b/res/examples/consts.v @@ -0,0 +1,28 @@ +import strings + +struct Color { + r int + g int + b int +} + +pub fn (c Color) str() string { + return '{$c.r, $c.g, $c.b}' +} + +fn rgb(r, g, b int) Color { + return Color{r: r, g: g, b: b} +} + +const ( + NUMBERS = [1, 2, 3] + + RED = Color{r: 255, g: 0, b: 0} + BLUE = rgb(0, 0, 255) +) + +fn main() { + println(NUMBERS) + println(RED) + println(BLUE) +} diff --git a/res/examples/copy_struct.v b/res/examples/copy_struct.v new file mode 100755 index 000000000..0cfe2f5eb --- /dev/null +++ b/res/examples/copy_struct.v @@ -0,0 +1,13 @@ +struct User { + name string + age int +} + +fn main() { + user1 := User{'Bob', 20} + user2 := { user1 | name: 'Peter' } + println(user1.name) + println(user1.age) + println(user2.name) + println(user2.age) +} diff --git a/res/examples/fib.v b/res/examples/fib.v new file mode 100755 index 000000000..06e9f563e --- /dev/null +++ b/res/examples/fib.v @@ -0,0 +1,12 @@ +fn fib(n int) int { + if n <= 1 { + return n + } + return fib(n - 1) + fib(n - 2) +} + +fn main() { + for i := 0; i < 10; i++ { + println(fib(i)) + } +} \ No newline at end of file diff --git a/res/examples/fibmem.v b/res/examples/fibmem.v new file mode 100755 index 000000000..124bd41fe --- /dev/null +++ b/res/examples/fibmem.v @@ -0,0 +1,27 @@ +const ( + MAX = 15 +) + +struct Fib { + nums []int +} + +fn (fib mut Fib) calc(n int) int { + if n <= 1 { + return n + } + if fib.nums[n] != 0 { + return fib.nums[n] + } + fib.nums[n] = fib.calc(n - 1) + fib.calc(n - 2) + return fib.nums[n] +} + +fn main() { + mut fib := Fib { + nums: [0].repeat(MAX) + } + for i := 0; i < MAX; i++ { + println(fib.calc(i)) + } +} diff --git a/res/examples/hello.v b/res/examples/hello.v new file mode 100755 index 000000000..a5ac8d7d4 --- /dev/null +++ b/res/examples/hello.v @@ -0,0 +1,6 @@ +fn main() { + areas := ['game', 'web', 'tools', 'science', 'systems', 'GUI', 'mobile'] + for area in areas { + println('Hello, $area developers!') + } +} \ No newline at end of file diff --git a/res/examples/json.v b/res/examples/json.v new file mode 100755 index 000000000..26d1bd51e --- /dev/null +++ b/res/examples/json.v @@ -0,0 +1,39 @@ +import json + +struct User { + name string + age int +mut: + is_registered bool +} + +fn main() { + s := '[{ "name":"Frodo", "age":25}, {"name":"Bobby", "age":10}]' + mut users := json.decode( []User, s) or { + eprintln('Failed to parse json') + return + } + for user in users { + println('$user.name: $user.age') + } + println('') + for i, user in users { + println('$i) $user.name') + if !user.can_register() { + println('Cannot register $user.name, they are too young') + continue + } + users[i].register() // `user` is immutable, we have to modify the array + } + // Let's encode users again just for fun + println('') + println(json.encode(users)) +} + +fn (u User) can_register() bool { + return u.age >= 16 +} + +fn (u mut User) register() { + u.is_registered = true +} diff --git a/res/examples/op_overload.v b/res/examples/op_overload.v new file mode 100755 index 000000000..f8d3f45bc --- /dev/null +++ b/res/examples/op_overload.v @@ -0,0 +1,29 @@ +struct Vec { + x int + y int +} + +pub fn (a Vec) str() string { + return '{$a.x, $a.y}' +} + +fn (a Vec) + (b Vec) Vec { + return Vec { + a.x + b.x, + a.y + b.y + } +} + +fn (a Vec) - (b Vec) Vec { + return Vec { + a.x - b.x, + a.y - b.y + } +} + +fn main() { + a := Vec{2, 3} + b := Vec{4, 5} + println(a + b) + println(a - b) +} diff --git a/res/examples/users.v b/res/examples/users.v new file mode 100755 index 000000000..a538a3c20 --- /dev/null +++ b/res/examples/users.v @@ -0,0 +1,36 @@ +struct User { + id int + name string +} + +struct Repo { + users []User +} + +fn new_repo() Repo { + return Repo { + users: [User{1, 'Andrew'}, User {2, 'Bob'}, User {10, 'Charles'}] + } +} + +fn (r Repo) find_user_by_id(id int) ?User { + for user in r.users { + if user.id == id { + // V automatically wraps this into an option type + return user + } + } + return error('User $id not found') +} + +fn main() { + repo := new_repo() + // Option types must be handled by `or` blocks + user := repo.find_user_by_id(10) or { + // `or` block must end with `return`, `break`, or `continue` + println('not found') + return + } + println(user.id) // ==> '10' + println(user.name) // ==> 'Charles' +} diff --git a/res/media/arrow-left.png b/res/media/arrow-left.png new file mode 100644 index 000000000..78b22920a Binary files /dev/null and b/res/media/arrow-left.png differ diff --git a/res/media/arrow-right.png b/res/media/arrow-right.png new file mode 100644 index 000000000..d5a7e008f Binary files /dev/null and b/res/media/arrow-right.png differ diff --git a/res/media/book.jpg b/res/media/book.jpg new file mode 100755 index 000000000..3a516db67 Binary files /dev/null and b/res/media/book.jpg differ diff --git a/res/media/buildv.mp4 b/res/media/buildv.mp4 new file mode 100755 index 000000000..98dc5c008 Binary files /dev/null and b/res/media/buildv.mp4 differ diff --git a/res/media/dk b/res/media/dk new file mode 100755 index 000000000..41b56ec6a --- /dev/null +++ b/res/media/dk @@ -0,0 +1 @@ +Discord: 818 onlineDiscord818 online \ No newline at end of file diff --git a/res/media/dk.svg b/res/media/dk.svg new file mode 100755 index 000000000..85a13c971 --- /dev/null +++ b/res/media/dk.svg @@ -0,0 +1 @@ +Discord: 542 onlineDiscord542 online \ No newline at end of file diff --git a/res/media/doom.png b/res/media/doom.png new file mode 100755 index 000000000..86d06f899 Binary files /dev/null and b/res/media/doom.png differ diff --git a/res/media/down.png b/res/media/down.png new file mode 100755 index 000000000..97737aa84 Binary files /dev/null and b/res/media/down.png differ diff --git a/res/media/emacs.png b/res/media/emacs.png new file mode 100755 index 000000000..9ab43d704 Binary files /dev/null and b/res/media/emacs.png differ diff --git a/res/media/gg.png b/res/media/gg.png new file mode 100755 index 000000000..5d8b18ee8 Binary files /dev/null and b/res/media/gg.png differ diff --git a/res/media/hot.mp4 b/res/media/hot.mp4 new file mode 100644 index 000000000..c7b548cc8 Binary files /dev/null and b/res/media/hot.mp4 differ diff --git a/res/media/intellij.png b/res/media/intellij.png new file mode 100755 index 000000000..2dfea2108 Binary files /dev/null and b/res/media/intellij.png differ diff --git a/res/media/patreon.png b/res/media/patreon.png new file mode 100755 index 000000000..06adabf7d Binary files /dev/null and b/res/media/patreon.png differ diff --git a/res/media/screen3.png b/res/media/screen3.png new file mode 100644 index 000000000..f98c40f5a Binary files /dev/null and b/res/media/screen3.png differ diff --git a/res/media/sponsor_chipnetics.svg b/res/media/sponsor_chipnetics.svg new file mode 100755 index 000000000..ebdb2c490 --- /dev/null +++ b/res/media/sponsor_chipnetics.svg @@ -0,0 +1,170 @@ + + + + + + + + image/svg+xml + + + + + + + + + diff --git a/res/media/sponsor_mx.png b/res/media/sponsor_mx.png new file mode 100755 index 000000000..5aa5b73e0 Binary files /dev/null and b/res/media/sponsor_mx.png differ diff --git a/res/media/sponsor_syndica.jpg b/res/media/sponsor_syndica.jpg new file mode 100755 index 000000000..ddca49db3 Binary files /dev/null and b/res/media/sponsor_syndica.jpg differ diff --git a/res/media/sponsor_threefold.svg b/res/media/sponsor_threefold.svg new file mode 100755 index 000000000..567d83fed --- /dev/null +++ b/res/media/sponsor_threefold.svg @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/media/sublime.png b/res/media/sublime.png new file mode 100644 index 000000000..8be1c1f54 Binary files /dev/null and b/res/media/sublime.png differ diff --git a/res/media/tw b/res/media/tw new file mode 100755 index 000000000..1da1ed957 --- /dev/null +++ b/res/media/tw @@ -0,0 +1 @@ +Follow7.5k \ No newline at end of file diff --git a/res/media/tw.svg b/res/media/tw.svg new file mode 100755 index 000000000..17e720e0e --- /dev/null +++ b/res/media/tw.svg @@ -0,0 +1 @@ +Follow7.6k \ No newline at end of file diff --git a/res/media/v-logo.png b/res/media/v-logo.png new file mode 100755 index 000000000..c55a04d70 Binary files /dev/null and b/res/media/v-logo.png differ diff --git a/res/media/veasel.png b/res/media/veasel.png new file mode 100755 index 000000000..1bf86da19 Binary files /dev/null and b/res/media/veasel.png differ diff --git a/res/media/vid.png b/res/media/vid.png new file mode 100755 index 000000000..8a5141afa Binary files /dev/null and b/res/media/vid.png differ diff --git a/res/media/vim.png b/res/media/vim.png new file mode 100755 index 000000000..9d1f781c8 Binary files /dev/null and b/res/media/vim.png differ diff --git a/res/media/volt.png b/res/media/volt.png new file mode 100755 index 000000000..4ba1b8def Binary files /dev/null and b/res/media/volt.png differ diff --git a/res/media/vscode.png b/res/media/vscode.png new file mode 100755 index 000000000..8be88a81a Binary files /dev/null and b/res/media/vscode.png differ diff --git a/res/media/vwin.mp4 b/res/media/vwin.mp4 new file mode 100755 index 000000000..a4384df8d Binary files /dev/null and b/res/media/vwin.mp4 differ diff --git a/res/media/youtube_comp_speed.png b/res/media/youtube_comp_speed.png new file mode 100755 index 000000000..80372aa38 Binary files /dev/null and b/res/media/youtube_comp_speed.png differ diff --git a/res/media/youtube_compile_speed.png b/res/media/youtube_compile_speed.png new file mode 100755 index 000000000..74b3474a9 Binary files /dev/null and b/res/media/youtube_compile_speed.png differ diff --git a/res/tokenizer.js b/res/tokenizer.js new file mode 100755 index 000000000..e82ad20d9 --- /dev/null +++ b/res/tokenizer.js @@ -0,0 +1,130 @@ +// WARNING!!! // +// Very bad parser, i'm not a big brain low level girl :( // +// - Leah // + +const keywords = [ + "break", + "const", + "continue", + "defer", + "else", + "enum", + "fn", + "for", + "go", + "goto", + "if", + "import", + "in", + "interface", + "match", + "module", + "mut", + "none", + "or", + "pub", + "struct", + "type" +] +const ops = ["+","-","*","/","%","&","|","^","<<",">>"] +const assignments = ["+=","-=", "*=","/=","%=","&=","|=","^=",">>=","<<=",":=","="] +const breakers = ["(",")", "{","}"] +const types = ["bool","string","i8","i16","int","i64","i128","byte","u16","u32","u64","u128","rune","f32","f64","byteptr","voidptr"] + +function peek (tokens, steps = 1) { + const token = tokens[tokens.length - steps] + if (typeof token === 'object') { + token.setType = (value) => { tokens[tokens.length - steps].type = value; return token } + token.setValue = (value) => { tokens[tokens.length - steps].value = value; return token } + token.pushValue = (value) => { tokens[tokens.length - steps].value += value; return token } + } + return { type: '', value: '', ...token } +} + +function finishType (tokens, type) { + peek(tokens).setType(type) + tokens.push({ type: 'unknown', value: '' }) +} + +function Tokenizer (code) { + return new Promise((resolve, reject) => { + let i = 0 + let readingString = false + let commentLayer = 0 + let stringStarter = "" + let readingComment = false + let readingMultiLineComment = false + const tokens = [{ type: 'unknown', value: '' }] + + function IsKeyword (next, str) { return keywords.indexOf(str) > -1 && !readingString && !readingComment && (next === ' ' || next === '\n' || !next) } + function IsType (next, str) { return types.indexOf(str) > -1 && !readingString && !readingComment && (next === ' ' || next === '\n' || !next || IsBreak(next)) } + function IsAssignment (str) { return assignments.indexOf(str) > -1 && !readingString && !readingComment } + function IsOp (str) { return ops.indexOf(str) > -1 && !readingString && !readingComment } + function IsBreak (str) { return breakers.indexOf(str) > -1 && !readingString && !readingComment} + function IsNumber (str) { return str.match(/^[0-9]+$/) && !readingString && !readingComment} + + while (i <= code.length) { + if (code[i] === '/' && (code[i+1] === '/' || code[i+1] === '*') && code[i-1] !== '\\') { + commentLayer++ + readingComment = true + if (code[i+1] === '*') readingMultiLineComment = true + } else + if (code[i] === '*' && code[i+1] === '/' && code[i-1] !== '\\') { + commentLayer-- + if(commentLayer === 0) { + readingComment = false + readingMultiLineComment = false + finishType(tokens, 'comment') + } + } else + if (IsKeyword(code[i], peek(tokens).value)) { finishType(tokens, 'keyword') } else + if (IsType(code[i], peek(tokens).value)) { finishType(tokens, 'type') } else + if (IsAssignment(peek(tokens).value)) { finishType(tokens, 'definition') } else + if (IsOp(peek(tokens).value)) { finishType(tokens, 'operator') } else + if (IsBreak(peek(tokens).value)) { finishType(tokens, 'separator') } else + if (IsNumber(peek(tokens).value)) { finishType(tokens, 'number') } else + if (peek(tokens).value === 'return' && !readingString && !readingComment && (code[i] === ' ' || code[i] === '\n' || !code[i])) { finishType(tokens, 'return') } + + if (peek(tokens).value === ' ' || peek(tokens).value === '\n') { finishType(tokens, 'whitespace') } else + if (IsBreak(code[i])) { + if (peek(tokens, 3).type === 'keyword') { finishType(tokens, 'key') } else { finishType(tokens, 'unknown') } + } else if ((code[i] === ' ' && !readingString) || (code[i] === '\n' && !readingString && code[i-1] !== '\\')) { + if(code[i] === '\n' && readingComment && !readingMultiLineComment) { + commentLayer-- + if(commentLayer === 0) { + finishType(tokens, 'comment') + readingComment = false + } + } else if (!readingComment) { + finishType(tokens, 'unknown') + } + } + + if ((code[i] === '\'' || code[i] === '\"') && code[i - 1] !== "\\" && !readingComment) { + if (code[i] === stringStarter && readingString) { + peek(tokens).pushValue(code[i]) + if (readingString) { finishType(tokens, 'string') } + readingString = false + } else if(!readingString) { + finishType(tokens, 'unknown') + peek(tokens).pushValue(code[i]) + stringStarter = code[i] + readingString = true + } else { + peek(tokens).pushValue(code[i]) + } + } else { + if(i < code.length) { peek(tokens).pushValue(code[i]) } else { + if(peek(tokens).value.endsWith('\n')) { tokens.push({ type: 'whitespace', value: ' ' }) } + else if (peek(tokens).value === '' && peek(tokens).type === 'unknown' && peek(tokens, 2).value.endsWith('\n')) { + peek(tokens).setType('whitespace') + peek(tokens).setValue(' ') + } + } + } + i++ + } + if(peek(tokens).value.endsWith('\n')) tokens.push({ type: 'whitespace', value: ' ' }) + resolve(tokens.length === 1 && tokens[0].value === '' ? [{ type: 'whitespace', value: ' ' }] : tokens) + }) +} \ No newline at end of file diff --git a/styles/book.sass b/styles/book.sass new file mode 100755 index 000000000..7e3f04f52 --- /dev/null +++ b/styles/book.sass @@ -0,0 +1,13 @@ +.book + position: absolute + right: 0px + text-align: center + display: block + max-width: 155px + font-size: 12px + + +@media (max-width: 825px) + .book + display: none + diff --git a/styles/built-in-v.sass b/styles/built-in-v.sass new file mode 100755 index 000000000..d440b834d --- /dev/null +++ b/styles/built-in-v.sass @@ -0,0 +1,18 @@ +.built-in-v + display: grid + grid-template-columns: 1fr 1fr + grid-auto-flow: row dense + margin-top: 16px + .first, .second + padding-bottom: 16px + .first + grid-column-start: 1 + padding-right: 70px + .second + grid-column-start: 2 + +@media (max-width: 750px) + .built-in-v + grid-template-columns: 1fr + .first, .second + grid-column-start: 1 \ No newline at end of file diff --git a/styles/codeblock.sass b/styles/codeblock.sass new file mode 100755 index 000000000..2d596aeaf --- /dev/null +++ b/styles/codeblock.sass @@ -0,0 +1,78 @@ +$code-font: "Roboto Mono", "Courier New", Menlo, "DejaVu Sans Mono", Monaco, Courier, monospace +.codeblock + background: #333344 + padding: 12px 12px 4px 12px + max-width: calc(100vw - 56px) + border-radius: 8px + margin: 0px + color: #c9c5c4 + font-size: 15px + position: relative + font-family: $code-font + + .play-btn-fixed + position: absolute + top: 10px + right: 10px + + pre + overflow-x: auto + overflow-y: hidden + line-height: 1.2 + font-family: $code-font + white-space: pre-wrap + + textarea + font-size: 15px + line-height: 1.2 + font-family: $code-font + position: absolute + top: 49px + left: 10px + height: calc(100% - 48px) + width: calc(100% - 22px) + caret-color: #fff + color: transparent + background: transparent + overflow: hidden + border: none + resize: none + &.no-header + top: 25px + .titlebar + display: flex + align-items: center + margin-bottom: 6px + position: relative + top: -2px + .play-btn + background: transparent + border: none + margin: 0px + background: #ffffff33 + color: #ffeeeecf + border-radius: 4px + padding: 4px 12px + font-size: 12px + z-index: 10 + cursor: pointer + svg + height: 1.1em + &:hover + background: #ffffff55 + color: #ffeeeedd + + .keyword + color: #dcd02d + .return + color: #ea3b7b + .key + color:#5f84ba + .string + color: #ca763c + .number + color: #b068e7 + .separator, .comment + color: #9e9795 + .definition, .type + color: #c5ac41 \ No newline at end of file diff --git a/styles/customselect.css b/styles/customselect.css new file mode 100755 index 000000000..2fa44d885 --- /dev/null +++ b/styles/customselect.css @@ -0,0 +1,53 @@ +.select { + position: relative; + display: inline-block; + width: 100%; +} .select select { + font-size: 14px; + display: inline-block; + width: 100%; + cursor: pointer; + padding: 10px 15px; + outline: 0; + border: none; + border-radius: 8px; + overflow: hidden; + background: #333344; + color: #ccc; + appearance: none; + -webkit-appearance: none; + -moz-appearance: none; + } + .select select::-ms-expand { + display: none; + } + .select select:hover, + .select select:focus { + color: #ddd; + background: #444455; + } + .select select:disabled { + opacity: 0.5; + pointer-events: none; + } +.select_arrow { + position: absolute; + pointer-events: none; + top: 12px; + right: 15px; + width: 0px; + height: 0px; + border: solid #aaa; + border-width: 0 3px 3px 0; + display: inline-block; + padding: 3px; + transform: rotate(45deg); + -webkit-transform: rotate(45deg); +} +.select select:hover ~ .select_arrow, +.select select:focus ~ .select_arrow { + border-color: #ccc; +} +.select select:disabled ~ .select_arrow { + border-top-color: #ccc; +} \ No newline at end of file diff --git a/styles/documentation.sass b/styles/documentation.sass new file mode 100755 index 000000000..65e4c4b14 --- /dev/null +++ b/styles/documentation.sass @@ -0,0 +1,61 @@ +.documentation + display: flex + justify-content: center + max-width: 1200px + height: calc(100vh - 72px) + padding-right: 6px + margin-left: auto + margin-right: auto + overflow-y: scroll + .toc + margin-right: 32px + ul + padding-inline-start: 24px + .markdown + margin-left: 32px + padding-bottom: 64px + max-width: calc(100vw - 24px) + h1, h2, h3 + font-weight: normal + h1 + margin: 12px 0px + h2 + margin: 32px 0px 8px 0px + h3 + margin: 8px 0px + a + word-break: break-word + p + margin: 8px 0px + code + background: #eee + padding: 2px 6px + border-radius: 5px + font-size: 14px + .markdownIt-Anchor + color: #c3cad6 + &:hover + color: #4078c0 + .codeblock + margin-bottom: 4px + +@media (max-width: 1100px) + .documentation + height: calc(100vh - 143px) + +@media (max-width: 845px) + .documentation + height: calc(100vh - 154px) + +@media (max-width: 800px) + .documentation + flex-direction: column + align-items: center + height: 100% + overflow-y: visible + padding-right: 0px + .markdown + margin-left: 8px + .toc + margin-right: 0px + margin-bottom: 32px \ No newline at end of file diff --git a/styles/download-button.sass b/styles/download-button.sass new file mode 100755 index 000000000..7a4d36410 --- /dev/null +++ b/styles/download-button.sass @@ -0,0 +1,91 @@ +.button + background: #222 + color: #fff + margin-top: 16px + margin-right: 8px + padding: 7px 14px 6px 8px + border-radius: 6px + display: inline-flex + align-items: center + cursor: pointer + position: relative + .svg-inline--fa + width: 32px + height: 32px + margin-right: 4px + .options-container + .options + position: absolute + background: white + color: #333 + border: 1px solid #eee + right: 0px + top: 54px + box-sizing: border-box + border-radius: 6px + opacity: 0 + //pointer-events: none// + transform: translateY(-12px) + transition: all 0.2s cubic-bezier(0.67, 0.16, 0.4, 1) + .dl-option + display: flex + padding: 8px 8px 8px 6px + align-items: center + color: #333 + .name + flex: 1 + margin-right: 32px + .size + color: #818e9c + font-size: 15px + svg + margin-right: 6px + width: 22px + height: 22px + &:hover + background: #f7f7f7 + &:focus + outline: none + .options + opacity: 1 + pointer-events: all + transform: translateY(0px) + &:active + .right-icon + transform: translateY(3px) + .right-icon + width: 18px + padding: 12px 2px + cursor: pointer + transition: transform 0.1s + + .text + display: flex + flex-direction: column + margin-right: 10px + .link + margin: 0px 4px 0px 8px + font-size: 15px + .details + color: #ddd + padding: 0px 4px + font-size: 13px + line-height: 18px + border-radius: 4px + margin-left: 5px + svg + fill: #ddd + position: relative + top: 2px + left: -1px + + .fast, .changelog + position: absolute + bottom: -24px + left: 0px + color: #333 + text-decoration: none + + .changelog + left: auto + right: 0px \ No newline at end of file diff --git a/styles/editors.sass b/styles/editors.sass new file mode 100755 index 000000000..ea8f564c8 --- /dev/null +++ b/styles/editors.sass @@ -0,0 +1,43 @@ +.editors-info + max-width: 600px + text-align: center + margin-right: auto + margin-left: auto + margin-top: 32px + h1 + font-weight: 300 + margin: 0 0 0 -2px + p + margin: 4px 0 +.editors + display: flex + justify-content: space-evenly + width: calc(100vw - 32px) + max-width: 600px + margin-top: 32px + margin-right: auto + margin-left: auto + flex-wrap: wrap + .editor + display: flex + flex-direction: column + align-items: center + justify-content: center + background: #fff + color: #000 + height: 100px + width: 125px + border: 1px solid #efefef + border-radius: 12px + text-decoration: none + box-shadow: none + cursor: pointer + margin-bottom: 16px + transition: transform 0.1s, box-shadow 0.1s + &:hover + transform: translateY(-3px) + box-shadow: 0 6px 8px 0px rgba(0, 0, 0, 0.05), 0 16px 32px -2px rgba(0, 0, 0, 0.05) + img + flex: 0 + height: 42px + margin-bottom: 6px \ No newline at end of file diff --git a/styles/header.sass b/styles/header.sass new file mode 100755 index 000000000..05a9db7b1 --- /dev/null +++ b/styles/header.sass @@ -0,0 +1,105 @@ +$small-screen-width: 1100px + +.header + grid-area: header + height: 100% + width: 100% + position: sticky + background: #fff + z-index: 100 + top: 0px + display: flex + align-items: center + + .logo + width: 32px + margin-bottom: -3px + margin-right: 16px + margin-left: 16px + + .nav + display: flex + flex-wrap: wrap + justify-content: center + .item + color: #777 + text-decoration: none + padding-right: 18px + padding-left: 18px + font-size: 22px + font-weight: 300 + &.active + color: #222b38 + + .donate-button + display: flex + align-items: center + margin-top: 2px + margin-left: 12px + + .patreon img + width: 168px + height: 33px + margin-left: 10px + .paypal + width: 80px + height: 33px + background: #3b7bbf + margin-bottom: 3px + border-radius: 3px + color: #fff + text-align: center + line-height: 32px + font-size: 15px + margin-left: 10px + + .github + width: 80px + height: 33px + background: #3b7bbf + margin-bottom: 3px + border-radius: 3px + color: #fff + text-align: center + line-height: 32px + font-size: 15px + margin-left: 10px + + + +@media (max-width: $small-screen-width) + .header + position: static + flex-direction: column + .donate-button + flex-direction: row + margin-top: 8px + margin-left: 0px + margin-bottom: 8px + .patreon + margin-right: 12px + .paypal + width: 168px + height: 33px + background: #3b7bbf + margin-bottom: 3px + border-radius: 3px + color: #fff + text-align: center + line-height: 32px + font-size: 15px + .github + width: 168px + height: 33px + background: #3b7bbf + margin-bottom: 3px + border-radius: 3px + color: #fff + text-align: center + line-height: 32px + font-size: 15px + .logo + width: 42px + margin-top: 8px + margin-bottom: 12px + margin-right: 0px diff --git a/styles/hero.sass b/styles/hero.sass new file mode 100755 index 000000000..d980e2cda --- /dev/null +++ b/styles/hero.sass @@ -0,0 +1,84 @@ +.landing + .hero + display: flex + justify-content: space-evenly + align-items: center + width: calc(100% - 32px) + max-width: 1200px + color: #444 + margin: 34px 0px + .info + max-width: 500px + h1 + font-weight: 300 + margin: 0px 0px 0px -2px + p + margin: 4px 0px + //added + .button + align-items: normal + // till here + + + @import "./download-button.sass" + + .examples + margin-right: 32px + display: flex + flex-direction: column + align-items: center + .codeblock,.menu + margin-top: 12px + display: flex + justify-content: center + align-items: center + + button + background: transparent + border: none + cursor: pointer + i + font-size: 32px !important + color: #333 + + select + font-size: 18px + .select + margin: 0px 16px + width: 200px + .social + margin-top: 16px + padding: 9px 12px + border-radius: 6px + margin-right: 38px + text-align: center + p + color: #444 + svg + font-size: 28px + margin: 0px 12px 0px 0px + cursor: pointer + color: #949fad + pointer: cursor + &:hover + opacity: 0.8 + .fa-telegram + color: #0088cc + .fa-youtube + color: #ff0000 + .fa-discord + color: #7289da + .fa-twitter + color: #00acee + .links + margin-top: 12px + margin-right: 38px + margin-left: 10px + display: flex + flex-direction: row + flex-wrap: wrap + justify-content: space-between + font-size: 18px + a + &:hover + opacity: 0.9 diff --git a/styles/icons.css b/styles/icons.css new file mode 100755 index 000000000..90cb26f1f --- /dev/null +++ b/styles/icons.css @@ -0,0 +1,11 @@ +.svg-inline--fa { + display: inline-block; + font-size: inherit; + height: 1em; + overflow: visible; + vertical-align: -.125em; +} + +.svg-inline--fa.fa-w-14 { + width: .875em; +} \ No newline at end of file diff --git a/styles/landing.sass b/styles/landing.sass new file mode 100755 index 000000000..de8dec54c --- /dev/null +++ b/styles/landing.sass @@ -0,0 +1,88 @@ +.landing + display: flex + flex-direction: column + justify-content: flex-start + align-items: center + background: linear-gradient(168deg, white 800px, #f6f9fc 800px) + padding-bottom: 32px + .section + display: flex + max-width: 1100px + width: calc(100vw - 32px) + justify-content: space-around + margin-top: 32px + background: #fff + color: #222 + border-radius: 12px + border: 1px solid #efefef + h2, h1 + font-weight: 300 + margin: 0px + .block + flex: 1 + padding: 18px 16px + margin: 12px + border-radius: 12px + td + width: 120px + line-height: 1.5 + .sidenote + font-size: 75% + position: relative + top: -5px + pre + white-space: pre-wrap + word-break: break-word + // added by me + img + max-width: 100% + code + overflow-wrap: break-word + a + overflow-wrap: break-word + // till here + ul + padding-inline-start: 22px + i + max-width: calc(100vw - 64px) + text-align: center + font-size: 14px + + +@media (max-width: 1500px) + .landing + .hero + .examples + .codeblock + min-width: auto + +@media (max-width: 1380px) + .landing + .hero + margin: 32px 0px + flex-direction: column + .info + margin-bottom: 32px + text-align: center + .button + text-align: left + &:last-child + margin-right: 0px + .links, .social + margin-right: 12px + .social + margin-top: 16px + i + font-size: 28px + margin-left: 6px + margin-right: 6px + .examples + margin: 0px 8px 0px 8px !important + .editors + margin-right: 0px + +@media (max-width: 750px) + .landing + .section + flex-direction: column + \ No newline at end of file diff --git a/styles/news.sass b/styles/news.sass new file mode 100755 index 000000000..b28e49cc0 --- /dev/null +++ b/styles/news.sass @@ -0,0 +1,57 @@ +.left:hover + cursor: pointer + +.right:hover + cursor: pointer + +.news + font-size: 80% + margin-top: 0 !important + flex-direction: column + +.news .container + display: flex + overflow-x: auto + scroll-behavior: smooth + -webkit-overflow-scrolling: touch + +.news .block + min-width: 89.5px + +.news_header + text-align: center + padding-top: 1rem + +.news_date + font-weight: bold + +.text-center + text-align: center + +@media (max-width: 920px) + .news .container + flex-direction: column + .left + display: none + .right + display: none + +.left + position: absolute + left: 5px + top: 50% + transform: translateY(-50%) + height: 180px + width: 35px + +.right + position: absolute + right: 5px + top: 50% + transform: translateY(-50%) + height: 180px + width: 35px + +.actual_news + padding: 0px 40px + position: relative \ No newline at end of file diff --git a/styles/playground.sass b/styles/playground.sass new file mode 100755 index 000000000..147b424d7 --- /dev/null +++ b/styles/playground.sass @@ -0,0 +1,18 @@ +.playground + display: flex + flex-direction: column + .editor + display: flex + flex: 1 + .codeblock, .output + flex: 1 + margin: 6px + .select + margin-left: 8px + width: 220px +@media (max-width: 1100px) + .playground + .editor + flex-direction: column + .codeblock + max-width: calc(100vw - 36px) \ No newline at end of file diff --git a/arabic.tr b/translations/arabic.tr similarity index 100% rename from arabic.tr rename to translations/arabic.tr diff --git a/bahasa.tr b/translations/bahasa.tr similarity index 100% rename from bahasa.tr rename to translations/bahasa.tr diff --git a/bosnian.tr b/translations/bosnian.tr similarity index 100% rename from bosnian.tr rename to translations/bosnian.tr diff --git a/catalan.tr b/translations/catalan.tr similarity index 100% rename from catalan.tr rename to translations/catalan.tr diff --git a/chinese.tr b/translations/chinese.tr similarity index 100% rename from chinese.tr rename to translations/chinese.tr diff --git a/english.tr b/translations/english.tr similarity index 100% rename from english.tr rename to translations/english.tr diff --git a/french.tr b/translations/french.tr similarity index 100% rename from french.tr rename to translations/french.tr diff --git a/german.tr b/translations/german.tr similarity index 100% rename from german.tr rename to translations/german.tr diff --git a/indonesian.tr b/translations/indonesian.tr similarity index 100% rename from indonesian.tr rename to translations/indonesian.tr diff --git a/japanese.tr b/translations/japanese.tr similarity index 100% rename from japanese.tr rename to translations/japanese.tr diff --git a/norwegian.tr b/translations/norwegian.tr similarity index 100% rename from norwegian.tr rename to translations/norwegian.tr diff --git a/portuguese.tr b/translations/portuguese.tr similarity index 100% rename from portuguese.tr rename to translations/portuguese.tr diff --git a/russian.tr b/translations/russian.tr similarity index 100% rename from russian.tr rename to translations/russian.tr diff --git a/spanish.tr b/translations/spanish.tr similarity index 100% rename from spanish.tr rename to translations/spanish.tr diff --git a/turkish.tr b/translations/turkish.tr similarity index 100% rename from turkish.tr rename to translations/turkish.tr