Bug 1612941 - vendor SWGL's rust dependencies. r=froydnj

Differential Revision: https://phabricator.services.mozilla.com/D65617

--HG--
extra : moz-landing-system : lando
This commit is contained in:
Lee Salzman 2020-03-11 11:13:40 +00:00
parent 2b34a82b49
commit 9bf1ae5b21
34 changed files with 10189 additions and 18 deletions

30
Cargo.lock generated
View File

@ -1715,9 +1715,9 @@ dependencies = [
[[package]]
name = "gleam"
version = "0.9.2"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "332d1f4e6c6181ed07178f84a552b2387d43ecf6821a86c22cfb3883ea3fb1b9"
checksum = "77b1fd76468fff720bad31016688b805c6442ebf2d7c29123e10e4984aa61986"
dependencies = [
"gl_generator",
]
@ -1758,6 +1758,22 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574"
[[package]]
name = "glsl"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "766443890761b3c4edcce86cafaac97971b200662fbdd0446eb7c6b99b4401ea"
dependencies = [
"nom",
]
[[package]]
name = "glsl-to-cxx"
version = "0.1.0"
dependencies = [
"glsl",
]
[[package]]
name = "goblin"
version = "0.1.2"
@ -4137,6 +4153,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c666f0fed8e1e20e057af770af9077d72f3d5a33157b8537c1475dd8ffd6d32b"
[[package]]
name = "swgl"
version = "0.1.0"
dependencies = [
"cc",
"gleam",
"glsl-to-cxx",
]
[[package]]
name = "syn"
version = "1.0.5"
@ -4845,6 +4870,7 @@ dependencies = [
"nsstring",
"num_cpus",
"rayon",
"swgl",
"thin-vec",
"thread_profiler",
"uuid",

View File

@ -182,6 +182,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore-
'fuchsia-zircon',
'fuchsia-zircon-sys',
'fuchsia-cprng',
'glsl',
]
}

View File

@ -1 +1 @@
{"files":{"COPYING":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"834f409ac81917f5b5730483c90611e3193a8fb7400c87d30e7988d866bc5740","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"1acb12040be43a3582d5897f11870b3ffdcd7ce0f4f32de158175bb6b33ec0b7","build.rs":"b6b30972ee2be2e151af0ca93b30ccc3c8bce2cfeef4217244d6b413b6bd0c9d","rustfmt.toml":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","src/gl.rs":"e923f4ccfeae5112e6cea8f78ff279e8a26c041dcfb5cfb63d9713e733d249c3","src/gl_fns.rs":"67b5eac2a686f4a58201b8d51fc27db1aca6d597dfaa5c8ad4007170ffb18887","src/gles_fns.rs":"1c206adf96e6b9767d526aad54ddfb48e99aa0f5766d3cb72019470f4bdd88f9","src/lib.rs":"16610c19b45a3f26d56b379a3591aa2e4fc9477e7bd88f86b31c6ea32e834861"},"package":"332d1f4e6c6181ed07178f84a552b2387d43ecf6821a86c22cfb3883ea3fb1b9"}
{"files":{"COPYING":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"7fd2d6695ffe34ceef70faf02bd5df9d17d650951f038a84bcfe8c09d714a2be","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"1acb12040be43a3582d5897f11870b3ffdcd7ce0f4f32de158175bb6b33ec0b7","build.rs":"b6b30972ee2be2e151af0ca93b30ccc3c8bce2cfeef4217244d6b413b6bd0c9d","rustfmt.toml":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","src/gl.rs":"89e61e0ecb0c8c1d3dbd8cdf3f26270d4cdf8bf6832c9b356ed5694620271967","src/gl_fns.rs":"517f195005a45f13fb9928a684c1e0c831136404ec7eeac1b5f0c0dbef1ac64a","src/gles_fns.rs":"bd46d068d41d4fd405a99e9b5a966a69fc186195da9fb3e9dcbd73f62f95f73a","src/lib.rs":"16610c19b45a3f26d56b379a3591aa2e4fc9477e7bd88f86b31c6ea32e834861"},"package":"77b1fd76468fff720bad31016688b805c6442ebf2d7c29123e10e4984aa61986"}

0
third_party/rust/gleam/COPYING vendored Executable file → Normal file
View File

View File

@ -12,7 +12,7 @@
[package]
name = "gleam"
version = "0.9.2"
version = "0.10.0"
authors = ["The Servo Project Developers"]
build = "build.rs"
description = "Generated OpenGL bindings and wrapper for Servo."

0
third_party/rust/gleam/LICENSE-APACHE vendored Executable file → Normal file
View File

0
third_party/rust/gleam/LICENSE-MIT vendored Executable file → Normal file
View File

0
third_party/rust/gleam/README.md vendored Executable file → Normal file
View File

0
third_party/rust/gleam/build.rs vendored Executable file → Normal file
View File

0
third_party/rust/gleam/rustfmt.toml vendored Executable file → Normal file
View File

13
third_party/rust/gleam/src/gl.rs vendored Executable file → Normal file
View File

@ -74,22 +74,13 @@ pub struct DebugMessage {
pub severity: GLenum,
}
mod private {
// Private marker trait extended by the Gl public trait so that no one
// else outside this crate can implement Gl. Why? So that adding new methods
// to it don't lead to a breaking change.
pub trait Sealed {}
}
use self::private::Sealed;
macro_rules! declare_gl_apis {
// garbo is a hack to handle unsafe methods.
($($(unsafe $([$garbo:expr])*)* fn $name:ident(&self $(, $arg:ident: $t:ty)* $(,)*) $(-> $retty:ty)* ;)+) => {
pub trait Gl: Sealed {
pub trait Gl {
$($(unsafe $($garbo)*)* fn $name(&self $(, $arg:$t)*) $(-> $retty)* ;)+
}
impl Sealed for ErrorCheckingGl {}
impl Gl for ErrorCheckingGl {
$($(unsafe $($garbo)*)* fn $name(&self $(, $arg:$t)*) $(-> $retty)* {
let rv = self.gl.$name($($arg,)*);
@ -98,7 +89,6 @@ macro_rules! declare_gl_apis {
})+
}
impl<F> Sealed for ErrorReactingGl<F> {}
impl<F: Fn(&dyn Gl, &str, GLenum)> Gl for ErrorReactingGl<F> {
$($(unsafe $($garbo)*)* fn $name(&self $(, $arg:$t)*) $(-> $retty)* {
let rv = self.gl.$name($($arg,)*);
@ -110,7 +100,6 @@ macro_rules! declare_gl_apis {
})+
}
impl<F> Sealed for ProfilingGl<F> {}
impl<F: Fn(&str, Duration)> Gl for ProfilingGl<F> {
$($(unsafe $($garbo)*)* fn $name(&self $(, $arg:$t)*) $(-> $retty)* {
let start = Instant::now();

1
third_party/rust/gleam/src/gl_fns.rs vendored Executable file → Normal file
View File

@ -21,7 +21,6 @@ impl GlFns {
}
}
impl Sealed for GlFns {}
impl Gl for GlFns {
fn get_type(&self) -> GlType {
GlType::Gl

1
third_party/rust/gleam/src/gles_fns.rs vendored Executable file → Normal file
View File

@ -21,7 +21,6 @@ impl GlesFns {
}
}
impl Sealed for GlesFns {}
impl Gl for GlesFns {
fn get_type(&self) -> GlType {
GlType::Gles

0
third_party/rust/gleam/src/lib.rs vendored Executable file → Normal file
View File

View File

@ -0,0 +1 @@
{"files":{"CHANGELOG.md":"59a3fb395bdfc3f41a2c9111797ff1686b74b0d4bb0c62beee5b01b56ff84b8f","Cargo.toml":"00f31c7fc51a327fcccefb7a3b54899191ff8bf274eb317540b48eba863de07e","LICENSE":"09719a44ba10012b20e7a36e7f2e7806a89476813668b66067e0e5dbcc9ce34c","README.md":"42336a3535b2623375349950931860716369e1c3fd4a61b36785c9276427cd16","data/tests/buffer_block_0.glsl":"335b2b5360635eb0a1c994e44a33787d43ea6ce84da4c0a795e7526da64b37bd","data/tests/layout_buffer_block_0.glsl":"d64c27188cd27b7fc81413e8afe621d6f44ddcdeddb115d62661358b2131e8a3","src/lib.rs":"f630de25bc1d7264037c0e07ecacc766aae67388c4077f5c3156bf7021705161","src/parse_tests.rs":"1cfcc2fe92d757aef3c5b0acb81f90a60d5f04a3ff2ebc50dc1abea4c50b61af","src/parser.rs":"6ed2ac80114c1f4c7859d7c78817bab997493ebf16dca2ce54fac28c8d4827e5","src/parsers.rs":"fdd69e02a2be8ae9807fba465a5bda5d345ef46afa36d99d729a64c3400ea46d","src/parsers/nom_helpers.rs":"07cfaef9ee01bda7ead0587e21a58626ad97a33cb942c2dd2d7693c9daa41f79","src/syntax.rs":"4ac6a1a5e6de4753efbeec4ce73eccde97f052eb19929a935723e472f746bd10","src/transpiler/glsl.rs":"c42ca794c4c326d52e9d0d29fe54c287ae4fb1bc1b3ef26b13bfcbdf5fd25974","src/transpiler/mod.rs":"244cc5d9ab4c6e6ac4a30d42df81f4718b79fe653cc04e138071ae5905aa9e28","src/transpiler/spirv.rs":"8c777f0f5717a3e269f9062b187da3e66706705a81a392f6aeea0630ed498deb","src/visitor.rs":"68161858479f39c81fa71e73397ec178407bdcede7b6f9a75af6c9dc5b890c54","tests/incorrect_statement.rs":"6b182e705421450d016d6a078cf8fcc0b748bf6208dfbf2fd3474467261241fd","tests/left_associativity.rs":"c5390754390ea262cf11a088584d74511fedc314146c51670c46ddbf90a9992c","tests/missing_zero_float.rs":"1bb2fa7c55354ecec8fb5e82b1cb821b052c2047c32edc030ed0e529d77af3d2"},"package":"766443890761b3c4edcce86cafaac97971b200662fbdd0446eb7c6b99b4401ea"}

397
third_party/rust/glsl/CHANGELOG.md vendored Normal file
View File

@ -0,0 +1,397 @@
# 4.0.3
> Fri Mar 6th 2020
- Move all the unit tests code into their ow module to prevent rustc from parsing them if we
dont build with tests.
# 4.0.2
> Mon 10th Feb 2020
- Remove the `lexical` feature from `nom`. Its useful only when using functions such as the
`float` combinator, which we dont use.
# 4.0.1
> Tue 21st Jan 2020
- Fix a bug occurring in the function-like `#define` parser (i.e. `#define foo(x) (y)`) that
would prevent the use of whitespaces in the argument list.
# 4.0
> Mon 6th Jan 2020
## Major changes
- Add support for `attribute` and `varying` keyword as a backward-compatible parser.
- Fix binary operator associativity. They were (_erroneously_) right-associative. Theyre now
parsed as left-associative.
# 3.0
> Wed 14th Nov 2019
## Major changes
- `JumpStatement::Return` now takes an optional `Expr` instead of an `Expr` directly. That allows
for parsing statements such as `return;`, which should have
been supported from the beginning.
- Support for missing preprocessor directives:
- `#if`.
- `#ifdef`.
- `#ifndef`.
- `#elseif`.
- `#else`.
- `#endif`.
- `#error`.
- `#include`.
- `#line`.
- `#pragma`.
- `#undef`.
## Patch changes
- Add a `rustfmt.toml` to reformat everything and stay consistent. If you want contribute, ensure
you are correctly using `rustfmt` (either by running `cargo fmt` before submitting a PR or by
configuring your editor to format the code for you). This is important, as not respecting the
formatting would make your contribution impossible to merge due to a CI check.
- Support for _multiline_ annotations (`\`). Multiline annotations are currently supported as
part of _spaces_ — i.e. you cannot use them to break an identifier on two lines for instance.
This choice makes it faster to parse without too much compromises (after all, `\` is mostly used
in CPP directives in GLSL).
- Fix a bug with _recoverable parsers_ that would produce parent parsers to ignore GLSL grammar
errors. That fix also implies a boost in performance due to short-circuiting optimizations.
# 2.0.1
> Fri 8th Nov 2019
- Improve performance of expression parsers.
# 2.0
> Thu 24th Oct 2019
## Major changes
- Add `ShaderKind::Compute`.
- Remove `NonEmpty::from_iter` and `TranslationUnit::from_iter` as they were deprecated. Use
`*::from_non_empty_iter` instead.
## Patch changes
- Fix tokenizer of `Block`.
- Fix a bug while parsing floating-point numbers.
- Reformat with `rustfmt`.
# 1.2
> Wed 18th Sep 2019
## Deprecations
- `NonEmpty::from_iter` and `TranslationUnit::from_iter` are deprecated in favor of
`*::from_non_empty_iter`.
## Minor changes
- Add binary SPIR-V transpilation. That enables to transpile GLSL directly into a SPIR-V buffer.
- Add `NonEmpty::from_non_empty_iter` and `TranslationUnit::from_non_empty_iter`.
# 1.1.1
> Tue 17th Sep 2019
- Update internal code for Rust edition 2018.
# 1.1
> Tue 30th of July 2019
- Add the `ShaderStage` type alias to `TranslationUnit`.
- Enhance the front documentation to showcase how to use how to use the crate.
# 1.0.2
> Tue 23rd of July 2019
- Change the description of the project and update documentation.
# 1.0.1
> Tue 23rd of July 2019
- Change the `external_declaration` parser so that it can also accept _GLSL460_. That should be a
breaking change because now, _GLSL450_ formatted input accepts feature from _GLSL460_, which
shouldnt be allowed. Nevertheless, the added feature (being able to use semicolons (`;`) on
empty lines at top-level) is not really an interesting property and no breakage should happen.
# 1.0
> Thu 18th of July 2019
- Migrate all parsers to [nom-5](https://crates.io/crates/nom/5.0.0).
- Improve and add unit and integration tests.
- Improve overall documentation.
- Enhance some allocation scheme (removed them by using more adapted parsers).
- Completely remove the byte (`&[u8]`) parsing. That was a bad idea, for both its impractical
aspect and error removing. Parsing is done on string slices now (`&str`).
# 0.13.5
> Sun 9th of December 2018
- Add the SPIR-V transpiler. Currently, its feature-gated and *very* experimental. Feel free to
try and provide feedback about it.
- Add simple accessors for `ParseResult`.
- Fix a typo in the documentation of syntax.
- Add some unit and integration tests.
- Add `Identifier::as_str` and `TypeName::as_str`
# 0.13.4
> Wed 25nd of November 2018
- Add `NonEmpty::push` and `NonEmpty::pop`.
- Implement `Deref` and `DerefMut` for `TranslationUnit`.
# 0.13.3
> Wed 24nd of November 2018
- Add `NonEmpty::from_iter` and `TranslationUnit::from_iter`.
- Implement `IntoIterator` for `NonEmpty` and `TranslationUnit`.
# 0.13.2
> Wed 22nd of November 2018
- Fix a typo in documentation.
# 0.13.1
> Wed 22nd of November 2018
- Fix a link in documentation.
# 0.13
> Wed 21st of November 2018
- Update/reset hyperlinks in all the documentation for types, traits, methods, etc.
- General enhancement of the documentation.
- `ExternalDeclaration::new_struct` can now fail. Check the doc for further details.
- `NonEmpty`, `Identifier` and `TypeName` and `TranslationUnit` are now plain types and not
aliases anymore.
- Add AST visitors. Visitors allow for traversing through an AST and on-the-fly mutation,
filtering, etc.
- The `#define` preprocessor pragma is now supported in a limited form (it can only be used in
the global scope).
# 0.12
> Sun 11th of November 2018
- Fix the type of identifier stored in `Block`: it now uses the new encoding for arrayed
identifiers.
- `Block` parsers update for the arrayd identifier change.
# 0.11
> Sat 10th of November 2018
- Add helper functions to build objects form the `syntax` module. Those are intended to be a
simple way to build ASTs out of Rust code instead of parsing.
- Enhance the documentation of the `Preprocessor` type.
# 0.10.1
> Fri 2nd of November 2018
- Add some missing implementors of `Parse` for types from `glsl::syntax`.
# 0.10
> Fri 2nd of November 2018
- Hide the `parsers` module. Its not exposed anymore as it was mostly
[nom](https://crates.io/crates/nom) parsers and we dont like leaking internals.
- Introduce the `Parser` trait, acting as an abstraction over the internal parsers. Implementors
provide a type-driven parsing experience that is very similar to the one as
[FromStr](https://doc.rust-lang.org/std/str/trait.FromStr.html). This change is actually
mandatory for the [glsl-quasiquote](https://crates.io/crates/glsl-quasiquote) crates `glsl!`
proc-macro to allow people use it for any GLSL item (and not only `TranslationUnit`).
- Enhance the overall documentation.
# 0.9.2
> Wed 3rd of October 2018
- Fix GLSL transpiled representation of `IVec*`. It was plain wrong.
# 0.9.1
> Sat 7th of July 2018
- Fix unit testing in transpilers.
# 0.9
> Sat 7th of July 2018
- Big cleanup of the module hierarchy.
- Enhanced the documentation.
# 0.8.1
> Sun, 17th of June 2018
- Add the `README.md` path to the `Cargo.toml` manifest.
# 0.8
> Sun 17th of June 2018
This version introduces breaking changes because public types used in return positions have changed.
These concern only intermediate `nom` functions, so if you do not make a fancy use of this crate,
you souldnt have to worry too much when migrating.
- Fix the roundtrip issue with the GLSL writer (precedence wasnt correctly respected).
- Simplify internal code.
- Error instead of panicking when parsing overflowing integer literals.
- Fix panic trying to parse literals starting with whitespace.
- Add fuzzing to find out panics.
# 0.7.2
> Wed 13th of December 2017
- Fix the `show_expr` when the `Expr` is a `Expr::UIntConst`.
# 0.7.1
> Mon 20th of November 2017
- `std::error::Error` is now implemented for `ParseError`.
# 0.7
> Wed 27th of September 2017
- Add support for postfix expressions as function identifiers.
# 0.6.5
> Mon 4th of September 2017
- Fix the formatting of floating values when the fractional part is `0`.
# 0.6.4
> Mon 4th of September 2017
- Fix the output for `show_struct_specifier`.
# 0.6.3
> Mon 4th of September 2017
- Fix the output for `show_struct_specifier`.
# 0.6.2
> Mon 4th of September 2017
- Remove a warning.
# 0.6.1
> Mon 4th of September 2017
- Fix `show_struct_specifier`.
# 0.6
> Fri 1st of September 2017
- The `TypeSpecifier` type was wrong as it didnt carry any `ArraySpecifier` information while the
GLSL specifications grammar about type specifiers states they should. Fixed.
# 0.5
> Mon 7th of August 2017
- The `parse` and `parse_str` functions now take as second argument the parser to run. This enables
using those functions and all the neat logic the wrap in dependent projects.
# 0.4.2
> Fri 4th of August 2017
- A GLSL writer is now available.
- Some parsers yield non-empty list of syntax trees. Those had the incorrect `Vec` type. They were
replaced by `NonEmpty`, which is an alias to `Vec`, but carry the semantic that it has at least
one element in it.
# 0.4.1
> Thu 3rd of August 2017
- Uni/multi-line comments are now supported.
# 0.4
> Wed 2nd of August 2017
- The `Declaration::Block` variant was refactored for a better usage.
- Dot field selections and, in a mory general way, postfix expressions completely fixed. The
`syntax` module was altered to make it easier to work with dot field selection. Also related,
the function identifier syntax is now isomorphic to an identifier.
# 0.3.1
> Tue 1st of August 2017
- Fix the `preprocessor` parser so that it eats surrounding blanks.
# 0.3
> Mon 31st of July 2017
- Add a very minimalistic yet working preprocessor. It parses `#version` and `#extension`
commands. Those have to be declared at the top of your file, even though this implementation
accepts them at any place an external declaration could be defined. Feel free to submit a PR
if you want to change that behavior, I dont really mind.
- Enhance the runtime error reporting. Its not perfect, but its way better than before!
- `void` is now recognized as `TypeSpecifier::Void` instead of the erroneous
`TypeSpecifier::TypeName("void")`.
# 0.2.2
> Mon 31st of July 2017
- The `layout` parser had a nasty bug that would treat a list of key-value pairs as an expression
assignment. This was fixed and it now treats it as a list of pairs of identifier associated with a
possible constant expression.
- The `StructFieldSpecifier` type and its associated parser were wrong. Was missing:
+ the type qualifier
+ for each identifier defined in the field specifier, its optional array specifier, as in
`float foo[3];` or `vec3 bar[];` for unsized ones.
# 0.2.1
> Sun 30th of July 2017
- More documentation to help people to get their feet wet.
# 0.2
> Sat 29th of July 2017
- The whole parsing API is public.
# 0.1
- Initial revision.

39
third_party/rust/glsl/Cargo.toml vendored Normal file
View File

@ -0,0 +1,39 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
edition = "2018"
name = "glsl"
version = "4.0.3"
authors = ["Dimitri Sabadie <dimitri.sabadie@gmail.com>"]
description = "A GLSL450/GLSL460 parser."
homepage = "https://github.com/phaazon/glsl"
documentation = "https://docs.rs/glsl"
readme = "README.md"
keywords = ["GLSL", "OpenGL", "SPIR-V", "parser"]
categories = ["parsing", "rendering"]
license = "BSD-3-Clause"
repository = "https://github.com/phaazon/glsl"
[dependencies.nom]
version = "5"
features = ["std"]
default-features = false
[dependencies.shaderc]
version = "0.6"
optional = true
[features]
spirv = ["shaderc"]
[badges.travis-ci]
branch = "master"
repository = "phaazon/glsl"

30
third_party/rust/glsl/LICENSE vendored Normal file
View File

@ -0,0 +1,30 @@
Copyright (c) 2018, Dimitri Sabadie <dimitri.sabadie@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Dimitri Sabadie <dimitri.sabadie@gmail.com> nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

127
third_party/rust/glsl/README.md vendored Normal file
View File

@ -0,0 +1,127 @@
[![Talk on IRC!](https://img.shields.io/badge/chat-%23glsl--rs%40irc.freenode.net-blueviolet)](https://webchat.freenode.net)
[![Build Status](https://travis-ci.org/phaazon/glsl.svg?branch=master)](https://travis-ci.org/phaazon/glsl)
[![crates.io](https://img.shields.io/crates/v/glsl.svg)](https://crates.io/crates/glsl)
[![docs.rs](https://docs.rs/glsl/badge.svg)](https://docs.rs/glsl)
![License](https://img.shields.io/badge/license-BSD3-blue.svg?style=flat)
<!-- cargo-sync-readme start -->
This crate is a GLSL450/GLSL460 compiler. Its able to parse valid GLSL formatted source into
an abstract syntax tree (AST). That AST can then be transformed into SPIR-V, your own format or
even folded back to a raw GLSL [`String`] (think of a minifier, for instance).
Youll find several modules:
- [`parser`], which exports the parsing interface. This is the place you will get most
interesting types and traits, such as [`Parse`] and [`ParseError`].
- [`syntax`], which exports the AST and language definitions. If you look into destructuring,
transpiling or getting information on the GLSL code that got parsed, you will likely
manipulate objects which types are defined in this module.
- [`transpiler`], which provides you with GLSL transpilers. For instance, you will find _GLSL
to GLSL_ transpiler, _GLSL to SPIR-V_ transpiler, etc.
- [`visitor`](visitor), which gives you a way to visit AST nodes and mutate them, both with
inner and outer mutation.
Feel free to inspect those modules for further information.
# GLSL parsing and transpiling
Parsing is the most common operation you will do. It is not required per-se (you can still
create your AST by hand or use [glsl-quasiquote] to create it at compile-time by using the GLSL
syntax directly in Rust). However, in this section, we are going to see how we can parse from a
string to several GLSL types.
## Parsing architecture
Basically, the [`Parse`] trait gives you all you need to start parsing. This crate is designed
around the concept of type-driven parsing: parsers are hidden and you just have to state what
result type you expect.
The most common type you want to parse to is [`TranslationUnit`], which represents a set of
[`ExternalDeclaration`]s. An [`ExternalDeclaration`] is just a declaration at the top-most level
of a shader. It can be a global, uniform declarations, vertex attributes, a function, a
structure, etc. In that sense, a [`TranslationUnit`] is akin to a shader stage (vertex shader,
fragment shader, etc.).
You can parse any type that implements [`Parse`]. Parsers are mostly sensible to external
blanks, which means that parsing an [`Expr`] starting with a blank will not work (this is not
true for a [`TranslationUnit`] as its exceptionnally more permissive).
## Parsing an expression
Lets try to parse an expression.
```rust
use glsl::parser::Parse;
use glsl::syntax::Expr;
let glsl = "(vec3(r, g, b) * cos(t * PI * .5)).xxz";
let expr = Expr::parse(glsl);
assert!(expr.is_ok());
```
Here, `expr` is an AST which type is `Result<Expr, ParseError>` that represents the GLSL
expression `(vec3(r, g, b) * cos(t * PI * .5)).xxz`, which is an outer (scalar) multiplication
of an RGB color by a cosine of a time, the whole thing being
[swizzled](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) with XXZ. It is your
responsibility to check if the parsing process has succeeded.
In the previous example, the GLSL string is a constant and hardcoded. It could come from a file,
network or built on the fly, but in the case of constant GLSL code, it would be preferable not
to parse the string at runtime, right? Well, [glsl-quasiquote] is there exactly for that. You
can ask **rustc** to parse that string and, if the parsing has succeeded, inject the AST
directly into your code. No [`Result`], just the pure AST. Have a look at [glsl-quasiquote] for
further details.
## Parsing a whole shader
Vertex shaders, geometry shaders, fragment shaders and control and evaluation tessellation
shaders can be parsed the same way by using one of the `TranslationUnit` or `ShaderStage` types.
Here, a simple vertex shader being parsed.
```rust
use glsl::parser::Parse;
use glsl::syntax::ShaderStage;
let glsl = "
layout (location = 0) in vec3 pos;
layout (location = 1) in vec4 col;
out vec4 v_col;
uniform mat4 projview;
void main() {
v_col = col; // pass color to the next stage
gl_Position = projview * vec4(pos, 1.);
}
";
let stage = ShaderStage::parse(glsl);
assert!(stage.is_ok());
```
## Visiting AST nodes
The crate is also getting more and more combinators and functions to transform the AST or create
nodes with regular Rust. The [`Visitor`] trait will be a great friend of yours when you will
want to cope with deep mutation, filtering and validation. Have a look at the
[`visitor`](visitor) module for a tutorial on how to use visitors.
# About the GLSL versions…
This crate can parse both GLSL450 and GLSL460 formatted input sources. At the language level,
the difference between GLSL450 and GLSL460 is pretty much nothing, so both cases are covered.
> If youre wondering, the only difference between both versions is that in GLSL460, its
> authorized to have semicolons (`;`) on empty lines at top-level in a shader.
[glsl-quasiquote]: https://crates.io/crates/glsl-quasiquote
[`Parse`]: crate::parser::Parse
[`ParseError`]: crate::parser::ParseError
[`ExternalDeclaration`]: crate::syntax::ExternalDeclaration
[`TranslationUnit`]: crate::syntax::TranslationUnit
[`Expr`]: crate::syntax::Expr
[`Visitor`]: crate::visitor::Visitor
<!-- cargo-sync-readme end -->

View File

@ -0,0 +1,6 @@
buffer Foo {
char tiles[];
} main_tiles;
void main() {
}

View File

@ -0,0 +1,3 @@
layout(set = 0, binding = 0) buffer Foo {
char a;
} foo;

125
third_party/rust/glsl/src/lib.rs vendored Normal file
View File

@ -0,0 +1,125 @@
//! This crate is a GLSL450/GLSL460 compiler. Its able to parse valid GLSL formatted source into
//! an abstract syntax tree (AST). That AST can then be transformed into SPIR-V, your own format or
//! even folded back to a raw GLSL [`String`] (think of a minifier, for instance).
//!
//! Youll find several modules:
//!
//! - [`parser`], which exports the parsing interface. This is the place you will get most
//! interesting types and traits, such as [`Parse`] and [`ParseError`].
//! - [`syntax`], which exports the AST and language definitions. If you look into destructuring,
//! transpiling or getting information on the GLSL code that got parsed, you will likely
//! manipulate objects which types are defined in this module.
//! - [`transpiler`], which provides you with GLSL transpilers. For instance, you will find _GLSL
//! to GLSL_ transpiler, _GLSL to SPIR-V_ transpiler, etc.
//! - [`visitor`](visitor), which gives you a way to visit AST nodes and mutate them, both with
//! inner and outer mutation.
//!
//! Feel free to inspect those modules for further information.
//!
//! # GLSL parsing and transpiling
//!
//! Parsing is the most common operation you will do. It is not required per-se (you can still
//! create your AST by hand or use [glsl-quasiquote] to create it at compile-time by using the GLSL
//! syntax directly in Rust). However, in this section, we are going to see how we can parse from a
//! string to several GLSL types.
//!
//! ## Parsing architecture
//!
//! Basically, the [`Parse`] trait gives you all you need to start parsing. This crate is designed
//! around the concept of type-driven parsing: parsers are hidden and you just have to state what
//! result type you expect.
//!
//! The most common type you want to parse to is [`TranslationUnit`], which represents a set of
//! [`ExternalDeclaration`]s. An [`ExternalDeclaration`] is just a declaration at the top-most level
//! of a shader. It can be a global, uniform declarations, vertex attributes, a function, a
//! structure, etc. In that sense, a [`TranslationUnit`] is akin to a shader stage (vertex shader,
//! fragment shader, etc.).
//!
//! You can parse any type that implements [`Parse`]. Parsers are mostly sensible to external
//! blanks, which means that parsing an [`Expr`] starting with a blank will not work (this is not
//! true for a [`TranslationUnit`] as its exceptionnally more permissive).
//!
//! ## Parsing an expression
//!
//! Lets try to parse an expression.
//!
//! ```rust
//! use glsl::parser::Parse;
//! use glsl::syntax::Expr;
//!
//! let glsl = "(vec3(r, g, b) * cos(t * PI * .5)).xxz";
//! let expr = Expr::parse(glsl);
//! assert!(expr.is_ok());
//! ```
//!
//! Here, `expr` is an AST which type is `Result<Expr, ParseError>` that represents the GLSL
//! expression `(vec3(r, g, b) * cos(t * PI * .5)).xxz`, which is an outer (scalar) multiplication
//! of an RGB color by a cosine of a time, the whole thing being
//! [swizzled](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) with XXZ. It is your
//! responsibility to check if the parsing process has succeeded.
//!
//! In the previous example, the GLSL string is a constant and hardcoded. It could come from a file,
//! network or built on the fly, but in the case of constant GLSL code, it would be preferable not
//! to parse the string at runtime, right? Well, [glsl-quasiquote] is there exactly for that. You
//! can ask **rustc** to parse that string and, if the parsing has succeeded, inject the AST
//! directly into your code. No [`Result`], just the pure AST. Have a look at [glsl-quasiquote] for
//! further details.
//!
//! ## Parsing a whole shader
//!
//! Vertex shaders, geometry shaders, fragment shaders and control and evaluation tessellation
//! shaders can be parsed the same way by using one of the `TranslationUnit` or `ShaderStage` types.
//!
//! Here, a simple vertex shader being parsed.
//!
//! ```rust
//! use glsl::parser::Parse;
//! use glsl::syntax::ShaderStage;
//!
//! let glsl = "
//! layout (location = 0) in vec3 pos;
//! layout (location = 1) in vec4 col;
//!
//! out vec4 v_col;
//!
//! uniform mat4 projview;
//!
//! void main() {
//! v_col = col; // pass color to the next stage
//! gl_Position = projview * vec4(pos, 1.);
//! }
//! ";
//! let stage = ShaderStage::parse(glsl);
//! assert!(stage.is_ok());
//! ```
//!
//! ## Visiting AST nodes
//!
//! The crate is also getting more and more combinators and functions to transform the AST or create
//! nodes with regular Rust. The [`Visitor`] trait will be a great friend of yours when you will
//! want to cope with deep mutation, filtering and validation. Have a look at the
//! [`visitor`](visitor) module for a tutorial on how to use visitors.
//!
//! # About the GLSL versions…
//!
//! This crate can parse both GLSL450 and GLSL460 formatted input sources. At the language level,
//! the difference between GLSL450 and GLSL460 is pretty much nothing, so both cases are covered.
//!
//! > If youre wondering, the only difference between both versions is that in GLSL460, its
//! > authorized to have semicolons (`;`) on empty lines at top-level in a shader.
//!
//! [glsl-quasiquote]: https://crates.io/crates/glsl-quasiquote
//! [`Parse`]: crate::parser::Parse
//! [`ParseError`]: crate::parser::ParseError
//! [`ExternalDeclaration`]: crate::syntax::ExternalDeclaration
//! [`TranslationUnit`]: crate::syntax::TranslationUnit
//! [`Expr`]: crate::syntax::Expr
//! [`Visitor`]: crate::visitor::Visitor
#[cfg(test)]
mod parse_tests;
pub mod parser;
mod parsers;
pub mod syntax;
pub mod transpiler;
pub mod visitor;

2772
third_party/rust/glsl/src/parse_tests.rs vendored Normal file

File diff suppressed because it is too large Load Diff

119
third_party/rust/glsl/src/parser.rs vendored Normal file
View File

@ -0,0 +1,119 @@
//! GLSL parsing.
//!
//! This module gives you several functions and types to deal with GLSL parsing, transforming an
//! input source into an AST. The AST is defined in the [`syntax`] module.
//!
//! You want to use the [`Parse`]s methods to get starting with parsing and pattern match on
//! the resulting [`Result`]. In case of an error, you can inspect the content of the [`ParseError`]
//! object in the `Err` variant.
//!
//! [`Parse`]: crate::parser::Parse
//! [`ParseError`]: crate::parser::ParseError
use nom::error::convert_error;
use nom::Err as NomErr;
use std::fmt;
use crate::parsers::ParserResult;
use crate::syntax;
/// A parse error. It contains a [`String`] giving information on the reason why the parser failed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseError {
pub info: String,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "error: {}", self.info)
}
}
/// Run a parser `P` on a given `[&str`] input.
pub(crate) fn run_parser<P, T>(source: &str, parser: P) -> Result<T, ParseError>
where
P: FnOnce(&str) -> ParserResult<T>,
{
match parser(source) {
Ok((_, x)) => Ok(x),
Err(e) => match e {
NomErr::Incomplete(_) => Err(ParseError {
info: "incomplete parser".to_owned(),
}),
NomErr::Error(err) | NomErr::Failure(err) => {
let info = convert_error(source, err);
Err(ParseError { info })
}
},
}
}
/// Class of types that can be parsed.
///
/// This trait exposes the [`Parse::parse`] function that can be used to parse GLSL types.
///
/// The methods from this trait are the standard way to parse data into GLSL ASTs.
pub trait Parse: Sized {
/// Parse from a string slice.
fn parse<B>(source: B) -> Result<Self, ParseError>
where
B: AsRef<str>;
}
/// Macro to implement Parse for a given type.
macro_rules! impl_parse {
($type_name:ty, $parser_name:ident) => {
impl Parse for $type_name {
fn parse<B>(source: B) -> Result<Self, ParseError>
where
B: AsRef<str>,
{
run_parser(source.as_ref(), $crate::parsers::$parser_name)
}
}
};
}
impl_parse!(syntax::Identifier, identifier);
impl_parse!(syntax::TypeSpecifierNonArray, type_specifier_non_array);
impl_parse!(syntax::TypeSpecifier, type_specifier);
impl_parse!(syntax::UnaryOp, unary_op);
impl_parse!(syntax::StructFieldSpecifier, struct_field_specifier);
impl_parse!(syntax::StructSpecifier, struct_specifier);
impl_parse!(syntax::StorageQualifier, storage_qualifier);
impl_parse!(syntax::LayoutQualifier, layout_qualifier);
impl_parse!(syntax::PrecisionQualifier, precision_qualifier);
impl_parse!(syntax::InterpolationQualifier, interpolation_qualifier);
impl_parse!(syntax::TypeQualifier, type_qualifier);
impl_parse!(syntax::TypeQualifierSpec, type_qualifier_spec);
impl_parse!(syntax::FullySpecifiedType, fully_specified_type);
impl_parse!(syntax::ArraySpecifier, array_specifier);
impl_parse!(syntax::Expr, expr);
impl_parse!(syntax::Declaration, declaration);
impl_parse!(syntax::FunctionPrototype, function_prototype);
impl_parse!(syntax::InitDeclaratorList, init_declarator_list);
impl_parse!(syntax::SingleDeclaration, single_declaration);
impl_parse!(syntax::Initializer, initializer);
impl_parse!(syntax::FunIdentifier, function_identifier);
impl_parse!(syntax::AssignmentOp, assignment_op);
impl_parse!(syntax::SimpleStatement, simple_statement);
impl_parse!(syntax::ExprStatement, expr_statement);
impl_parse!(syntax::SelectionStatement, selection_statement);
impl_parse!(syntax::SwitchStatement, switch_statement);
impl_parse!(syntax::CaseLabel, case_label);
impl_parse!(syntax::IterationStatement, iteration_statement);
impl_parse!(syntax::JumpStatement, jump_statement);
impl_parse!(syntax::Condition, condition);
impl_parse!(syntax::Statement, statement);
impl_parse!(syntax::CompoundStatement, compound_statement);
impl_parse!(syntax::FunctionDefinition, function_definition);
impl_parse!(syntax::ExternalDeclaration, external_declaration);
impl_parse!(syntax::TranslationUnit, translation_unit);
impl_parse!(syntax::Preprocessor, preprocessor);
impl_parse!(syntax::PreprocessorVersion, pp_version);
impl_parse!(syntax::PreprocessorVersionProfile, pp_version_profile);
impl_parse!(syntax::PreprocessorExtensionName, pp_extension_name);
impl_parse!(syntax::PreprocessorExtensionBehavior, pp_extension_behavior);
impl_parse!(syntax::PreprocessorExtension, pp_extension);

1856
third_party/rust/glsl/src/parsers.rs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,95 @@
//! Various nom parser helpers.
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::{anychar, multispace1, newline};
use nom::combinator::{map, recognize, value};
use nom::error::{ErrorKind, VerboseError, VerboseErrorKind};
use nom::multi::fold_many0;
use nom::{Err as NomErr, IResult};
pub type ParserResult<'a, O> = IResult<&'a str, O, VerboseError<&'a str>>;
// A constant parser that just forwards the value its parametered with without reading anything
// from the input. Especially useful as “fallback” in an alternative parser.
pub fn cnst<'a, T, E>(t: T) -> impl Fn(&'a str) -> Result<(&'a str, T), E>
where
T: 'a + Clone,
{
move |i| Ok((i, t.clone()))
}
// End-of-input parser.
//
// Yields `()` if the parser is at the end of the input; an error otherwise.
pub fn eoi(i: &str) -> ParserResult<()> {
if i.is_empty() {
Ok((i, ()))
} else {
Err(NomErr::Error(VerboseError {
errors: vec![(i, VerboseErrorKind::Nom(ErrorKind::Eof))],
}))
}
}
// A newline parser that accepts:
//
// - A newline.
// - The end of input.
pub fn eol(i: &str) -> ParserResult<()> {
alt((
eoi, // this one goes first because its very cheap
value((), newline),
))(i)
}
// Apply the `f` parser until `g` succeeds. Both parsers consume the input.
pub fn till<'a, A, B, F, G>(f: F, g: G) -> impl Fn(&'a str) -> ParserResult<'a, ()>
where
F: Fn(&'a str) -> ParserResult<'a, A>,
G: Fn(&'a str) -> ParserResult<'a, B>,
{
move |mut i| loop {
if let Ok((i2, _)) = g(i) {
break Ok((i2, ()));
}
let (i2, _) = f(i)?;
i = i2;
}
}
// A version of many0 that discards the result of the parser, preventing allocating.
pub fn many0_<'a, A, F>(f: F) -> impl Fn(&'a str) -> ParserResult<'a, ()>
where
F: Fn(&'a str) -> ParserResult<'a, A>,
{
move |i| fold_many0(&f, (), |_, _| ())(i)
}
/// Parse a string until the end of line.
///
/// This parser accepts the multiline annotation (\) to break the string on several lines.
///
/// Discard any leading newline.
pub fn str_till_eol(i: &str) -> ParserResult<&str> {
map(
recognize(till(alt((value((), tag("\\\n")), value((), anychar))), eol)),
|i| {
if i.as_bytes().last() == Some(&b'\n') {
&i[0..i.len() - 1]
} else {
i
}
},
)(i)
}
// Blank base parser.
//
// This parser succeeds with multispaces and multiline annotation.
//
// Taylor Swift loves it.
pub fn blank_space(i: &str) -> ParserResult<&str> {
recognize(many0_(alt((multispace1, tag("\\\n")))))(i)
}

1354
third_party/rust/glsl/src/syntax.rs vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
//! GLSL transpilers i.e. going from GLSL to anything else.
//!
//! Theres no public interface / trait to define what a transpiler is. It depends on the target
//! representation you aim.
pub mod glsl;
#[cfg(feature = "spirv")]
pub mod spirv;

View File

@ -0,0 +1,95 @@
//! SPIR-V transpiler.
//!
//! The current implementation uses the [shaderc](https://crates.io/crates/shaderc) crate to
//! transpile GLSL to SPIR-V. This is not ideal but will provide a default and starting
//! implementation.
use shaderc;
use crate::syntax;
use crate::transpiler::glsl as glsl_transpiler;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ShaderKind {
TessControl,
TessEvaluation,
Vertex,
Geometry,
Fragment,
Compute,
}
impl From<ShaderKind> for shaderc::ShaderKind {
fn from(kind: ShaderKind) -> Self {
match kind {
ShaderKind::TessControl => shaderc::ShaderKind::TessControl,
ShaderKind::TessEvaluation => shaderc::ShaderKind::TessEvaluation,
ShaderKind::Vertex => shaderc::ShaderKind::Vertex,
ShaderKind::Geometry => shaderc::ShaderKind::Geometry,
ShaderKind::Fragment => shaderc::ShaderKind::Fragment,
ShaderKind::Compute => shaderc::ShaderKind::Compute,
}
}
}
/// Transpile a GLSL AST into a SPIR-V internal buffer and write it to the given buffer.
///
/// The current implementation is highly inefficient as it relies on internal allocations and
/// [shaderc](https://crates.io/crates/shaderc).
///
/// If any error happens while transpiling, theyre returned as an opaque string.
pub fn transpile_translation_unit_to_binary<F>(
f: &mut F,
tu: &syntax::TranslationUnit,
kind: ShaderKind,
) -> Result<(), String>
where
F: std::io::Write,
{
// write as GLSL in an intermediate buffer
let mut glsl_buffer = String::new();
glsl_transpiler::show_translation_unit(&mut glsl_buffer, tu);
// pass the GLSL-formatted string to shaderc
let mut compiler = shaderc::Compiler::new().unwrap();
let options = shaderc::CompileOptions::new().unwrap();
let kind = kind.into();
let output = compiler
.compile_into_spirv(&glsl_buffer, kind, "glsl input", "main", Some(&options))
.map_err(|e| format!("{}", e))?;
let _ = f.write_all(output.as_binary_u8());
Ok(())
}
/// Transpile a GLSL AST into a SPIR-V internal buffer and write it to the given buffer.
///
/// The current implementation is highly inefficient as it relies on internal allocations and
/// [shaderc](https://crates.io/crates/shaderc).
///
/// If any error happens while transpiling, theyre returned as an opaque string.
pub fn transpile_translation_unit<F>(
f: &mut F,
tu: &syntax::TranslationUnit,
kind: ShaderKind,
) -> Result<(), String>
where
F: std::fmt::Write,
{
// write as GLSL in an intermediate buffer
let mut glsl_buffer = String::new();
glsl_transpiler::show_translation_unit(&mut glsl_buffer, tu);
// pass the GLSL-formatted string to shaderc
let mut compiler = shaderc::Compiler::new().unwrap();
let options = shaderc::CompileOptions::new().unwrap();
let kind = kind.into();
let output = compiler
.compile_into_spirv_assembly(&glsl_buffer, kind, "glsl input", "main", Some(&options))
.map_err(|e| format!("{}", e))?;
let _ = f.write_str(&output.as_text());
Ok(())
}

1424
third_party/rust/glsl/src/visitor.rs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,19 @@
use glsl::parser::Parse;
use glsl::syntax;
#[test]
fn incorrect_statement() {
let r = syntax::TranslationUnit::parse(
"
int fetch_transform(int id) {
return id;
}
bool ray_plane() {
if 1 {
}
",
);
assert!(r.is_err());
}

View File

@ -0,0 +1,49 @@
use glsl::parser::Parse;
use glsl::syntax;
#[test]
fn left_associativity() {
let r = syntax::TranslationUnit::parse(
"
void main() {
x = a + b + c;
}
",
);
let expected = syntax::TranslationUnit::from_non_empty_iter(vec![
syntax::ExternalDeclaration::FunctionDefinition(syntax::FunctionDefinition {
prototype: syntax::FunctionPrototype {
ty: syntax::FullySpecifiedType {
qualifier: None,
ty: syntax::TypeSpecifier {
ty: syntax::TypeSpecifierNonArray::Void,
array_specifier: None,
},
},
name: "main".into(),
parameters: Vec::new(),
},
statement: syntax::CompoundStatement {
statement_list: vec![syntax::Statement::Simple(Box::new(
syntax::SimpleStatement::Expression(Some(syntax::Expr::Assignment(
Box::new(syntax::Expr::Variable("x".into())),
syntax::AssignmentOp::Equal,
Box::new(syntax::Expr::Binary(
syntax::BinaryOp::Add,
Box::new(syntax::Expr::Binary(
syntax::BinaryOp::Add,
Box::new(syntax::Expr::Variable("a".into())),
Box::new(syntax::Expr::Variable("b".into())),
)),
Box::new(syntax::Expr::Variable("c".into())),
)),
))),
))],
},
}),
])
.unwrap();
assert_eq!(r, Ok(expected));
}

View File

@ -0,0 +1,28 @@
extern crate glsl;
use glsl::parser::Parse;
use glsl::syntax::TranslationUnit;
#[test]
fn missing_zero_float_is_valid() {
let r = TranslationUnit::parse(
"
void main() {
float x = 1. * .5;
}",
);
assert!(r.is_ok());
}
#[test]
fn float_exp_is_valid() {
let r = TranslationUnit::parse(
"
void main() {
float x = 1e-5;
}",
);
assert!(r.is_ok());
}